--- python2.6-2.6.1.orig/Doc/tools/sphinxext/download.html +++ python2.6-2.6.1/Doc/tools/sphinxext/download.html @@ -54,7 +54,7 @@

Problems

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

+email to docs@python.org.

{% endif %} {% endblock %} --- python2.6-2.6.1.orig/debian/PVER-dbg.prerm.in +++ python2.6-2.6.1/debian/PVER-dbg.prerm.in @@ -0,0 +1,10 @@ +#! /bin/sh -e + +PACKAGE=@PVER@-dbg + +rmdir /usr/local/lib/@PVER@/site-packages/debug 2>/dev/null && \ + rmdir /usr/local/lib/@PVER@/site-packages 2>/dev/null || \ + rmdir /usr/local/lib/@PVER@ 2>/dev/null || \ + true + +#DEBHELPER# --- python2.6-2.6.1.orig/debian/pyhtml2devhelp.py +++ python2.6-2.6.1/debian/pyhtml2devhelp.py @@ -0,0 +1,189 @@ +#! /usr/bin/python + +import formatter, htmllib +import os, sys, re + +class PyHTMLParser(htmllib.HTMLParser): + pages_to_include = set(('modindex.html', + 'api/api.html', 'doc/doc.html', 'ext/ext.html', + 'lib/lib.html', 'mac/mac.html', 'ref/ref.html', + 'tut/tut.html', 'inst/inst.html', 'dist/dist.html', + 'whatsnew/whatsnew25.html')) + include_modindex = False + + 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 + + def process_link(self): + new_href = os.path.join(self.dir, self.link['href']) + text = self.link['text'] + indent = self.indent + self.sub_indent + while self.last_indent >= indent: + print '%s' % (' ' * self.last_indent) + self.last_indent -= 1 + print '%s' % (' ' * indent, new_href, text) + self.last_indent = self.indent + self.sub_indent + + def start_ul(self, attrs): + self.sub_indent += 1 + + def end_ul(self): + self.sub_indent -= 1 + + def start_dl(self, attrs): + self.sub_indent += 1 + + def end_dl(self): + 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): + 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 self.link.get('rel', None) in ('prev', 'parent', 'next', 'contents', 'index'): + return + if href == 'about.html': + return + if href == 'modindex.html' and not self.include_modindex: + return + self.process_link() + if href in self.pages_to_include: + self.parse_file(os.path.join(self.dir, href)) + if href == 'tut/tut.html': + self.include_modindex = True + + def finish(self): + indent = self.indent + self.sub_indent + while self.last_indent > indent: + print '%s' % (' ' * self.last_indent) + self.last_indent -= 1 + + 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.header = '' + self.last_letter = 'letter-z' + + 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 == '[Link]': + return + if self.link.get('rel', None) in ('prev', 'parent', 'next', 'contents', 'index'): + return + indent = self.indent + print '%s' % (' ' * indent, new_href, text) + + def start_h2(self, attrs): + for k, v in attrs: + if k == 'id': + self.header = v + if v == 'letter-_': + self.active = True + + 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.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 '' + print '' % (sys.version[:3], sys.version[:3]) + print '' + parser.parse_file(fn) + print '' + + print '' + + fn = 'lib/genindex.html' + parser = PyIdxHTMLParser(formatter.NullFormatter(), base, fn, indent=1) + text = file(base + '/' + fn).read() + parser.feed(text) + parser.close() + + fn = 'api/genindex.html' + parser = PyIdxHTMLParser(formatter.NullFormatter(), base, fn, indent=1) + text = file(base + '/' + fn).read() + parser.last_letter = 'letter-v' + parser.feed(text) + parser.close() + + print '' + print '' + +main() --- python2.6-2.6.1.orig/debian/PVER-minimal.preinst.in +++ python2.6-2.6.1/debian/PVER-minimal.preinst.in @@ -0,0 +1,77 @@ +#!/bin/sh + +set -e + +syssite=/usr/lib/@PVER@/site-packages +oldsite=/usr/lib/@PVER@/old-site-packages +localsite=/usr/local/lib/@PVER@/dist-packages +syslink=../../${localsite#/usr/*} + +move_site_packages() +{ + [ -d $localsite ] || mkdir -p $localsite + + if [ -h $syssite ]; then + : + elif [ -d $syssite ]; then + for i in $(find $syssite -mindepth 1 -maxdepth 1 -printf '%P\n'); do + echo "Moving $syssite/$i to new location:" + if [ ! -e $localsite/$i ]; then + echo " --> $localsite/$i" + mv $syssite/$i $localsite/ + elif [ ! -e $oldsite/$i ]; then + echo " --> $oldsite/$i (already exist in $localsite/" + mv $syssite/$i $oldsite/ + else + echo " already exists in $localsite/ and $oldsite/" + echo " please proceed manually" + exit 1 + fi + done + echo "removing $syssite" + rmdir $syssite + #echo "symlinking $syssite to $localsite" + #ln -s $syslink $syssite + else + : + #ln -sf $syslink $syssite + fi +} + +case "$1" in + install) + # there never was a python2.6 package using site-packages. + #if [ -n "$2" ] && dpkg --compare-versions "$2" lt '2.6.1-0'; then + # move_site_packages + #fi + if [ -z "$2" ] && [ -d $syssite ] && [ ! -h $syssite ]; then + echo "new installation of @PVER@-minimal; $syssite is a directory" + echo "which is expected a symlink to $localsite." + echo "please find the package shipping files in $syssite and" + echo "file a bug report to ship these in /usr/lib/@PVER@/dist-packages instead" + echo "aborting installation of @PVER@-minimal" + exit 1 + fi + + # remember newly installed runtime + mkdir -p /var/lib/python + touch /var/lib/python/@PVER@_installed + ;; + upgrade) + if [ -n "$2" ] && dpkg --compare-versions "$2" lt '3.0~rc1'; then + move_site_packages + fi + ;; + + abort-upgrade) + ;; + + *) + echo "preinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python2.6-2.6.1.orig/debian/PVER.menu.in +++ python2.6-2.6.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@" --- python2.6-2.6.1.orig/debian/PVER-minimal.prerm.in +++ python2.6-2.6.1/debian/PVER-minimal.prerm.in @@ -0,0 +1,44 @@ +#! /bin/sh -e + +syssite=/usr/lib/@PVER@/site-packages +localsite=/usr/local/lib/@PVER@/dist-packages + +case "$1" in + remove) + if [ "$DEBIAN_FRONTEND" != noninteractive ]; then + echo "Unlinking and removing bytecode for runtime @PVER@" + fi + for hook in /usr/share/python/runtime.d/*.rtremove; do + [ -x $hook ] || continue + $hook rtremove @PVER@ || continue + done + dpkg -L @PVER@-minimal \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs rm -f >&2 + + if which update-binfmts >/dev/null; then + update-binfmts --package @PVER@ --remove @PVER@ /usr/bin/@PVER@ + fi + + if [ -h $syssite ]; then + rm -f $syssite + fi + [ -d $localsite ] && rmdir $localsite 2>/dev/null || true + [ -d $(dirname $localsite) ] && rmdir $(dirname $localsite) 2>/dev/null || true + ;; + upgrade) + dpkg -L @PVER@-minimal \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs rm -f >&2 + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.6-2.6.1.orig/debian/PVER.pycentral.in +++ python2.6-2.6.1/debian/PVER.pycentral.in @@ -0,0 +1,4 @@ +[@PVER@] +runtime: @PVER@ +interpreter: /usr/bin/@PVER@ +prefix: /usr/lib/@PVER@ --- python2.6-2.6.1.orig/debian/dh_rmemptydirs +++ python2.6-2.6.1/debian/dh_rmemptydirs @@ -0,0 +1,10 @@ +#! /bin/sh -e + +pkg=`echo $1 | sed 's/^-p//'` + +: # remove empty directories, when all components are in place +for d in `find debian/$pkg -depth -type d -empty 2> /dev/null`; do \ + while rmdir $$d 2> /dev/null; do d=`dirname $$d`; done; \ +done + +exit 0 --- python2.6-2.6.1.orig/debian/README.python +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/pymindeps.py +++ python2.6-2.6.1/debian/pymindeps.py @@ -0,0 +1,170 @@ +#! /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(('doctest', 'cPickle')), + 'copy': set(('reprlib',)), + 'difflib': set(('doctest',)), + 'hashlib': set(('_hashlib', '_md5', '_sha', '_sha256','_sha512',)), + 'heapq': set(('doctest',)), + 'inspect': set(('compiler',)), + 'os': set(('nt', 'ntpath', 'os2', 'os2emxpath', 'mac', 'macpath', + 'riscos', 'riscospath', 'riscosenviron')), + 'optparse': set(('gettext',)), + 'pickle': set(('doctest',)), + 'platform': set(('tempfile',)), + 'socket': set(('_ssl', 'ssl')), + 'tempfile': set(('dummy_thread',)), + '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:]) --- python2.6-2.6.1.orig/debian/README.maintainers.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/watch +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/PVER-dbg.postinst.in +++ python2.6-2.6.1/debian/PVER-dbg.postinst.in @@ -0,0 +1,29 @@ +#! /bin/sh -e + +PACKAGE=@PVER@-dbg + +case "$1" in + configure|abort-upgrade|abort-remove|abort-deconfigure) + + # Create empty debug directories in /usr/local + if [ ! -e /usr/local/lib/@PVER@ ]; then + mkdir -p /usr/local/lib/@PVER@ + chmod 2775 /usr/local/lib/@PVER@ + chown root:staff /usr/local/lib/@PVER@ + fi + if [ ! -e /usr/local/lib/@PVER@/site-packages/debug ]; then + mkdir -p /usr/local/lib/@PVER@/site-packages/debug + chmod 2775 /usr/local/lib/@PVER@/site-packages/debug + chown root:staff /usr/local/lib/@PVER@/site-packages/debug + fi + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python2.6-2.6.1.orig/debian/PVER.prerm.in +++ python2.6-2.6.1/debian/PVER.prerm.in @@ -0,0 +1,27 @@ +#! /bin/sh -e +# +# prerm script for the Debian @PVER@-base package. +# Written 1998 by Gregor Hoffleit . +# + +case "$1" in + remove|upgrade) + dpkg -L @PVER@ \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs rm -f >&2 + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +rmdir /usr/local/lib/python@VER@/site-packages 2>/dev/null && \ + rmdir /usr/local/lib/python@VER@ 2>/dev/null || \ + true + +#DEBHELPER# --- python2.6-2.6.1.orig/debian/control +++ python2.6-2.6.1/debian/control @@ -0,0 +1,112 @@ +Source: python2.6 +Section: python +Priority: optional +Maintainer: Ubuntu Core Developers +XSBC-Original-Maintainer: Matthias Klose +Build-Depends: debhelper (>= 5), autoconf, automake1.10, libreadline5-dev, libncursesw5-dev (>= 5.3), tk8.5-dev, zlib1g-dev, blt-dev (>= 2.4z), libssl-dev, sharutils, libbz2-dev, libbluetooth-dev [!hurd-i386 !kfreebsd-i386 !kfreebsd-amd64], locales [!armel !hppa !ia64 !mipsel], libsqlite3-dev, libffi-dev (>= 3.0.5), mime-support, libgpm2 [!hurd-i386 !kfreebsd-i386 !kfreebsd-amd64], netbase, lsb-release, bzip2, libdb-dev +Build-Depends-Indep: python-sphinx +Build-Conflicts: tcl8.3-dev, tk8.3-dev, python2.6-xml, python-xml, libgdbm-dev +XS-Python-Version: 2.6 +Standards-Version: 3.8.0 +Vcs-Browser: https://code.launchpad.net/~doko/python/pkg2.6 +Vcs-Bzr: http://bazaar.launchpad.net/~doko/python/pkg2.6 + +Package: python2.6 +Architecture: any +Priority: optional +Depends: python2.6-minimal (= ${binary:Version}), mime-support, ${shlibs:Depends} +Suggests: python2.6-doc, python2.6-profiler, binutils +Provides: python2.6-cjkcodecs, python2.6-ctypes, python2.6-elementtree, python2.6-celementtree, python2.6-wsgiref +XB-Python-Version: 2.6 +Description: An interactive high-level object-oriented language (version 2.6) + Version 2.6 of the high-level, interactive object oriented language, + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + +Package: python2.6-minimal +Architecture: any +Priority: required +Depends: ${shlibs:Depends} +Recommends: python2.6 +Suggests: binfmt-support +Replaces: python2.6 (<< 2.6) +Conflicts: binfmt-support (<< 1.1.2) +XB-Python-Runtime: python2.6 +XB-Python-Version: 2.6 +Description: A minimal subset of the Python language (version 2.6) + This package contains the interpreter and some essential modules. It can + be used in the boot process for some basic tasks. + See /usr/share/doc/python2.6-minimal/README.Debian for a list of the modules + contained in this package. + +Package: libpython2.6 +Architecture: any +Section: libs +Priority: optional +Depends: python2.6 (= ${binary:Version}), ${shlibs:Depends} +Replaces: python2.6 (<< 2.6) +Description: Shared Python runtime library (version 2.6) + Version 2.6 of the high-level, interactive object oriented language, + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains the shared runtime library, normally not needed + for programs using the statically linked interpreter. + +Package: python2.6-examples +Architecture: all +Depends: python2.6 (>= ${source:Version}) +Description: Examples for the Python language (v2.6) + Examples, Demos and Tools for Python (v2.6). These are files included in + the upstream Python distribution (v2.6). + +Package: python2.6-dev +Architecture: any +Depends: python2.6 (= ${binary:Version}), libpython2.6 (= ${binary:Version}), ${shlibs:Depends} +Recommends: libc6-dev | libc-dev +Replaces: python2.6 (<< 2.6.1-2) +Description: Header files and a static library for Python (v2.6) + Header files, a static library and development tools for building + Python (v2.6) modules, extending the Python interpreter or embedding + Python (v2.6) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: idle-python2.6 +Architecture: all +Depends: python2.6, python-tk (>= 2.6~a3), python2.6-tk +Enhances: python2.6 +Replaces: python2.6 (<< 2.6.1-2) +XB-Python-Version: 2.6 +Description: An IDE for Python (v2.6) using Tkinter + IDLE is an Integrated Development Environment for Python (v2.6). + IDLE is written using Tkinter and therefore quite platform-independent. + +Package: python2.6-doc +Section: doc +Architecture: all +Suggests: python2.6 +Description: Documentation for the high-level object-oriented language Python (v2.6) + These is the official set of documentation for the interactive high-level + object-oriented language Python (v2.6). All documents are provided + in HTML format. The package consists of ten documents: + . + * What's New in Python2.6 + * Tutorial + * Python Library Reference + * Macintosh Module Reference + * Python Language Reference + * Extending and Embedding Python + * Python/C API Reference + * Installing Python Modules + * Documenting Python + * Distributing Python Modules + +Package: python2.6-dbg +Architecture: any +Priority: extra +Depends: python2.6 (>= ${binary:Version}), ${shlibs:Depends} +Suggests: python-gdbm-dbg, python-tk-dbg +Description: Debug Build of the Python Interpreter (version 2.6) + Python interpreter configured with --pydebug. Dynamically loaded modules are + searched in /usr/lib/python2.6/lib-dynload/debug first. --- python2.6-2.6.1.orig/debian/depgraph.py +++ python2.6-2.6.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() + + + --- python2.6-2.6.1.orig/debian/PVER-minimal.postrm.in +++ python2.6-2.6.1/debian/PVER-minimal.postrm.in @@ -0,0 +1,27 @@ +#! /bin/sh -e + +if [ "$1" = "remove" ]; then + + (find /usr/lib/@PVER@ -name '*.py[co]' | xargs rm -f {}) 2>/dev/null || true + + for d in `find /usr/lib/@PVER@ -depth -type d -empty 2> /dev/null`; do \ + while rmdir $d 2> /dev/null; do d=`dirname $d`; done; \ + done + + if [ -f /var/lib/python/@PVER@_installed ]; then + rm -f /var/lib/python/@PVER@_installed + rmdir --ignore-fail-on-non-empty /var/lib/python 2>/dev/null + fi +fi + +if [ "$1" = "purge" ]; then + for d in `find /usr/lib/@PVER@ -depth -type d -empty 2> /dev/null`; do \ + while rmdir $d 2> /dev/null; do d=`dirname $d`; done; \ + done + rm -f /etc/@PVER@/site.py /etc/@PVER@/sitecustomize.py + rmdir --ignore-fail-on-non-empty /etc/@PVER@ 2>/dev/null +fi + +#DEBHELPER# + +exit 0 --- python2.6-2.6.1.orig/debian/idle.desktop.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/PVER.overrides.in +++ python2.6-2.6.1/debian/PVER.overrides.in @@ -0,0 +1,5 @@ +# idlelib images +@PVER@ binary: image-file-in-usr-lib + +# yes, we have to +@PVER@ binary: depends-on-python-minimal --- python2.6-2.6.1.orig/debian/PVER-minimal.README.Debian.in +++ python2.6-2.6.1/debian/PVER-minimal.README.Debian.in @@ -0,0 +1,127 @@ +Contents of the @PVER@-minimal package +----------------------------------------- + +@PVER@-minimal consists of a minimum set of modules which may be needed +for python scripts used during the boot process. If other packages +are needed in these scripts, don't work around the missing module, but +file a bug report against this package. The modules in this package +are: + + __builtin__ builtin + __future__ module + _abcoll module + _bisect extension + _bytesio extension + _codecs builtin + _collections extension + _fileio extension + _functools extension + _locale extension + _random extension + _socket extension + _sre builtin + _struct extension + _symtable builtin + _types builtin + _warnings builtin + _weakref extension + abc module + ConfigParser module + StringIO module + UserDict module + cPickle extension + cStringIO extension + array extension + binascii extension + collections module + compileall module + copy module + copy_reg module + dis module + errno builtin + exceptions builtin + fcntl extension + fnmatch module + gc builtin + genericpath module + getopt module + glob module + grp extension + hashlib module + imp builtin + inspect module + itertools extension + keyword module + linecache module + marshal builtin + math extension + md5 module + opcode module + operator extension + optparse module + os module + pickle module + platform module + popen2 module + posix builtin + posixpath module + pwd builtin + py_compile module + random module + re module + repr module + select extension + sha module + signal builtin + socket module + spwd extension + sre module + sre_compile module + sre_constants module + sre_parse module + stat module + string module + strop extension + struct module + subprocess module + sys builtin + syslog extension + tempfile module + textwrap module + time extension + token module + thread builtin + token module + tokenize module + traceback module + types module + unicodedata extension + warnings module + zlib extension + +Included are as well the codecs and stringprep modules, and the encodings +modules for all encodings except the multibyte encodings and the bz2 codec. + +The following modules are excluded, their import is guarded from the +importing module (i.e. omit the import of _ssl in socket): + + _hashlib hashlib + os nt ntpath os2 os2emxpath mac macpath + riscos riscospath riscosenviron + optparse gettext + pickle doctest + platform tempfile + socket _ssl + subprocess threading + +This list was derived by looking at the modules in the perl-base package, +then adding python specific "core modules". + +TODO's +------ + +- time.strptime cannot be used. The required _strptime module is not + included in the -minimal package yet. _strptime, locale, _locale and + calendar have to be added. + +- modules used very often in the testsuite: copy, cPickle, operator. --- python2.6-2.6.1.orig/debian/dh_doclink +++ python2.6-2.6.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 < +Build-Depends: debhelper (>= 5), autoconf, automake1.10, libreadline5-dev, libncursesw5-dev (>= 5.3), tk8.5-dev, zlib1g-dev, blt-dev (>= 2.4z), libssl-dev, sharutils, libbz2-dev, libbluetooth-dev [!hurd-i386 !kfreebsd-i386 !kfreebsd-amd64], locales [!armel !hppa !ia64 !mipsel], libsqlite3-dev, libffi-dev (>= 3.0.5), mime-support, libgpm2 [!hurd-i386 !kfreebsd-i386 !kfreebsd-amd64], netbase, lsb-release, bzip2, libdb-dev +Build-Depends-Indep: python-sphinx +Build-Conflicts: tcl8.3-dev, tk8.3-dev, @PVER@-xml, python-xml, libgdbm-dev +XS-Python-Version: @VER@ +Standards-Version: 3.8.0 +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} +Suggests: @PVER@-doc, @PVER@-profiler, binutils +Provides: @PVER@-cjkcodecs, @PVER@-ctypes, @PVER@-elementtree, @PVER@-celementtree, @PVER@-wsgiref +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} +Recommends: @PVER@ +Suggests: binfmt-support +Replaces: @PVER@ (<< 2.6) +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} +Replaces: @PVER@ (<< 2.6) +Description: Shared Python runtime library (version @VER@) + Version @VER@ of the high-level, interactive object oriented language, + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains the shared runtime library, normally not needed + for programs using the statically linked interpreter. + +Package: @PVER@-examples +Architecture: all +Depends: @PVER@ (>= ${source:Version}) +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} +Recommends: libc6-dev | libc-dev +Replaces: @PVER@ (<< 2.6.1-2) +Description: Header files and a static library for Python (v@VER@) + Header files, a static library and development tools for building + Python (v@VER@) modules, extending the Python interpreter or embedding + Python (v@VER@) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: idle-@PVER@ +Architecture: all +Depends: @PVER@, python-tk (>= 2.6~a3), @PVER@-tk +Enhances: @PVER@ +Replaces: @PVER@ (<< 2.6.1-2) +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 +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 +Architecture: any +Priority: extra +Depends: @PVER@ (>= ${binary:Version}), ${shlibs:Depends} +Suggests: python-gdbm-dbg, python-tk-dbg +Description: Debug Build of the Python Interpreter (version @VER@) + Python interpreter configured with --pydebug. Dynamically loaded modules are + searched in /usr/lib/@PVER@/lib-dynload/debug first. --- python2.6-2.6.1.orig/debian/compat +++ python2.6-2.6.1/debian/compat @@ -0,0 +1 @@ +5 --- python2.6-2.6.1.orig/debian/PVER-doc.doc-base.PVER-ref.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/PVER-minimal.postinst.in +++ python2.6-2.6.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 2> /dev/null || true + chmod 2775 $localsite 2> /dev/null || true + chown root:staff $localsite 2> /dev/null || true + fi + #if [ ! -h $syssite ]; then + # ln -s $syslink $syssite + #fi + + if which update-binfmts >/dev/null; then + update-binfmts --import @PVER@ + fi + + ;; +esac + +if [ "$1" = configure ]; then + ( + files=$(dpkg -L @PVER@-minimal | sed -n '/^\/usr\/lib\/@PVER@\/.*\.py$/p') + /usr/bin/@PVER@ /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + /usr/bin/@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 --- python2.6-2.6.1.orig/debian/PVER-doc.overrides.in +++ python2.6-2.6.1/debian/PVER-doc.overrides.in @@ -0,0 +1,2 @@ +# this is referenced by the html docs +@PVER@-doc binary: extra-license-file --- python2.6-2.6.1.orig/debian/idle-PVER.prerm.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/PVER-doc.doc-base.PVER-lib.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/sitecustomize.py.in +++ python2.6-2.6.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() --- python2.6-2.6.1.orig/debian/PVER-doc.doc-base.PVER-tut.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/rules +++ python2.6-2.6.1/debian/rules @@ -0,0 +1,1011 @@ +#!/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 +ifeq ($(on_buildd),yes) + ifneq (,$(findstring $(DEB_BUILD_ARCH), hppa s390)) + WITHOUT_CHECK := yes + endif +endif + +COMMA = , +ifneq (,$(filter parallel=%,$(subst $(COMMA), ,$(DEB_BUILD_OPTIONS)))) + NJOBS := -j $(subst parallel=,,$(filter parallel=%,$(subst $(COMMA), ,$(DEB_BUILD_OPTIONS)))) +endif + +distribution := $(shell lsb_release -is) +#distribution := Ubuntu + +export VER=2.6 +export NVER=2.7 +export PVER=python2.6 +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_gdbm := 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 + with_fpectl = yes +else + PY_MINPRIO = $(PY_PRIO) +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 + +PWD := $(shell pwd) +buildd_static := $(CURDIR)/build-static +buildd_shared := $(CURDIR)/build-shared +buildd_debug := $(CURDIR)/build-debug + +d := debian/tmp +scriptdir = usr/share/lib/python$(VER) +scriptdir = usr/share/python$(VER) +scriptdir = usr/lib/python$(VER) + +# package names and directories +p_base := $(PVER) +p_min := $(PVER)-minimal +p_lib := lib$(PVER) +p_tk := $(PVER)-tk +p_gdbm := $(PVER)-gdbm +p_dev := $(PVER)-dev +p_exam := $(PVER)-examples +p_idle := idle-$(PVER) +p_doc := $(PVER)-doc +p_dbg := $(PVER)-dbg + +d_base := debian/$(p_base) +d_min := debian/$(p_min) +d_lib := debian/$(p_lib) +d_tk := debian/$(p_tk) +d_gdbm := debian/$(p_gdbm) +d_dev := debian/$(p_dev) +d_exam := debian/$(p_exam) +d_idle := debian/$(p_idle) +d_doc := debian/$(p_doc) +d_dbg := debian/$(p_dbg) + +# profiled build fails on amd64, lpia, sparc +ifneq (,$(filter $(DEB_BUILD_ARCH), amd64 armel lpia sparc)) + make_build_target = +else + make_build_target = profile-opt +endif +make_build_target = + +build: $(build_target) +build-all: stamp-build +stamp-build: stamp-build-static stamp-build-shared stamp-build-debug stamp-mincheck stamp-check stamp-pystone stamp-pybench + touch stamp-build + +PROFILE_EXCLUDES = test_compiler test_distutils test_platform test_subprocess \ + test_pstats test_profile test_multiprocessing test_cprofile \ + test_thread test_threaded_import test_threadedtempfile \ + test_threading test_threading_local test_threadsignals \ + test_dbm_dumb test_dbm_ndbm test_pydoc test_sundry + +ifneq (,$(filter $(DEB_BUILD_ARCH), arm armel)) + PROFILE_EXCLUDES += test_float +endif +PROFILE_EXCLUDES += test_zipfile + +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 + $(MAKE) $(NJOBS) -C $(buildd_debug) + touch stamp-build-debug + +common_configure_args = \ + --prefix=/usr \ + --enable-ipv6 \ + --enable-unicode=ucs4 \ + --without-cxx \ + --with-system-ffi \ + +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-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 = +# not built from this source +TEST_EXCLUDES += test_bsddb3 +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), m68k)) + TEST_EXCLUDES += test_bsddb3 +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 (0,1) + 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 +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=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. ./python ../Lib/test/pystone.py + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. ./python ../Lib/test/pystone.py + @echo "END pystone shared" + @echo "BEGIN pystone debug" + cd $(buildd_debug) && ./python ../Lib/test/pystone.py + cd $(buildd_debug) && ./python ../Lib/test/pystone.py + @echo "END pystone debug" + touch stamp-pystone + +stamp-pybench: +ifeq ($(WITHOUT_CHECK),yes) + echo "pybench run disabled for this build" > $(buildd_static)/pybench.log +else + ifeq (,$(filter $(DEB_BUILD_ARCH), arm armel hppa m68k)) + @echo "BEGIN pybench static" + cd $(buildd_static) \ + && time ./python ../Tools/pybench/pybench.py -f run1.pybench + cd $(buildd_static) \ + && ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench + @echo "END pybench static" + @echo "BEGIN pybench shared" + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. ./python ../Tools/pybench/pybench.py -f run1.pybench + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench + @echo "END pybench shared" + ifeq (,$(filter $(DEB_BUILD_ARCH), arm armel m68k)) + @echo "BEGIN pybench debug" + cd $(buildd_debug) \ + && time ./python ../Tools/pybench/pybench.py -f run1.pybench + cd $(buildd_debug) \ + && ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench + @echo "END pybench debug" + endif + @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" + else + echo "pybench not run on arch $(DEB_BUILD_ARCH)." > $(buildd_static)/pybench.log + endif +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 + -$(MAKE) -f Makefile.pre.in srcdir=. distclean + rm -rf Lib/test/db_home + rm -rf $(buildd_static) $(buildd_shared) $(buildd_debug) + 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 + + : # 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 + mv $(d)/usr/share/man/man1/python.1 \ + $(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/python-config + + mv $(d)/usr/bin/2to3 $(d)/usr/bin/2to3-$(VER) + +# : # remove the bsddb stuff +# rm -rf $(d)/$(scriptdir)/bsddb +# rm -f $(d)/$(scriptdir)/lib-dynload/_bsddb.so + + : # Remove version information from the egg-info file + mv $(d)/$(scriptdir)/lib-dynload/Python-2.6*.egg-info \ + $(d)/$(scriptdir)/lib-dynload/Python-$(VER).egg-info + + dh_installdirs -p$(p_lib) \ + $(scriptdir)/config \ + usr/share/doc + : # install the shared library + cp -p $(buildd_shared)/libpython$(VER).so.1.0 $(d_lib)/usr/lib/ + ln -sf libpython$(VER).so.1.0 $(d_lib)/usr/lib/libpython$(VER).so.1 + ln -sf ../../libpython$(VER).so \ + $(d_lib)/$(scriptdir)/config/libpython$(VER).so + ln -sf $(p_base) $(d_lib)/usr/share/doc/$(p_lib) + + ln -sf libpython$(VER).so.1 $(d)/usr/lib/libpython$(VER).so + +ifeq ($(with_interp),shared) + : # install the statically linked runtime + install -m755 $(buildd_static)/python $(d)/usr/bin/python$(VER)-static +endif + + mv $(d)/usr/bin/pydoc $(d)/usr/bin/pydoc$(VER) + cp -p Tools/i18n/pygettext.py $(d)/usr/bin/pygettext$(VER) + cp -p debian/pygettext.1 $(d)/usr/share/man/man1/pygettext$(VER).1 + + : # install the Makefile of the shared python build + sed -e '/^OPT/s,-O3,-O2,' \ + -e 's,^RUNSHARED *=.*,RUNSHARED=,' \ + build-shared/Makefile > $(d)/$(scriptdir)/config/Makefile + + : # Move the binary and the minimal libraries into $(p_min). + dh_installdirs -p$(p_min) \ + usr/bin \ + usr/share/man/man1 \ + $(scriptdir) + 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) \ + + : # Install sitecustomize.py. + dh_installdirs -p$(p_min) etc/$(PVER) + 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/lib/libpython$(VER).a \ + usr/bin/python$(VER)-config + 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 + +ifeq ($(with_gdbm),yes) + : # gdbm and dbm modules into $(p_gdbm). + dh_installdirs -p$(p_gdbm) \ + usr/lib/python$(VER)/lib-dynload + DH_COMPAT=2 dh_movefiles -p$(p_gdbm) --sourcedir=$(d) \ + usr/lib/python$(VER)/lib-dynload/gdbm.so +endif + +# : # The test framework into $(p_base), regression tests dropped + DH_COMPAT=2 dh_movefiles -p$(p_base) --sourcedir=$(d) \ + $(scriptdir)/test/{regrtest.py,test_support.py,__init__.py,README,pystone.py} + rm -rf $(d)/$(scriptdir)/test + rm -rf $(d)/$(scriptdir)/ctypes/test + rm -rf $(d)/$(scriptdir)/bsddb/test + rm -rf $(d)/$(scriptdir)/email/test + rm -rf $(d)/$(scriptdir)/json/tests + rm -rf $(d)/$(scriptdir)/sqlite3/test + rm -rf $(d)/$(scriptdir)/distutils/tests + rm -rf $(d)/$(scriptdir)/lib2to3/tests + + : # IDLE + mv $(d)/usr/bin/idle $(d)/usr/bin/idle-python$(VER) + rm -f $(d)/usr/lib/python$(VER)/idlelib/idle.bat + dh_installdirs -p$(p_idle) \ + usr/bin \ + usr/share/man/man1 + DH_COMPAT=2 dh_movefiles -p$(p_idle) \ + usr/lib/python$(VER)/idlelib \ + usr/bin/idle-python$(VER) + cp -p debian/idle-$(PVER).1 $(d_idle)/usr/share/man/man1/ + + : # Move the demos and tools into $(p_exam)'s doc directory + dh_installdirs -p$(p_exam) \ + usr/share/doc/python$(VER)/examples + + cp -rp Demo Tools $(d_exam)/usr/share/doc/python$(VER)/examples/ + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Demo/sgi + : # IDLE is in its own package: + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Tools/idle + : # XXX: We don't need rgb.txt, we'll use our own: + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Tools/pynche/X + + : # XXX: Some files in upstream Demo and Tools have strange + : # exec permissions, make lintian glad: + -chmod 644 $(d_tk)/$(scriptdir)/lib-tk/Tix.py + -chmod 644 $(d)/$(scriptdir)/runpy.py + + cd $(d_exam)/usr/share/doc/python$(VER)/examples && chmod 644 \ + Demo/{classes/*.py*,comparisons/patterns} \ + Demo/{rpc/test,threads/*.py*,md5test/*} \ + Demo/pdist/{client.py,cmdfw.py,cmptree.py,cvslib.py,cvslock.py,FSProxy.py,mac.py,rcsclient.py,rcslib.py,security.py,server.py,sumtree.py} \ + Demo/scripts/{morse.py,newslist.doc,wh.py} \ + Demo/sockets/{broadcast.py,ftp.py,mcast.py,radio.py} \ + Demo/tix/{bitmaps/{tix.gif,*x[pb]m*},samples/*.py} \ + Demo/tkinter/guido/{AttrDialog.py,hanoi.py,hello.py,imagedraw.py,imageview.py,listtree.py,ManPage.py,ShellWindow.py,wish.py} \ + Tools/scripts/pydocgui.pyw \ + Tools/{scripts/mailerdaemon.py,modulator/genmodule.py} + + : # Replace all '#!' calls to python with $(PY_INTERPRETER) + : # and make them executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch'`; do \ + sed '1s,#!.*python[^ ]*\(.*\),#! $(PY_INTERPRETER)\1,' \ + $$i > $$i.temp; \ + if cmp --quiet $$i $$i.temp; then \ + rm -f $$i.temp; \ + else \ + mv -f $$i.temp $$i; \ + chmod 755 $$i; \ + echo "fixed interpreter: $$i"; \ + fi; \ + done + + : # Move the docs into $(p_base)'s /usr/share/doc/$(PVER) directory, + : # all other packages only have a copyright file. + dh_installdocs -p$(p_base) \ + README Misc/NEWS Misc/ACKS + ln -sf NEWS.gz $(d_base)/usr/share/doc/$(p_base)/changelog.gz + dh_installdocs --all -N$(p_base) -N$(p_dev) -N$(p_dbg) -N$(p_lib) debian/README.Debian + + : # IDLE has its own changelogs, docs... + dh_installchangelogs -p$(p_idle) Lib/idlelib/ChangeLog + dh_installdocs -p$(p_idle) Lib/idlelib/{NEWS,README,TODO,extend}.txt + + mkdir -p $(d_idle)/usr/share/applications + cp -p debian/idle.desktop \ + $(d_idle)/usr/share/applications/idle-$(PVER).desktop + + : # those packages have own README.Debian's + install -m 644 -p debian/README.$(p_base) \ + $(d_base)/usr/share/doc/$(PVER)/README.Debian + install -m 644 -p debian/README.$(p_idle) \ + $(d_idle)/usr/share/doc/$(p_idle)/README.Debian +ifeq ($(with_tk),yes) + cp -p debian/README.Tk $(d_tk)/usr/share/doc/$(p_tk)/ +endif + + : # The rest goes into $(p_base) + mkdir -p $(d)/usr/lib/python$(VER)/dist-packages + (cd $(d) && tar cf - .) | (cd $(d_base) && tar xpf -) + sh debian/dh_rmemptydirs -p$(p_base) + rm -f $(d_base)/usr/bin/python + + : # Install 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 -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/ +ifneq ($(with_gdbm),yes) + rm -f $(d_dbg)/$(scriptdir)/lib-dynload/gdbm_d.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/gdbm.so +endif +ifneq ($(with_tk),yes) + rm -f $(d_dbg)/$(scriptdir)/lib-dynload/_tkinter_d.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/_tkinter.so +endif +# rm -f $(d_dbg)/$(scriptdir)/lib-dynload/_bsddb_d.so + + cp -a $(d)-dbg/$(scriptdir)/config_d $(d_dbg)/$(scriptdir)/ + 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)/ + + dh_link -p$(p_doc) \ + /usr/share/doc/$(p_base)/html /usr/share/doc/$(p_doc)/html + +ifeq (no,yes) + : # devhelp docs + python debian/pyhtml2devhelp.py \ + $(d_doc)/usr/share/doc/$(p_base)/html index.html \ + > $(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) +endif + dh_installdebconf -i $(dh_args) + dh_installexamples -i $(dh_args) + dh_installmenu -i $(dh_args) + dh_desktop -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 -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 +ifneq ($(with_gdbm),yes) + rm -f $(d_base)/$(scriptdir)/lib-dynload/gdbm.so +endif + dh_strip -a -N$(p_dbg) -Xdebug -Xdbg --dbg-package=$(p_dbg) + 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 'lib$(PVER) (>= 2.6)' + 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 + +# 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 \ + hotshot-import \ + profile-doc \ + webbrowser \ + linecache \ + doc-nodownload \ + profiled-build2 \ + ctypes-mips-configure \ + platform-lsbrelease \ + +# setup-modules \ +# profiled-build \ +# subprocess-eintr-safety \ +# pydebug-path \ +# svn-updates \ +# db4.6 \ + +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-stampx: + dh_testdir + QUILT_PATCHES=debian/patches quilt push -a || test $$? = 2 + touch 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 + mv -f pxxx $@ + +reverse-patches: unpatch +unpatchx: + QUILT_PATCHES=debian/patches quilt pop -a -R || test $$? = 2 + rm -f patch-stamp + +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." > $@ + autoconf +# autoreconf -i + +binary: binary-indep binary-arch + +.PHONY: control-file configure build clean binary-indep binary-arch binary install + +# Local Variables: +# mode: makefile +# end: --- python2.6-2.6.1.orig/debian/mincheck.py +++ python2.6-2.6.1/debian/mincheck.py @@ -0,0 +1,41 @@ + +import sys + +def get_listed(fn): + modules = set() + for line in file(fn).readlines(): + modules.add(line.split()[1]) + return modules + +def get_dependencies(fn): + t = eval(file(fn).read()) + modules = set() + depgraph = t['depgraph'] + for mod, deps in depgraph.iteritems(): + if mod != '__main__': + modules.add(mod) + modules.update(deps.keys()) + return depgraph, modules + +def main(): + mods = get_listed(sys.argv[1]) + depgraph, deps = get_dependencies(sys.argv[2]) + print "Listed modules:", sorted(mods) + print + print "Dependent modules:", sorted(deps) + print + + missing = deps.difference(mods) + if missing: + print "Missing modules in python-minimal:" + print missing + for m in missing: + users = [] + for caller, callees in depgraph.iteritems(): + if m in callees: + users.append(caller) + print m, "used in: ", users + sys.exit(len(missing)) + +main() + --- python2.6-2.6.1.orig/debian/FAQ.html +++ python2.6-2.6.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
+ + --- python2.6-2.6.1.orig/debian/PVER.desktop.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/README.dbm +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/pylogo.xpm +++ python2.6-2.6.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@ "}; --- python2.6-2.6.1.orig/debian/mkbinfmt.py +++ python2.6-2.6.1/debian/mkbinfmt.py @@ -0,0 +1,17 @@ +# mkbinfmt.py +import imp, sys, string, os.path + +magic = string.join(["\\x%.2x" % ord(c) for c in imp.get_magic()],"") + +name = sys.argv[1] + +binfmt = '''\ +package %s +interpreter /usr/bin/%s +magic %s\ +''' % (name, name, magic) + +#filename = '/usr/share/binfmts/' + name +#open(filename,'w+').write(binfmt) + +print binfmt --- python2.6-2.6.1.orig/debian/control.doc +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/control.stdlib +++ python2.6-2.6.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. + --- python2.6-2.6.1.orig/debian/README.Tk +++ python2.6-2.6.1/debian/README.Tk @@ -0,0 +1,8 @@ +Tkinter documentation can be found at + + http://www.pythonware.com/library/index.htm + +more specific: + + http://www.pythonware.com/library/tkinter/introduction/index.htm + http://www.pythonware.com/library/tkinter/an-introduction-to-tkinter.pdf --- python2.6-2.6.1.orig/debian/pdb.1.in +++ python2.6-2.6.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/python2.3/html/lib/module-pdb.html. --- python2.6-2.6.1.orig/debian/PVER-doc.doc-base.PVER-ext.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/README.Debian.in +++ python2.6-2.6.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. --- python2.6-2.6.1.orig/debian/idle-PVER.overrides.in +++ python2.6-2.6.1/debian/idle-PVER.overrides.in @@ -0,0 +1,2 @@ +# icon in dependent package +idle-@PVER@ binary: menu-icon-missing --- python2.6-2.6.1.orig/debian/PVER-doc.prerm.in +++ python2.6-2.6.1/debian/PVER-doc.prerm.in @@ -0,0 +1,15 @@ +#! /bin/sh + +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 --- python2.6-2.6.1.orig/debian/README.idle-PVER.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/idle-PVER.1.in +++ python2.6-2.6.1/debian/idle-PVER.1.in @@ -0,0 +1,104 @@ +.TH IDLE 1 "21 September 2004" +.SH NAME +\fBIDLE\fP \- An Integrated DeveLopment Environment for Python +.SH SYNTAX +.B idle [ \fI-dins\fP ] [ \fI-t title\fP ] [ \fIfile\fP ...] +.PP +.B idle [ \fI-dins\fP ] [ \fI-t title\fP ] ( \fI-c cmd\fP | \fI-r file\fP ) [ \fIarg\fP ...] +.PP +.B idle [ \fI-dins\fP ] [ \fI-t title\fP ] - [ \fIarg\fP ...] +.SH DESCRIPTION +This manual page documents briefly the +.BR idle +command. +This manual page was written for Debian +because the original program does not have a manual page. +For more information, refer to IDLE's help menu. +.PP +.B IDLE +is an Integrated DeveLopment Environment for Python. IDLE is based on +Tkinter, Python's bindings to the Tk widget set. Features are 100% pure +Python, multi-windows with multiple undo and Python colorizing, a Python +shell window subclass, a debugger. IDLE is cross-platform, i.e. it works +on all platforms where Tk is installed. +.LP +.SH OPTIONS +.TP +.B \-h +.PD +Print this help message and exit. +.TP +.B \-n +.PD +Run IDLE without a subprocess (see Help/IDLE Help for details). +.PP +The following options will override the IDLE 'settings' configuration: +.TP +.B \-e +.PD +Open an edit window. +.TP +.B \-i +.PD +Open a shell window. +.PP +The following options imply -i and will open a shell: +.TP +.B \-c cmd +.PD +Run the command in a shell, or +.TP +.B \-r file +.PD +Run script from file. +.PP +.TP +.B \-d +.PD +Enable the debugger. +.TP +.B \-s +.PD +Run $IDLESTARTUP or $PYTHONSTARTUP before anything else. +.TP +.B \-t title +.PD +Set title of shell window. +.PP +A default edit window will be bypassed when -c, -r, or - are used. +.PP +[arg]* and [file]* are passed to the command (-c) or script (-r) in sys.argv[1:]. +.SH EXAMPLES +.TP +idle +.PD +Open an edit window or shell depending on IDLE's configuration. +.TP +idle foo.py foobar.py +.PD +Edit the files, also open a shell if configured to start with shell. +.TP +idle -est "Baz" foo.py +.PD +Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell +window with the title "Baz". +.TP +idle -c "import sys; print sys.argv" "foo" +.PD +Open a shell window and run the command, passing "-c" in sys.argv[0] +and "foo" in sys.argv[1]. +.TP +idle -d -s -r foo.py "Hello World" +.PD +Open a shell window, run a startup script, enable the debugger, and +run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in +sys.argv[1]. +.TP +echo "import sys; print sys.argv" | idle - "foobar" +.PD +Open a shell window, run the script piped in, passing '' in sys.argv[0] +and "foobar" in sys.argv[1]. +.SH SEE ALSO +python(1). +.SH AUTHORS +Various. --- python2.6-2.6.1.orig/debian/PVER-examples.overrides.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/PVER-doc.postinst.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/changelog +++ python2.6-2.6.1/debian/changelog @@ -0,0 +1,1868 @@ +python2.6 (2.6.1-1ubuntu3) jaunty; urgency=low + + * Use the information in /etc/lsb-release for platform.dist(). LP: #196526. + * Fix typo in installation scheme, introduced in previous upload. + + -- Matthias Klose Wed, 18 Mar 2009 19:44:34 +0100 + +python2.6 (2.6.1-1ubuntu2) jaunty; urgency=low + + * 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. + - The options --install-layout=deb and --prefix are exclusive. + * Don't fail installation/removal if directories in /usr/local cannot + be created. LP: #338227. + + -- Matthias Klose Wed, 18 Mar 2009 12:12:34 +0100 + +python2.6 (2.6.1-1ubuntu1) jaunty; urgency=low + + * Update to 20090302, taken from the 2.6 release branch. + * Move libpython2.6.a into the python2.6-dev package. + * Move idlelib into the idle-python2.6 package. + + -- Matthias Klose Wed, 25 Feb 2009 18:42:19 +0100 + +python2.6 (2.6.1-1) experimental; urgency=low + + * New upstream version, upload to experimental. + * Update to 20090225, taken from the 2.6 release branch. + * Don't build-depend on locales on armel, hppa, ia64 and mipsel; package is + currently not installable. + + -- Matthias Klose Wed, 25 Feb 2009 18:42:19 +0100 + +python2.6 (2.6.1-0ubuntu9) jaunty; urgency=low + + * Don't build pyexpat, _elementtree and _ctypes as builtin extensions, + third party packages make too many assumptions about these not built + as builtins. + + -- Matthias Klose Tue, 24 Feb 2009 16:34:27 +0100 + +python2.6 (2.6.1-0ubuntu8) jaunty; urgency=low + + * Link the shared libpython with $(MODLIBS). + + -- Matthias Klose Sun, 22 Feb 2009 16:38:49 +0100 + +python2.6 (2.6.1-0ubuntu7) jaunty; urgency=low + + * Update to 20090222, taken from the 2.6 release branch. + + -- Matthias Klose Sun, 22 Feb 2009 10:35:29 +0100 + +python2.6 (2.6.1-0ubuntu6) jaunty; urgency=low + + * Don't build the gdbm extension from the python2.6 source. + * Build the dbm extension using libdb. + * Don't build-depend on locales on sparc (currently not installable), only + needed by the testsuite. + * Update to 20090219, taken from the 2.6 release branch. + + -- Matthias Klose Thu, 19 Feb 2009 12:43:20 +0100 + +python2.6 (2.6.1-0ubuntu5) jaunty; urgency=low + + * Add build dependency on libdb-dev. + + -- Matthias Klose Mon, 16 Feb 2009 13:34:41 +0100 + +python2.6 (2.6.1-0ubuntu4) jaunty; urgency=low + + * Disable the profiled build on all architectures. + + -- Matthias Klose Mon, 16 Feb 2009 11:18:51 +0100 + +python2.6 (2.6.1-0ubuntu3) jaunty; urgency=low + + * Disable the profiled build on armel as well. + + -- Matthias Klose Sun, 15 Feb 2009 10:38:02 +0100 + +python2.6 (2.6.1-0ubuntu2) jaunty; urgency=low + + * Don't use the profiled build on amd64, lpia and sparc (GCC + PR profile/38292). + + -- Matthias Klose Sat, 14 Feb 2009 14:09:34 +0100 + +python2.6 (2.6.1-0ubuntu1) jaunty; urgency=low + + * Update to 20090211, taken from the 2.6 release branch. + + -- Matthias Klose Fri, 13 Feb 2009 12:51:00 +0100 + +python2.6 (2.6.1-0ubuntu1~ppa1) jaunty; urgency=low + + * Python 2.6.1 release. + * Update to 20081206, taken from the 2.6 release branch. + * Ensure that all extensions from the -minimal package are statically + linked into the interpreter. + * Include expat, _elementtree, datetime, bisect, _bytesio, _locale, + _fileio in -minimal to link these extensions statically. + + -- Matthias Klose Fri, 05 Dec 2008 20:43:51 +0100 + +python2.6 (2.6-0ubuntu1~ppa5) intrepid; urgency=low + + * Test build + + -- Matthias Klose Fri, 14 Nov 2008 10:14:38 +0100 + +python2.6 (2.6-0ubuntu1~ppa4) intrepid; urgency=low + + * Do not build the bsddb3 module from this source, but recommend the + python-bsddb3 package (will be a dependency after python-bsddb3 is in + the archive). + * For locally installed packages, create a directory + /usr/local/lib/python2.6/dist-packages. This is the default for + installations done with distutils and setuptools. Third party stuff + packaged within the distribution goes to /usr/lib/python2.6/dist-packages. + There is no /usr/lib/python2.6/site-packages in the file system and + on sys.path. No package within the distribution must not install + anything in this location. + * Place the gdbm extension into the python2.6 package. + * distutils: Add an option --install-layout=deb, which + - installs into $prefix/dist-packages instead of $prefix/site-packages. + - doesn't encode the python version into the egg name. + + -- Matthias Klose Sat, 25 Oct 2008 11:12:24 +0000 + +python2.6 (2.6-0ubuntu1~ppa3) intrepid; urgency=low + + * Build-depend on libdb4.6-dev, instead of libdb-dev (4.7). Test suite + hangs in the bsddb tests. + + -- Matthias Klose Wed, 22 Oct 2008 11:05:13 +0200 + +python2.6 (2.6-0ubuntu1~ppa2) intrepid; urgency=low + + * Update to 20081021, taken from the 2.6 release branch. + * Fix typos and section names in doc-base files. LP: #273344. + * Build a new package libpython2.6. + * For locally installed packages, create a directory + /usr/local/lib/python2.6/system-site-packages, which is symlinked + from /usr/lib/python2.6/site-packages. Third party stuff packaged + within the distribution goes to /usr/lib/python2.6/dist-packages. + + -- Matthias Klose Tue, 21 Oct 2008 18:09:31 +0200 + +python2.6 (2.6-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 release. + * Update to current branch 20081009. + + -- Matthias Klose Thu, 09 Oct 2008 14:28:26 +0200 + +python2.6 (2.6~b3-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta3 release. + + -- Matthias Klose Sun, 24 Aug 2008 01:34:54 +0000 + +python2.6 (2.6~b2-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta2 release. + + -- Matthias Klose Thu, 07 Aug 2008 16:45:56 +0200 + +python2.6 (2.6~b1-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta1 release. + + -- Matthias Klose Tue, 15 Jul 2008 12:57:20 +0000 + +python2.6 (2.6~a3-0ubuntu1~ppa2) hardy; urgency=low + + * Test build + + -- Matthias Klose Thu, 29 May 2008 18:08:48 +0200 + +python2.6 (2.6~a3-0ubuntu1~ppa1) hardy; urgency=low + + * Python 2.6 alpha3 release. + * Update to current trunk 20080523. + + -- Matthias Klose Thu, 22 May 2008 17:37:46 +0200 + +python2.5 (2.5.2-5) unstable; urgency=low + + * Backport new function signal.set_wakeup_fd from the trunk. + Background: http://bugzilla.gnome.org/show_bug.cgi?id=481569 + + -- Matthias Klose Wed, 30 Apr 2008 12:05:10 +0000 + +python2.5 (2.5.2-4) unstable; urgency=low + + * Update to 20080427, taken from the 2.5 release branch. + - Fix issues #2670, #2682. + * Disable running pybench on the hppa buildd (ftbfs). + * Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, + CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + * Support parallel= in DEB_BUILD_OPTIONS (see #209008). + + -- Matthias Klose Sun, 27 Apr 2008 10:40:51 +0200 + +python2.5 (2.5.2-3) unstable; urgency=medium + + * Update to 20080416, taken from the 2.5 release branch. + - Fix CVE-2008-1721, integer signedness error in the zlib extension module. + - Fix urllib2 file descriptor happens byte-at-a-time, reverting + a fix for excessively large memory allocations when calling .read() + on a socket object wrapped with makefile(). + * Disable some regression tests on some architectures: + - arm: test_compiler, test_ctypes. + - armel: test_compiler. + - hppa: test_fork1, test_wait3. + - m68k: test_bsddb3, test_compiler. + * Build-depend on libffi-dev instead of libffi4-dev. + * Fix CVE-2008-1679, integer overflows in the imageop module. + + -- Matthias Klose Wed, 16 Apr 2008 23:37:46 +0200 + +python2.5 (2.5.2-2) unstable; urgency=low + + * Use site.addsitedir() to add directories in /usr/local to sys.path. + Addresses: #469157, #469818. + + -- Matthias Klose Sat, 08 Mar 2008 16:11:23 +0100 + +python2.5 (2.5.2-1) unstable; urgency=low + + * Python 2.5.2 release. + * Merge from Ubuntu: + - Move site customization into sitecustomize.py, don't make site.py + a config file. Addresses: #309719, #413172, #457361. + - Move site.py to python2.4-minimal, remove `addbuilddir' from site.py, + which is unnecessary for installed builds. + - python2.5-dev: Recommend libc-dev instead of suggesting it. LP: #164909. + - Fix issue 961805, Tk Text.edit_modified() fails. LP: #84720. + + -- Matthias Klose Thu, 28 Feb 2008 23:18:52 +0100 + +python2.5 (2.5.1-7) unstable; urgency=low + + * Update to 20080209, taken from the 2.5 release branch. + * Build the _bsddb extension with db-4.5 again; 4.6 is seriously + broken when used with the _bsddb extension. + * Do not run pybench on arm and armel. + * python2.5: Provide python2.5-wsgiref. + * Fix a pseudo RC report with duplicated attributes in the control + file. Closes: #464307. + + -- Matthias Klose Sun, 10 Feb 2008 00:22:57 +0100 + +python2.5 (2.5.1-6) unstable; urgency=low + + * Update to 20080102, taken from the 2.5 release branch. + - Only define _BSD_SOURCE on OpenBSD systems. Closes: #455400. + * Fix handling of packages in linecache.py (Kevin Goodsell). LP: #70902. + * Bump debhelper to v5. + * Register binfmt for .py[co] files. + * Use absolute paths when byte-compiling files. Addresses: #453346. + Closes: #413566, LP: #177722. + * CVE-2007-4965, http://bugs.python.org/issue1179: + Multiple integer overflows in the imageop module in Python 2.5.1 and + earlier allow context-dependent attackers to cause a denial of service + (application crash) and possibly obtain sensitive information (memory + contents) via crafted arguments to (1) the tovideo method, and unspecified + other vectors related to (2) imageop.c, (3) rbgimgmodule.c, and other + files, which trigger heap-based buffer overflows. + Patch prepared by Stephan Herrmann. Closes: #443333, LP: #163845. + * Register info docs when doing source only uploads. LP: #174786. + * Remove deprecated value from categories in desktop file. LP: #172874. + * python2.5-dbg: Don't include the gdbm and _tkinter extensions, now provided + in separate packages. + * Provide a symlink changelog -> NEWS. Closes: #439271. + * Fix build failure on hurd, working around poll() on systems on which it + returns an error on invalid FDs. Closes: #438914. + * Configure --with-system-ffi on all architectures. Closes: #448520. + * Fix version numbers in copyright and README files (Dan O'Huiginn). + Closes: #446682. + * Move some documents from python2.5 to python2.5-dev. + + -- Matthias Klose Wed, 02 Jan 2008 22:22:19 +0100 + +python2.5 (2.5.1-5) unstable; urgency=low + + * Build the _bsddb extension with db-4.6. + + -- Matthias Klose Fri, 17 Aug 2007 00:39:35 +0200 + +python2.5 (2.5.1-4) unstable; urgency=low + + * Update to 20070813, taken from the 2.5 release branch. + * Include plat-mac/plistlib.py (plat-mac is not in sys.path by default. + Closes: #435826. + * Use emacs22 to build the documentation in info format. Closes: #434969. + * Build-depend on db-dev (>= 4.6). Closes: #434965. + + -- Matthias Klose Mon, 13 Aug 2007 22:22:44 +0200 + +python2.5 (2.5.1-3) unstable; urgency=high + + * Support mixed-endian IEEE floating point, as found in the ARM old-ABI + (Aurelien Jarno). Closes: #434905. + + -- Matthias Klose Fri, 27 Jul 2007 20:01:35 +0200 + +python2.5 (2.5.1-2) unstable; urgency=low + + * Update to 20070717, taken from the 2.5 release branch. + * Fix reference count for sys.pydebug variable. Addresses: #431393. + * Build depend on libbluetooth-dev instead of libbluetooth2-dev. + + -- Matthias Klose Tue, 17 Jul 2007 14:09:47 +0200 + +python2.5 (2.5.1-1) unstable; urgency=low + + * Python-2.5.1 release. + * Build-depend on gcc-4.1 (>= 4.1.2-4) on alpha, powerpc, s390, sparc. + * Merge from Ubuntu: + - Add debian/patches/subprocess-eintr-safety.dpatch (LP: #87292): + - Create and use wrappers around read(), write(), and os.waitpid() in the + subprocess module which retry the operation on an EINTR (which happens + if e. g. an alarm was raised while the system call was in progress). + It is incredibly hard and inconvenient to sensibly handle this in + applications, so let's fix this at the right level. + - Patch based on original proposal of Peter <85>strand + in http://python.org/sf/1068268. + - Add two test cases. + - Change the interpreter to build and install python extensions + built with the python-dbg interpreter with a different name into + the same path (by appending `_d' to the extension name). The debug build + of the interpreter tries to first load a foo_d.so or foomodule_d.so + extension, then tries again with the normal name. + - When trying to import the profile and pstats modules, don't + exit, add a hint to the exception pointing to the python-profiler + package, don't exit. + - Keep the module version in the .egg-info name, only remove the + python version. + - python2.5-dbg: Install Misc/SpecialBuilds.txt, document the + debug changes in README.debug. + * Update to 20070425, taken from the 2.5 release branch. + + -- Matthias Klose Wed, 25 Apr 2007 22:12:50 +0200 + +python2.5 (2.5-6) unstable; urgency=medium + + * webbrowser.py: Recognize other browsers: www-browser, x-www-browser, + iceweasel, iceape. + * Move pyconfig.h from the python2.5-dev into the python2.5 package; + required by builds for pure python modules without having python2.5-dev + installed (matching the functionality in python2.4). + * Move the unicodedata module into python2.5-minimal; allows byte compilation + of UTF8 encoded files. + * Do not install anymore outdated debhelper sample scripts. + * Install Misc/SpecialBuilds.txt as python2.5-dbg document. + + -- Matthias Klose Wed, 21 Feb 2007 01:17:12 +0100 + +python2.5 (2.5-5) unstable; urgency=high + + * Do not run the python benchmark on m68k. Timer problems. + Fixes FTBFS on m68k. + * Update to 20061209, taken from the 2.5 release branch. + - Fixes building the library reference in info format. + + -- Matthias Klose Sat, 9 Dec 2006 13:40:48 +0100 + +python2.5 (2.5-4) unstable; urgency=medium + + * Update to 20061203, taken from the 2.5 release branch. + - Fixes build failures on knetfreebsd and the hurd. Closes: #397000. + * Clarify README about distutils. Closes: #396394. + * Move python2.5-config to python2.5-dev. Closes: #401451. + * Cleanup build-conflicts. Addresses: #394512. + + -- Matthias Klose Sun, 3 Dec 2006 18:22:49 +0100 + +python2.5 (2.5-3.1) unstable; urgency=low + + * Non-maintainer upload. + * python2.5-minimal depends on python-minimal (>= 2.4.4-1) because it's the + first version which lists python2.5 as an unsupported runtime (ie a + runtime that is available but for which modules are not auto-compiled). + And being listed there is required for python-central to accept the + installation of python2.5-minimal. Closes: #397006 + + -- Raphael Hertzog Wed, 22 Nov 2006 15:41:06 +0100 + +python2.5 (2.5-3) unstable; urgency=medium + + * Update to 20061029 (2.4.4 was released on 20061019), taken from + the 2.5 release branch. We do not want to have regressions in + 2.5 compared to the 2.4.4 release. + * Don't run pybench on m68k, fails in the calibration loop. Closes: #391030. + * Run the installation/removal hooks. Closes: #383292, #391036. + + -- Matthias Klose Sun, 29 Oct 2006 11:35:19 +0100 + +python2.5 (2.5-2) unstable; urgency=medium + + * Update to 20061003, taken from the 2.5 release branch. + * On arm and m68k, don't run the pybench in debug mode. + * Fix building the source within exec_prefix (Alexander Wirt). + Closes: #385336. + + -- Matthias Klose Tue, 3 Oct 2006 10:08:36 +0200 + +python2.5 (2.5-1) unstable; urgency=low + + * Python 2.5 release. + * Update to 20060926, taken from the 2.5 release branch. + * Run the Python benchmark during the build, compare the results + of the static and shared builds. + * Fix invalid html in python2.5.devhelp.gz. + * Add a python2.5 console entry to the menu (hidden by default). + * python2.5: Suggest python-profiler. + + -- Matthias Klose Tue, 26 Sep 2006 02:36:11 +0200 + +python2.5 (2.5~c1-1) unstable; urgency=low + + * Python 2.5 release candidate 1. + * Update to trunk 20060818. + + -- Matthias Klose Sat, 19 Aug 2006 19:21:05 +0200 + +python2.5 (2.5~b3-1) unstable; urgency=low + + * Build the _ctypes module for m68k-linux. + + -- Matthias Klose Fri, 11 Aug 2006 18:19:19 +0000 + +python2.5 (2.5~b3-0ubuntu1) edgy; urgency=low + + * Python 2.5 beta3 release. + * Update to trunk 20060811. + * Rebuild the documentation. + * Fix value of sys.exec_prefix in the debug build. + * Do not build the library reference in info format; fails to build. + * Link the interpreter against the shared runtime library. With + gcc-4.1 the difference in the pystones benchmark dropped from about + 12% to about 6%. + * Install the statically linked version of the interpreter as + python2.5-static for now. + * Link the shared libpython with -O1. + + -- Matthias Klose Thu, 10 Aug 2006 14:04:48 +0000 + +python2.5 (2.4.3+2.5b2-3) unstable; urgency=low + + * Disable the testsuite on s390; don't care about "minimally configured" + buildd's. + + -- Matthias Klose Sun, 23 Jul 2006 11:45:03 +0200 + +python2.5 (2.4.3+2.5b2-2) unstable; urgency=low + + * Update to trunk 20060722. + * Merge idle-lib from idle-python2.5 into python2.5. + * Merge lib-tk from python-tk into python2.5. + * Tkinter.py: Suggest installation of python-tk package on failed + import of the _tkinter extension. + * Don't run the testsuite for the debug build on alpha. + * Don't run the test_compiler test on m68k. Just takes too long. + * Disable building ctypes on m68k (requires support for closures). + + -- Matthias Klose Sat, 22 Jul 2006 22:26:42 +0200 + +python2.5 (2.4.3+2.5b2-1) unstable; urgency=low + + * Python 2.5 beta2 release. + * Update to trunk 20060716. + * When built on a buildd, do not run the following test which try to + access the network: test_codecmaps_cn, test_codecmaps_hk, test_codecmaps_jp, + test_codecmaps_kr, test_codecmaps_tw, test_normalization. + * When built on a buildd, do not run tests requiring missing write permissions: + test_ossaudiodev. + + -- Matthias Klose Sun, 16 Jul 2006 02:53:50 +0000 + +python2.5 (2.4.3+2.5b2-0ubuntu1) edgy; urgency=low + + * Python 2.5 beta2 release. + + -- Matthias Klose Thu, 13 Jul 2006 17:16:52 +0000 + +python2.5 (2.4.3+2.5b1-1ubuntu2) edgy; urgency=low + + * Fix python-dev dependencies. + * Update to trunk 20060709. + + -- Matthias Klose Sun, 9 Jul 2006 18:50:32 +0200 + +python2.5 (2.4.3+2.5b1-1ubuntu1) edgy; urgency=low + + * Python 2.5 beta1 release. + * Update to trunk 20060623. + * Merge changes from the python2.4 packages. + * python2.5-minimal: Add _struct. + + -- Matthias Klose Fri, 23 Jun 2006 16:04:46 +0200 + +python2.5 (2.4.3+2.5a1-1) experimental; urgency=low + + * Update to trunk 20060409. + * Run testsuite for debug build as well. + * Build-depend on gcc-4.1. + + -- Matthias Klose Sun, 9 Apr 2006 22:27:05 +0200 + +python2.5 (2.4.3+2.5a1-0ubuntu1) dapper; urgency=low + + * Python 2.5 alpha1 release. + * Drop integrated patches. + * Add build dependencies on libsqlite3-dev and libffi4-dev. + * Add (build-)dependency on mime-support, libgpmg1 (test suite). + * Build using the system FFI. + * python2.5 provides python2.5-ctypes and python2.5-pysqlite2, + python2.5-elementtree. + * Move hashlib.py to python-minimal. + * Lib/hotshot/pstats.py: Error out on missing profile/pstats modules. + + -- Matthias Klose Wed, 5 Apr 2006 14:56:15 +0200 + +python2.4 (2.4.3-8ubuntu1) edgy; urgency=low + + * Resynchronize with Debian unstable. Remaining changes: + - Apply langpack-gettext patch. + - diff.gz contains pregenerated html and info docs. + - Build the -doc package from this source. + + -- Matthias Klose Thu, 22 Jun 2006 18:39:57 +0200 + +python2.4 (2.4.3-8) unstable; urgency=low + + * Remove python2.4's dependency on python-central. On installation of + the runtime, call hooks /usr/share/python/runtime.d/*.rtinstall. + On removal, call hooks /usr/share/python/runtime.d/*.rtremove. + Addresses: #372658. + * Call the rtinstall hooks only, if it's a new installation, or the first + installation using the hooks. Adresses: #373677. + + -- Matthias Klose Sun, 18 Jun 2006 00:56:13 +0200 + +python2.4 (2.4.3-7) unstable; urgency=medium + + * Reupload, depend on python-central (>= 0.4.15). + * Add build-conflict on python-xml. + + -- Matthias Klose Wed, 14 Jun 2006 18:56:57 +0200 + +python2.4 (2.4.3-6) medium; urgency=low + + * idle-python2.4: Remove the old postinst and prerm scripts. + * Name the runtime correctly in python2.4-minimal's installation + scripts. + + -- Matthias Klose Mon, 12 Jun 2006 17:39:56 +0000 + +python2.4 (2.4.3-5) unstable; urgency=low + + * python2.4-prerm: Handle the case, when python-central is not installed. + * idle-python2.4: Depend on python-tk instead of python2.4-tk. + + -- Matthias Klose Fri, 9 Jun 2006 05:17:17 +0200 + +python2.4 (2.4.3-4) unstable; urgency=low + + * SVN update up to 2006-06-07 + * Use python-central. + * Don't build the -tk and -gdbm packages from this source; now built + from the python-stdlib-extensions source. + * Remove leftover build dependency on libgmp3-dev. + * Do not build-depend on libbluetooth1-dev and libgpmg1-dev on + hurd-i386, kfreebsd-i386, kfreebsd-amd64. Closes: #365830. + * Do not run the test_tcl test; hangs for unknown reasons on at least + the following buildds: vivaldi(m68k), goedel (alpha), mayer (mipsel). + And no virtual package to file bug reports for the buildds ... + Closes: #364419. + * Move the Makefile from python2.4-dev to python2.4. Closes: #366473. + * Fix typo in pdb(1). Closes: #365772. + * New autoconf likes the mandir in /usr/share instead of /usr; work + with both locations. Closes: #367618. + + -- Matthias Klose Wed, 7 Jun 2006 21:37:20 +0200 + +python2.4 (2.4.3-3) unstable; urgency=low + + * SVN update up to 2006-04-21 + * Update locale aliases from /usr/share/X11/locale/locale.alias. + * Start idle with option -n from the desktop menu, so that the program + can be started in parallel. + * Testsuite related changes only: + - Add build dependencies mime-support, libgpmg1 (needed by test cases). + - Run the testsuite with bsddb, audio and curses resources enabled. + - Re-run the failed tests in verbose mode. + - Run the test suite for the debug build as well. + - Build depend on netbase, needed by test_socketmodule. + - Build depend on libgpmg1, needed by test_curses. + - On the buildds do not run the tests needing the network resource. + * Update python logo. + * Check for the availability of the profile and pstats modules when + importing hotshot.pstats. Closes: #334067. + * Don't build the -doc package from the python2.4 source. + * Set OPT in the installed Makefile to -O2. + + -- Matthias Klose Fri, 21 Apr 2006 19:58:43 +0200 + +python2.4 (2.4.3-2) unstable; urgency=low + + * Add (build-)dependency on mime-support. + + -- Matthias Klose Tue, 4 Apr 2006 22:21:41 +0200 + +python2.4 (2.4.3-1) unstable; urgency=low + + * Python 2.4.3 release. + + -- Matthias Klose Thu, 30 Mar 2006 23:42:37 +0200 + +python2.4 (2.4.3-0ubuntu1) dapper; urgency=low + + * Python 2.4.3 release. + - Fixed a bug that the gb18030 codec raises RuntimeError on encoding + surrogate pair area on UCS4 build. Ubuntu: #29289. + + -- Matthias Klose Thu, 30 Mar 2006 10:57:32 +0200 + +python2.4 (2.4.2+2.4.3c1-0ubuntu1) dapper; urgency=low + + * SVN update up to 2006-03-25 (2.4.3 candidate 1). + - Regenerate the documentation. + + -- Matthias Klose Mon, 27 Mar 2006 12:03:05 +0000 + +python2.4 (2.4.2-1ubuntu3) dapper; urgency=low + + * SVN update up to 2006-03-04 + - Regenerate the documentation. + - map.mmap(-1, size, ...) can return anonymous memory again on Unix. + Ubuntu #26201. + * Build-depend on libncursesw5-dev, ncursesw5 is preferred for linking. + Provides UTF-8 compliant curses bindings. + * Fix difflib where certain patterns of differences were making difflib + touch the recursion limit. + + -- Matthias Klose Sat, 4 Mar 2006 21:38:24 +0000 + +python2.4 (2.4.2-1ubuntu2) dapper; urgency=low + + * SVN update up to 2006-01-17 + - pwd is now a builtin module, remove it from python-minimal. + - Regenerate the documentation. + * python2.4-tk: Suggest tix instead of tix8.1. + * Move config/Makefile from the -dev package into the runtime package + to be able to use the bdist_wininst distutils command. Closes: #348335. + + -- Matthias Klose Tue, 17 Jan 2006 11:02:24 +0000 + +python2.4 (2.4.2-1ubuntu1) dapper; urgency=low + + * Temporarily remove build dependency on lsb-release. + + -- Matthias Klose Sun, 20 Nov 2005 17:40:18 +0100 + +python2.4 (2.4.2-1build1) dapper; urgency=low + + * Rebuild (openssl-0.9.8). + + -- Matthias Klose Sun, 20 Nov 2005 15:27:24 +0000 + +python2.4 (2.4.2-1) unstable; urgency=low + + * Python 2.4.2 release. + + -- Matthias Klose Thu, 29 Sep 2005 01:49:28 +0200 + +python2.4 (2.4.1+2.4.2rc1-1) unstable; urgency=low + + * Python 2.4.2 release candidate 1. + * Fix "Fatal Python error" from cStringIO's writelines. + Patch by Andrew Bennetts. + + -- Matthias Klose Thu, 22 Sep 2005 10:33:22 +0200 + +python2.4 (2.4.1-5) unstable; urgency=low + + * CVS update up to 2005-09-14 + - Regenerate the html and info docs. + * Add some more locale aliases. + * Fix substitution pf python version in README.python2.4-minimal. + Closes: #327487. + * On m68k, build using -O2 (closes: #326903). + * On Debian, don't configure --with-fpectl, which stopped working with + glibc-2.3.5. + + -- Matthias Klose Wed, 14 Sep 2005 17:32:56 +0200 + +python2.4 (2.4.1-4) unstable; urgency=low + + * CVS update up to 2005-09-04 + - teTeX 3.0 related fixes (closes: #322407). + - Regenerate the html and info docs. + * Add entry for IDLE in the Gnome menus. + * Don't build-depend on libbluetooth-dev on the Hurd (closes: #307037). + * Reenable the cthreads patch for the Hurd (closes: #307052). + + -- Matthias Klose Sun, 4 Sep 2005 18:31:42 +0200 + +python2.4 (2.4.1-3) unstable; urgency=low + + * Synchronise with Ubuntu: + - Build a python2.4-minimal package. + + -- Matthias Klose Tue, 12 Jul 2005 00:23:10 +0000 + +python2.4 (2.4.1-2ubuntu3) breezy; urgency=low + + * CVS update up to 2005-07-07 + * Regenerate the documentation. + + -- Matthias Klose Thu, 7 Jul 2005 09:21:28 +0200 + +python2.4 (2.4.1-2ubuntu2) breezy; urgency=low + + * CVS update up to 2005-06-15 + * Regenerate the documentation. + * Synchronize with Debian. Ubuntu 10485. + * idle-python2.4 enhances python2.4. Ubuntu 11562. + * README.Debian: Fix reference to the doc directory (closes: #311677). + + -- Matthias Klose Wed, 15 Jun 2005 08:56:57 +0200 + +python2.4 (2.4.1-2ubuntu1) breezy; urgency=low + + * Update build dependencies: + db4.2-dev -> db4.3-dev, + libreadline4-dev -> libreadline5-dev. + * python2.4-dev: Add missing templates to generate HTML docs. Ubuntu 11531. + + -- Matthias Klose Sun, 29 May 2005 00:01:05 +0200 + +python2.4 (2.4.1-2) unstable; urgency=low + + * Add the debug symbols for the python2.4, python2.4-gdbm + and python2.4-tk packages to the python2.4-dbg package. + * Add gdbinit example to doc directory. + + -- Matthias Klose Thu, 5 May 2005 11:12:32 +0200 + +python2.4 (2.4.1-1ubuntu2) breezy; urgency=low + + * Add the debug symbols for the python2.4, python2.4-minimal, python2.4-gdbm + and python2.4-tk packages to the python2.4-dbg package. Ubuntu 10261, + * Add gdbinit example to doc directory. + * For os.utime, use utimes(2), correctly working with glibc-2.3.5. + Ubuntu 10294. + + -- Matthias Klose Thu, 5 May 2005 09:06:07 +0200 + +python2.4 (2.4.1-1ubuntu1) breezy; urgency=low + + * Reupload as 2.4.1-1ubuntu1. + + -- Matthias Klose Thu, 14 Apr 2005 10:46:32 +0200 + +python2.4 (2.4.1-1) unstable; urgency=low + + * Python 2.4.1 release. + * Fix noise in python-doc installation/removal. + * New Python section for the info docs. + + -- Matthias Klose Wed, 30 Mar 2005 19:42:03 +0200 + +python2.4 (2.4.1-0) hoary; urgency=low + + * Python 2.4.1 release. + * Fix noise in python-doc installation/removal. + * New Python section for the info docs. + + -- Matthias Klose Wed, 30 Mar 2005 16:35:34 +0200 + +python2.4 (2.4+2.4.1rc2-2) unstable; urgency=low + + * Add the valgrind support file to /etc/python2.4 + * Build the -dbg package with -DPy_USING_MEMORY_DEBUGGER. + * Lib/locale.py: + - correctly parse LANGUAGE as a colon separated list of languages. + - prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE to get the correct + encoding. + - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding + for glibc. + * Fix two typos in python(1). Addresses: #300124. + + -- Matthias Klose Sat, 19 Mar 2005 21:50:14 +0100 + +python2.4 (2.4+2.4.1rc2-1) unstable; urgency=low + + * Python 2.4.1 release candidate 2. + * Build-depend on libbluetooth1-dev. + + -- Matthias Klose Sat, 19 Mar 2005 00:57:14 +0100 + +python2.4 (2.4dfsg-2) unstable; urgency=low + + * CVS update up to 2005-03-03 + + -- Matthias Klose Thu, 3 Mar 2005 22:22:16 +0100 + +python2.4 (2.4dfsg-1ubuntu4) hoary; urgency=medium + + * Move exception finalisation later in the shutdown process - this + fixes the crash seen in bug #1165761, taken from CVS. + * codecs.StreamReader: Reset codec when seeking. Ubuntu #6972. + * Apply fix for SF1124295, fixing an obscure bit of Zope's security machinery. + * distutils: Don't add standard library dirs to library_dirs + and runtime_library_dirs. On amd64, runtime paths pointing to /usr/lib64 + aren't recognized by dpkg-shlibdeps, and the packages containing these + libraries aren't added to ${shlibs:Depends}. + * Lib/locale.py: + - correctly parse LANGUAGE as a colon separated list of languages. + - prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE to get the correct + encoding. + - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding + for glibc. + * os.py: Avoid using items() in environ.update(). Fixes #1124513. + * Python/pythonrun.c: + * Build depend on locales, generate the locales needed for the + testsuite. + * Add build dependency on libbluetooth1-dev, adding some bluetooth + functionality to the socket module. + * Lib/test/test_sundry.py: Don't fail on import of profile & pstats, + which are separated out to the python-profiler package. + * Fix typos in manpage. + + -- Matthias Klose Tue, 29 Mar 2005 13:35:53 +0200 + + +python2.4 (2.4dfsg-1ubuntu3) hoary; urgency=low + + * debian/patches/langpack-gettext.dpatch: + - langpack support for python-gettext added + + -- Michael Vogt Tue, 1 Mar 2005 13:13:36 +0100 + +python2.4 (2.4dfsg-1ubuntu2) hoary; urgency=low + + * Revert 'essential' status on python2.4-minimal. This status on + on python-minimal is sufficient (Ubuntu #6392). + + -- Matthias Klose Wed, 9 Feb 2005 23:09:42 +0100 + +python2.4 (2.4dfsg-1ubuntu1) hoary; urgency=low + + * Resyncronise with Debian. + * Mark the python2.4-minimal package as 'essential'. + + -- Matthias Klose Wed, 9 Feb 2005 13:31:09 +0100 + +python2.4 (2.4dfsg-1) unstable; urgency=medium + + * Add licenses and acknowledgements for incorporated software in the + debian/copyright file (addresses: #293932). + * Replace md5 implementation with one having a DFSG conforming license. + * Remove the profile.py and pstats.py modules from the source package, + not having a DFSG conforming license. The modules can be found in + the python2.x-profile package in the non-free section. + Addresses: #293932. + * Add missing norwegian locales (Tollef Fog Heen). + * CVS updates of the release24-maint branch upto 2005-02-08 (date of + the Python 2.3.5 release). + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-7ubuntu1) hoary; urgency=low + + * Fix the name of the python-dbg man page. + * Resyncronise with Debian. + * Move more modules to -minimal (new code in copy.py requires these): + dis, inspect, opcode, token, tokenize. + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-7) unstable; urgency=medium + + * Add licenses and acknowledgements for incorporated software in the + debian/copyright file (addresses: #293932). + * Replace md5 implementation with one having a DFSG conforming license. + * Add missing norwegian locales (Tollef Fog Heen). + * CVS updates of the release24-maint branch upto 2005-02-08 (date of + the Python 2.3.5 release). + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-6) unstable; urgency=low + + * Build a python2.4-dbg package using --with-pydebug. Add a debug + directory /lib-dynload/debug to sys.path instead of + /lib-dynload und install the extension modules of the + debug build in this directory. + Change the module load path to load extension modules from other + site-packages/debug directories (for further details see the + README in the python2.4-dbg package). Closes: #5415. + * Apply the pydebug-path patch. The package was already built in -5. + + -- Matthias Klose Fri, 4 Feb 2005 22:15:13 +0100 + +python2.4 (2.4-5) unstable; urgency=high + + * Fix a flaw in SimpleXMLRPCServerthat can affect any XML-RPC servers. + This affects any programs have been written that allow remote + untrusted users to do unrestricted traversal and can allow them to + access or change function internals using the im_* and func_* attributes. + References: CAN-2005-0089. + * CVS updates of the release24-maint branch upto 2005-02-04. + + -- Matthias Klose Fri, 4 Feb 2005 08:12:10 +0100 + +python2.4 (2.4-4) unstable; urgency=medium + + * Update debian/copyright to the 2.4 license text (closes: #290898). + * Remove /usr/bin/smtpd.py (closes: #291049). + + -- Matthias Klose Mon, 17 Jan 2005 23:54:37 +0100 + +python2.4 (2.4-3ubuntu6) hoary; urgency=low + + * Use old-style dpatches instead of dpatch-run. + + -- Tollef Fog Heen Mon, 7 Feb 2005 15:58:05 +0100 + +python2.4 (2.4-3ubuntu5) hoary; urgency=low + + * Actually apply the patch as well (add to list of patches in + debian/rules) + + -- Tollef Fog Heen Sun, 6 Feb 2005 15:12:58 +0100 + +python2.4 (2.4-3ubuntu4) hoary; urgency=low + + * Add nb_NO and nn_NO locales to Lib/locale.py + + -- Tollef Fog Heen Sun, 6 Feb 2005 14:33:05 +0100 + +python2.4 (2.4-3ubuntu3) hoary; urgency=low + + * Fix a flaw in SimpleXMLRPCServerthat can affect any XML-RPC servers. + This affects any programs have been written that allow remote + untrusted users to do unrestricted traversal and can allow them to + access or change function internals using the im_* and func_* attributes. + References: CAN-2005-0089. + + -- Matthias Klose Wed, 2 Feb 2005 09:08:20 +0000 + +python2.4 (2.4-3ubuntu2) hoary; urgency=low + + * Build a python2.4-dbg package using --with-pydebug. Add a debug + directory /lib-dynload/debug to sys.path instead of + /lib-dynload und install the extension modules of the + debug build in this directory. + Change the module load path to load extension modules from other + site-packages/debug directories (for further details see the + README in the python2.4-dbg package). Closes: #5415. + * Update debian/copyright to the 2.4 license text (closes: #290898). + * Add operator and copy to the -minimal package. + + -- Matthias Klose Mon, 17 Jan 2005 23:19:47 +0100 + +python2.4 (2.4-3ubuntu1) hoary; urgency=low + + * Resynchronise with Debian. + * python2.4: Depend on the very same version of python2.4-minimal. + * Docment, that time.strptime currently cannot be used, if the + python-minimal package is installed without the python package. + + -- Matthias Klose Sun, 9 Jan 2005 19:35:48 +0100 + +python2.4 (2.4-3) unstable; urgency=medium + + * Build the fpectl module. + * Updated to CVS release24-maint 20050107. + + -- Matthias Klose Sat, 8 Jan 2005 19:05:21 +0100 + +python2.4 (2.4-2ubuntu5) hoary; urgency=low + + * Updated to CVS release24-maint 20050102. + * python-minimal: + - os.py: Use dict instead of UserDict, remove UserDict from -minimal. + - add pickle, threading, needed for subprocess module. + - optparse.py: conditionally import gettext, if not available, + define _ as the identity function. Patch taken from the trunk. + Avoids import of _locale, locale, gettext, copy, repr, itertools, + collections, token, tokenize. + - Add a build check to make sure that the minimal module list is + closed under dependency. + * Fix lintian warnings. + + -- Matthias Klose Sun, 2 Jan 2005 22:00:14 +0100 + +python2.4 (2.4-2ubuntu4) hoary; urgency=low + + * Add UserDict.py to the -minimal package, since os.py needs it. + + -- Colin Watson Thu, 30 Dec 2004 20:41:28 +0000 + +python2.4 (2.4-2ubuntu3) hoary; urgency=low + + * Add os.py and traceback.py to the -minimal package, get the list + of modules from the README. + + -- Matthias Klose Mon, 27 Dec 2004 08:20:45 +0100 + +python2.4 (2.4-2ubuntu2) hoary; urgency=low + + * Add compileall.py and py_compile.py to the -minimal package, not + just to the README ... + + -- Matthias Klose Sat, 25 Dec 2004 22:24:56 +0100 + +python2.4 (2.4-2ubuntu1) hoary; urgency=low + + * Separate the interpreter and a minimal subset of modules into + a python2.4-minimal package. See the README.Debian.gz in this + package. + * Move site.py to python2.4-minimal as well. + * Add documentation files for devhelp. + + -- Matthias Klose Sun, 19 Dec 2004 22:47:32 +0100 + +python2.4 (2.4-2) unstable; urgency=medium + + * Updated patch for #283108. Thanks to Jim Meyering. + + -- Matthias Klose Fri, 3 Dec 2004 17:00:16 +0100 + +python2.4 (2.4-1) unstable; urgency=low + + * Final 2.4 release. + * Flush stdout/stderr if closed (SF #1074011). + + -- Matthias Klose Wed, 1 Dec 2004 07:54:34 +0100 + +python2.4 (2.3.97-2) unstable; urgency=low + + * Don't run test_tcl, hanging on the buildds. + + -- Matthias Klose Fri, 19 Nov 2004 23:48:42 +0100 + +python2.4 (2.3.97-1) unstable; urgency=low + + * Python 2.4 Release Candidate 1. + + -- Matthias Klose Fri, 19 Nov 2004 21:27:02 +0100 + +python2.4 (2.3.96-1) experimental; urgency=low + + * Updated to CVS release24-maint 20041113. + * Build the docs in info format again. + + -- Matthias Klose Sat, 13 Nov 2004 21:21:10 +0100 + +python2.4 (2.3.95-2) experimental; urgency=low + + * Move distutils package from the python2.4-dev into the python2.4 + package. + + -- Matthias Klose Thu, 11 Nov 2004 22:56:14 +0100 + +python2.4 (2.3.95-1) experimental; urgency=low + + * Python 2.4 beta2 release. + + -- Matthias Klose Thu, 4 Nov 2004 23:43:47 +0100 + +python2.4 (2.3.94-1) experimental; urgency=low + + * Python 2.4 beta1 release. + + -- Matthias Klose Sat, 16 Oct 2004 08:33:57 +0200 + +python2.4 (2.3.93-1) experimental; urgency=low + + * Python 2.4 alpha3 release. + + -- Matthias Klose Fri, 3 Sep 2004 21:53:47 +0200 + +python2.4 (2.3.92-1) experimental; urgency=low + + * Python 2.4 alpha2 release. + + -- Matthias Klose Thu, 5 Aug 2004 23:53:18 +0200 + +python2.4 (2.3.91-1) experimental; urgency=low + + * Python 2.4 alpha1 release. + Highlights: http://www.python.org/2.4/highlights.html + + -- Matthias Klose Fri, 9 Jul 2004 17:38:54 +0200 + +python2.4 (2.3.90-1) experimental; urgency=low + + * Package HEAD branch (pre alpha ..). + + -- Matthias Klose Mon, 14 Jun 2004 23:19:57 +0200 + +python2.3 (2.3.4-1) unstable; urgency=medium + + * Final Python 2.3.4 Release. + * In the API docs, fix signature of PyModule_AddIntConstant (closes: #250826). + * locale.getdefaultlocale: don't fail with empty environment variables. + Closes: #249816. + * Include distutils/command/wininst.exe in -dev package (closes: #249006). + * Disable cthreads on the Hurd (Michael Banck). Closes: #247211. + * Add a note to pygettext(1), that this program is deprecated in favour + of xgettext, which now includes support for Python as well. + Closes: #246332. + + -- Matthias Klose Fri, 28 May 2004 22:59:42 +0200 + +python2.3 (2.3.3.91-1) unstable; urgency=low + + * Python 2.3.4 Release Candidate 1. + * Do not use the default namespace for attributes. Patch taken from the + 2.3 maintenance branch. + The xmllib module is obsolete. Use xml.sax instead. + * http://python.org/sf/945642 - fix nonblocking i/o with ssl socket. + + -- Matthias Klose Thu, 13 May 2004 21:24:52 +0200 + +python2.3 (2.3.3-7) unstable; urgency=low + + * Add a workaround for GNU libc nl_langinfo()'s returning NULL. + Closes: #239237. + Patch taken from 2.3 maintenance branch. + * threading.py: Remove calls to currentThread() in _Condition methods that + were side-effect. Side-effects were deemed unnecessary and were causing + problems at shutdown time when threads were catching exceptions at start + time and then triggering exceptions trying to call currentThread() after + gc'ed. Masked the initial exception which was deemed bad. + Closes: #195812. + * Properly support normalization of empty unicode strings. Closes: #239986. + Patch taken from 2.3 maintenance branch. + * README.maintainers: Add section where to find the documentation tools. + * Fix crash in pyexpat module (closes: #229281). + * For the Hurd, set the interpreters recursion limit to 930. + * Do not try to byte-compile the test files on installation; this + currently breaks the Hurd install. + + -- Matthias Klose Sat, 1 May 2004 07:50:46 +0200 + +python2.3 (2.3.3-6) unstable; urgency=low + + * Don't build the unversioned python{,-*} packages anymore. Now + built from the python-defaults package. + * Update to the proposed python-policy: byte-compile using -E. + * Remove python-elisp's dependency on emacs20 (closes: #232785). + * Don't build python-elisp from the python2.3 source anymore, + get it from python-mode.sf.net as a separate source package. + * python2.3-dev suggests libc-dev (closes: #231091). + * get LDSHARED and CCSHARED (like, CC, CXX, CPP, CFLAGS) from + the environment + * Set CXX in installed config/Makefile (closes: #230273). + + -- Matthias Klose Tue, 24 Feb 2004 07:07:51 +0100 + +python2.3 (2.3.3-5) unstable; urgency=low + + * Build-depend on libdb4.2-dev, instead of libdb4.1-dev. According + to the docs the file format is compatible. + + -- Matthias Klose Mon, 12 Jan 2004 10:37:45 +0100 + +python2.3 (2.3.3-4) unstable; urgency=low + + * Fix broken _bsddb module. setup.py picked up the wrong library. + + -- Matthias Klose Sun, 4 Jan 2004 11:30:00 +0100 + +python2.3 (2.3.3-3) unstable; urgency=low + + * Fix typo in patch (closes: #224797, #226064). + + -- Matthias Klose Sun, 4 Jan 2004 09:23:21 +0100 + +python2.3 (2.3.3-2) unstable; urgency=medium + + * Lib/email/Charset: use locale unaware function to lower case of locale + name (closes: #224797). + * Update python-mode to version from python-mode.sf.net. Fixes highlighting + problems (closes: #223520). + * Backport from mainline: Add IPV6_ socket options from RFCs 3493 and 3542. + + -- Matthias Klose Fri, 2 Jan 2004 14:03:26 +0100 + +python2.3 (2.3.3-1) unstable; urgency=low + + * New upstream release. + * Copy the templates, tools and scripts from the Doc dir in the source + to /usr/share/lib/python2.3/doc in the python2.3-dev package. Needed + for packages building documentation like python does (closes: #207337). + + -- Matthias Klose Fri, 19 Dec 2003 10:57:39 +0100 + +python2.3 (2.3.2.91-1) unstable; urgency=low + + * New upstream version (2.3.3 release candidate). + * Update python-mode.el (closes: #158811, #159630). + Closing unreproducible report (closes: #159628). + + -- Matthias Klose Sat, 6 Dec 2003 14:41:14 +0100 + +python2.3 (2.3.2-7) unstable; urgency=low + + * Put the conflict in the correct direction. python2.3 (2.3.2-6) doesn't + conflict with python (<= 2.3.2-5) but python (2.3.2-6) conflicts with + python2.3 (<= 2.3.2-5) (thanks to Brian May). Really closes #221791. + + -- Matthias Klose Fri, 21 Nov 2003 00:20:02 +0100 + +python2.3 (2.3.2-6) unstable; urgency=low + + * Add conflicts with older python{,2.3} packages to fix overwrite + errors (closes: #221791). + + -- Matthias Klose Thu, 20 Nov 2003 07:24:36 +0100 + +python2.3 (2.3.2-5) unstable; urgency=low + + * Updated to CVS release23-maint 20031119. + * Re-upgrade the dependency of python2.3 on python (>= 2.3) to + a dependency (closes: #221523). + + -- Matthias Klose Wed, 19 Nov 2003 00:30:27 +0100 + +python2.3 (2.3.2-4) unstable; urgency=low + + * Don't build-depend on latex2html (moved to non-free), but keep + the prebuilt docs in debian/patches (closes: #221347). + * Fix typos in the library reference (closes: #220510, #220954). + * Fix typo in python-elisp's autoloading code (closes: #220308). + * Update proposed python policy: private modules can be installed + into /usr/lib/ (arch dependent) and into /usr/share/ + (arch independent). + + -- Matthias Klose Tue, 18 Nov 2003 00:41:39 +0100 + +python2.3 (2.3.2-3) unstable; urgency=low + + * Downgrade the dependency of python2.3 on python (>= 2.3) to + a recommendation. + * Fix path to interpreter in binfmt file. + * Fix segfault in unicodedata module (closes: #218697). + * Adjust python-elisp autoload code (closes: #219821). + + -- Matthias Klose Sun, 9 Nov 2003 19:43:37 +0100 + +python2.3 (2.3.2-2) unstable; urgency=medium + + * Fix broken doc link (closes: #214217). + * Disable wrongly detected large file support for GNU/Hurd. + * Really fix the FTBFS for the binary-indep target (closes: #214303). + + -- Matthias Klose Mon, 6 Oct 2003 07:54:58 +0200 + +python2.3 (2.3.2-1) unstable; urgency=low + + * New upstream version. + * Fix a FTBFS for the binary-indep target. + + -- Matthias Klose Sat, 4 Oct 2003 10:20:15 +0200 + +python2.3 (2.3.1-3) unstable; urgency=low + + * Fix names of codec packages in recommends. + * On alpha compile using -mieee (see #212912). + + -- Matthias Klose Sun, 28 Sep 2003 10:48:12 +0200 + +python2.3 (2.3.1-2) unstable; urgency=low + + * Update python policy draft (closes: #128911, #163785). + * Re-add os.fsync function (closes: #212672). + * Let python2.3-doc conflict with older python2.3 versions (closes: #211882). + * Add recommends for pythonX.Y-japanese-codecs, pythonX.Y-iconvcodec, + pythonX.Y-cjkcodecs, pythonX.Y-korean-codecs (closes: #207161). + * Generate binfmt file (closes: #208005). + * Add IPPROTO_IPV6 option to the socketmodule (closes: #206569). + * Bugs reported against python2.2 and fixed in python2.3: + - Crashes in idle (closes: #186887, #200084). + + -- Matthias Klose Sat, 27 Sep 2003 11:21:47 +0200 + +python2.3 (2.3.1-1) unstable; urgency=low + + * New upstream version (bug fix release). + + -- Matthias Klose Wed, 24 Sep 2003 11:27:43 +0200 + +python2.3 (2.3-4) unstable; urgency=high + + * Disable check for utimes function, which is broken in glibc-2.3.2. + Packages using distutils had '1970/01/01-01:00:01' timestamps in files. + * Bugs fixed by making python2.3 the default python version: + - Canvas.scan_dragto() takes a 3rd optional parmeter "gain". + Closes: #158168. + - New command line parsing module (closes: #38628). + - compileall.py allows compiling single files (closes: #139971). + * Bugs reported for 2.2 and fixed in 2.3: + - Idle does save files with ASCII characters (closes: #179313). + - imaplib support for prefix-quoted strings (closes: #150485). + - posixpath includes getctime (closes: #173827). + - pydoc has support for keywords (closes: #186775). + * Bugs reported for 2.1 and fixed in 2.3: + - Fix handling of "#anchor" URLs in urlparse (closes: #147844). + - Fix readline if C stdin is not a tty, even if sys.stdin is. + Closes: #131810. + * Updated to CVS release23-maint 20030810 (fixing memory leaks in + array and socket modules). + * pydoc's usage output uses the basename of the script. + * Don't explicitely remove /etc/python2.3 on purge (closes: #202864). + * python conflicts with python-xmlbase (closes: #204773). + * Add dependency python (>= 2.3) to python2.3, so make sure the + unversioned names can be used. + + -- Matthias Klose Sun, 10 Aug 2003 09:27:52 +0200 + +python2.3 (2.3-3) unstable; urgency=medium + + * Fix shlibs file. + + -- Matthias Klose Fri, 8 Aug 2003 08:45:12 +0200 + +python2.3 (2.3-2) unstable; urgency=medium + + * Make python2.3 the default python version. + + -- Matthias Klose Tue, 5 Aug 2003 22:13:22 +0200 + +python2.3 (2.3-1) unstable; urgency=low + + * Python 2.3 final release. + + -- Matthias Klose Wed, 30 Jul 2003 08:12:28 +0200 + +python2.3 (2.2.107-1rc2) unstable; urgency=medium + + * Python 2.3 release candidate 2. + * Don't compress .txt files referenced by the html docs (closes: #200298). + * Include the email/_compat* files (closes: #200349). + + -- Matthias Klose Fri, 25 Jul 2003 07:08:09 +0200 + +python2.3 (2.2.106-2beta2) unstable; urgency=medium + + * Python 2.3 beta2 release, updated to CVS 20030704. + - Fixes AssertionError in httplib (closed: #192452). + - Fixes uncaught division by zero in difflib.py (closed: #199287). + * Detect presence of setgroups(2) at configure time (closes: #199839). + * Use default gcc on arm as well. + + -- Matthias Klose Sat, 5 Jul 2003 10:21:33 +0200 + +python2.3 (2.2.105-1beta2) unstable; urgency=low + + * Python 2.3 beta2 release. + - Includes merged idle fork. + - Fixed socket.setdefaulttimeout(). Closes: #189380. + - socket.ssl works with _socketobj. Closes: #196082. + * Do not link libtix to the _tkinter module. It's loaded via + 'package require tix' at runtime. python2.3-tkinter now + suggests tix8.1 instead. + * On arm, use gcc-3.2 to build. + * Add -fno-strict-aliasing rules to OPT to avoid warnings + "dereferencing type-punned pointer will break strict-aliasing rules", + when building with gcc-3.3. + + -- Matthias Klose Mon, 30 Jun 2003 00:19:32 +0200 + +python2.3 (2.2.104-1beta1.1) unstable; urgency=low + + * Non-maintainer upload with maintainer consent. + * debian/control (Build-Depends): s/libgdbmg1-dev/libgdbm-dev/. + + -- James Troup Wed, 4 Jun 2003 02:24:27 +0100 + +python2.3 (2.2.104-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release, updated to CVS 20030514. + - build the current documentation. + * Reenable Tix support. + + -- Matthias Klose Wed, 14 May 2003 07:38:57 +0200 + +python2.3 (2.2.103-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release, updated to CVS 20030506. + - updated due to build problems on mips/mipsel. + - keep the 2.3b1 documentation (doc build problems with cvs). + + -- Matthias Klose Wed, 7 May 2003 06:26:39 +0200 + +python2.3 (2.2.102-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release. + + -- Matthias Klose Sat, 3 May 2003 22:45:16 +0200 + +python2.3 (2.2.101-1exp1) unstable; urgency=medium + + * Python 2.3 alpha2 release, updated to CVS 20030321. + * Tkinter: Catch exceptions thrown for undefined substitutions in + events (needed for tk 8.4.2). + + -- Matthias Klose Fri, 21 Mar 2003 21:32:14 +0100 + +python2.3 (2.2.100-1exp1) unstable; urgency=low + + * Python 2.3 alpha2 release, updated to CVS 20030221. + + -- Matthias Klose Fri, 21 Feb 2003 19:37:17 +0100 + +python2.3 (2.2.99-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030123. + - should fix the testsuite (and package build) failure on alpha. + * Remove build dependency on libexpat1-dev. Merge the python2.3-xmlbase + package into python2.3 (closes: #177739). + + -- Matthias Klose Thu, 23 Jan 2003 22:48:12 +0100 + +python2.3 (2.2.98-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030117. + * Build using libdb4.1. + + -- Matthias Klose Sat, 18 Jan 2003 00:14:01 +0100 + +python2.3 (2.2.97-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030109. + * Build-Depend on g++ (>= 3:3.2). + * Python package maintainers: please wait uploading python dependent + packages until python2.2 and python2.1 are compiled using gcc-3.2. + + -- Matthias Klose Thu, 9 Jan 2003 23:56:42 +0100 + +python2.3 (2.2.96-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release (not exactly the tarball, but taken from + CVS 20030101). + - Includes support for linking with threaded tk8.4 (closes: #172714). + * Install and register whatsnew document (closes: #173859). + * Properly unregister info documentation. + + -- Matthias Klose Wed, 1 Jan 2003 17:38:54 +0100 + +python2.3 (2.2.95-1exp1) unstable; urgency=low + + * Experimental packages from CVS 021212. + - data in unicodedate module is up to date (closes: #171061). + * Fix idle packaging (closes: #170394). + * Configure using unicode UCS-4 (closes: #171062). + This change breaks compatibility with binary modules, but what do you + expect from experimental packages ... Please recompile dependent packages. + * Don't strip binaries for now. + + -- Matthias Klose Thu, 12 Dec 2002 21:42:27 +0100 + +python2.3 (2.2.94-1exp1) unstable; urgency=low + + * Experimental packages from CVS 021120. + * Remove outdated README.dbm. + * Depend on tk8.4. + * python-elisp: Install emacsen install file with mode 644 (closes: #167718). + + -- Matthias Klose Thu, 21 Nov 2002 01:04:51 +0100 + +python2.3 (2.2.93-1exp1) unstable; urgency=medium + + * Experimental packages from CVS 021015. + * Build a static library libpython2.3-pic.a. + * Enable large file support for the Hurd (closes: #164602). + + -- Matthias Klose Tue, 15 Oct 2002 21:06:27 +0200 + +python2.3 (2.2.92-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020922. + * Fix build error on ia64 (closes: #161234). + * Build depend on gcc-3.2-3.2.1-0pre2 to fix build error on arm. + + -- Matthias Klose Sun, 22 Sep 2002 18:30:28 +0200 + +python2.3 (2.2.91-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020906. + * idle-python2.3: Fix conflict (closes: #159267). + * Fix location of python-mode.el (closes: #159564, #159619). + * Use tix8.1. + * Apply fix for distutils/ccompiler problem (closes: #159288). + + -- Matthias Klose Sat, 7 Sep 2002 09:55:07 +0200 + +python2.3 (2.2.90-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020820. + * Don't build python2.3-elisp, but put the latest version into + python-elisp. + + -- Matthias Klose Thu, 22 Aug 2002 21:52:04 +0200 + +python2.2 (2.2.1-6) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 2002-07-23. + * Enable IPv6 support (closes: #152543). + * Add python2.2-tk suggestion for python2.2 (pydoc -g). + * Fix from SF patch #527518: proxy config with user+pass authentication. + * Point pydoc to the correct location of the docs (closes: #147579). + * Remove '*.py[co]' files, when removing the python package, + not when purging (closes: #147130). + * Update to new py2texi.el version (Milan Zamazal). + + -- Matthias Klose Mon, 29 Jul 2002 23:11:32 +0200 + +python2.2 (2.2.1-5) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 2002-05-03. + * Build the info docs (closes: #145653). + + -- Matthias Klose Fri, 3 May 2002 22:35:46 +0200 + +python2.2 (2.2.1-4) unstable; urgency=high + + * Fix indentation errors introduced in last upload (closes: #143809). + + -- Matthias Klose Sun, 21 Apr 2002 01:00:14 +0200 + +python2.2 (2.2.1-3) unstable; urgency=high + + * Add Build-Conflicts: tcl8.0-dev, tk8.0-dev, tcl8.2-dev, tk8.2-dev. + Closes: #143534 (build a working _tkinter module, on machines, where + 8.0's tk.h gets included). + * CVS updates of the release22-maint branch upto 2002-04-20. + + -- Matthias Klose Sat, 20 Apr 2002 09:22:37 +0200 + +python2.2 (2.2.1-2) unstable; urgency=low + + * Forgot to copy the dlmodule patch from the 2.1.3 package. Really + closes: #141681. + + -- Matthias Klose Sat, 13 Apr 2002 01:28:05 +0200 + +python2.2 (2.2.1-1) unstable; urgency=high + + * Final 2.2.1 release. + * According to report #131813, the python interpreter is much faster on some + architectures, when beeing linked statically with the python library (25%). + Gregor and me tested on i386, m68k and alpha, but we could not reproduce + such a speedup (generally between 5% and 10%). But we are linking the + python executable now statically ... + * Build info docs from the tex source, merge the python-doc-info + package into the python-doc package. + * Always build the dl module. Failure in case of + sizeof(int)!=sizeof(long)!=sizeof(void*) + is delayed until dl.open is called. Closes: #141681. + + -- Matthias Klose Thu, 11 Apr 2002 00:19:19 +0200 + +python2.2 (2.2.0.92-0) unstable; urgency=low + + * Package CVS sources, omit cvs-updates.dpatch (closes: #140977). + + -- Matthias Klose Wed, 3 Apr 2002 08:20:52 +0200 + +python2.2 (2.2-6) unstable; urgency=medium + + * Update to python-2.2.1 release candidate 2 (final release scheduled + for April 10). + * Enable dl module (closes: #138992). + * Build doc files with python binary from package (closes: #139657). + * Build _tkinter module with BLT and Tix support. + * python2.2-elisp: Conflict with python2-elisp (closes: #138970). + * string.split docs updated in python-2.2.1 (closes: #129272). + + -- Matthias Klose Mon, 1 Apr 2002 13:52:36 +0200 + +python2.2 (2.2-5) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 20020310 (aproaching + the first 2.2.1 release candidate). + * Stolen from HEAD: check argument of locale.nl_langinfo (closes: #137371). + + -- Matthias Klose Fri, 15 Mar 2002 01:05:59 +0100 + +python2.2 (2.2-4) unstable; urgency=medium + + * Include test/{__init__.py,README,pystone.py} in package (closes: #129013). + * Fix python-elisp conflict (closes: #129046). + * Don't compress stylesheets (closes: #133179). + * CVS updates of the release22-maint branch upto 20020310. + + -- Matthias Klose Sun, 10 Mar 2002 23:32:28 +0100 + +python2.2 (2.2-3) unstable; urgency=medium + + * Updates from the CVS python22-maint branch up to 20020107. + webbrowser.py: properly escape url's. + * The Hurd does not have large file support: disabled. + + -- Matthias Klose Mon, 7 Jan 2002 21:55:57 +0100 + +python2.2 (2.2-2) unstable; urgency=medium + + * CVS updates of the release22-maint branch upto 20011229. Fixes: + - Include TCP_CORK flag in plat-linux2 headers (fixes: #84340). + - Update CDROM.py module (fixes: #125785). + * Add missing chunk of the GNU/Hurd patch (therefore urgency medium). + * Send anonymous password when using anonftp (closes: #126814). + + -- Matthias Klose Sat, 29 Dec 2001 20:18:26 +0100 + +python2.2 (2.2-1) unstable; urgency=low + + * New upstream version: 2.2. + * Bugs fixed upstream: + - Docs for os.kill reference the signal module for constants. + - Documentation strings in the tutorial end with a period (closes: #94770). + - Tk: grid_location method moved from Grid to Misc (closes: #98338). + - mhlib.SubMessage.getbodytext takes decode parameter (closes: #31876). + - Strings in modules are locale aware (closes: #51444). + - Printable 8-bit characters in strings are correctly printed + (closes: #64354). + - Dictionary can be updated with abstract mapping object (closes: #46566). + * Make site.py a config files. + + -- Matthias Klose Sat, 22 Dec 2001 00:51:46 +0100 + +python2.2 (2.1.99c1-1) unstable; urgency=low + + * New upstream version: 2.2c1 (release candidate). + * Do not provide python2.2-base anymore. + * Install correct README.Debian for python2.2 package. Include hint + where to find Makefile.pre.in. + * Suggest installation of python-ssl. + * Remove idle config files on purge. + * Remove empty /usr/lib/python2.2 directory on purge. + + -- Matthias Klose Sat, 15 Dec 2001 17:56:27 +0100 + +python2.2 (2.1.99beta2-1) unstable; urgency=high + + * debian/rules: Reflect removal of regrtest package (closes: #122278). + Resulted in build failures on all architectures. + * Build -doc package from source. + + -- Matthias Klose Sat, 8 Dec 2001 00:38:41 +0100 + +python2.2 (2.1.99beta2-0.1) unstable; urgency=low + + * Non maintainer upload. + * New upstream version (this is 2.2beta2). + * Do not build the python-regrtest package anymore; keep the test framework + components test/regrtest.py and test/test_support.py in the python + package (closes: #119408). + + -- Gregor Hoffleit Tue, 27 Nov 2001 09:53:26 +0100 + +python2.2 (2.1.99beta1-4) unstable; urgency=low + + * Configure with --with-fpectl (closes: #118125). + * setup.py: Remove broken check for _curses_panel module (#116081). + * idle: Move config-* files to /etc and mark as conffiles (#106390). + * Move idle packages to section `devel'. + + -- Matthias Klose Wed, 31 Oct 2001 10:56:45 +0100 + +python2.2 (2.1.99beta1-3) unstable; urgency=low + + * Fix shlibs file (was still referring to 2.1). Closes: #116810. + * README.Debian: point to draft of python-policy in the python package. + + -- Matthias Klose Wed, 31 Oct 2001 10:56:45 +0100 + +python2.2 (2.1.99beta1-2) unstable; urgency=medium + + * Fix shlibs file (was still referring to 2.1). Closes: #116810. + * Rename package python2.2-base to python2.2. + + -- Matthias Klose Wed, 24 Oct 2001 23:00:50 +0200 + +python2.2 (2.1.99beta1-1) unstable; urgency=low + + * New upstream version (beta). Call the package version 2.1.99beta1-1. + * New maintainer until the final 2.2 release. + * Updated the debian patches. + + -- Matthias Klose Sat, 20 Oct 2001 18:56:26 +0200 + +python2.1 (2.1.1-1.2) unstable; urgency=low + + * Really remove the python alternative. + + -- Matthias Klose Sat, 20 Oct 2001 15:16:56 +0200 + +python2.1 (2.1.1-1.1) unstable; urgency=low + + * README FOR PACKAGE MAINTAINERS: It is planned to remove the python2-XXX + packages from unstable and move on to python2.1. + If you repackage/adapt your modules for python2.1, don't build + python2-XXX and python2.1-XXX packages from the same source package, + so that the python2-XXX package can be removed without influencing the + python2.1-XXX package. + + See the debian-python mailing list at http://lists.debian.org/devel.html + for details and the current discussion and a draft for a debian-python + policy (August to October 2001). + + * Remove alternative for /usr/bin/python. The python-base package now + provides the default python version. + + * Regenerate control file to fix build dependencies (closes: #116190). + * Remove alternative for /usr/bin/{python,pydoc}. + * Provide a libpython2.1.so symlink in /usr/lib/python2.1/config, + so that the shared library is found when -L/usr/lib/python2.1/config + is specified. + * Conflict with old package versions, where /usr/bin/python is a real + program (closes: #115943). + * python2.1-elisp conflicts with python-elisp (closes: #115895). + * We now have 2.1 (closes: #96851, #107849, #110243). + + -- Matthias Klose Fri, 19 Oct 2001 17:34:41 +0200 + +python2.1 (2.1.1-1) unstable; urgency=low + + * Incorporated Matthias' modifications. + + -- Gregor Hoffleit Thu, 11 Oct 2001 00:16:42 +0200 + +python2.1 (2.1.1-0.2) unstable; urgency=low + + * New upstream 2.1.1. + * GPL compatible licence (fixes #84080, #102949, #110643). + * Fixed upstream (closes: #99692, #111340). + * Build in separate build directory. + * Split Debian patches into debian/patches directory. + * Build dependencies: Add libgmp3-dev, libexpat1-dev, tighten + debhelper dependency. + * debian/rules: Updated a "bit". + * python-elisp: Remove custom dependency (closes: #87783), + fix emacs path (closes: #89712), remove emacs19 dependency (#82694). + * Mention distutils in python-dev package description (closes: #108170). + * Update README.Debian (closes: #85430). + * Run versioned python in postinsts (closes: #113349). + * debian/sample.{postinst,prerm}: Change to version independent scripts. + * Use '/usr/bin/env python2.1' as interpreter for all python scripts. + * Add libssl-dev to Build-Conflicts. + * python-elisp: Add support for emacs21 (closes: #98635). + * Do not compress .py files in doc directories. + * Don't link explicitely with libc. + + -- Matthias Klose Wed, 3 Oct 2001 09:53:08 +0200 + +python2.1 (2.1.1-0.1) unstable; urgency=low + + * New upstream version (CVS branch release21-maint, will become 2.1.1): + This CVS branch will be released as 2.1.1 under a GPL compatible + license. + + -- Gregor Hoffleit Wed, 27 Jun 2001 22:47:58 +0200 + +python2 (2.1-0.1) unstable; urgency=low + + * Fixed Makefile.pre.in. + * Fixed the postinst files in order to use 2.1 (instead of 2.0). + * Mention the immanent release of 2.0.1 and 2.1.1, with a GPL + compatible license. + + -- Gregor Hoffleit Sun, 17 Jun 2001 21:05:25 +0200 + +python2 (2.1-0) unstable; urgency=low + + * New upstream version. + * Experimental packages. + + -- Gregor Hoffleit Thu, 10 May 2001 00:20:04 +0200 + +python2 (2.0-7) unstable; urgency=low + + * Rebuilt with recent tcl8.3-dev/tk8.3-dev in order to fix a + dependency problem with python2-tk (closes: #87793, #92962). + * Change postinst to create and update /usr/local/lib/python2.0 and + site-python with permissions and owner as mandated by policy: + 2775 and root:staff (closes: #89047). + * Fix to compileall.py: A superfluous argument made compileall without + options fail (cf. #92990 for python). + * Move the distutils module into python2-dev. It needs Makefile.pre.in + in order to work (closes: #89900). + * Remove build-dependency on libgdbm2-dev (which isn't built anyway). + * Add a build-dependency on libdb2-dev (cf. #90220 for python). + + -- Gregor Hoffleit Sat, 14 Apr 2001 21:07:51 +0200 + +python2 (2.0-6) unstable; urgency=low + + * Remove python-zlib package; merge it into python-base. + * Mark that README.python2 is not yet updated. + + -- Gregor Hoffleit Wed, 21 Feb 2001 12:34:18 +0100 + +python2 (2.0-5) unstable; urgency=low + + * Recompile with tcl/tk8.3 (closes: #82088). + * Modifications to README.why-python2 (closes: #82116). + * Add menu hint to idle2 menu entry. + * idle2 is renamed idle-python2 and now build correctly (closes: #82218). + * Add build-dependency on autoconf (closes: #85339). + * Build bsddbmodule as shared module (Modules/Setup.config.in), + and link libpython2.so with -lm in Makefile (closes: #86027). + * various cleanups in debian/rules, e.g. removing dh_suidregister. + * Make pdb available as /usr/bin/pdb-python2 in python2-dev + (cf. #79870 in python-base). + * Remove libgmp3 from build-dependencies, since we currently can't + build the mpzmodule for Python2 due to license problems. + + -- Gregor Hoffleit Sun, 18 Feb 2001 00:12:17 +0100 + +python2 (2.0-4) unstable; urgency=low + + * control: make python2-elisp conflict with python-elisp (it doesn't + make sense to have both of them installed, does it ?) + * include build-depend on libxmltok1-dev. + * again, build with tcl/tk8.0. + + -- Gregor Hoffleit Wed, 10 Jan 2001 23:37:01 +0100 + +python2 (2.0-3) unstable; urgency=low + + * Modules/Setup.in: Added a missing \ that made _tkinter be built + incorrectly. + * rules: on the fly, change all '#!' python scripts to use python2. + + -- Gregor Hoffleit Wed, 13 Dec 2000 20:07:24 +0100 + +python2 (2.0-2) unstable; urgency=low + + * Aaargh. Remove conflicts/provides/replaces on python-base to make + parallel installation of python-base and python2-base possible. + * Install examples into /usr/share/doc/python2 (not python) and fix + symlink to python2.0 (thanks to Rick Younie for + pointing out this). + * Rename man page to python2.1. + + -- Gregor Hoffleit Wed, 13 Dec 2000 09:31:05 +0100 + +python2 (2.0-1) unstable; urgency=low + + * New upstream version. Initial release for python2. + + -- Gregor Hoffleit Mon, 11 Dec 2000 22:39:46 +0100 --- python2.6-2.6.1.orig/debian/idle-PVER.postinst.in +++ python2.6-2.6.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 + /usr/bin/@PVER@ /usr/lib/@PVER@/compileall.py -q $i + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config + then + /usr/bin/@PVER@ -O /usr/lib/@PVER@/compileall.py -q $i + fi + done + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; + +esac + +#DEBHELPER# + +exit 0 --- python2.6-2.6.1.orig/debian/copyright +++ python2.6-2.6.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. --- python2.6-2.6.1.orig/debian/PVER-doc.doc-base.PVER-dist.in +++ python2.6-2.6.1/debian/PVER-doc.doc-base.PVER-dist.in @@ -0,0 +1,13 @@ +Document: @PVER@-dist +Title: Distributing Python Modules (v@VER@) +Author: Greg Ward +Abstract: This document describes the Python Distribution Utilities + (``Distutils'') from the module developer's point-of-view, describing + how to use the Distutils to make Python modules and extensions easily + available to a wider audience with very little overhead for + build/release/install mechanics. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/distutils/index.html +Files: /usr/share/doc/@PVER@/html/distutils/*.html --- python2.6-2.6.1.orig/debian/PVER.postinst.in +++ python2.6-2.6.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') + /usr/bin/@PVER@ /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + /usr/bin/@PVER@ -O /usr/lib/@PVER@/py_compile.py $files + fi + ) +fi + +case "$1" in + configure|abort-upgrade|abort-remove|abort-deconfigure) + + # Create empty directories in /usr/local + if [ ! -e /usr/local/lib/python@VER@ ]; then + mkdir -p /usr/local/lib/python@VER@ 2> /dev/null || true + chmod 2775 /usr/local/lib/python@VER@ 2> /dev/null || true + chown root:staff /usr/local/lib/python@VER@ 2> /dev/null || true + fi + if [ ! -e /usr/local/lib/python@VER@/site-packages ]; then + mkdir -p /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + chmod 2775 /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + chown root:staff /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + fi + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python2.6-2.6.1.orig/debian/libPVER.overrides.in +++ python2.6-2.6.1/debian/libPVER.overrides.in @@ -0,0 +1 @@ +lib@PVER@ binary: package-name-doesnt-match-sonames --- python2.6-2.6.1.orig/debian/pydoc.1.in +++ python2.6-2.6.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" --- python2.6-2.6.1.orig/debian/PVER-doc.doc-base.PVER-inst.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/pygettext.1 +++ python2.6-2.6.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". --- python2.6-2.6.1.orig/debian/PVER-doc.doc-base.PVER-api.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/PVER-doc.doc-base.PVER-doc.in +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/README.PVER.in +++ python2.6-2.6.1/debian/README.PVER.in @@ -0,0 +1,95 @@ + + Python @VER@ for Debian + --------------------- + +This is Python @VER@ packaged for Debian. + +This document contains information specific to the Debian packages of +Python @VER@. + + + + [TODO: This document is not yet up-to-date with the packages.] + +Currently, it features those two main topics: + + 1. Release notes for the Debian packages: + 2. Notes for developers using the Debian Python packages: + +Release notes and documentation from the upstream package are installed +in /usr/share/doc/@PVER@/. + +There's a mailing list for discussion of issues related to Python on Debian +systems: debian-python@lists.debian.org. The list is not intended for +general Python problems, but as a forum for maintainers of Python-related +packages and interested third parties. + + + +1. Release notes for the Debian packages: + + +Results of the regression test: +------------------------------ + +The package does successfully run the regression tests for all included +modules. Seven packages are skipped since they are platform-dependent and +can't be used with Linux. + + +2. Notes for developers using the Debian python packages: + +See the draft of the Debian Python policy in /usr/share/doc/python. + +distutils can be found in the @PVER@-dev package. Development files +like the python library or Makefiles can be found in the @PVER@-dev +package in /usr/lib/@PVER@/config. Therefore, if you need to install +a pure python extension, you only need @PVER@. On the other hand, to +install a C extension, you need @PVER@-dev. + +a) Locally installed Python add-ons + + /usr/local/lib/@PVER@/site-packages/ + /usr/local/lib/site-python/ (version-independent modules) + +b) Python add-ons packaged for Debian + + /usr/lib/@PVER@/site-packages/ + /usr/lib/site-python/ (version-independent modules) + +Note that no package must install files directly into /usr/lib/@PVER@/ +or /usr/local/lib/@PVER@/. Only the site-packages directory is allowed +for third-party extensions. + +Use of the new `package' scheme is strongly encouraged. The `ni' interface +is obsolete in python 1.5. + +Header files for extensions go into /usr/include/@PVER@/. + + +Installing extensions for local use only: +---------------------------------------- + +Consider using distutils ... + +Most extensions use Python's Makefile.pre.in. Note that Makefile.pre.in +by default will install files into /usr/lib/, not into /usr/local/lib/, +which is not allowed for local extensions. You'll have to change the +Makefile accordingly. Most times, "make prefix=/usr/local install" will +work. + + +Packaging python extensions for Debian: +-------------------------------------- + +Maintainers of Python extension packages should read + + /usr/share/doc/python/python-policy.txt.gz + + + + + 03/09/98 + Gregor Hoffleit + +Last change: 2001-12-14 --- python2.6-2.6.1.orig/debian/locale-gen +++ python2.6-2.6.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 "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.py~ 2009-03-18 16:40:47.000000000 +0100 ++++ Lib/distutils/command/install.py 2009-03-18 20:34:48.000000000 +0100 +@@ -47,6 +47,20 @@ + 'scripts': '$base/bin', + 'data' : '$base', + }, ++ 'unix_local': { ++ 'purelib': '$base/local/lib/python$py_version_short/dist-packages', ++ 'platlib': '$platbase/local/lib/python$py_version_short/dist-packages', ++ 'headers': '$base/local/include/python$py_version_short/$dist_name', ++ 'scripts': '$base/local/bin', ++ 'data' : '$base/local', ++ }, ++ 'deb_system': { ++ 'purelib': '$base/lib/python$py_version_short/dist-packages', ++ 'platlib': '$platbase/lib/python$py_version_short/dist-packages', ++ 'headers': '$base/include/python$py_version_short/$dist_name', ++ 'scripts': '$base/bin', ++ 'data' : '$base', ++ }, + 'unix_home': { + 'purelib': '$base/lib/python', + 'platlib': '$base/lib/python', +@@ -168,6 +182,9 @@ + + ('record=', None, + "filename in which to record list of installed files"), ++ ++ ('install-layout=', None, ++ "installation layout to choose (known values: deb)"), + ] + + boolean_options = ['compile', 'force', 'skip-build', 'user'] +@@ -182,6 +199,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 +@@ -203,6 +221,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 + +@@ -435,6 +456,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, \ +@@ -449,7 +471,19 @@ + + self.install_base = self.prefix + self.install_platbase = self.exec_prefix +- self.select_scheme("unix_prefix") ++ if self.prefix_option: ++ if self.install_layout: ++ raise DistutilsOptionError( ++ "options --install-layout and --prefix are exclusive") ++ self.select_scheme("unix_prefix") ++ elif self.install_layout == None: ++ self.select_scheme("unix_local") ++ else: ++ if self.install_layout.lower() in ['deb']: ++ self.select_scheme("deb_system") ++ else: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") + + # finalize_unix () + +--- Lib/distutils/command/install_egg_info.py~ 2009-03-18 16:40:47.000000000 +0100 ++++ Lib/distutils/command/install_egg_info.py 2009-03-18 20:43:58.000000000 +0100 +@@ -14,18 +14,32 @@ + 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.prefix_option: ++ basename = "%s-%s-py%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())), ++ sys.version[:3] ++ ) ++ else: ++ basename = "%s-%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())) ++ ) ++ if self.install_layout and not self.install_layout.lower() in ['deb']: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") + self.target = os.path.join(self.install_dir, basename) + self.outputs = [self.target] + +--- Lib/distutils/sysconfig.py~ 2009-02-19 13:07:31.000000000 +0100 ++++ Lib/distutils/sysconfig.py 2009-02-22 10:31:48.000000000 +0100 +@@ -121,7 +121,7 @@ + if standard_lib: + return libpython + else: +- return os.path.join(libpython, "site-packages") ++ return os.path.join(libpython, "dist-packages") + + elif os.name == "nt": + if standard_lib: --- python2.6-2.6.1.orig/debian/patches/disable-utimes.dpatch +++ python2.6-2.6.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. --- python2.6-2.6.1.orig/debian/patches/enable-fpectl.dpatch +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/patches/doc-faq.dpatch +++ python2.6-2.6.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 @@ + + + ++ ++ ++   ++

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

--- python2.6-2.6.1.orig/debian/patches/doc-nodownload.dpatch +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/patches/profile-doc.dpatch +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/patches/linecache.dpatch +++ python2.6-2.6.1/debian/patches/linecache.dpatch @@ -0,0 +1,40 @@ +#! /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.original 2007-07-14 21:00:48.000000000 -0700 ++++ Lib/linecache.py 2007-07-14 20:59:16.000000000 -0700 +@@ -104,7 +104,11 @@ + ) + return cache[filename][2] + +- # Try looking through the module search path. ++ # Try looking through the module search path, taking care to handle packages. ++ ++ if basename == '__init__.py': ++ # filename referes to a package ++ basename = filename + + for dirname in sys.path: + # When using imputil, sys.path may contain things other than --- python2.6-2.6.1.orig/debian/patches/distutils-sysconfig.dpatch +++ python2.6-2.6.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~ 2008-05-23 11:12:19.000000000 +0000 ++++ Lib/distutils/sysconfig.py 2008-05-23 11:19:00.000000000 +0000 +@@ -162,8 +162,9 @@ + varies across Unices and is stored in Python's Makefile. + """ + if compiler.compiler_type == "unix": +- (cc, cxx, opt, cflags, ccshared, ldshared, so_ext) = \ ++ (cc, cxx, opt, cflags, opt, extra_cflags, basecflags, ccshared, ldshared, so_ext) = \ + get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', ++ 'OPT', 'EXTRA_CFLAGS', 'BASECFLAGS', + 'CCSHARED', 'LDSHARED', 'SO') + + if 'CC' in os.environ: +@@ -178,8 +179,13 @@ + cpp = cc + " -E" # not always + if 'LDFLAGS' in os.environ: + ldshared = ldshared + ' ' + os.environ['LDFLAGS'] ++ if 'BASECFLAGS' in os.environ: ++ basecflags = os.environ['BASECFLAGS'] ++ if 'OPT' in os.environ: ++ opt = os.environ['OPT'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, extra_cflags) if x) + if 'CFLAGS' in os.environ: +- cflags = opt + ' ' + os.environ['CFLAGS'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, os.environ['CFLAGS'], extra_cflags) if x) + ldshared = ldshared + ' ' + os.environ['CFLAGS'] + if 'CPPFLAGS' in os.environ: + cpp = cpp + ' ' + os.environ['CPPFLAGS'] --- python2.6-2.6.1.orig/debian/patches/locale-module.dpatch +++ python2.6-2.6.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', --- python2.6-2.6.1.orig/debian/patches/setup-modules.dpatch +++ python2.6-2.6.1/debian/patches/setup-modules.dpatch @@ -0,0 +1,68 @@ +#! /bin/sh -e + +# DP: Modules/Setup.dist: patches to build some extensions statically + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Modules/_elementtree.c~ 2008-11-27 10:01:33.000000000 +0100 ++++ Modules/_elementtree.c 2008-11-27 10:03:30.000000000 +0100 +@@ -1837,7 +1837,10 @@ + static struct PyExpat_CAPI* expat_capi; + #define EXPAT(func) (expat_capi->func) + #else +-#define EXPAT(func) (XML_##func) ++#define EXPAT(func) (PyExpat_XML_##func) ++#define PyExpat_XML_GetErrorLineNumber PyExpat_XML_GetCurrentLineNumber ++#define PyExpat_XML_GetErrorColumnNumber PyExpat_XML_GetCurrentColumnNumber ++#define PyExpat_XML_GetErrorByteIndex PyExpat_XML_GetCurrentByteIndex + #endif + + typedef struct { +--- Modules/Setup.dist~ 2008-11-27 10:59:37.000000000 +0100 ++++ Modules/Setup.dist 2008-11-27 11:00:26.000000000 +0100 +@@ -165,7 +165,7 @@ + #itertools itertoolsmodule.c # Functions creating iterators for efficient looping + #atexit atexitmodule.c # Register functions to be run at interpreter-shutdown + #_functools _functoolsmodule.c # Tools for working with functions and callable objects +-#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator ++#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H _elementtree.c # elementtree accelerator + #_pickle _pickle.c # pickle accelerator + #datetime datetimemodule.c # date/time type + #_bisect _bisectmodule.c # Bisection algorithms +@@ -341,6 +341,7 @@ + #DBLIB=$(DB)/lib + #_bsddb _bsddb.c -I$(DBINC) -L$(DBLIB) -ldb-$(DBLIBVER) + ++#_ctypes _ctypes/_ctypes.c _ctypes/callbacks.c _ctypes/callproc.c _ctypes/stgdict.c _ctypes/cfield.c _ctypes/malloc_closure.c -Wl,-Bstatic -lffi -Wl,-Bdynamic + + # Helper module for various ascii-encoders + #binascii binascii.c +@@ -382,7 +382,7 @@ + # + # More information on Expat can be found at www.libexpat.org. + # +-#pyexpat expat/xmlparse.c expat/xmlrole.c expat/xmltok.c pyexpat.c -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI ++#pyexpat expat/xmlparse.c expat/xmlrole.c expat/xmltok.c pyexpat.c -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H + + # Hye-Shik Chang's CJKCodecs + +#! /bin/sh -e --- python2.6-2.6.1.orig/debian/patches/svn-updates.dpatch +++ python2.6-2.6.1/debian/patches/svn-updates.dpatch @@ -0,0 +1,36792 @@ +#! /bin/sh -e + +# DP: SVN updates of the release26-maint branch (until 2009-03-18). + +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 + rm -f configure + 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/r261 http://svn.python.org/projects/python/branches/release26-maint +# diff -urN --exclude=.svn Python-2.6 svn + +Index: Python/ceval.c +=================================================================== +--- Python/ceval.c (.../tags/r261) (Revision 70449) ++++ Python/ceval.c (.../branches/release26-maint) (Revision 70449) +@@ -504,6 +504,13 @@ + static enum why_code do_raise(PyObject *, PyObject *, PyObject *); + static int unpack_iterable(PyObject *, int, PyObject **); + ++/* Records whether tracing is on for any thread. Counts the number of ++ threads for which tstate->c_tracefunc is non-NULL, so if the value ++ is 0, we know we don't have to check this thread's c_tracefunc. ++ This speeds up the if statement in PyEval_EvalFrameEx() after ++ fast_next_opcode*/ ++static int _Py_TracingPossible = 0; ++ + /* for manipulating the thread switch and periodic "stuff" - used to be + per thread, now just a pair o' globals */ + int _Py_CheckInterval = 100; +@@ -886,7 +893,8 @@ + + /* line-by-line tracing support */ + +- if (tstate->c_tracefunc != NULL && !tstate->tracing) { ++ if (_Py_TracingPossible && ++ tstate->c_tracefunc != NULL && !tstate->tracing) { + /* see maybe_call_line_trace + for expository comments */ + f->f_stacktop = stack_pointer; +@@ -1041,6 +1049,7 @@ + } + Py_FatalError("invalid argument to DUP_TOPX" + " (bytecode corruption?)"); ++ /* Never returns, so don't bother to set why. */ + break; + + case UNARY_POSITIVE: +@@ -1634,9 +1643,11 @@ + case PRINT_NEWLINE: + if (stream == NULL || stream == Py_None) { + w = PySys_GetObject("stdout"); +- if (w == NULL) ++ if (w == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "lost sys.stdout"); ++ why = WHY_EXCEPTION; ++ } + } + if (w != NULL) { + /* w.write() may replace sys.stdout, so we +@@ -1862,6 +1873,7 @@ + PyErr_Format(PyExc_SystemError, + "no locals when loading %s", + PyObject_REPR(w)); ++ why = WHY_EXCEPTION; + break; + } + if (PyDict_CheckExact(v)) { +@@ -2337,11 +2349,20 @@ + /* XXX Not the fastest way to call it... */ + x = PyObject_CallFunctionObjArgs(exit_func, u, v, w, + NULL); +- if (x == NULL) { +- Py_DECREF(exit_func); ++ Py_DECREF(exit_func); ++ if (x == NULL) + break; /* Go to error exit */ +- } +- if (u != Py_None && PyObject_IsTrue(x)) { ++ ++ if (u != Py_None) ++ err = PyObject_IsTrue(x); ++ else ++ err = 0; ++ Py_DECREF(x); ++ ++ if (err < 0) ++ break; /* Go to error exit */ ++ else if (err > 0) { ++ err = 0; + /* There was an exception and a true return */ + STACKADJ(-2); + Py_INCREF(Py_None); +@@ -2353,8 +2374,6 @@ + /* The stack was rearranged to remove EXIT + above. Let END_FINALLY do its thing */ + } +- Py_DECREF(x); +- Py_DECREF(exit_func); + PREDICT(END_FINALLY); + break; + } +@@ -2451,7 +2470,10 @@ + Py_DECREF(v); + if (x != NULL) { + v = POP(); +- err = PyFunction_SetClosure(x, v); ++ if (PyFunction_SetClosure(x, v) != 0) { ++ /* Can't happen unless bytecode is corrupt. */ ++ why = WHY_EXCEPTION; ++ } + Py_DECREF(v); + } + if (x != NULL && oparg > 0) { +@@ -2465,7 +2487,11 @@ + w = POP(); + PyTuple_SET_ITEM(v, oparg, w); + } +- err = PyFunction_SetDefaults(x, v); ++ if (PyFunction_SetDefaults(x, v) != 0) { ++ /* Can't happen unless ++ PyFunction_SetDefaults changes. */ ++ why = WHY_EXCEPTION; ++ } + Py_DECREF(v); + } + PUSH(x); +@@ -3414,6 +3440,7 @@ + { + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_traceobj; ++ _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL); + Py_XINCREF(arg); + tstate->c_tracefunc = NULL; + tstate->c_traceobj = NULL; +Index: Python/getargs.c +=================================================================== +--- Python/getargs.c (.../tags/r261) (Revision 70449) ++++ Python/getargs.c (.../branches/release26-maint) (Revision 70449) +@@ -1601,7 +1601,7 @@ + } + } + +- if (!IS_END_OF_FORMAT(*format)) { ++ if (!IS_END_OF_FORMAT(*format) && *format != '|') { + PyErr_Format(PyExc_RuntimeError, + "more argument specifiers than keyword list entries " + "(remaining format:'%s')", format); +Index: Python/graminit.c +=================================================================== +--- Python/graminit.c (.../tags/r261) (Revision 70449) ++++ Python/graminit.c (.../branches/release26-maint) (Revision 70449) +@@ -2,6 +2,7 @@ + + #include "pgenheaders.h" + #include "grammar.h" ++PyAPI_DATA(grammar) _PyParser_Grammar; + static arc arcs_0_0[3] = { + {2, 1}, + {3, 1}, +Index: Python/ast.c +=================================================================== +--- Python/ast.c (.../tags/r261) (Revision 70449) ++++ Python/ast.c (.../branches/release26-maint) (Revision 70449) +@@ -3177,6 +3177,7 @@ + int imflag; + #endif + ++ assert(s != NULL); + errno = 0; + end = s + strlen(s) - 1; + #ifndef WITHOUT_COMPLEX +Index: Python/pythonrun.c +=================================================================== +--- Python/pythonrun.c (.../tags/r261) (Revision 70449) ++++ Python/pythonrun.c (.../branches/release26-maint) (Revision 70449) +@@ -22,6 +22,10 @@ + #include + #endif + ++#ifdef MS_WINDOWS ++#include "malloc.h" /* for alloca */ ++#endif ++ + #ifdef HAVE_LANGINFO_H + #include + #include +@@ -1628,9 +1632,21 @@ + { + fprintf(stderr, "Fatal Python error: %s\n", msg); + #ifdef MS_WINDOWS +- OutputDebugString("Fatal Python error: "); +- OutputDebugString(msg); +- OutputDebugString("\n"); ++ { ++ size_t len = strlen(msg); ++ WCHAR* buffer; ++ size_t i; ++ ++ /* Convert the message to wchar_t. This uses a simple one-to-one ++ conversion, assuming that the this error message actually uses ASCII ++ only. If this ceases to be true, we will have to convert. */ ++ buffer = alloca( (len+1) * (sizeof *buffer)); ++ for( i=0; i<=len; ++i) ++ buffer[i] = msg[i]; ++ OutputDebugStringW(L"Fatal Python error: "); ++ OutputDebugStringW(buffer); ++ OutputDebugStringW(L"\n"); ++ } + #ifdef _DEBUG + DebugBreak(); + #endif +Index: Python/import.c +=================================================================== +--- Python/import.c (.../tags/r261) (Revision 70449) ++++ Python/import.c (.../branches/release26-maint) (Revision 70449) +@@ -910,7 +910,50 @@ + PySys_WriteStderr("# wrote %s\n", cpathname); + } + ++static void ++update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname) ++{ ++ PyObject *constants, *tmp; ++ Py_ssize_t i, n; + ++ if (!_PyString_Eq(co->co_filename, oldname)) ++ return; ++ ++ tmp = co->co_filename; ++ co->co_filename = newname; ++ Py_INCREF(co->co_filename); ++ Py_DECREF(tmp); ++ ++ constants = co->co_consts; ++ n = PyTuple_GET_SIZE(constants); ++ for (i = 0; i < n; i++) { ++ tmp = PyTuple_GET_ITEM(constants, i); ++ if (PyCode_Check(tmp)) ++ update_code_filenames((PyCodeObject *)tmp, ++ oldname, newname); ++ } ++} ++ ++static int ++update_compiled_module(PyCodeObject *co, char *pathname) ++{ ++ PyObject *oldname, *newname; ++ ++ if (strcmp(PyString_AsString(co->co_filename), pathname) == 0) ++ return 0; ++ ++ newname = PyString_FromString(pathname); ++ if (newname == NULL) ++ return -1; ++ ++ oldname = co->co_filename; ++ Py_INCREF(oldname); ++ update_code_filenames(co, oldname, newname); ++ Py_DECREF(oldname); ++ Py_DECREF(newname); ++ return 1; ++} ++ + /* Load a source module from a given file and return its module + object WITH INCREMENTED REFERENCE COUNT. If there's a matching + byte-compiled file, use that instead. */ +@@ -950,6 +993,8 @@ + fclose(fpc); + if (co == NULL) + return NULL; ++ if (update_compiled_module(co, pathname) < 0) ++ return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # precompiled from %s\n", + name, cpathname); +@@ -3154,24 +3199,11 @@ + return -1; + } else { + #ifndef RISCOS ++#ifndef MS_WINDOWS + struct stat statbuf; + int rv; + + rv = stat(path, &statbuf); +-#ifdef MS_WINDOWS +- /* MS Windows stat() chokes on paths like C:\path\. Try to +- * recover *one* time by stripping off a trailing slash or +- * backslash. http://bugs.python.org/issue1293 +- */ +- if (rv != 0 && pathlen <= MAXPATHLEN && +- (path[pathlen-1] == '/' || path[pathlen-1] == '\\')) { +- char mangled[MAXPATHLEN+1]; +- +- strcpy(mangled, path); +- mangled[pathlen-1] = '\0'; +- rv = stat(mangled, &statbuf); +- } +-#endif + if (rv == 0) { + /* it exists */ + if (S_ISDIR(statbuf.st_mode)) { +@@ -3181,7 +3213,24 @@ + return -1; + } + } +-#else ++#else /* MS_WINDOWS */ ++ DWORD rv; ++ /* see issue1293 and issue3677: ++ * stat() on Windows doesn't recognise paths like ++ * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs. ++ */ ++ rv = GetFileAttributesA(path); ++ if (rv != INVALID_FILE_ATTRIBUTES) { ++ /* it exists */ ++ if (rv & FILE_ATTRIBUTE_DIRECTORY) { ++ /* it's a directory */ ++ PyErr_SetString(PyExc_ImportError, ++ "existing directory"); ++ return -1; ++ } ++ } ++#endif ++#else /* RISCOS */ + if (object_exists(path)) { + /* it exists */ + if (isdir(path)) { +Index: Python/dynload_win.c +=================================================================== +--- Python/dynload_win.c (.../tags/r261) (Revision 70449) ++++ Python/dynload_win.c (.../branches/release26-maint) (Revision 70449) +@@ -11,6 +11,10 @@ + #include "importdl.h" + #include + ++// "activation context" magic - see dl_nt.c... ++extern ULONG_PTR _Py_ActivateActCtx(); ++void _Py_DeactivateActCtx(ULONG_PTR cookie); ++ + const struct filedescr _PyImport_DynLoadFiletab[] = { + #ifdef _DEBUG + {"_d.pyd", "rb", C_EXTENSION}, +@@ -172,6 +176,7 @@ + char pathbuf[260]; + LPTSTR dummy; + unsigned int old_mode; ++ ULONG_PTR cookie = 0; + /* We use LoadLibraryEx so Windows looks for dependent DLLs + in directory of pathname first. However, Windows95 + can sometimes not work correctly unless the absolute +@@ -184,10 +189,13 @@ + if (GetFullPathName(pathname, + sizeof(pathbuf), + pathbuf, +- &dummy)) ++ &dummy)) { ++ ULONG_PTR cookie = _Py_ActivateActCtx(); + /* XXX This call doesn't exist in Windows CE */ + hDLL = LoadLibraryEx(pathname, NULL, + LOAD_WITH_ALTERED_SEARCH_PATH); ++ _Py_DeactivateActCtx(cookie); ++ } + + /* restore old error mode settings */ + SetErrorMode(old_mode); +Index: Python/getcopyright.c +=================================================================== +--- Python/getcopyright.c (.../tags/r261) (Revision 70449) ++++ Python/getcopyright.c (.../branches/release26-maint) (Revision 70449) +@@ -4,7 +4,7 @@ + + static char cprt[] = + "\ +-Copyright (c) 2001-2008 Python Software Foundation.\n\ ++Copyright (c) 2001-2009 Python Software Foundation.\n\ + All Rights Reserved.\n\ + \n\ + Copyright (c) 2000 BeOpen.com.\n\ +Index: Python/bltinmodule.c +=================================================================== +--- Python/bltinmodule.c (.../tags/r261) (Revision 70449) ++++ Python/bltinmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -268,6 +268,8 @@ + + /* Guess a result list size. */ + len = _PyObject_LengthHint(seq, 8); ++ if (len == -1) ++ goto Fail_it; + + /* Get a result list. */ + if (PyList_Check(seq) && seq->ob_refcnt == 1) { +Index: Python/sysmodule.c +=================================================================== +--- Python/sysmodule.c (.../tags/r261) (Revision 70449) ++++ Python/sysmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -1296,8 +1296,13 @@ + PyDict_SetItemString(sysdict, key, v); \ + Py_XDECREF(v) + ++ /* Check that stdin is not a directory ++ Using shell redirection, you can redirect stdin to a directory, ++ crashing the Python interpreter. Catch this common mistake here ++ and output a useful error message. Note that under MS Windows, ++ the shell already prevents that. */ ++#if !defined(MS_WINDOWS) + { +- /* XXX: does this work on Win/Win64? (see posix_fstat) */ + struct stat sb; + if (fstat(fileno(stdin), &sb) == 0 && + S_ISDIR(sb.st_mode)) { +@@ -1307,6 +1312,7 @@ + exit(EXIT_FAILURE); + } + } ++#endif + + /* Closing the standard FILE* if sys.std* goes aways causes problems + * for embedded Python usages. Closing them when somebody explicitly +@@ -1526,7 +1532,7 @@ + { + #if defined(HAVE_REALPATH) + char fullpath[MAXPATHLEN]; +-#elif defined(MS_WINDOWS) ++#elif defined(MS_WINDOWS) && !defined(MS_WINCE) + char fullpath[MAX_PATH]; + #endif + PyObject *av = makeargvobject(argc, argv); +@@ -1571,7 +1577,10 @@ + #if SEP == '\\' /* Special case for MS filename syntax */ + if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) { + char *q; +-#ifdef MS_WINDOWS ++#if defined(MS_WINDOWS) && !defined(MS_WINCE) ++ /* This code here replaces the first element in argv with the full ++ path that it represents. Under CE, there are no relative paths so ++ the argument must be the full path anyway. */ + char *ptemp; + if (GetFullPathName(argv0, + sizeof(fullpath), +Index: LICENSE +=================================================================== +--- LICENSE (.../tags/r261) (Revision 70449) ++++ LICENSE (.../branches/release26-maint) (Revision 70449) +@@ -55,7 +55,10 @@ + 2.4.4 2.4.3 2006 PSF yes + 2.5 2.4 2006 PSF yes + 2.5.1 2.5 2007 PSF yes ++ 2.5.2 2.5.1 2008 PSF yes ++ 2.5.3 2.5.2 2008 PSF yes + 2.6 2.5 2008 PSF yes ++ 2.6.1 2.6 2008 PSF yes + + Footnotes: + +@@ -85,15 +88,14 @@ + otherwise using this software ("Python") in source or binary form and + its associated documentation. + +-2. Subject to the terms and conditions of this License Agreement, PSF +-hereby grants Licensee a nonexclusive, royalty-free, world-wide +-license to reproduce, analyze, test, perform and/or display publicly, +-prepare derivative works, distribute, and otherwise use Python +-alone or in any derivative version, provided, however, that PSF's +-License Agreement and PSF's notice of copyright, i.e., "Copyright (c) +-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Python Software Foundation; +-All Rights Reserved" are retained in Python alone or in any derivative +-version prepared by Licensee. ++2. Subject to the terms and conditions of this License Agreement, PSF hereby ++grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, ++analyze, test, perform and/or display publicly, prepare derivative works, ++distribute, and otherwise use Python alone or in any derivative version, ++provided, however, that PSF's License Agreement and PSF's notice of copyright, ++i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 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 +Index: PCbuild/sqlite3.vsprops +=================================================================== +--- PCbuild/sqlite3.vsprops (.../tags/r261) (Revision 0) ++++ PCbuild/sqlite3.vsprops (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,14 @@ ++ ++ ++ ++ + +Eigenschaftsänderungen: PCbuild/sqlite3.vsprops +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: PCbuild/bdist_wininst.vcproj +=================================================================== +--- PCbuild/bdist_wininst.vcproj (.../tags/r261) (Revision 70449) ++++ PCbuild/bdist_wininst.vcproj (.../branches/release26-maint) (Revision 70449) +@@ -55,7 +55,7 @@ + AdditionalIncludeDirectories="..\PC\bdist_wininst;..\Include;..\Modules\zlib" + PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE" + StringPooling="true" +- RuntimeLibrary="2" ++ RuntimeLibrary="0" + EnableFunctionLevelLinking="true" + WarningLevel="3" + SuppressStartupBanner="true" +@@ -145,7 +145,7 @@ + AdditionalIncludeDirectories="..\PC\bdist_wininst;..\Include;..\Modules\zlib" + PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE" + StringPooling="true" +- RuntimeLibrary="2" ++ RuntimeLibrary="0" + EnableFunctionLevelLinking="true" + WarningLevel="3" + SuppressStartupBanner="true" +Index: PCbuild/build_ssl.bat +=================================================================== +--- PCbuild/build_ssl.bat (.../tags/r261) (Revision 70449) ++++ PCbuild/build_ssl.bat (.../branches/release26-maint) (Revision 70449) +@@ -2,10 +2,10 @@ + if not defined HOST_PYTHON ( + if %1 EQU Debug ( + set HOST_PYTHON=python_d.exe +- if not exist python30_d.dll exit 1 ++ if not exist python26_d.dll exit 1 + ) ELSE ( + set HOST_PYTHON=python.exe +- if not exist python30.dll exit 1 ++ if not exist python26.dll exit 1 + ) + ) + %HOST_PYTHON% build_ssl.py %1 %2 %3 +Index: PCbuild/sqlite3.vcproj +=================================================================== +--- PCbuild/sqlite3.vcproj (.../tags/r261) (Revision 70449) ++++ PCbuild/sqlite3.vcproj (.../branches/release26-maint) (Revision 70449) +@@ -22,7 +22,7 @@ + + + + + + + +@@ -166,8 +164,7 @@ + /> + + +@@ -229,8 +226,7 @@ + /> + + +@@ -291,8 +287,7 @@ + /> + + +@@ -354,8 +349,7 @@ + /> + + +@@ -415,8 +409,7 @@ + /> + + +@@ -478,8 +471,7 @@ + /> + + = 3 ++#define Py_ALIGNED(x) __attribute__((aligned(x))) ++#else ++#define Py_ALIGNED(x) ++#endif ++ + /* Eliminate end-of-loop code not reached warnings from SunPro C + * when using do{...}while(0) macros + */ +Index: Include/unicodeobject.h +=================================================================== +--- Include/unicodeobject.h (.../tags/r261) (Revision 70449) ++++ Include/unicodeobject.h (.../branches/release26-maint) (Revision 70449) +@@ -130,6 +130,10 @@ + typedef unsigned long Py_UCS4; + #endif + ++/* Py_UNICODE is the native Unicode storage format (code unit) used by ++ Python and represents a single Unicode element in the Unicode ++ type. */ ++ + typedef PY_UNICODE_TYPE Py_UNICODE; + + /* --- UCS-2/UCS-4 Name Mangling ------------------------------------------ */ +@@ -153,6 +157,7 @@ + # define PyUnicode_AsUnicode PyUnicodeUCS2_AsUnicode + # define PyUnicode_AsUnicodeEscapeString PyUnicodeUCS2_AsUnicodeEscapeString + # define PyUnicode_AsWideChar PyUnicodeUCS2_AsWideChar ++# define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist + # define PyUnicode_Compare PyUnicodeUCS2_Compare + # define PyUnicode_Concat PyUnicodeUCS2_Concat + # define PyUnicode_Contains PyUnicodeUCS2_Contains +@@ -182,13 +187,13 @@ + # define PyUnicode_Find PyUnicodeUCS2_Find + # define PyUnicode_Format PyUnicodeUCS2_Format + # define PyUnicode_FromEncodedObject PyUnicodeUCS2_FromEncodedObject ++# define PyUnicode_FromFormat PyUnicodeUCS2_FromFormat ++# define PyUnicode_FromFormatV PyUnicodeUCS2_FromFormatV + # define PyUnicode_FromObject PyUnicodeUCS2_FromObject + # define PyUnicode_FromOrdinal PyUnicodeUCS2_FromOrdinal +-# define PyUnicode_FromUnicode PyUnicodeUCS2_FromUnicode + # define PyUnicode_FromString PyUnicodeUCS2_FromString + # define PyUnicode_FromStringAndSize PyUnicodeUCS2_FromStringAndSize +-# define PyUnicode_FromFormatV PyUnicodeUCS2_FromFormatV +-# define PyUnicode_FromFormat PyUnicodeUCS2_FromFormat ++# define PyUnicode_FromUnicode PyUnicodeUCS2_FromUnicode + # define PyUnicode_FromWideChar PyUnicodeUCS2_FromWideChar + # define PyUnicode_GetDefaultEncoding PyUnicodeUCS2_GetDefaultEncoding + # define PyUnicode_GetMax PyUnicodeUCS2_GetMax +@@ -209,7 +214,6 @@ + # define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS2_AsDefaultEncodedString + # define _PyUnicode_Fini _PyUnicodeUCS2_Fini + # define _PyUnicode_Init _PyUnicodeUCS2_Init +-# define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist + # define _PyUnicode_IsAlpha _PyUnicodeUCS2_IsAlpha + # define _PyUnicode_IsDecimalDigit _PyUnicodeUCS2_IsDecimalDigit + # define _PyUnicode_IsDigit _PyUnicodeUCS2_IsDigit +@@ -240,6 +244,7 @@ + # define PyUnicode_AsUnicode PyUnicodeUCS4_AsUnicode + # define PyUnicode_AsUnicodeEscapeString PyUnicodeUCS4_AsUnicodeEscapeString + # define PyUnicode_AsWideChar PyUnicodeUCS4_AsWideChar ++# define PyUnicode_ClearFreeList PyUnicodeUCS4_ClearFreelist + # define PyUnicode_Compare PyUnicodeUCS4_Compare + # define PyUnicode_Concat PyUnicodeUCS4_Concat + # define PyUnicode_Contains PyUnicodeUCS4_Contains +@@ -269,13 +274,13 @@ + # define PyUnicode_Find PyUnicodeUCS4_Find + # define PyUnicode_Format PyUnicodeUCS4_Format + # define PyUnicode_FromEncodedObject PyUnicodeUCS4_FromEncodedObject ++# define PyUnicode_FromFormat PyUnicodeUCS4_FromFormat ++# define PyUnicode_FromFormatV PyUnicodeUCS4_FromFormatV + # define PyUnicode_FromObject PyUnicodeUCS4_FromObject + # define PyUnicode_FromOrdinal PyUnicodeUCS4_FromOrdinal +-# define PyUnicode_FromUnicode PyUnicodeUCS4_FromUnicode + # define PyUnicode_FromString PyUnicodeUCS4_FromString + # define PyUnicode_FromStringAndSize PyUnicodeUCS4_FromStringAndSize +-# define PyUnicode_FromFormatV PyUnicodeUCS4_FromFormatV +-# define PyUnicode_FromFormat PyUnicodeUCS4_FromFormat ++# define PyUnicode_FromUnicode PyUnicodeUCS4_FromUnicode + # define PyUnicode_FromWideChar PyUnicodeUCS4_FromWideChar + # define PyUnicode_GetDefaultEncoding PyUnicodeUCS4_GetDefaultEncoding + # define PyUnicode_GetMax PyUnicodeUCS4_GetMax +@@ -296,7 +301,6 @@ + # define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS4_AsDefaultEncodedString + # define _PyUnicode_Fini _PyUnicodeUCS4_Fini + # define _PyUnicode_Init _PyUnicodeUCS4_Init +-# define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist + # define _PyUnicode_IsAlpha _PyUnicodeUCS4_IsAlpha + # define _PyUnicode_IsDecimalDigit _PyUnicodeUCS4_IsDecimalDigit + # define _PyUnicode_IsDigit _PyUnicodeUCS4_IsDigit +@@ -350,12 +354,12 @@ + + #else + +-/* Since splitting on whitespace is an important use case, and whitespace +- in most situations is solely ASCII whitespace, we optimize for the common +- case by using a quick look-up table with an inlined check. ++/* Since splitting on whitespace is an important use case, and ++ whitespace in most situations is solely ASCII whitespace, we ++ optimize for the common case by using a quick look-up table ++ _Py_ascii_whitespace (see below) with an inlined check. ++ + */ +-PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[]; +- + #define Py_UNICODE_ISSPACE(ch) \ + ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch)) + +@@ -389,13 +393,14 @@ + #define Py_UNICODE_COPY(target, source, length) \ + Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE)) + +-#define Py_UNICODE_FILL(target, value, length) do\ +- {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\ ++#define Py_UNICODE_FILL(target, value, length) \ ++ do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\ + for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\ + } while (0) + +-/* check if substring matches at given offset. the offset must be ++/* Check if substring matches at given offset. the offset must be + valid, and the substring must not be empty */ ++ + #define Py_UNICODE_MATCH(string, offset, substring) \ + ((*((string)->str + (offset)) == *((substring)->str)) && \ + ((*((string)->str + (offset) + (substring)->length-1) == *((substring)->str + (substring)->length-1))) && \ +@@ -405,8 +410,6 @@ + extern "C" { + #endif + +-PyAPI_FUNC(int) PyUnicode_ClearFreeList(void); +- + /* --- Unicode Type ------------------------------------------------------- */ + + typedef struct { +@@ -605,6 +608,17 @@ + + PyAPI_FUNC(PyObject*) PyUnicode_FromOrdinal(int ordinal); + ++/* --- Free-list management ----------------------------------------------- */ ++ ++/* Clear the free list used by the Unicode implementation. ++ ++ This can be used to release memory used for objects on the free ++ list back to the Python memory allocator. ++ ++*/ ++ ++PyAPI_FUNC(int) PyUnicode_ClearFreeList(void); ++ + /* === Builtin Codecs ===================================================== + + Many of these APIs take two arguments encoding and errors. These +@@ -1323,6 +1337,10 @@ + + /* === Characters Type APIs =============================================== */ + ++/* Helper array used by Py_UNICODE_ISSPACE(). */ ++ ++PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[]; ++ + /* These should not be used directly. Use the Py_UNICODE_IS* and + Py_UNICODE_TO* macros instead. + +Index: Include/patchlevel.h +=================================================================== +--- Include/patchlevel.h (.../tags/r261) (Revision 70449) ++++ Include/patchlevel.h (.../branches/release26-maint) (Revision 70449) +@@ -27,7 +27,7 @@ + #define PY_RELEASE_SERIAL 0 + + /* Version as a string */ +-#define PY_VERSION "2.6.1" ++#define PY_VERSION "2.6.1+" + /*--end constants--*/ + + /* Subversion Revision number of this file (not of the repository) */ +Index: Include/abstract.h +=================================================================== +--- Include/abstract.h (.../tags/r261) (Revision 70449) ++++ Include/abstract.h (.../branches/release26-maint) (Revision 70449) +@@ -438,7 +438,7 @@ + /* + Guess the size of object o using len(o) or o.__length_hint__(). + If neither of those return a non-negative value, then return the +- default value. This function never fails. All exceptions are cleared. ++ default value. If one of the calls fails, this function returns -1. + */ + + PyAPI_FUNC(PyObject *) PyObject_GetItem(PyObject *o, PyObject *key); +Index: Include/pymacconfig.h +=================================================================== +--- Include/pymacconfig.h (.../tags/r261) (Revision 70449) ++++ Include/pymacconfig.h (.../branches/release26-maint) (Revision 70449) +@@ -15,6 +15,8 @@ + # undef SIZEOF_SIZE_T + # undef SIZEOF_TIME_T + # undef SIZEOF_VOID_P ++# undef SIZEOF__BOOL ++# undef WORDS_BIGENDIAN + + # undef VA_LIST_IS_ARRAY + # if defined(__LP64__) && defined(__x86_64__) +@@ -28,12 +30,19 @@ + + # undef SIZEOF_LONG + # ifdef __LP64__ ++# define SIZEOF__BOOL 1 ++# define SIZEOF__BOOL 1 + # define SIZEOF_LONG 8 + # define SIZEOF_PTHREAD_T 8 + # define SIZEOF_SIZE_T 8 + # define SIZEOF_TIME_T 8 + # define SIZEOF_VOID_P 8 + # else ++# ifdef __ppc__ ++# define SIZEOF__BOOL 4 ++# else ++# define SIZEOF__BOOL 1 ++# endif + # define SIZEOF_LONG 4 + # define SIZEOF_PTHREAD_T 4 + # define SIZEOF_SIZE_T 4 +@@ -54,6 +63,11 @@ + + # endif + ++#ifdef __BIG_ENDIAN__ ++#define WORDS_BIGENDIAN 1 ++#endif /* __BIG_ENDIAN */ ++ ++ + #endif /* defined(_APPLE__) */ + + #endif /* PYMACCONFIG_H */ +Index: configure.in +=================================================================== +--- configure.in (.../tags/r261) (Revision 70449) ++++ configure.in (.../branches/release26-maint) (Revision 70449) +@@ -1,7 +1,7 @@ + dnl *********************************************** + dnl * Please run autoreconf to test your changes! * + dnl *********************************************** +-dnl NOTE: autoconf 2.64 doesn't seem to work (use 2.63). ++dnl NOTE: autoconf 2.64 doesn't seem to work (use 2.61). + + # Set VERSION so we only need to edit in one place (i.e., here) + m4_define(PYTHON_VERSION, 2.6) +@@ -407,7 +407,7 @@ + AC_HELP_STRING(--without-gcc,never use gcc), + [ + case $withval in +- no) CC=cc ++ no) CC=${CC:-cc} + without_gcc=yes;; + yes) CC=gcc + without_gcc=no;; +@@ -737,6 +737,12 @@ + BLDLIBRARY='-L. -lpython$(VERSION)' + RUNSHARED=DLL_PATH=`pwd`:${DLL_PATH:-/atheos/sys/libs:/atheos/autolnk/lib} + ;; ++ Darwin*) ++ LDLIBRARY='libpython$(VERSION).dylib' ++ BLDLIBRARY='-L. -lpython$(VERSION)' ++ RUNSHARED='DYLD_LIBRARY_PATH=`pwd`:${DYLD_LIBRARY_PATH}' ++ ;; ++ + esac + else # shared is disabled + case $ac_sys_system in +@@ -1597,6 +1603,7 @@ + sleep 10 + fi + AC_MSG_RESULT($SO) ++ + AC_DEFINE_UNQUOTED(SHLIB_EXT, "$SO", [Define this to be extension of shared libraries (including the dot!).]) + # LDSHARED is the ld *command* used to create shared library + # -- "cc -G" on SunOS 5.x, "ld -shared" on IRIX 5 +@@ -1844,7 +1851,7 @@ + AC_CHECK_LIB(dl, dlopen) # Dynamic linking for SunOS/Solaris and SYSV + AC_CHECK_LIB(dld, shl_load) # Dynamic linking for HP-UX + +-# only check for sem_ini if thread support is requested ++# only check for sem_init if thread support is requested + if test "$with_threads" = "yes" -o -z "$with_threads"; then + AC_SEARCH_LIBS(sem_init, pthread rt posix4) # 'Real Time' functions on Solaris + # posix4 on Solaris 2.6 +@@ -3162,10 +3169,8 @@ + [Define if tanh(-0.) is -0., or if platform doesn't have signed zeros]) + fi + +-AC_REPLACE_FUNCS(hypot) ++AC_CHECK_FUNCS([acosh asinh atanh copysign expm1 finite hypot isinf isnan log1p]) + +-AC_CHECK_FUNCS(acosh asinh atanh copysign expm1 finite isinf isnan log1p) +- + LIBS=$LIBS_SAVE + + # check for wchar.h +Index: setup.py +=================================================================== +--- setup.py (.../tags/r261) (Revision 70449) ++++ setup.py (.../branches/release26-maint) (Revision 70449) +@@ -458,7 +458,8 @@ + # _json speedups + exts.append( Extension("_json", ["_json.c"]) ) + # Python C API test module +- exts.append( Extension('_testcapi', ['_testcapimodule.c']) ) ++ exts.append( Extension('_testcapi', ['_testcapimodule.c'], ++ depends=['testcapi_long.h']) ) + # profilers (_lsprof is for cProfile.py) + exts.append( Extension('_hotshot', ['_hotshot.c']) ) + exts.append( Extension('_lsprof', ['_lsprof.c', 'rotatingtree.c']) ) +@@ -1019,11 +1020,22 @@ + exts.append( Extension('dbm', ['dbmmodule.c'], + define_macros=[('HAVE_NDBM_H',None)], + libraries = ndbm_libs ) ) +- elif (self.compiler.find_library_file(lib_dirs, 'gdbm') +- and find_file("gdbm/ndbm.h", inc_dirs, []) is not None): +- exts.append( Extension('dbm', ['dbmmodule.c'], +- define_macros=[('HAVE_GDBM_NDBM_H',None)], +- libraries = ['gdbm'] ) ) ++ elif self.compiler.find_library_file(lib_dirs, 'gdbm'): ++ gdbm_libs = ['gdbm'] ++ if self.compiler.find_library_file(lib_dirs, 'gdbm_compat'): ++ gdbm_libs.append('gdbm_compat') ++ if find_file("gdbm/ndbm.h", inc_dirs, []) is not None: ++ exts.append( Extension( ++ 'dbm', ['dbmmodule.c'], ++ define_macros=[('HAVE_GDBM_NDBM_H',None)], ++ libraries = gdbm_libs ) ) ++ elif find_file("gdbm-ndbm.h", inc_dirs, []) is not None: ++ exts.append( Extension( ++ 'dbm', ['dbmmodule.c'], ++ define_macros=[('HAVE_GDBM_DASH_NDBM_H',None)], ++ libraries = gdbm_libs ) ) ++ else: ++ missing.append('dbm') + elif db_incs is not None: + exts.append( Extension('dbm', ['dbmmodule.c'], + library_dirs=dblib_dir, +@@ -1438,8 +1450,8 @@ + # different the UNIX search logic is not sharable. + from os.path import join, exists + framework_dirs = [ ++ '/Library/Frameworks', + '/System/Library/Frameworks/', +- '/Library/Frameworks', + join(os.getenv('HOME'), '/Library/Frameworks') + ] + +Index: Objects/abstract.c +=================================================================== +--- Objects/abstract.c (.../tags/r261) (Revision 70449) ++++ Objects/abstract.c (.../branches/release26-maint) (Revision 70449) +@@ -85,8 +85,8 @@ + + /* The length hint function returns a non-negative value from o.__len__() + or o.__length_hint__(). If those methods aren't found or return a negative +- value, then the defaultvalue is returned. This function never fails. +- Accordingly, it will mask exceptions raised in either method. ++ value, then the defaultvalue is returned. If one of the calls fails, ++ this function returns -1. + */ + + Py_ssize_t +@@ -100,29 +100,32 @@ + rv = PyObject_Size(o); + if (rv >= 0) + return rv; +- if (PyErr_Occurred()) ++ if (PyErr_Occurred()) { ++ if (!PyErr_ExceptionMatches(PyExc_TypeError) && ++ !PyErr_ExceptionMatches(PyExc_AttributeError)) ++ return -1; + PyErr_Clear(); ++ } + + /* cache a hashed version of the attribute string */ + if (hintstrobj == NULL) { + hintstrobj = PyString_InternFromString("__length_hint__"); + if (hintstrobj == NULL) +- goto defaultcase; ++ return -1; + } + + /* try o.__length_hint__() */ + ro = PyObject_CallMethodObjArgs(o, hintstrobj, NULL); +- if (ro == NULL) +- goto defaultcase; +- rv = PyInt_AsLong(ro); ++ if (ro == NULL) { ++ if (!PyErr_ExceptionMatches(PyExc_TypeError) && ++ !PyErr_ExceptionMatches(PyExc_AttributeError)) ++ return -1; ++ PyErr_Clear(); ++ return defaultvalue; ++ } ++ rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue; + Py_DECREF(ro); +- if (rv >= 0) +- return rv; +- +-defaultcase: +- if (PyErr_Occurred()) +- PyErr_Clear(); +- return defaultvalue; ++ return rv; + } + + PyObject * +@@ -2114,7 +2117,7 @@ + { + PyObject *it; /* iter(v) */ + Py_ssize_t n; /* guess for result tuple size */ +- PyObject *result; ++ PyObject *result = NULL; + Py_ssize_t j; + + if (v == NULL) +@@ -2139,6 +2142,8 @@ + + /* Guess result size and allocate space. */ + n = _PyObject_LengthHint(v, 10); ++ if (n == -1) ++ goto Fail; + result = PyTuple_New(n); + if (result == NULL) + goto Fail; +Index: Objects/object.c +=================================================================== +--- Objects/object.c (.../tags/r261) (Revision 70449) ++++ Objects/object.c (.../branches/release26-maint) (Revision 70449) +@@ -331,8 +331,11 @@ + if (op == NULL) + fprintf(stderr, "NULL\n"); + else { ++ PyGILState_STATE gil; + fprintf(stderr, "object : "); ++ gil = PyGILState_Ensure(); + (void)PyObject_Print(op, stderr, 0); ++ PyGILState_Release(gil); + /* XXX(twouters) cast refcount to long until %zd is + universally available */ + fprintf(stderr, "\n" +@@ -1020,7 +1023,7 @@ + fractpart = modf(v, &intpart); + if (fractpart == 0.0) { + /* This must return the same hash as an equal int or long. */ +- if (intpart > LONG_MAX || -intpart > LONG_MAX) { ++ if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) { + /* Convert to long and use its hash. */ + PyObject *plong; /* converted to Python long */ + if (Py_IS_INFINITY(intpart)) +@@ -1097,6 +1100,17 @@ + PyTypeObject *tp = v->ob_type; + if (tp->tp_hash != NULL) + return (*tp->tp_hash)(v); ++ /* To keep to the general practice that inheriting ++ * solely from object in C code should work without ++ * an explicit call to PyType_Ready, we implicitly call ++ * PyType_Ready here and then check the tp_hash slot again ++ */ ++ if (tp->tp_dict == NULL) { ++ if (PyType_Ready(tp) < 0) ++ return -1; ++ if (tp->tp_hash != NULL) ++ return (*tp->tp_hash)(v); ++ } + if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) { + return _Py_HashPointer(v); /* Use address as hash value */ + } +Index: Objects/dictobject.c +=================================================================== +--- Objects/dictobject.c (.../tags/r261) (Revision 70449) ++++ Objects/dictobject.c (.../branches/release26-maint) (Revision 70449) +@@ -2331,7 +2331,7 @@ + dictiter_new(PyDictObject *dict, PyTypeObject *itertype) + { + dictiterobject *di; +- di = PyObject_New(dictiterobject, itertype); ++ di = PyObject_GC_New(dictiterobject, itertype); + if (di == NULL) + return NULL; + Py_INCREF(dict); +@@ -2348,6 +2348,7 @@ + } + else + di->di_result = NULL; ++ _PyObject_GC_TRACK(di); + return (PyObject *)di; + } + +@@ -2356,9 +2357,17 @@ + { + Py_XDECREF(di->di_dict); + Py_XDECREF(di->di_result); +- PyObject_Del(di); ++ PyObject_GC_Del(di); + } + ++static int ++dictiter_traverse(dictiterobject *di, visitproc visit, void *arg) ++{ ++ Py_VISIT(di->di_dict); ++ Py_VISIT(di->di_result); ++ return 0; ++} ++ + static PyObject * + dictiter_len(dictiterobject *di) + { +@@ -2435,9 +2444,9 @@ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ +- Py_TPFLAGS_DEFAULT, /* tp_flags */ ++ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ +- 0, /* tp_traverse */ ++ (traverseproc)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +@@ -2507,9 +2516,9 @@ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ +- Py_TPFLAGS_DEFAULT, /* tp_flags */ ++ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ +- 0, /* tp_traverse */ ++ (traverseproc)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +@@ -2593,9 +2602,9 @@ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ +- Py_TPFLAGS_DEFAULT, /* tp_flags */ ++ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ +- 0, /* tp_traverse */ ++ (traverseproc)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +Index: Objects/unicodeobject.c +=================================================================== +--- Objects/unicodeobject.c (.../tags/r261) (Revision 70449) ++++ Objects/unicodeobject.c (.../branches/release26-maint) (Revision 70449) +@@ -12,8 +12,8 @@ + -------------------------------------------------------------------- + The original string type implementation is: + +- Copyright (c) 1999 by Secret Labs AB +- Copyright (c) 1999 by Fredrik Lundh ++ Copyright (c) 1999 by Secret Labs AB ++ Copyright (c) 1999 by Fredrik Lundh + + By obtaining, using, and/or copying this software and/or its + associated documentation, you agree that you have read, understood, +@@ -114,59 +114,59 @@ + + /* Fast detection of the most frequent whitespace characters */ + const unsigned char _Py_ascii_whitespace[] = { +- 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, + /* case 0x0009: * HORIZONTAL TABULATION */ + /* case 0x000A: * LINE FEED */ + /* case 0x000B: * VERTICAL TABULATION */ + /* case 0x000C: * FORM FEED */ + /* case 0x000D: * CARRIAGE RETURN */ +- 0, 1, 1, 1, 1, 1, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 1, 1, 1, 1, 1, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, + /* case 0x001C: * FILE SEPARATOR */ + /* case 0x001D: * GROUP SEPARATOR */ + /* case 0x001E: * RECORD SEPARATOR */ + /* case 0x001F: * UNIT SEPARATOR */ +- 0, 0, 0, 0, 1, 1, 1, 1, ++ 0, 0, 0, 0, 1, 1, 1, 1, + /* case 0x0020: * SPACE */ +- 1, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, ++ 1, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, + +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0 ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0 + }; + + /* Same for linebreaks */ + static unsigned char ascii_linebreak[] = { +- 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, + /* 0x000A, * LINE FEED */ + /* 0x000D, * CARRIAGE RETURN */ +- 0, 0, 1, 0, 0, 1, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 1, 0, 0, 1, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, + /* 0x001C, * FILE SEPARATOR */ + /* 0x001D, * GROUP SEPARATOR */ + /* 0x001E, * RECORD SEPARATOR */ +- 0, 0, 0, 0, 1, 1, 1, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 1, 1, 1, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, + +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0, +- 0, 0, 0, 0, 0, 0, 0, 0 ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0, ++ 0, 0, 0, 0, 0, 0, 0, 0 + }; + + +@@ -174,11 +174,11 @@ + PyUnicode_GetMax(void) + { + #ifdef Py_UNICODE_WIDE +- return 0x10FFFF; ++ return 0x10FFFF; + #else +- /* This is actually an illegal character, so it should +- not be passed to unichr. */ +- return 0xFFFF; ++ /* This is actually an illegal character, so it should ++ not be passed to unichr. */ ++ return 0xFFFF; + #endif + } + +@@ -196,9 +196,9 @@ + + #define BLOOM(mask, ch) ((mask & (1 << ((ch) & 0x1F)))) + +-#define BLOOM_LINEBREAK(ch) \ +- ((ch) < 128U ? ascii_linebreak[(ch)] : \ +- (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch))) ++#define BLOOM_LINEBREAK(ch) \ ++ ((ch) < 128U ? ascii_linebreak[(ch)] : \ ++ (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch))) + + Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len) + { +@@ -225,29 +225,29 @@ + return 0; + } + +-#define BLOOM_MEMBER(mask, chr, set, setlen)\ ++#define BLOOM_MEMBER(mask, chr, set, setlen) \ + BLOOM(mask, chr) && unicode_member(chr, set, setlen) + + /* --- Unicode Object ----------------------------------------------------- */ + + static + int unicode_resize(register PyUnicodeObject *unicode, +- Py_ssize_t length) ++ Py_ssize_t length) + { + void *oldstr; + + /* Shortcut if there's nothing much to do. */ + if (unicode->length == length) +- goto reset; ++ goto reset; + + /* Resizing shared object (unicode_empty or single character + objects) in-place is not allowed. Use PyUnicode_Resize() + instead ! */ + +- if (unicode == unicode_empty || +- (unicode->length == 1 && +- unicode->str[0] < 256U && +- unicode_latin1[unicode->str[0]] == unicode)) { ++ if (unicode == unicode_empty || ++ (unicode->length == 1 && ++ unicode->str[0] < 256U && ++ unicode_latin1[unicode->str[0]] == unicode)) { + PyErr_SetString(PyExc_SystemError, + "can't resize shared unicode objects"); + return -1; +@@ -260,16 +260,16 @@ + + oldstr = unicode->str; + unicode->str = PyObject_REALLOC(unicode->str, +- sizeof(Py_UNICODE) * (length + 1)); ++ sizeof(Py_UNICODE) * (length + 1)); + if (!unicode->str) { +- unicode->str = (Py_UNICODE *)oldstr; ++ unicode->str = (Py_UNICODE *)oldstr; + PyErr_NoMemory(); + return -1; + } + unicode->str[length] = 0; + unicode->length = length; + +- reset: ++ reset: + /* Reset the object caches */ + if (unicode->defenc) { + Py_DECREF(unicode->defenc); +@@ -284,7 +284,7 @@ + Ux0000 terminated -- XXX is this needed ? + + XXX This allocator could further be enhanced by assuring that the +- free list never reduces its size below 1. ++ free list never reduces its size below 1. + + */ + +@@ -309,33 +309,33 @@ + unicode = free_list; + free_list = *(PyUnicodeObject **)unicode; + numfree--; +- if (unicode->str) { +- /* Keep-Alive optimization: we only upsize the buffer, +- never downsize it. */ +- if ((unicode->length < length) && ++ if (unicode->str) { ++ /* Keep-Alive optimization: we only upsize the buffer, ++ never downsize it. */ ++ if ((unicode->length < length) && + unicode_resize(unicode, length) < 0) { +- PyObject_DEL(unicode->str); +- unicode->str = NULL; +- } +- } ++ PyObject_DEL(unicode->str); ++ unicode->str = NULL; ++ } ++ } + else { +- size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1); +- unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size); ++ size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1); ++ unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size); + } + PyObject_INIT(unicode, &PyUnicode_Type); + } + else { +- size_t new_size; ++ size_t new_size; + unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type); + if (unicode == NULL) + return NULL; +- new_size = sizeof(Py_UNICODE) * ((size_t)length + 1); +- unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size); ++ new_size = sizeof(Py_UNICODE) * ((size_t)length + 1); ++ unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size); + } + + if (!unicode->str) { +- PyErr_NoMemory(); +- goto onError; ++ PyErr_NoMemory(); ++ goto onError; + } + /* Initialize the first element to guard against cases where + * the caller fails before initializing str -- unicode_resize() +@@ -351,7 +351,7 @@ + unicode->defenc = NULL; + return unicode; + +- onError: ++ onError: + /* XXX UNREF/NEWREF interface should be more symmetrical */ + _Py_DEC_REFTOTAL; + _Py_ForgetReference((PyObject *)unicode); +@@ -363,57 +363,58 @@ + void unicode_dealloc(register PyUnicodeObject *unicode) + { + if (PyUnicode_CheckExact(unicode) && +- numfree < PyUnicode_MAXFREELIST) { ++ numfree < PyUnicode_MAXFREELIST) { + /* Keep-Alive optimization */ +- if (unicode->length >= KEEPALIVE_SIZE_LIMIT) { +- PyObject_DEL(unicode->str); +- unicode->str = NULL; +- unicode->length = 0; +- } +- if (unicode->defenc) { +- Py_DECREF(unicode->defenc); +- unicode->defenc = NULL; +- } +- /* Add to free list */ ++ if (unicode->length >= KEEPALIVE_SIZE_LIMIT) { ++ PyObject_DEL(unicode->str); ++ unicode->str = NULL; ++ unicode->length = 0; ++ } ++ if (unicode->defenc) { ++ Py_DECREF(unicode->defenc); ++ unicode->defenc = NULL; ++ } ++ /* Add to free list */ + *(PyUnicodeObject **)unicode = free_list; + free_list = unicode; + numfree++; + } + else { +- PyObject_DEL(unicode->str); +- Py_XDECREF(unicode->defenc); +- Py_TYPE(unicode)->tp_free((PyObject *)unicode); ++ PyObject_DEL(unicode->str); ++ Py_XDECREF(unicode->defenc); ++ Py_TYPE(unicode)->tp_free((PyObject *)unicode); + } + } + +-int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length) ++static ++int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length) + { + register PyUnicodeObject *v; + + /* Argument checks */ + if (unicode == NULL) { +- PyErr_BadInternalCall(); +- return -1; ++ PyErr_BadInternalCall(); ++ return -1; + } +- v = (PyUnicodeObject *)*unicode; ++ v = *unicode; + if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0) { +- PyErr_BadInternalCall(); +- return -1; ++ PyErr_BadInternalCall(); ++ return -1; + } + + /* Resizing unicode_empty and single character objects is not + possible since these are being shared. We simply return a fresh + copy with the same Unicode content. */ + if (v->length != length && +- (v == unicode_empty || v->length == 1)) { +- PyUnicodeObject *w = _PyUnicode_New(length); +- if (w == NULL) +- return -1; +- Py_UNICODE_COPY(w->str, v->str, +- length < v->length ? length : v->length); +- Py_DECREF(*unicode); +- *unicode = (PyObject *)w; +- return 0; ++ (v == unicode_empty || v->length == 1)) { ++ PyUnicodeObject *w = _PyUnicode_New(length); ++ if (w == NULL) ++ return -1; ++ Py_UNICODE_COPY(w->str, v->str, ++ length < v->length ? length : v->length); ++ Py_DECREF(*unicode); ++ *unicode = w; ++ return 0; + } + + /* Note that we don't have to modify *unicode for unshared Unicode +@@ -421,12 +422,13 @@ + return unicode_resize(v, length); + } + +-/* Internal API for use in unicodeobject.c only ! */ +-#define _PyUnicode_Resize(unicodevar, length) \ +- PyUnicode_Resize(((PyObject **)(unicodevar)), length) ++int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length) ++{ ++ return _PyUnicode_Resize((PyUnicodeObject **)unicode, length); ++} + + PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u, +- Py_ssize_t size) ++ Py_ssize_t size) + { + PyUnicodeObject *unicode; + +@@ -434,26 +436,26 @@ + some optimizations which share commonly used objects. */ + if (u != NULL) { + +- /* Optimization for empty strings */ +- if (size == 0 && unicode_empty != NULL) { +- Py_INCREF(unicode_empty); +- return (PyObject *)unicode_empty; +- } ++ /* Optimization for empty strings */ ++ if (size == 0 && unicode_empty != NULL) { ++ Py_INCREF(unicode_empty); ++ return (PyObject *)unicode_empty; ++ } + +- /* Single character Unicode objects in the Latin-1 range are +- shared when using this constructor */ +- if (size == 1 && *u < 256) { +- unicode = unicode_latin1[*u]; +- if (!unicode) { +- unicode = _PyUnicode_New(1); +- if (!unicode) +- return NULL; +- unicode->str[0] = *u; +- unicode_latin1[*u] = unicode; +- } +- Py_INCREF(unicode); +- return (PyObject *)unicode; +- } ++ /* Single character Unicode objects in the Latin-1 range are ++ shared when using this constructor */ ++ if (size == 1 && *u < 256) { ++ unicode = unicode_latin1[*u]; ++ if (!unicode) { ++ unicode = _PyUnicode_New(1); ++ if (!unicode) ++ return NULL; ++ unicode->str[0] = *u; ++ unicode_latin1[*u] = unicode; ++ } ++ Py_INCREF(unicode); ++ return (PyObject *)unicode; ++ } + } + + unicode = _PyUnicode_New(size); +@@ -462,7 +464,7 @@ + + /* Copy the Unicode data into the new object */ + if (u != NULL) +- Py_UNICODE_COPY(unicode->str, u, size); ++ Py_UNICODE_COPY(unicode->str, u, size); + + return (PyObject *)unicode; + } +@@ -471,11 +473,11 @@ + { + PyUnicodeObject *unicode; + +- if (size < 0) { +- PyErr_SetString(PyExc_SystemError, +- "Negative size passed to PyUnicode_FromStringAndSize"); +- return NULL; +- } ++ if (size < 0) { ++ PyErr_SetString(PyExc_SystemError, ++ "Negative size passed to PyUnicode_FromStringAndSize"); ++ return NULL; ++ } + + /* If the Unicode data is known at construction time, we can apply + some optimizations which share commonly used objects. +@@ -483,26 +485,26 @@ + UTF-8 decoder at the end. */ + if (u != NULL) { + +- /* Optimization for empty strings */ +- if (size == 0 && unicode_empty != NULL) { +- Py_INCREF(unicode_empty); +- return (PyObject *)unicode_empty; +- } ++ /* Optimization for empty strings */ ++ if (size == 0 && unicode_empty != NULL) { ++ Py_INCREF(unicode_empty); ++ return (PyObject *)unicode_empty; ++ } + +- /* Single characters are shared when using this constructor. ++ /* Single characters are shared when using this constructor. + Restrict to ASCII, since the input must be UTF-8. */ +- if (size == 1 && Py_CHARMASK(*u) < 128) { +- unicode = unicode_latin1[Py_CHARMASK(*u)]; +- if (!unicode) { +- unicode = _PyUnicode_New(1); +- if (!unicode) +- return NULL; +- unicode->str[0] = Py_CHARMASK(*u); +- unicode_latin1[Py_CHARMASK(*u)] = unicode; +- } +- Py_INCREF(unicode); +- return (PyObject *)unicode; +- } ++ if (size == 1 && Py_CHARMASK(*u) < 128) { ++ unicode = unicode_latin1[Py_CHARMASK(*u)]; ++ if (!unicode) { ++ unicode = _PyUnicode_New(1); ++ if (!unicode) ++ return NULL; ++ unicode->str[0] = Py_CHARMASK(*u); ++ unicode_latin1[Py_CHARMASK(*u)] = unicode; ++ } ++ Py_INCREF(unicode); ++ return (PyObject *)unicode; ++ } + + return PyUnicode_DecodeUTF8(u, size, NULL); + } +@@ -528,13 +530,13 @@ + #ifdef HAVE_WCHAR_H + + PyObject *PyUnicode_FromWideChar(register const wchar_t *w, +- Py_ssize_t size) ++ Py_ssize_t size) + { + PyUnicodeObject *unicode; + + if (w == NULL) { +- PyErr_BadInternalCall(); +- return NULL; ++ PyErr_BadInternalCall(); ++ return NULL; + } + + unicode = _PyUnicode_New(size); +@@ -546,11 +548,11 @@ + memcpy(unicode->str, w, size * sizeof(wchar_t)); + #else + { +- register Py_UNICODE *u; +- register Py_ssize_t i; +- u = PyUnicode_AS_UNICODE(unicode); +- for (i = size; i > 0; i--) +- *u++ = *w++; ++ register Py_UNICODE *u; ++ register Py_ssize_t i; ++ u = PyUnicode_AS_UNICODE(unicode); ++ for (i = size; i > 0; i--) ++ *u++ = *w++; + } + #endif + +@@ -560,23 +562,23 @@ + static void + makefmt(char *fmt, int longflag, int size_tflag, int zeropad, int width, int precision, char c) + { +- *fmt++ = '%'; +- if (width) { +- if (zeropad) +- *fmt++ = '0'; +- fmt += sprintf(fmt, "%d", width); +- } +- if (precision) +- fmt += sprintf(fmt, ".%d", precision); +- if (longflag) +- *fmt++ = 'l'; +- else if (size_tflag) { +- char *f = PY_FORMAT_SIZE_T; +- while (*f) +- *fmt++ = *f++; +- } +- *fmt++ = c; +- *fmt = '\0'; ++ *fmt++ = '%'; ++ if (width) { ++ if (zeropad) ++ *fmt++ = '0'; ++ fmt += sprintf(fmt, "%d", width); ++ } ++ if (precision) ++ fmt += sprintf(fmt, ".%d", precision); ++ if (longflag) ++ *fmt++ = 'l'; ++ else if (size_tflag) { ++ char *f = PY_FORMAT_SIZE_T; ++ while (*f) ++ *fmt++ = *f++; ++ } ++ *fmt++ = c; ++ *fmt = '\0'; + } + + #define appendstring(string) {for (copy = string;*copy;) *s++ = *copy++;} +@@ -584,373 +586,373 @@ + PyObject * + PyUnicode_FromFormatV(const char *format, va_list vargs) + { +- va_list count; +- Py_ssize_t callcount = 0; +- PyObject **callresults = NULL; +- PyObject **callresult = NULL; +- Py_ssize_t n = 0; +- int width = 0; +- int precision = 0; +- int zeropad; +- const char* f; +- Py_UNICODE *s; +- PyObject *string; +- /* used by sprintf */ +- char buffer[21]; +- /* use abuffer instead of buffer, if we need more space +- * (which can happen if there's a format specifier with width). */ +- char *abuffer = NULL; +- char *realbuffer; +- Py_ssize_t abuffersize = 0; +- char fmt[60]; /* should be enough for %0width.precisionld */ +- const char *copy; ++ va_list count; ++ Py_ssize_t callcount = 0; ++ PyObject **callresults = NULL; ++ PyObject **callresult = NULL; ++ Py_ssize_t n = 0; ++ int width = 0; ++ int precision = 0; ++ int zeropad; ++ const char* f; ++ Py_UNICODE *s; ++ PyObject *string; ++ /* used by sprintf */ ++ char buffer[21]; ++ /* use abuffer instead of buffer, if we need more space ++ * (which can happen if there's a format specifier with width). */ ++ char *abuffer = NULL; ++ char *realbuffer; ++ Py_ssize_t abuffersize = 0; ++ char fmt[60]; /* should be enough for %0width.precisionld */ ++ const char *copy; + + #ifdef VA_LIST_IS_ARRAY +- Py_MEMCPY(count, vargs, sizeof(va_list)); ++ Py_MEMCPY(count, vargs, sizeof(va_list)); + #else + #ifdef __va_copy +- __va_copy(count, vargs); ++ __va_copy(count, vargs); + #else +- count = vargs; ++ count = vargs; + #endif + #endif +- /* step 1: count the number of %S/%R format specifications +- * (we call PyObject_Str()/PyObject_Repr() for these objects +- * once during step 3 and put the result in an array) */ +- for (f = format; *f; f++) { +- if (*f == '%' && (*(f+1)=='S' || *(f+1)=='R')) +- ++callcount; +- } +- /* step 2: allocate memory for the results of +- * PyObject_Str()/PyObject_Repr() calls */ +- if (callcount) { +- callresults = PyObject_Malloc(sizeof(PyObject *)*callcount); +- if (!callresults) { +- PyErr_NoMemory(); +- return NULL; +- } +- callresult = callresults; +- } +- /* step 3: figure out how large a buffer we need */ +- for (f = format; *f; f++) { +- if (*f == '%') { +- const char* p = f; +- width = 0; +- while (isdigit((unsigned)*f)) +- width = (width*10) + *f++ - '0'; +- while (*++f && *f != '%' && !isalpha((unsigned)*f)) +- ; ++ /* step 1: count the number of %S/%R format specifications ++ * (we call PyObject_Str()/PyObject_Repr() for these objects ++ * once during step 3 and put the result in an array) */ ++ for (f = format; *f; f++) { ++ if (*f == '%' && (*(f+1)=='S' || *(f+1)=='R')) ++ ++callcount; ++ } ++ /* step 2: allocate memory for the results of ++ * PyObject_Str()/PyObject_Repr() calls */ ++ if (callcount) { ++ callresults = PyObject_Malloc(sizeof(PyObject *)*callcount); ++ if (!callresults) { ++ PyErr_NoMemory(); ++ return NULL; ++ } ++ callresult = callresults; ++ } ++ /* step 3: figure out how large a buffer we need */ ++ for (f = format; *f; f++) { ++ if (*f == '%') { ++ const char* p = f; ++ width = 0; ++ while (isdigit((unsigned)*f)) ++ width = (width*10) + *f++ - '0'; ++ while (*++f && *f != '%' && !isalpha((unsigned)*f)) ++ ; + +- /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since +- * they don't affect the amount of space we reserve. +- */ +- if ((*f == 'l' || *f == 'z') && +- (f[1] == 'd' || f[1] == 'u')) +- ++f; ++ /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since ++ * they don't affect the amount of space we reserve. ++ */ ++ if ((*f == 'l' || *f == 'z') && ++ (f[1] == 'd' || f[1] == 'u')) ++ ++f; + +- switch (*f) { +- case 'c': +- (void)va_arg(count, int); +- /* fall through... */ +- case '%': +- n++; +- break; +- case 'd': case 'u': case 'i': case 'x': +- (void) va_arg(count, int); +- /* 20 bytes is enough to hold a 64-bit +- integer. Decimal takes the most space. +- This isn't enough for octal. +- If a width is specified we need more +- (which we allocate later). */ +- if (width < 20) +- width = 20; +- n += width; +- if (abuffersize < width) +- abuffersize = width; +- break; +- case 's': +- { +- /* UTF-8 */ +- unsigned char*s; +- s = va_arg(count, unsigned char*); +- while (*s) { +- if (*s < 128) { +- n++; s++; +- } else if (*s < 0xc0) { +- /* invalid UTF-8 */ +- n++; s++; +- } else if (*s < 0xc0) { +- n++; +- s++; if(!*s)break; +- s++; +- } else if (*s < 0xe0) { +- n++; +- s++; if(!*s)break; +- s++; if(!*s)break; +- s++; +- } else { +- #ifdef Py_UNICODE_WIDE +- n++; +- #else +- n+=2; +- #endif +- s++; if(!*s)break; +- s++; if(!*s)break; +- s++; if(!*s)break; +- s++; +- } +- } +- break; +- } +- case 'U': +- { +- PyObject *obj = va_arg(count, PyObject *); +- assert(obj && PyUnicode_Check(obj)); +- n += PyUnicode_GET_SIZE(obj); +- break; +- } +- case 'V': +- { +- PyObject *obj = va_arg(count, PyObject *); +- const char *str = va_arg(count, const char *); +- assert(obj || str); +- assert(!obj || PyUnicode_Check(obj)); +- if (obj) +- n += PyUnicode_GET_SIZE(obj); +- else +- n += strlen(str); +- break; +- } +- case 'S': +- { +- PyObject *obj = va_arg(count, PyObject *); +- PyObject *str; +- assert(obj); +- str = PyObject_Str(obj); +- if (!str) +- goto fail; +- n += PyUnicode_GET_SIZE(str); +- /* Remember the str and switch to the next slot */ +- *callresult++ = str; +- break; +- } +- case 'R': +- { +- PyObject *obj = va_arg(count, PyObject *); +- PyObject *repr; +- assert(obj); +- repr = PyObject_Repr(obj); +- if (!repr) +- goto fail; +- n += PyUnicode_GET_SIZE(repr); +- /* Remember the repr and switch to the next slot */ +- *callresult++ = repr; +- break; +- } +- case 'p': +- (void) va_arg(count, int); +- /* maximum 64-bit pointer representation: +- * 0xffffffffffffffff +- * so 19 characters is enough. +- * XXX I count 18 -- what's the extra for? +- */ +- n += 19; +- break; +- default: +- /* if we stumble upon an unknown +- formatting code, copy the rest of +- the format string to the output +- string. (we cannot just skip the +- code, since there's no way to know +- what's in the argument list) */ +- n += strlen(p); +- goto expand; +- } +- } else +- n++; +- } +- expand: +- if (abuffersize > 20) { +- abuffer = PyObject_Malloc(abuffersize); +- if (!abuffer) { +- PyErr_NoMemory(); +- goto fail; +- } +- realbuffer = abuffer; +- } +- else +- realbuffer = buffer; +- /* step 4: fill the buffer */ +- /* Since we've analyzed how much space we need for the worst case, +- we don't have to resize the string. +- There can be no errors beyond this point. */ +- string = PyUnicode_FromUnicode(NULL, n); +- if (!string) +- goto fail; ++ switch (*f) { ++ case 'c': ++ (void)va_arg(count, int); ++ /* fall through... */ ++ case '%': ++ n++; ++ break; ++ case 'd': case 'u': case 'i': case 'x': ++ (void) va_arg(count, int); ++ /* 20 bytes is enough to hold a 64-bit ++ integer. Decimal takes the most space. ++ This isn't enough for octal. ++ If a width is specified we need more ++ (which we allocate later). */ ++ if (width < 20) ++ width = 20; ++ n += width; ++ if (abuffersize < width) ++ abuffersize = width; ++ break; ++ case 's': ++ { ++ /* UTF-8 */ ++ unsigned char*s; ++ s = va_arg(count, unsigned char*); ++ while (*s) { ++ if (*s < 128) { ++ n++; s++; ++ } else if (*s < 0xc0) { ++ /* invalid UTF-8 */ ++ n++; s++; ++ } else if (*s < 0xc0) { ++ n++; ++ s++; if(!*s)break; ++ s++; ++ } else if (*s < 0xe0) { ++ n++; ++ s++; if(!*s)break; ++ s++; if(!*s)break; ++ s++; ++ } else { ++#ifdef Py_UNICODE_WIDE ++ n++; ++#else ++ n+=2; ++#endif ++ s++; if(!*s)break; ++ s++; if(!*s)break; ++ s++; if(!*s)break; ++ s++; ++ } ++ } ++ break; ++ } ++ case 'U': ++ { ++ PyObject *obj = va_arg(count, PyObject *); ++ assert(obj && PyUnicode_Check(obj)); ++ n += PyUnicode_GET_SIZE(obj); ++ break; ++ } ++ case 'V': ++ { ++ PyObject *obj = va_arg(count, PyObject *); ++ const char *str = va_arg(count, const char *); ++ assert(obj || str); ++ assert(!obj || PyUnicode_Check(obj)); ++ if (obj) ++ n += PyUnicode_GET_SIZE(obj); ++ else ++ n += strlen(str); ++ break; ++ } ++ case 'S': ++ { ++ PyObject *obj = va_arg(count, PyObject *); ++ PyObject *str; ++ assert(obj); ++ str = PyObject_Str(obj); ++ if (!str) ++ goto fail; ++ n += PyUnicode_GET_SIZE(str); ++ /* Remember the str and switch to the next slot */ ++ *callresult++ = str; ++ break; ++ } ++ case 'R': ++ { ++ PyObject *obj = va_arg(count, PyObject *); ++ PyObject *repr; ++ assert(obj); ++ repr = PyObject_Repr(obj); ++ if (!repr) ++ goto fail; ++ n += PyUnicode_GET_SIZE(repr); ++ /* Remember the repr and switch to the next slot */ ++ *callresult++ = repr; ++ break; ++ } ++ case 'p': ++ (void) va_arg(count, int); ++ /* maximum 64-bit pointer representation: ++ * 0xffffffffffffffff ++ * so 19 characters is enough. ++ * XXX I count 18 -- what's the extra for? ++ */ ++ n += 19; ++ break; ++ default: ++ /* if we stumble upon an unknown ++ formatting code, copy the rest of ++ the format string to the output ++ string. (we cannot just skip the ++ code, since there's no way to know ++ what's in the argument list) */ ++ n += strlen(p); ++ goto expand; ++ } ++ } else ++ n++; ++ } ++ expand: ++ if (abuffersize > 20) { ++ abuffer = PyObject_Malloc(abuffersize); ++ if (!abuffer) { ++ PyErr_NoMemory(); ++ goto fail; ++ } ++ realbuffer = abuffer; ++ } ++ else ++ realbuffer = buffer; ++ /* step 4: fill the buffer */ ++ /* Since we've analyzed how much space we need for the worst case, ++ we don't have to resize the string. ++ There can be no errors beyond this point. */ ++ string = PyUnicode_FromUnicode(NULL, n); ++ if (!string) ++ goto fail; + +- s = PyUnicode_AS_UNICODE(string); +- callresult = callresults; ++ s = PyUnicode_AS_UNICODE(string); ++ callresult = callresults; + +- for (f = format; *f; f++) { +- if (*f == '%') { +- const char* p = f++; +- int longflag = 0; +- int size_tflag = 0; +- zeropad = (*f == '0'); +- /* parse the width.precision part */ +- width = 0; +- while (isdigit((unsigned)*f)) +- width = (width*10) + *f++ - '0'; +- precision = 0; +- if (*f == '.') { +- f++; +- while (isdigit((unsigned)*f)) +- precision = (precision*10) + *f++ - '0'; +- } +- /* handle the long flag, but only for %ld and %lu. +- others can be added when necessary. */ +- if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { +- longflag = 1; +- ++f; +- } +- /* handle the size_t flag. */ +- if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { +- size_tflag = 1; +- ++f; +- } ++ for (f = format; *f; f++) { ++ if (*f == '%') { ++ const char* p = f++; ++ int longflag = 0; ++ int size_tflag = 0; ++ zeropad = (*f == '0'); ++ /* parse the width.precision part */ ++ width = 0; ++ while (isdigit((unsigned)*f)) ++ width = (width*10) + *f++ - '0'; ++ precision = 0; ++ if (*f == '.') { ++ f++; ++ while (isdigit((unsigned)*f)) ++ precision = (precision*10) + *f++ - '0'; ++ } ++ /* handle the long flag, but only for %ld and %lu. ++ others can be added when necessary. */ ++ if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { ++ longflag = 1; ++ ++f; ++ } ++ /* handle the size_t flag. */ ++ if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { ++ size_tflag = 1; ++ ++f; ++ } + +- switch (*f) { +- case 'c': +- *s++ = va_arg(vargs, int); +- break; +- case 'd': +- makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'd'); +- if (longflag) +- sprintf(realbuffer, fmt, va_arg(vargs, long)); +- else if (size_tflag) +- sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t)); +- else +- sprintf(realbuffer, fmt, va_arg(vargs, int)); +- appendstring(realbuffer); +- break; +- case 'u': +- makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'u'); +- if (longflag) +- sprintf(realbuffer, fmt, va_arg(vargs, unsigned long)); +- else if (size_tflag) +- sprintf(realbuffer, fmt, va_arg(vargs, size_t)); +- else +- sprintf(realbuffer, fmt, va_arg(vargs, unsigned int)); +- appendstring(realbuffer); +- break; +- case 'i': +- makefmt(fmt, 0, 0, zeropad, width, precision, 'i'); +- sprintf(realbuffer, fmt, va_arg(vargs, int)); +- appendstring(realbuffer); +- break; +- case 'x': +- makefmt(fmt, 0, 0, zeropad, width, precision, 'x'); +- sprintf(realbuffer, fmt, va_arg(vargs, int)); +- appendstring(realbuffer); +- break; +- case 's': +- { +- /* Parameter must be UTF-8 encoded. +- In case of encoding errors, use +- the replacement character. */ +- PyObject *u; +- p = va_arg(vargs, char*); +- u = PyUnicode_DecodeUTF8(p, strlen(p), +- "replace"); +- if (!u) +- goto fail; +- Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(u), +- PyUnicode_GET_SIZE(u)); +- s += PyUnicode_GET_SIZE(u); +- Py_DECREF(u); +- break; +- } +- case 'U': +- { +- PyObject *obj = va_arg(vargs, PyObject *); +- Py_ssize_t size = PyUnicode_GET_SIZE(obj); +- Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size); +- s += size; +- break; +- } +- case 'V': +- { +- PyObject *obj = va_arg(vargs, PyObject *); +- const char *str = va_arg(vargs, const char *); +- if (obj) { +- Py_ssize_t size = PyUnicode_GET_SIZE(obj); +- Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size); +- s += size; +- } else { +- appendstring(str); +- } +- break; +- } +- case 'S': +- case 'R': +- { +- Py_UNICODE *ucopy; +- Py_ssize_t usize; +- Py_ssize_t upos; +- /* unused, since we already have the result */ +- (void) va_arg(vargs, PyObject *); +- ucopy = PyUnicode_AS_UNICODE(*callresult); +- usize = PyUnicode_GET_SIZE(*callresult); +- for (upos = 0; upos forget it */ +- Py_DECREF(*callresult); +- /* switch to next unicode()/repr() result */ +- ++callresult; +- break; +- } +- case 'p': +- sprintf(buffer, "%p", va_arg(vargs, void*)); +- /* %p is ill-defined: ensure leading 0x. */ +- if (buffer[1] == 'X') +- buffer[1] = 'x'; +- else if (buffer[1] != 'x') { +- memmove(buffer+2, buffer, strlen(buffer)+1); +- buffer[0] = '0'; +- buffer[1] = 'x'; +- } +- appendstring(buffer); +- break; +- case '%': +- *s++ = '%'; +- break; +- default: +- appendstring(p); +- goto end; +- } +- } else +- *s++ = *f; +- } ++ switch (*f) { ++ case 'c': ++ *s++ = va_arg(vargs, int); ++ break; ++ case 'd': ++ makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'd'); ++ if (longflag) ++ sprintf(realbuffer, fmt, va_arg(vargs, long)); ++ else if (size_tflag) ++ sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t)); ++ else ++ sprintf(realbuffer, fmt, va_arg(vargs, int)); ++ appendstring(realbuffer); ++ break; ++ case 'u': ++ makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'u'); ++ if (longflag) ++ sprintf(realbuffer, fmt, va_arg(vargs, unsigned long)); ++ else if (size_tflag) ++ sprintf(realbuffer, fmt, va_arg(vargs, size_t)); ++ else ++ sprintf(realbuffer, fmt, va_arg(vargs, unsigned int)); ++ appendstring(realbuffer); ++ break; ++ case 'i': ++ makefmt(fmt, 0, 0, zeropad, width, precision, 'i'); ++ sprintf(realbuffer, fmt, va_arg(vargs, int)); ++ appendstring(realbuffer); ++ break; ++ case 'x': ++ makefmt(fmt, 0, 0, zeropad, width, precision, 'x'); ++ sprintf(realbuffer, fmt, va_arg(vargs, int)); ++ appendstring(realbuffer); ++ break; ++ case 's': ++ { ++ /* Parameter must be UTF-8 encoded. ++ In case of encoding errors, use ++ the replacement character. */ ++ PyObject *u; ++ p = va_arg(vargs, char*); ++ u = PyUnicode_DecodeUTF8(p, strlen(p), ++ "replace"); ++ if (!u) ++ goto fail; ++ Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(u), ++ PyUnicode_GET_SIZE(u)); ++ s += PyUnicode_GET_SIZE(u); ++ Py_DECREF(u); ++ break; ++ } ++ case 'U': ++ { ++ PyObject *obj = va_arg(vargs, PyObject *); ++ Py_ssize_t size = PyUnicode_GET_SIZE(obj); ++ Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size); ++ s += size; ++ break; ++ } ++ case 'V': ++ { ++ PyObject *obj = va_arg(vargs, PyObject *); ++ const char *str = va_arg(vargs, const char *); ++ if (obj) { ++ Py_ssize_t size = PyUnicode_GET_SIZE(obj); ++ Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size); ++ s += size; ++ } else { ++ appendstring(str); ++ } ++ break; ++ } ++ case 'S': ++ case 'R': ++ { ++ Py_UNICODE *ucopy; ++ Py_ssize_t usize; ++ Py_ssize_t upos; ++ /* unused, since we already have the result */ ++ (void) va_arg(vargs, PyObject *); ++ ucopy = PyUnicode_AS_UNICODE(*callresult); ++ usize = PyUnicode_GET_SIZE(*callresult); ++ for (upos = 0; upos forget it */ ++ Py_DECREF(*callresult); ++ /* switch to next unicode()/repr() result */ ++ ++callresult; ++ break; ++ } ++ case 'p': ++ sprintf(buffer, "%p", va_arg(vargs, void*)); ++ /* %p is ill-defined: ensure leading 0x. */ ++ if (buffer[1] == 'X') ++ buffer[1] = 'x'; ++ else if (buffer[1] != 'x') { ++ memmove(buffer+2, buffer, strlen(buffer)+1); ++ buffer[0] = '0'; ++ buffer[1] = 'x'; ++ } ++ appendstring(buffer); ++ break; ++ case '%': ++ *s++ = '%'; ++ break; ++ default: ++ appendstring(p); ++ goto end; ++ } ++ } else ++ *s++ = *f; ++ } + +- end: +- if (callresults) +- PyObject_Free(callresults); +- if (abuffer) +- PyObject_Free(abuffer); +- _PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string)); +- return string; +- fail: +- if (callresults) { +- PyObject **callresult2 = callresults; +- while (callresult2 < callresult) { +- Py_DECREF(*callresult2); +- ++callresult2; +- } +- PyObject_Free(callresults); +- } +- if (abuffer) +- PyObject_Free(abuffer); +- return NULL; ++ end: ++ if (callresults) ++ PyObject_Free(callresults); ++ if (abuffer) ++ PyObject_Free(abuffer); ++ PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string)); ++ return string; ++ fail: ++ if (callresults) { ++ PyObject **callresult2 = callresults; ++ while (callresult2 < callresult) { ++ Py_DECREF(*callresult2); ++ ++callresult2; ++ } ++ PyObject_Free(callresults); ++ } ++ if (abuffer) ++ PyObject_Free(abuffer); ++ return NULL; + } + + #undef appendstring +@@ -958,48 +960,48 @@ + PyObject * + PyUnicode_FromFormat(const char *format, ...) + { +- PyObject* ret; +- va_list vargs; ++ PyObject* ret; ++ va_list vargs; + + #ifdef HAVE_STDARG_PROTOTYPES +- va_start(vargs, format); ++ va_start(vargs, format); + #else +- va_start(vargs); ++ va_start(vargs); + #endif +- ret = PyUnicode_FromFormatV(format, vargs); +- va_end(vargs); +- return ret; ++ ret = PyUnicode_FromFormatV(format, vargs); ++ va_end(vargs); ++ return ret; + } + + Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode, +- wchar_t *w, +- Py_ssize_t size) ++ wchar_t *w, ++ Py_ssize_t size) + { + if (unicode == NULL) { +- PyErr_BadInternalCall(); +- return -1; ++ PyErr_BadInternalCall(); ++ return -1; + } + + /* If possible, try to copy the 0-termination as well */ + if (size > PyUnicode_GET_SIZE(unicode)) +- size = PyUnicode_GET_SIZE(unicode) + 1; ++ size = PyUnicode_GET_SIZE(unicode) + 1; + + #ifdef HAVE_USABLE_WCHAR_T + memcpy(w, unicode->str, size * sizeof(wchar_t)); + #else + { +- register Py_UNICODE *u; +- register Py_ssize_t i; +- u = PyUnicode_AS_UNICODE(unicode); +- for (i = size; i > 0; i--) +- *w++ = *u++; ++ register Py_UNICODE *u; ++ register Py_ssize_t i; ++ u = PyUnicode_AS_UNICODE(unicode); ++ for (i = size; i > 0; i--) ++ *w++ = *u++; + } + #endif + + if (size > PyUnicode_GET_SIZE(unicode)) + return PyUnicode_GET_SIZE(unicode); + else +- return size; ++ return size; + } + + #endif +@@ -1010,17 +1012,17 @@ + + #ifdef Py_UNICODE_WIDE + if (ordinal < 0 || ordinal > 0x10ffff) { +- PyErr_SetString(PyExc_ValueError, +- "unichr() arg not in range(0x110000) " +- "(wide Python build)"); +- return NULL; ++ PyErr_SetString(PyExc_ValueError, ++ "unichr() arg not in range(0x110000) " ++ "(wide Python build)"); ++ return NULL; + } + #else + if (ordinal < 0 || ordinal > 0xffff) { +- PyErr_SetString(PyExc_ValueError, +- "unichr() arg not in range(0x10000) " +- "(narrow Python build)"); +- return NULL; ++ PyErr_SetString(PyExc_ValueError, ++ "unichr() arg not in range(0x10000) " ++ "(narrow Python build)"); ++ return NULL; + } + #endif + +@@ -1031,31 +1033,31 @@ + PyObject *PyUnicode_FromObject(register PyObject *obj) + { + /* XXX Perhaps we should make this API an alias of +- PyObject_Unicode() instead ?! */ ++ PyObject_Unicode() instead ?! */ + if (PyUnicode_CheckExact(obj)) { +- Py_INCREF(obj); +- return obj; ++ Py_INCREF(obj); ++ return obj; + } + if (PyUnicode_Check(obj)) { +- /* For a Unicode subtype that's not a Unicode object, +- return a true Unicode object with the same data. */ +- return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj), +- PyUnicode_GET_SIZE(obj)); ++ /* For a Unicode subtype that's not a Unicode object, ++ return a true Unicode object with the same data. */ ++ return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj), ++ PyUnicode_GET_SIZE(obj)); + } + return PyUnicode_FromEncodedObject(obj, NULL, "strict"); + } + + PyObject *PyUnicode_FromEncodedObject(register PyObject *obj, +- const char *encoding, +- const char *errors) ++ const char *encoding, ++ const char *errors) + { + const char *s = NULL; + Py_ssize_t len; + PyObject *v; + + if (obj == NULL) { +- PyErr_BadInternalCall(); +- return NULL; ++ PyErr_BadInternalCall(); ++ return NULL; + } + + #if 0 +@@ -1065,29 +1067,29 @@ + Unicode subclasses. + + NOTE: This API should really only be used for object which +- represent *encoded* Unicode ! ++ represent *encoded* Unicode ! + + */ +- if (PyUnicode_Check(obj)) { +- if (encoding) { +- PyErr_SetString(PyExc_TypeError, +- "decoding Unicode is not supported"); +- return NULL; +- } +- return PyObject_Unicode(obj); +- } ++ if (PyUnicode_Check(obj)) { ++ if (encoding) { ++ PyErr_SetString(PyExc_TypeError, ++ "decoding Unicode is not supported"); ++ return NULL; ++ } ++ return PyObject_Unicode(obj); ++ } + #else + if (PyUnicode_Check(obj)) { +- PyErr_SetString(PyExc_TypeError, +- "decoding Unicode is not supported"); +- return NULL; +- } ++ PyErr_SetString(PyExc_TypeError, ++ "decoding Unicode is not supported"); ++ return NULL; ++ } + #endif + + /* Coerce object */ + if (PyString_Check(obj)) { +- s = PyString_AS_STRING(obj); +- len = PyString_GET_SIZE(obj); ++ s = PyString_AS_STRING(obj); ++ len = PyString_GET_SIZE(obj); + } + else if (PyByteArray_Check(obj)) { + /* Python 2.x specific */ +@@ -1096,39 +1098,39 @@ + return NULL; + } + else if (PyObject_AsCharBuffer(obj, &s, &len)) { +- /* Overwrite the error message with something more useful in +- case of a TypeError. */ +- if (PyErr_ExceptionMatches(PyExc_TypeError)) +- PyErr_Format(PyExc_TypeError, +- "coercing to Unicode: need string or buffer, " +- "%.80s found", +- Py_TYPE(obj)->tp_name); +- goto onError; ++ /* Overwrite the error message with something more useful in ++ case of a TypeError. */ ++ if (PyErr_ExceptionMatches(PyExc_TypeError)) ++ PyErr_Format(PyExc_TypeError, ++ "coercing to Unicode: need string or buffer, " ++ "%.80s found", ++ Py_TYPE(obj)->tp_name); ++ goto onError; + } + + /* Convert to Unicode */ + if (len == 0) { +- Py_INCREF(unicode_empty); +- v = (PyObject *)unicode_empty; ++ Py_INCREF(unicode_empty); ++ v = (PyObject *)unicode_empty; + } + else +- v = PyUnicode_Decode(s, len, encoding, errors); ++ v = PyUnicode_Decode(s, len, encoding, errors); + + return v; + +- onError: ++ onError: + return NULL; + } + + PyObject *PyUnicode_Decode(const char *s, +- Py_ssize_t size, +- const char *encoding, +- const char *errors) ++ Py_ssize_t size, ++ const char *encoding, ++ const char *errors) + { + PyObject *buffer = NULL, *unicode; + + if (encoding == NULL) +- encoding = PyUnicode_GetDefaultEncoding(); ++ encoding = PyUnicode_GetDefaultEncoding(); + + /* Shortcuts for common default encodings */ + if (strcmp(encoding, "utf-8") == 0) +@@ -1159,7 +1161,7 @@ + Py_DECREF(buffer); + return unicode; + +- onError: ++ onError: + Py_XDECREF(buffer); + return NULL; + } +@@ -1176,7 +1178,7 @@ + } + + if (encoding == NULL) +- encoding = PyUnicode_GetDefaultEncoding(); ++ encoding = PyUnicode_GetDefaultEncoding(); + + /* Decode via the codec registry */ + v = PyCodec_Decode(unicode, encoding, errors); +@@ -1184,20 +1186,20 @@ + goto onError; + return v; + +- onError: ++ onError: + return NULL; + } + + PyObject *PyUnicode_Encode(const Py_UNICODE *s, +- Py_ssize_t size, +- const char *encoding, +- const char *errors) ++ Py_ssize_t size, ++ const char *encoding, ++ const char *errors) + { + PyObject *v, *unicode; + + unicode = PyUnicode_FromUnicode(s, size); + if (unicode == NULL) +- return NULL; ++ return NULL; + v = PyUnicode_AsEncodedString(unicode, encoding, errors); + Py_DECREF(unicode); + return v; +@@ -1215,7 +1217,7 @@ + } + + if (encoding == NULL) +- encoding = PyUnicode_GetDefaultEncoding(); ++ encoding = PyUnicode_GetDefaultEncoding(); + + /* Encode via the codec registry */ + v = PyCodec_Encode(unicode, encoding, errors); +@@ -1223,7 +1225,7 @@ + goto onError; + return v; + +- onError: ++ onError: + return NULL; + } + +@@ -1239,20 +1241,20 @@ + } + + if (encoding == NULL) +- encoding = PyUnicode_GetDefaultEncoding(); ++ encoding = PyUnicode_GetDefaultEncoding(); + + /* Shortcuts for common default encodings */ + if (errors == NULL) { +- if (strcmp(encoding, "utf-8") == 0) +- return PyUnicode_AsUTF8String(unicode); +- else if (strcmp(encoding, "latin-1") == 0) +- return PyUnicode_AsLatin1String(unicode); ++ if (strcmp(encoding, "utf-8") == 0) ++ return PyUnicode_AsUTF8String(unicode); ++ else if (strcmp(encoding, "latin-1") == 0) ++ return PyUnicode_AsLatin1String(unicode); + #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) +- else if (strcmp(encoding, "mbcs") == 0) +- return PyUnicode_AsMBCSString(unicode); ++ else if (strcmp(encoding, "mbcs") == 0) ++ return PyUnicode_AsMBCSString(unicode); + #endif +- else if (strcmp(encoding, "ascii") == 0) +- return PyUnicode_AsASCIIString(unicode); ++ else if (strcmp(encoding, "ascii") == 0) ++ return PyUnicode_AsASCIIString(unicode); + } + + /* Encode via the codec registry */ +@@ -1268,12 +1270,12 @@ + } + return v; + +- onError: ++ onError: + return NULL; + } + + PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode, +- const char *errors) ++ const char *errors) + { + PyObject *v = ((PyUnicodeObject *)unicode)->defenc; + +@@ -1293,7 +1295,7 @@ + } + return PyUnicode_AS_UNICODE(unicode); + +- onError: ++ onError: + return NULL; + } + +@@ -1305,7 +1307,7 @@ + } + return PyUnicode_GET_SIZE(unicode); + +- onError: ++ onError: + return -1; + } + +@@ -1322,14 +1324,14 @@ + loads the encoding into the codec registry cache. */ + v = _PyCodec_Lookup(encoding); + if (v == NULL) +- goto onError; ++ goto onError; + Py_DECREF(v); + strncpy(unicode_default_encoding, +- encoding, +- sizeof(unicode_default_encoding)); ++ encoding, ++ sizeof(unicode_default_encoding)); + return 0; + +- onError: ++ onError: + return -1; + } + +@@ -1342,10 +1344,10 @@ + + static + int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler, +- const char *encoding, const char *reason, +- const char *input, Py_ssize_t insize, Py_ssize_t *startinpos, +- Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr, +- PyObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr) ++ const char *encoding, const char *reason, ++ const char *input, Py_ssize_t insize, Py_ssize_t *startinpos, ++ Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr, ++ PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr) + { + static char *argparse = "O!n;decoding error handler must return (unicode, int) tuple"; + +@@ -1359,40 +1361,40 @@ + int res = -1; + + if (*errorHandler == NULL) { +- *errorHandler = PyCodec_LookupError(errors); +- if (*errorHandler == NULL) +- goto onError; ++ *errorHandler = PyCodec_LookupError(errors); ++ if (*errorHandler == NULL) ++ goto onError; + } + + if (*exceptionObject == NULL) { +- *exceptionObject = PyUnicodeDecodeError_Create( +- encoding, input, insize, *startinpos, *endinpos, reason); +- if (*exceptionObject == NULL) +- goto onError; ++ *exceptionObject = PyUnicodeDecodeError_Create( ++ encoding, input, insize, *startinpos, *endinpos, reason); ++ if (*exceptionObject == NULL) ++ goto onError; + } + else { +- if (PyUnicodeDecodeError_SetStart(*exceptionObject, *startinpos)) +- goto onError; +- if (PyUnicodeDecodeError_SetEnd(*exceptionObject, *endinpos)) +- goto onError; +- if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason)) +- goto onError; ++ if (PyUnicodeDecodeError_SetStart(*exceptionObject, *startinpos)) ++ goto onError; ++ if (PyUnicodeDecodeError_SetEnd(*exceptionObject, *endinpos)) ++ goto onError; ++ if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason)) ++ goto onError; + } + + restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL); + if (restuple == NULL) +- goto onError; ++ goto onError; + if (!PyTuple_Check(restuple)) { +- PyErr_Format(PyExc_TypeError, &argparse[4]); +- goto onError; ++ PyErr_Format(PyExc_TypeError, &argparse[4]); ++ goto onError; + } + if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos)) +- goto onError; ++ goto onError; + if (newpos<0) +- newpos = insize+newpos; ++ newpos = insize+newpos; + if (newpos<0 || newpos>insize) { +- PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos); +- goto onError; ++ PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos); ++ goto onError; + } + + /* need more space? (at least enough for what we +@@ -1403,11 +1405,11 @@ + repsize = PyUnicode_GET_SIZE(repunicode); + requiredsize = *outpos + repsize + insize-newpos; + if (requiredsize > outsize) { +- if (requiredsize<2*outsize) +- requiredsize = 2*outsize; +- if (PyUnicode_Resize(output, requiredsize) < 0) +- goto onError; +- *outptr = PyUnicode_AS_UNICODE(*output) + *outpos; ++ if (requiredsize<2*outsize) ++ requiredsize = 2*outsize; ++ if (_PyUnicode_Resize(output, requiredsize) < 0) ++ goto onError; ++ *outptr = PyUnicode_AS_UNICODE(*output) + *outpos; + } + *endinpos = newpos; + *inptr = input + newpos; +@@ -1417,7 +1419,7 @@ + /* we made it! */ + res = 0; + +- onError: ++ onError: + Py_XDECREF(restuple); + return res; + } +@@ -1430,10 +1432,10 @@ + char utf7_special[128] = { + /* indicate whether a UTF-7 character is special i.e. cannot be directly + encoded: +- 0 - not special +- 1 - special +- 2 - whitespace (optional) +- 3 - RFC2152 Set O (optional) */ ++ 0 - not special ++ 1 - special ++ 2 - whitespace (optional) ++ 3 - RFC2152 Set O (optional) */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 3, 3, 3, 3, 3, 3, 0, 0, 0, 3, 1, 0, 0, 0, 1, +@@ -1450,17 +1452,17 @@ + utf7_special[0] is 1, we can safely make that one comparison + true */ + +-#define SPECIAL(c, encodeO, encodeWS) \ ++#define SPECIAL(c, encodeO, encodeWS) \ + ((c) > 127 || (c) <= 0 || utf7_special[(c)] == 1 || \ +- (encodeWS && (utf7_special[(c)] == 2)) || \ ++ (encodeWS && (utf7_special[(c)] == 2)) || \ + (encodeO && (utf7_special[(c)] == 3))) + +-#define B64(n) \ ++#define B64(n) \ + ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f]) +-#define B64CHAR(c) \ ++#define B64CHAR(c) \ + (isalnum(c) || (c) == '+' || (c) == '/') +-#define UB64(c) \ +- ((c) == '+' ? 62 : (c) == '/' ? 63 : (c) >= 'a' ? \ ++#define UB64(c) \ ++ ((c) == '+' ? 62 : (c) == '/' ? 63 : (c) >= 'a' ? \ + (c) - 71 : (c) >= 'A' ? (c) - 65 : (c) + 4 ) + + #define ENCODE(out, ch, bits) \ +@@ -1489,16 +1491,16 @@ + } + + PyObject *PyUnicode_DecodeUTF7(const char *s, +- Py_ssize_t size, +- const char *errors) ++ Py_ssize_t size, ++ const char *errors) + { + return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL); + } + + PyObject *PyUnicode_DecodeUTF7Stateful(const char *s, +- Py_ssize_t size, +- const char *errors, +- Py_ssize_t *consumed) ++ Py_ssize_t size, ++ const char *errors, ++ Py_ssize_t *consumed) + { + const char *starts = s; + Py_ssize_t startinpos; +@@ -1529,7 +1531,7 @@ + + while (s < e) { + Py_UNICODE ch; +- restart: ++ restart: + ch = (unsigned char) *s; + + if (inShift) { +@@ -1563,7 +1565,7 @@ + } + } else if (SPECIAL(ch,0,0)) { + errmsg = "unexpected special character"; +- goto utf7Error; ++ goto utf7Error; + } else { + *p++ = ch; + } +@@ -1590,35 +1592,35 @@ + startinpos = s-starts; + errmsg = "unexpected special character"; + s++; +- goto utf7Error; ++ goto utf7Error; + } + else { + *p++ = ch; + s++; + } + continue; +- utf7Error: ++ utf7Error: + outpos = p-PyUnicode_AS_UNICODE(unicode); + endinpos = s-starts; + if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "utf7", errmsg, +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&unicode, &outpos, &p)) +- goto onError; ++ errors, &errorHandler, ++ "utf7", errmsg, ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &unicode, &outpos, &p)) ++ goto onError; + } + + if (inShift && !consumed) { + outpos = p-PyUnicode_AS_UNICODE(unicode); + endinpos = size; + if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "utf7", "unterminated shift sequence", +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&unicode, &outpos, &p)) ++ errors, &errorHandler, ++ "utf7", "unterminated shift sequence", ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &unicode, &outpos, &p)) + goto onError; + if (s < e) +- goto restart; ++ goto restart; + } + if (consumed) { + if(inShift) +@@ -1634,7 +1636,7 @@ + Py_XDECREF(exc); + return (PyObject *)unicode; + +-onError: ++ onError: + Py_XDECREF(errorHandler); + Py_XDECREF(exc); + Py_DECREF(unicode); +@@ -1643,10 +1645,10 @@ + + + PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s, +- Py_ssize_t size, +- int encodeSetO, +- int encodeWhiteSpace, +- const char *errors) ++ Py_ssize_t size, ++ int encodeSetO, ++ int encodeWhiteSpace, ++ const char *errors) + { + PyObject *v; + /* It might be possible to tighten this worst case */ +@@ -1662,7 +1664,7 @@ + return PyErr_NoMemory(); + + if (size == 0) +- return PyString_FromStringAndSize(NULL, 0); ++ return PyString_FromStringAndSize(NULL, 0); + + v = PyString_FromStringAndSize(NULL, cbAllocated); + if (v == NULL) +@@ -1770,16 +1772,16 @@ + }; + + PyObject *PyUnicode_DecodeUTF8(const char *s, +- Py_ssize_t size, +- const char *errors) ++ Py_ssize_t size, ++ const char *errors) + { + return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL); + } + + PyObject *PyUnicode_DecodeUTF8Stateful(const char *s, +- Py_ssize_t size, +- const char *errors, +- Py_ssize_t *consumed) ++ Py_ssize_t size, ++ const char *errors, ++ Py_ssize_t *consumed) + { + const char *starts = s; + int n; +@@ -1820,72 +1822,72 @@ + n = utf8_code_length[ch]; + + if (s + n > e) { +- if (consumed) +- break; +- else { +- errmsg = "unexpected end of data"; +- startinpos = s-starts; +- endinpos = size; +- goto utf8Error; +- } +- } ++ if (consumed) ++ break; ++ else { ++ errmsg = "unexpected end of data"; ++ startinpos = s-starts; ++ endinpos = size; ++ goto utf8Error; ++ } ++ } + + switch (n) { + + case 0: + errmsg = "unexpected code byte"; +- startinpos = s-starts; +- endinpos = startinpos+1; +- goto utf8Error; ++ startinpos = s-starts; ++ endinpos = startinpos+1; ++ goto utf8Error; + + case 1: + errmsg = "internal error"; +- startinpos = s-starts; +- endinpos = startinpos+1; +- goto utf8Error; ++ startinpos = s-starts; ++ endinpos = startinpos+1; ++ goto utf8Error; + + case 2: + if ((s[1] & 0xc0) != 0x80) { + errmsg = "invalid data"; +- startinpos = s-starts; +- endinpos = startinpos+2; +- goto utf8Error; +- } ++ startinpos = s-starts; ++ endinpos = startinpos+2; ++ goto utf8Error; ++ } + ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f); + if (ch < 0x80) { +- startinpos = s-starts; +- endinpos = startinpos+2; ++ startinpos = s-starts; ++ endinpos = startinpos+2; + errmsg = "illegal encoding"; +- goto utf8Error; +- } +- else +- *p++ = (Py_UNICODE)ch; ++ goto utf8Error; ++ } ++ else ++ *p++ = (Py_UNICODE)ch; + break; + + case 3: + if ((s[1] & 0xc0) != 0x80 || + (s[2] & 0xc0) != 0x80) { + errmsg = "invalid data"; +- startinpos = s-starts; +- endinpos = startinpos+3; +- goto utf8Error; +- } ++ startinpos = s-starts; ++ endinpos = startinpos+3; ++ goto utf8Error; ++ } + ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f); + if (ch < 0x0800) { +- /* Note: UTF-8 encodings of surrogates are considered +- legal UTF-8 sequences; ++ /* Note: UTF-8 encodings of surrogates are considered ++ legal UTF-8 sequences; + +- XXX For wide builds (UCS-4) we should probably try +- to recombine the surrogates into a single code +- unit. +- */ ++ XXX For wide builds (UCS-4) we should probably try ++ to recombine the surrogates into a single code ++ unit. ++ */ + errmsg = "illegal encoding"; +- startinpos = s-starts; +- endinpos = startinpos+3; +- goto utf8Error; +- } +- else +- *p++ = (Py_UNICODE)ch; ++ startinpos = s-starts; ++ endinpos = startinpos+3; ++ goto utf8Error; ++ } ++ else ++ *p++ = (Py_UNICODE)ch; + break; + + case 4: +@@ -1893,25 +1895,25 @@ + (s[2] & 0xc0) != 0x80 || + (s[3] & 0xc0) != 0x80) { + errmsg = "invalid data"; +- startinpos = s-starts; +- endinpos = startinpos+4; +- goto utf8Error; +- } ++ startinpos = s-starts; ++ endinpos = startinpos+4; ++ goto utf8Error; ++ } + ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) + +- ((s[2] & 0x3f) << 6) + (s[3] & 0x3f); ++ ((s[2] & 0x3f) << 6) + (s[3] & 0x3f); + /* validate and convert to UTF-16 */ + if ((ch < 0x10000) /* minimum value allowed for 4 +- byte encoding */ ++ byte encoding */ + || (ch > 0x10ffff)) /* maximum value allowed for +- UTF-16 */ +- { ++ UTF-16 */ ++ { + errmsg = "illegal encoding"; +- startinpos = s-starts; +- endinpos = startinpos+4; +- goto utf8Error; +- } ++ startinpos = s-starts; ++ endinpos = startinpos+4; ++ goto utf8Error; ++ } + #ifdef Py_UNICODE_WIDE +- *p++ = (Py_UNICODE)ch; ++ *p++ = (Py_UNICODE)ch; + #else + /* compute and append the two surrogates: */ + +@@ -1929,24 +1931,24 @@ + default: + /* Other sizes are only needed for UCS-4 */ + errmsg = "unsupported Unicode code range"; +- startinpos = s-starts; +- endinpos = startinpos+n; +- goto utf8Error; ++ startinpos = s-starts; ++ endinpos = startinpos+n; ++ goto utf8Error; + } + s += n; +- continue; ++ continue; + +- utf8Error: +- outpos = p-PyUnicode_AS_UNICODE(unicode); +- if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "utf8", errmsg, +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&unicode, &outpos, &p)) +- goto onError; ++ utf8Error: ++ outpos = p-PyUnicode_AS_UNICODE(unicode); ++ if (unicode_decode_call_errorhandler( ++ errors, &errorHandler, ++ "utf8", errmsg, ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &unicode, &outpos, &p)) ++ goto onError; + } + if (consumed) +- *consumed = s-starts; ++ *consumed = s-starts; + + /* Adjust length */ + if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0) +@@ -1956,7 +1958,7 @@ + Py_XDECREF(exc); + return (PyObject *)unicode; + +-onError: ++ onError: + Py_XDECREF(errorHandler); + Py_XDECREF(exc); + Py_DECREF(unicode); +@@ -1970,8 +1972,8 @@ + */ + PyObject * + PyUnicode_EncodeUTF8(const Py_UNICODE *s, +- Py_ssize_t size, +- const char *errors) ++ Py_ssize_t size, ++ const char *errors) + { + #define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */ + +@@ -2036,8 +2038,8 @@ + *p++ = (char)(0x80 | ((ch >> 6) & 0x3f)); + *p++ = (char)(0x80 | (ch & 0x3f)); + continue; +- } +-encodeUCS4: ++ } ++ encodeUCS4: + /* Encode UCS4 Unicode ordinals */ + *p++ = (char)(0xf0 | (ch >> 18)); + *p++ = (char)(0x80 | ((ch >> 12) & 0x3f)); +@@ -2053,7 +2055,7 @@ + v = PyString_FromStringAndSize(stackbuf, nneeded); + } + else { +- /* Cut back to size actually needed. */ ++ /* Cut back to size actually needed. */ + nneeded = p - PyString_AS_STRING(v); + assert(nneeded <= nallocated); + _PyString_Resize(&v, nneeded); +@@ -2070,27 +2072,27 @@ + return NULL; + } + return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode), +- PyUnicode_GET_SIZE(unicode), +- NULL); ++ PyUnicode_GET_SIZE(unicode), ++ NULL); + } + + /* --- UTF-32 Codec ------------------------------------------------------- */ + + PyObject * + PyUnicode_DecodeUTF32(const char *s, +- Py_ssize_t size, +- const char *errors, +- int *byteorder) ++ Py_ssize_t size, ++ const char *errors, ++ int *byteorder) + { + return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL); + } + + PyObject * + PyUnicode_DecodeUTF32Stateful(const char *s, +- Py_ssize_t size, +- const char *errors, +- int *byteorder, +- Py_ssize_t *consumed) ++ Py_ssize_t size, ++ const char *errors, ++ int *byteorder, ++ Py_ssize_t *consumed) + { + const char *starts = s; + Py_ssize_t startinpos; +@@ -2118,8 +2120,8 @@ + codepoints => count how much extra space we need. */ + #ifndef Py_UNICODE_WIDE + for (i = pairs = 0; i < size/4; i++) +- if (((Py_UCS4 *)s)[i] >= 0x10000) +- pairs++; ++ if (((Py_UCS4 *)s)[i] >= 0x10000) ++ pairs++; + #endif + + /* This might be one to much, because of a BOM */ +@@ -2144,27 +2146,27 @@ + if (bo == 0) { + if (size >= 4) { + const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) | +- (q[iorder[1]] << 8) | q[iorder[0]]; ++ (q[iorder[1]] << 8) | q[iorder[0]]; + #ifdef BYTEORDER_IS_LITTLE_ENDIAN +- if (bom == 0x0000FEFF) { +- q += 4; +- bo = -1; +- } +- else if (bom == 0xFFFE0000) { +- q += 4; +- bo = 1; +- } ++ if (bom == 0x0000FEFF) { ++ q += 4; ++ bo = -1; ++ } ++ else if (bom == 0xFFFE0000) { ++ q += 4; ++ bo = 1; ++ } + #else +- if (bom == 0x0000FEFF) { +- q += 4; +- bo = 1; +- } +- else if (bom == 0xFFFE0000) { +- q += 4; +- bo = -1; +- } ++ if (bom == 0x0000FEFF) { ++ q += 4; ++ bo = 1; ++ } ++ else if (bom == 0xFFFE0000) { ++ q += 4; ++ bo = -1; ++ } + #endif +- } ++ } + } + + if (bo == -1) { +@@ -2183,54 +2185,54 @@ + } + + while (q < e) { +- Py_UCS4 ch; +- /* remaining bytes at the end? (size should be divisible by 4) */ +- if (e-q<4) { +- if (consumed) +- break; +- errmsg = "truncated data"; +- startinpos = ((const char *)q)-starts; +- endinpos = ((const char *)e)-starts; +- goto utf32Error; +- /* The remaining input chars are ignored if the callback +- chooses to skip the input */ +- } +- ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) | +- (q[iorder[1]] << 8) | q[iorder[0]]; ++ Py_UCS4 ch; ++ /* remaining bytes at the end? (size should be divisible by 4) */ ++ if (e-q<4) { ++ if (consumed) ++ break; ++ errmsg = "truncated data"; ++ startinpos = ((const char *)q)-starts; ++ endinpos = ((const char *)e)-starts; ++ goto utf32Error; ++ /* The remaining input chars are ignored if the callback ++ chooses to skip the input */ ++ } ++ ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) | ++ (q[iorder[1]] << 8) | q[iorder[0]]; + +- if (ch >= 0x110000) +- { +- errmsg = "codepoint not in range(0x110000)"; +- startinpos = ((const char *)q)-starts; +- endinpos = startinpos+4; +- goto utf32Error; +- } ++ if (ch >= 0x110000) ++ { ++ errmsg = "codepoint not in range(0x110000)"; ++ startinpos = ((const char *)q)-starts; ++ endinpos = startinpos+4; ++ goto utf32Error; ++ } + #ifndef Py_UNICODE_WIDE +- if (ch >= 0x10000) +- { +- *p++ = 0xD800 | ((ch-0x10000) >> 10); +- *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF); +- } +- else ++ if (ch >= 0x10000) ++ { ++ *p++ = 0xD800 | ((ch-0x10000) >> 10); ++ *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF); ++ } ++ else + #endif +- *p++ = ch; +- q += 4; +- continue; +- utf32Error: +- outpos = p-PyUnicode_AS_UNICODE(unicode); +- if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "utf32", errmsg, +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&unicode, &outpos, &p)) +- goto onError; ++ *p++ = ch; ++ q += 4; ++ continue; ++ utf32Error: ++ outpos = p-PyUnicode_AS_UNICODE(unicode); ++ if (unicode_decode_call_errorhandler( ++ errors, &errorHandler, ++ "utf32", errmsg, ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &unicode, &outpos, &p)) ++ goto onError; + } + + if (byteorder) + *byteorder = bo; + + if (consumed) +- *consumed = (const char *)q-starts; ++ *consumed = (const char *)q-starts; + + /* Adjust length */ + if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0) +@@ -2240,7 +2242,7 @@ + Py_XDECREF(exc); + return (PyObject *)unicode; + +-onError: ++ onError: + Py_DECREF(unicode); + Py_XDECREF(errorHandler); + Py_XDECREF(exc); +@@ -2249,9 +2251,9 @@ + + PyObject * + PyUnicode_EncodeUTF32(const Py_UNICODE *s, +- Py_ssize_t size, +- const char *errors, +- int byteorder) ++ Py_ssize_t size, ++ const char *errors, ++ int byteorder) + { + PyObject *v; + unsigned char *p; +@@ -2268,34 +2270,34 @@ + int iorder[] = {3, 2, 1, 0}; + #endif + +-#define STORECHAR(CH) \ +- do { \ +- p[iorder[3]] = ((CH) >> 24) & 0xff; \ +- p[iorder[2]] = ((CH) >> 16) & 0xff; \ +- p[iorder[1]] = ((CH) >> 8) & 0xff; \ +- p[iorder[0]] = (CH) & 0xff; \ +- p += 4; \ ++#define STORECHAR(CH) \ ++ do { \ ++ p[iorder[3]] = ((CH) >> 24) & 0xff; \ ++ p[iorder[2]] = ((CH) >> 16) & 0xff; \ ++ p[iorder[1]] = ((CH) >> 8) & 0xff; \ ++ p[iorder[0]] = (CH) & 0xff; \ ++ p += 4; \ + } while(0) + + /* In narrow builds we can output surrogate pairs as one codepoint, + so we need less space. */ + #ifndef Py_UNICODE_WIDE + for (i = pairs = 0; i < size-1; i++) +- if (0xD800 <= s[i] && s[i] <= 0xDBFF && +- 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF) +- pairs++; ++ if (0xD800 <= s[i] && s[i] <= 0xDBFF && ++ 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF) ++ pairs++; + #endif + nsize = (size - pairs + (byteorder == 0)); + bytesize = nsize * 4; + if (bytesize / 4 != nsize) +- return PyErr_NoMemory(); ++ return PyErr_NoMemory(); + v = PyString_FromStringAndSize(NULL, bytesize); + if (v == NULL) + return NULL; + + p = (unsigned char *)PyString_AS_STRING(v); + if (byteorder == 0) +- STORECHAR(0xFEFF); ++ STORECHAR(0xFEFF); + if (size == 0) + return v; + +@@ -2315,16 +2317,16 @@ + } + + while (size-- > 0) { +- Py_UCS4 ch = *s++; ++ Py_UCS4 ch = *s++; + #ifndef Py_UNICODE_WIDE +- if (0xD800 <= ch && ch <= 0xDBFF && size > 0) { +- Py_UCS4 ch2 = *s; +- if (0xDC00 <= ch2 && ch2 <= 0xDFFF) { +- ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000; +- s++; +- size--; +- } +- } ++ if (0xD800 <= ch && ch <= 0xDBFF && size > 0) { ++ Py_UCS4 ch2 = *s; ++ if (0xDC00 <= ch2 && ch2 <= 0xDFFF) { ++ ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000; ++ s++; ++ size--; ++ } ++ } + #endif + STORECHAR(ch); + } +@@ -2339,28 +2341,28 @@ + return NULL; + } + return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode), +- PyUnicode_GET_SIZE(unicode), +- NULL, +- 0); ++ PyUnicode_GET_SIZE(unicode), ++ NULL, ++ 0); + } + + /* --- UTF-16 Codec ------------------------------------------------------- */ + + PyObject * + PyUnicode_DecodeUTF16(const char *s, +- Py_ssize_t size, +- const char *errors, +- int *byteorder) ++ Py_ssize_t size, ++ const char *errors, ++ int *byteorder) + { + return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL); + } + + PyObject * + PyUnicode_DecodeUTF16Stateful(const char *s, +- Py_ssize_t size, +- const char *errors, +- int *byteorder, +- Py_ssize_t *consumed) ++ Py_ssize_t size, ++ const char *errors, ++ int *byteorder, ++ Py_ssize_t *consumed) + { + const char *starts = s; + Py_ssize_t startinpos; +@@ -2404,25 +2406,25 @@ + if (size >= 2) { + const Py_UNICODE bom = (q[ihi] << 8) | q[ilo]; + #ifdef BYTEORDER_IS_LITTLE_ENDIAN +- if (bom == 0xFEFF) { +- q += 2; +- bo = -1; +- } +- else if (bom == 0xFFFE) { +- q += 2; +- bo = 1; +- } ++ if (bom == 0xFEFF) { ++ q += 2; ++ bo = -1; ++ } ++ else if (bom == 0xFFFE) { ++ q += 2; ++ bo = 1; ++ } + #else +- if (bom == 0xFEFF) { +- q += 2; +- bo = 1; +- } +- else if (bom == 0xFFFE) { +- q += 2; +- bo = -1; +- } ++ if (bom == 0xFEFF) { ++ q += 2; ++ bo = 1; ++ } ++ else if (bom == 0xFFFE) { ++ q += 2; ++ bo = -1; ++ } + #endif +- } ++ } + } + + if (bo == -1) { +@@ -2437,74 +2439,74 @@ + } + + while (q < e) { +- Py_UNICODE ch; +- /* remaining bytes at the end? (size should be even) */ +- if (e-q<2) { +- if (consumed) +- break; +- errmsg = "truncated data"; +- startinpos = ((const char *)q)-starts; +- endinpos = ((const char *)e)-starts; +- goto utf16Error; +- /* The remaining input chars are ignored if the callback +- chooses to skip the input */ +- } +- ch = (q[ihi] << 8) | q[ilo]; ++ Py_UNICODE ch; ++ /* remaining bytes at the end? (size should be even) */ ++ if (e-q<2) { ++ if (consumed) ++ break; ++ errmsg = "truncated data"; ++ startinpos = ((const char *)q)-starts; ++ endinpos = ((const char *)e)-starts; ++ goto utf16Error; ++ /* The remaining input chars are ignored if the callback ++ chooses to skip the input */ ++ } ++ ch = (q[ihi] << 8) | q[ilo]; + +- q += 2; ++ q += 2; + +- if (ch < 0xD800 || ch > 0xDFFF) { +- *p++ = ch; +- continue; +- } ++ if (ch < 0xD800 || ch > 0xDFFF) { ++ *p++ = ch; ++ continue; ++ } + +- /* UTF-16 code pair: */ +- if (q >= e) { +- errmsg = "unexpected end of data"; +- startinpos = (((const char *)q)-2)-starts; +- endinpos = ((const char *)e)-starts; +- goto utf16Error; +- } +- if (0xD800 <= ch && ch <= 0xDBFF) { +- Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo]; +- q += 2; +- if (0xDC00 <= ch2 && ch2 <= 0xDFFF) { ++ /* UTF-16 code pair: */ ++ if (q >= e) { ++ errmsg = "unexpected end of data"; ++ startinpos = (((const char *)q)-2)-starts; ++ endinpos = ((const char *)e)-starts; ++ goto utf16Error; ++ } ++ if (0xD800 <= ch && ch <= 0xDBFF) { ++ Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo]; ++ q += 2; ++ if (0xDC00 <= ch2 && ch2 <= 0xDFFF) { + #ifndef Py_UNICODE_WIDE +- *p++ = ch; +- *p++ = ch2; ++ *p++ = ch; ++ *p++ = ch2; + #else +- *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000; ++ *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000; + #endif +- continue; +- } +- else { ++ continue; ++ } ++ else { + errmsg = "illegal UTF-16 surrogate"; +- startinpos = (((const char *)q)-4)-starts; +- endinpos = startinpos+2; +- goto utf16Error; +- } ++ startinpos = (((const char *)q)-4)-starts; ++ endinpos = startinpos+2; ++ goto utf16Error; ++ } + +- } +- errmsg = "illegal encoding"; +- startinpos = (((const char *)q)-2)-starts; +- endinpos = startinpos+2; +- /* Fall through to report the error */ ++ } ++ errmsg = "illegal encoding"; ++ startinpos = (((const char *)q)-2)-starts; ++ endinpos = startinpos+2; ++ /* Fall through to report the error */ + +- utf16Error: +- outpos = p-PyUnicode_AS_UNICODE(unicode); +- if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "utf16", errmsg, +- starts, size, &startinpos, &endinpos, &exc, (const char **)&q, +- (PyObject **)&unicode, &outpos, &p)) +- goto onError; ++ utf16Error: ++ outpos = p-PyUnicode_AS_UNICODE(unicode); ++ if (unicode_decode_call_errorhandler( ++ errors, &errorHandler, ++ "utf16", errmsg, ++ starts, size, &startinpos, &endinpos, &exc, (const char **)&q, ++ &unicode, &outpos, &p)) ++ goto onError; + } + + if (byteorder) + *byteorder = bo; + + if (consumed) +- *consumed = (const char *)q-starts; ++ *consumed = (const char *)q-starts; + + /* Adjust length */ + if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0) +@@ -2514,7 +2516,7 @@ + Py_XDECREF(exc); + return (PyObject *)unicode; + +-onError: ++ onError: + Py_DECREF(unicode); + Py_XDECREF(errorHandler); + Py_XDECREF(exc); +@@ -2523,9 +2525,9 @@ + + PyObject * + PyUnicode_EncodeUTF16(const Py_UNICODE *s, +- Py_ssize_t size, +- const char *errors, +- int byteorder) ++ Py_ssize_t size, ++ const char *errors, ++ int byteorder) + { + PyObject *v; + unsigned char *p; +@@ -2542,33 +2544,33 @@ + int ihi = 0, ilo = 1; + #endif + +-#define STORECHAR(CH) \ +- do { \ +- p[ihi] = ((CH) >> 8) & 0xff; \ +- p[ilo] = (CH) & 0xff; \ +- p += 2; \ ++#define STORECHAR(CH) \ ++ do { \ ++ p[ihi] = ((CH) >> 8) & 0xff; \ ++ p[ilo] = (CH) & 0xff; \ ++ p += 2; \ + } while(0) + + #ifdef Py_UNICODE_WIDE + for (i = pairs = 0; i < size; i++) +- if (s[i] >= 0x10000) +- pairs++; ++ if (s[i] >= 0x10000) ++ pairs++; + #endif + /* 2 * (size + pairs + (byteorder == 0)) */ + if (size > PY_SSIZE_T_MAX || + size > PY_SSIZE_T_MAX - pairs - (byteorder == 0)) +- return PyErr_NoMemory(); ++ return PyErr_NoMemory(); + nsize = size + pairs + (byteorder == 0); + bytesize = nsize * 2; + if (bytesize / 2 != nsize) +- return PyErr_NoMemory(); ++ return PyErr_NoMemory(); + v = PyString_FromStringAndSize(NULL, bytesize); + if (v == NULL) + return NULL; + + p = (unsigned char *)PyString_AS_STRING(v); + if (byteorder == 0) +- STORECHAR(0xFEFF); ++ STORECHAR(0xFEFF); + if (size == 0) + return v; + +@@ -2584,13 +2586,13 @@ + } + + while (size-- > 0) { +- Py_UNICODE ch = *s++; +- Py_UNICODE ch2 = 0; ++ Py_UNICODE ch = *s++; ++ Py_UNICODE ch2 = 0; + #ifdef Py_UNICODE_WIDE +- if (ch >= 0x10000) { +- ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF); +- ch = 0xD800 | ((ch-0x10000) >> 10); +- } ++ if (ch >= 0x10000) { ++ ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF); ++ ch = 0xD800 | ((ch-0x10000) >> 10); ++ } + #endif + STORECHAR(ch); + if (ch2) +@@ -2607,9 +2609,9 @@ + return NULL; + } + return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode), +- PyUnicode_GET_SIZE(unicode), +- NULL, +- 0); ++ PyUnicode_GET_SIZE(unicode), ++ NULL, ++ 0); + } + + /* --- Unicode Escape Codec ----------------------------------------------- */ +@@ -2617,8 +2619,8 @@ + static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL; + + PyObject *PyUnicode_DecodeUnicodeEscape(const char *s, +- Py_ssize_t size, +- const char *errors) ++ Py_ssize_t size, ++ const char *errors) + { + const char *starts = s; + Py_ssize_t startinpos; +@@ -2666,7 +2668,7 @@ + c = '\0'; /* Invalid after \ */ + switch (c) { + +- /* \x escapes */ ++ /* \x escapes */ + case '\n': break; + case '\\': *p++ = '\\'; break; + case '\'': *p++ = '\''; break; +@@ -2679,7 +2681,7 @@ + case 'v': *p++ = '\013'; break; /* VT */ + case 'a': *p++ = '\007'; break; /* BEL, not classic C */ + +- /* \OOO (octal) escapes */ ++ /* \OOO (octal) escapes */ + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + x = s[-1] - '0'; +@@ -2691,20 +2693,20 @@ + *p++ = x; + break; + +- /* hex escapes */ +- /* \xXX */ ++ /* hex escapes */ ++ /* \xXX */ + case 'x': + digits = 2; + message = "truncated \\xXX escape"; + goto hexescape; + +- /* \uXXXX */ ++ /* \uXXXX */ + case 'u': + digits = 4; + message = "truncated \\uXXXX escape"; + goto hexescape; + +- /* \UXXXXXXXX */ ++ /* \UXXXXXXXX */ + case 'U': + digits = 8; + message = "truncated \\UXXXXXXXX escape"; +@@ -2714,10 +2716,10 @@ + if (s+digits>end) { + endinpos = size; + if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "unicodeescape", "end of string in escape sequence", +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&v, &outpos, &p)) ++ errors, &errorHandler, ++ "unicodeescape", "end of string in escape sequence", ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &v, &outpos, &p)) + goto onError; + goto nextByte; + } +@@ -2726,10 +2728,10 @@ + if (!isxdigit(c)) { + endinpos = (s+i+1)-starts; + if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "unicodeescape", message, +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&v, &outpos, &p)) ++ errors, &errorHandler, ++ "unicodeescape", message, ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &v, &outpos, &p)) + goto onError; + goto nextByte; + } +@@ -2765,15 +2767,15 @@ + endinpos = s-starts; + outpos = p-PyUnicode_AS_UNICODE(v); + if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "unicodeescape", "illegal Unicode character", +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&v, &outpos, &p)) ++ errors, &errorHandler, ++ "unicodeescape", "illegal Unicode character", ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &v, &outpos, &p)) + goto onError; + } + break; + +- /* \N{name} */ ++ /* \N{name} */ + case 'N': + message = "malformed \\N character escape"; + if (ucnhash_CAPI == NULL) { +@@ -2807,10 +2809,10 @@ + endinpos = s-starts; + outpos = p-PyUnicode_AS_UNICODE(v); + if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "unicodeescape", message, +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&v, &outpos, &p)) ++ errors, &errorHandler, ++ "unicodeescape", message, ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &v, &outpos, &p)) + goto onError; + break; + +@@ -2821,10 +2823,10 @@ + endinpos = s-starts; + outpos = p-PyUnicode_AS_UNICODE(v); + if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "unicodeescape", message, +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&v, &outpos, &p)) ++ errors, &errorHandler, ++ "unicodeescape", message, ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &v, &outpos, &p)) + goto onError; + } + else { +@@ -2833,7 +2835,7 @@ + } + break; + } +- nextByte: ++ nextByte: + ; + } + if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0) +@@ -2842,7 +2844,7 @@ + Py_XDECREF(exc); + return (PyObject *)v; + +-ucnhashError: ++ ucnhashError: + PyErr_SetString( + PyExc_UnicodeError, + "\\N escapes not supported (can't load unicodedata module)" +@@ -2852,7 +2854,7 @@ + Py_XDECREF(exc); + return NULL; + +-onError: ++ onError: + Py_XDECREF(v); + Py_XDECREF(errorHandler); + Py_XDECREF(exc); +@@ -2867,8 +2869,8 @@ + */ + + Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s, +- Py_ssize_t size, +- Py_UNICODE ch) ++ Py_ssize_t size, ++ Py_UNICODE ch) + { + /* like wcschr, but doesn't stop at NULL characters */ + +@@ -2915,12 +2917,12 @@ + */ + + if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize) +- return PyErr_NoMemory(); ++ return PyErr_NoMemory(); + + repr = PyString_FromStringAndSize(NULL, +- 2 +- + expandsize*size +- + 1); ++ 2 ++ + expandsize*size ++ + 1); + if (repr == NULL) + return NULL; + +@@ -2936,10 +2938,10 @@ + + /* Escape quotes and backslashes */ + if ((quotes && +- ch == (Py_UNICODE) PyString_AS_STRING(repr)[1]) || ch == '\\') { ++ ch == (Py_UNICODE) PyString_AS_STRING(repr)[1]) || ch == '\\') { + *p++ = '\\'; + *p++ = (char) ch; +- continue; ++ continue; + } + + #ifdef Py_UNICODE_WIDE +@@ -2955,34 +2957,34 @@ + *p++ = hexdigit[(ch >> 8) & 0x0000000F]; + *p++ = hexdigit[(ch >> 4) & 0x0000000F]; + *p++ = hexdigit[ch & 0x0000000F]; +- continue; ++ continue; + } + #else +- /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */ +- else if (ch >= 0xD800 && ch < 0xDC00) { +- Py_UNICODE ch2; +- Py_UCS4 ucs; ++ /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */ ++ else if (ch >= 0xD800 && ch < 0xDC00) { ++ Py_UNICODE ch2; ++ Py_UCS4 ucs; + +- ch2 = *s++; +- size--; +- if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { +- ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000; +- *p++ = '\\'; +- *p++ = 'U'; +- *p++ = hexdigit[(ucs >> 28) & 0x0000000F]; +- *p++ = hexdigit[(ucs >> 24) & 0x0000000F]; +- *p++ = hexdigit[(ucs >> 20) & 0x0000000F]; +- *p++ = hexdigit[(ucs >> 16) & 0x0000000F]; +- *p++ = hexdigit[(ucs >> 12) & 0x0000000F]; +- *p++ = hexdigit[(ucs >> 8) & 0x0000000F]; +- *p++ = hexdigit[(ucs >> 4) & 0x0000000F]; +- *p++ = hexdigit[ucs & 0x0000000F]; +- continue; +- } +- /* Fall through: isolated surrogates are copied as-is */ +- s--; +- size++; +- } ++ ch2 = *s++; ++ size--; ++ if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { ++ ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000; ++ *p++ = '\\'; ++ *p++ = 'U'; ++ *p++ = hexdigit[(ucs >> 28) & 0x0000000F]; ++ *p++ = hexdigit[(ucs >> 24) & 0x0000000F]; ++ *p++ = hexdigit[(ucs >> 20) & 0x0000000F]; ++ *p++ = hexdigit[(ucs >> 16) & 0x0000000F]; ++ *p++ = hexdigit[(ucs >> 12) & 0x0000000F]; ++ *p++ = hexdigit[(ucs >> 8) & 0x0000000F]; ++ *p++ = hexdigit[(ucs >> 4) & 0x0000000F]; ++ *p++ = hexdigit[ucs & 0x0000000F]; ++ continue; ++ } ++ /* Fall through: isolated surrogates are copied as-is */ ++ s--; ++ size++; ++ } + #endif + + /* Map 16-bit characters to '\uxxxx' */ +@@ -3030,7 +3032,7 @@ + } + + PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, +- Py_ssize_t size) ++ Py_ssize_t size) + { + return unicodeescape_string(s, size, 0); + } +@@ -3042,14 +3044,14 @@ + return NULL; + } + return PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode), +- PyUnicode_GET_SIZE(unicode)); ++ PyUnicode_GET_SIZE(unicode)); + } + + /* --- Raw Unicode Escape Codec ------------------------------------------- */ + + PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s, +- Py_ssize_t size, +- const char *errors) ++ Py_ssize_t size, ++ const char *errors) + { + const char *starts = s; + Py_ssize_t startinpos; +@@ -3068,75 +3070,75 @@ + handler might have to resize the string) */ + v = _PyUnicode_New(size); + if (v == NULL) +- goto onError; ++ goto onError; + if (size == 0) +- return (PyObject *)v; ++ return (PyObject *)v; + p = PyUnicode_AS_UNICODE(v); + end = s + size; + while (s < end) { +- unsigned char c; +- Py_UCS4 x; +- int i; ++ unsigned char c; ++ Py_UCS4 x; ++ int i; + int count; + +- /* Non-escape characters are interpreted as Unicode ordinals */ +- if (*s != '\\') { +- *p++ = (unsigned char)*s++; +- continue; +- } +- startinpos = s-starts; ++ /* Non-escape characters are interpreted as Unicode ordinals */ ++ if (*s != '\\') { ++ *p++ = (unsigned char)*s++; ++ continue; ++ } ++ startinpos = s-starts; + +- /* \u-escapes are only interpreted iff the number of leading +- backslashes if odd */ +- bs = s; +- for (;s < end;) { +- if (*s != '\\') +- break; +- *p++ = (unsigned char)*s++; +- } +- if (((s - bs) & 1) == 0 || +- s >= end || +- (*s != 'u' && *s != 'U')) { +- continue; +- } +- p--; ++ /* \u-escapes are only interpreted iff the number of leading ++ backslashes if odd */ ++ bs = s; ++ for (;s < end;) { ++ if (*s != '\\') ++ break; ++ *p++ = (unsigned char)*s++; ++ } ++ if (((s - bs) & 1) == 0 || ++ s >= end || ++ (*s != 'u' && *s != 'U')) { ++ continue; ++ } ++ p--; + count = *s=='u' ? 4 : 8; +- s++; ++ s++; + +- /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */ +- outpos = p-PyUnicode_AS_UNICODE(v); +- for (x = 0, i = 0; i < count; ++i, ++s) { +- c = (unsigned char)*s; +- if (!isxdigit(c)) { +- endinpos = s-starts; +- if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "rawunicodeescape", "truncated \\uXXXX", +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&v, &outpos, &p)) +- goto onError; +- goto nextByte; +- } +- x = (x<<4) & ~0xF; +- if (c >= '0' && c <= '9') +- x += c - '0'; +- else if (c >= 'a' && c <= 'f') +- x += 10 + c - 'a'; +- else +- x += 10 + c - 'A'; +- } ++ /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */ ++ outpos = p-PyUnicode_AS_UNICODE(v); ++ for (x = 0, i = 0; i < count; ++i, ++s) { ++ c = (unsigned char)*s; ++ if (!isxdigit(c)) { ++ endinpos = s-starts; ++ if (unicode_decode_call_errorhandler( ++ errors, &errorHandler, ++ "rawunicodeescape", "truncated \\uXXXX", ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &v, &outpos, &p)) ++ goto onError; ++ goto nextByte; ++ } ++ x = (x<<4) & ~0xF; ++ if (c >= '0' && c <= '9') ++ x += c - '0'; ++ else if (c >= 'a' && c <= 'f') ++ x += 10 + c - 'a'; ++ else ++ x += 10 + c - 'A'; ++ } + if (x <= 0xffff) +- /* UCS-2 character */ +- *p++ = (Py_UNICODE) x; ++ /* UCS-2 character */ ++ *p++ = (Py_UNICODE) x; + else if (x <= 0x10ffff) { +- /* UCS-4 character. Either store directly, or as +- surrogate pair. */ ++ /* UCS-4 character. Either store directly, or as ++ surrogate pair. */ + #ifdef Py_UNICODE_WIDE +- *p++ = (Py_UNICODE) x; ++ *p++ = (Py_UNICODE) x; + #else +- x -= 0x10000L; +- *p++ = 0xD800 + (Py_UNICODE) (x >> 10); +- *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF); ++ x -= 0x10000L; ++ *p++ = 0xD800 + (Py_UNICODE) (x >> 10); ++ *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF); + #endif + } else { + endinpos = s-starts; +@@ -3144,20 +3146,20 @@ + if (unicode_decode_call_errorhandler( + errors, &errorHandler, + "rawunicodeescape", "\\Uxxxxxxxx out of range", +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&v, &outpos, &p)) +- goto onError; ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &v, &outpos, &p)) ++ goto onError; + } +- nextByte: +- ; ++ nextByte: ++ ; + } + if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0) +- goto onError; ++ goto onError; + Py_XDECREF(errorHandler); + Py_XDECREF(exc); + return (PyObject *)v; + +- onError: ++ onError: + Py_XDECREF(v); + Py_XDECREF(errorHandler); + Py_XDECREF(exc); +@@ -3165,7 +3167,7 @@ + } + + PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, +- Py_ssize_t size) ++ Py_ssize_t size) + { + PyObject *repr; + char *p; +@@ -3177,22 +3179,22 @@ + #else + const Py_ssize_t expandsize = 6; + #endif +- ++ + if (size > PY_SSIZE_T_MAX / expandsize) +- return PyErr_NoMemory(); +- ++ return PyErr_NoMemory(); ++ + repr = PyString_FromStringAndSize(NULL, expandsize * size); + if (repr == NULL) + return NULL; + if (size == 0) +- return repr; ++ return repr; + + p = q = PyString_AS_STRING(repr); + while (size-- > 0) { + Py_UNICODE ch = *s++; + #ifdef Py_UNICODE_WIDE +- /* Map 32-bit characters to '\Uxxxxxxxx' */ +- if (ch >= 0x10000) { ++ /* Map 32-bit characters to '\Uxxxxxxxx' */ ++ if (ch >= 0x10000) { + *p++ = '\\'; + *p++ = 'U'; + *p++ = hexdigit[(ch >> 28) & 0xf]; +@@ -3206,34 +3208,34 @@ + } + else + #else +- /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */ +- if (ch >= 0xD800 && ch < 0xDC00) { +- Py_UNICODE ch2; +- Py_UCS4 ucs; ++ /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */ ++ if (ch >= 0xD800 && ch < 0xDC00) { ++ Py_UNICODE ch2; ++ Py_UCS4 ucs; + +- ch2 = *s++; +- size--; +- if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { +- ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000; +- *p++ = '\\'; +- *p++ = 'U'; +- *p++ = hexdigit[(ucs >> 28) & 0xf]; +- *p++ = hexdigit[(ucs >> 24) & 0xf]; +- *p++ = hexdigit[(ucs >> 20) & 0xf]; +- *p++ = hexdigit[(ucs >> 16) & 0xf]; +- *p++ = hexdigit[(ucs >> 12) & 0xf]; +- *p++ = hexdigit[(ucs >> 8) & 0xf]; +- *p++ = hexdigit[(ucs >> 4) & 0xf]; +- *p++ = hexdigit[ucs & 0xf]; +- continue; +- } +- /* Fall through: isolated surrogates are copied as-is */ +- s--; +- size++; +- } ++ ch2 = *s++; ++ size--; ++ if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { ++ ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000; ++ *p++ = '\\'; ++ *p++ = 'U'; ++ *p++ = hexdigit[(ucs >> 28) & 0xf]; ++ *p++ = hexdigit[(ucs >> 24) & 0xf]; ++ *p++ = hexdigit[(ucs >> 20) & 0xf]; ++ *p++ = hexdigit[(ucs >> 16) & 0xf]; ++ *p++ = hexdigit[(ucs >> 12) & 0xf]; ++ *p++ = hexdigit[(ucs >> 8) & 0xf]; ++ *p++ = hexdigit[(ucs >> 4) & 0xf]; ++ *p++ = hexdigit[ucs & 0xf]; ++ continue; ++ } ++ /* Fall through: isolated surrogates are copied as-is */ ++ s--; ++ size++; ++ } + #endif +- /* Map 16-bit characters to '\uxxxx' */ +- if (ch >= 256) { ++ /* Map 16-bit characters to '\uxxxx' */ ++ if (ch >= 256) { + *p++ = '\\'; + *p++ = 'u'; + *p++ = hexdigit[(ch >> 12) & 0xf]; +@@ -3241,8 +3243,8 @@ + *p++ = hexdigit[(ch >> 4) & 0xf]; + *p++ = hexdigit[ch & 15]; + } +- /* Copy everything else as-is */ +- else ++ /* Copy everything else as-is */ ++ else + *p++ = (char) ch; + } + *p = '\0'; +@@ -3253,18 +3255,18 @@ + PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode) + { + if (!PyUnicode_Check(unicode)) { +- PyErr_BadArgument(); +- return NULL; ++ PyErr_BadArgument(); ++ return NULL; + } + return PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode), +- PyUnicode_GET_SIZE(unicode)); ++ PyUnicode_GET_SIZE(unicode)); + } + + /* --- Unicode Internal Codec ------------------------------------------- */ + + PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s, +- Py_ssize_t size, +- const char *errors) ++ Py_ssize_t size, ++ const char *errors) + { + const char *starts = s; + Py_ssize_t startinpos; +@@ -3284,9 +3286,9 @@ + /* XXX overflow detection missing */ + v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE); + if (v == NULL) +- goto onError; ++ goto onError; + if (PyUnicode_GetSize((PyObject *)v) == 0) +- return (PyObject *)v; ++ return (PyObject *)v; + p = PyUnicode_AS_UNICODE(v); + end = s + size; + +@@ -3295,12 +3297,12 @@ + /* We have to sanity check the raw data, otherwise doom looms for + some malformed UCS-4 data. */ + if ( +- #ifdef Py_UNICODE_WIDE ++#ifdef Py_UNICODE_WIDE + *p > unimax || *p < 0 || +- #endif ++#endif + end-s < Py_UNICODE_SIZE + ) +- { ++ { + startinpos = s - starts; + if (end-s < Py_UNICODE_SIZE) { + endinpos = end-starts; +@@ -3315,7 +3317,7 @@ + errors, &errorHandler, + "unicode_internal", reason, + starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&v, &outpos, &p)) { ++ &v, &outpos, &p)) { + goto onError; + } + } +@@ -3331,7 +3333,7 @@ + Py_XDECREF(exc); + return (PyObject *)v; + +- onError: ++ onError: + Py_XDECREF(v); + Py_XDECREF(errorHandler); + Py_XDECREF(exc); +@@ -3341,69 +3343,69 @@ + /* --- Latin-1 Codec ------------------------------------------------------ */ + + PyObject *PyUnicode_DecodeLatin1(const char *s, +- Py_ssize_t size, +- const char *errors) ++ Py_ssize_t size, ++ const char *errors) + { + PyUnicodeObject *v; + Py_UNICODE *p; + + /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */ + if (size == 1) { +- Py_UNICODE r = *(unsigned char*)s; +- return PyUnicode_FromUnicode(&r, 1); ++ Py_UNICODE r = *(unsigned char*)s; ++ return PyUnicode_FromUnicode(&r, 1); + } + + v = _PyUnicode_New(size); + if (v == NULL) +- goto onError; ++ goto onError; + if (size == 0) +- return (PyObject *)v; ++ return (PyObject *)v; + p = PyUnicode_AS_UNICODE(v); + while (size-- > 0) +- *p++ = (unsigned char)*s++; ++ *p++ = (unsigned char)*s++; + return (PyObject *)v; + +- onError: ++ onError: + Py_XDECREF(v); + return NULL; + } + + /* create or adjust a UnicodeEncodeError */ + static void make_encode_exception(PyObject **exceptionObject, +- const char *encoding, +- const Py_UNICODE *unicode, Py_ssize_t size, +- Py_ssize_t startpos, Py_ssize_t endpos, +- const char *reason) ++ const char *encoding, ++ const Py_UNICODE *unicode, Py_ssize_t size, ++ Py_ssize_t startpos, Py_ssize_t endpos, ++ const char *reason) + { + if (*exceptionObject == NULL) { +- *exceptionObject = PyUnicodeEncodeError_Create( +- encoding, unicode, size, startpos, endpos, reason); ++ *exceptionObject = PyUnicodeEncodeError_Create( ++ encoding, unicode, size, startpos, endpos, reason); + } + else { +- if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos)) +- goto onError; +- if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos)) +- goto onError; +- if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason)) +- goto onError; +- return; +- onError: +- Py_DECREF(*exceptionObject); +- *exceptionObject = NULL; ++ if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos)) ++ goto onError; ++ if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos)) ++ goto onError; ++ if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason)) ++ goto onError; ++ return; ++ onError: ++ Py_DECREF(*exceptionObject); ++ *exceptionObject = NULL; + } + } + + /* raises a UnicodeEncodeError */ + static void raise_encode_exception(PyObject **exceptionObject, +- const char *encoding, +- const Py_UNICODE *unicode, Py_ssize_t size, +- Py_ssize_t startpos, Py_ssize_t endpos, +- const char *reason) ++ const char *encoding, ++ const Py_UNICODE *unicode, Py_ssize_t size, ++ Py_ssize_t startpos, Py_ssize_t endpos, ++ const char *reason) + { + make_encode_exception(exceptionObject, +- encoding, unicode, size, startpos, endpos, reason); ++ encoding, unicode, size, startpos, endpos, reason); + if (*exceptionObject != NULL) +- PyCodec_StrictErrors(*exceptionObject); ++ PyCodec_StrictErrors(*exceptionObject); + } + + /* error handling callback helper: +@@ -3411,11 +3413,11 @@ + put the result into newpos and return the replacement string, which + has to be freed by the caller */ + static PyObject *unicode_encode_call_errorhandler(const char *errors, +- PyObject **errorHandler, +- const char *encoding, const char *reason, +- const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject, +- Py_ssize_t startpos, Py_ssize_t endpos, +- Py_ssize_t *newpos) ++ PyObject **errorHandler, ++ const char *encoding, const char *reason, ++ const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject, ++ Py_ssize_t startpos, Py_ssize_t endpos, ++ Py_ssize_t *newpos) + { + static char *argparse = "O!n;encoding error handler must return (unicode, int) tuple"; + +@@ -3423,36 +3425,36 @@ + PyObject *resunicode; + + if (*errorHandler == NULL) { +- *errorHandler = PyCodec_LookupError(errors); ++ *errorHandler = PyCodec_LookupError(errors); + if (*errorHandler == NULL) +- return NULL; ++ return NULL; + } + + make_encode_exception(exceptionObject, +- encoding, unicode, size, startpos, endpos, reason); ++ encoding, unicode, size, startpos, endpos, reason); + if (*exceptionObject == NULL) +- return NULL; ++ return NULL; + + restuple = PyObject_CallFunctionObjArgs( +- *errorHandler, *exceptionObject, NULL); ++ *errorHandler, *exceptionObject, NULL); + if (restuple == NULL) +- return NULL; ++ return NULL; + if (!PyTuple_Check(restuple)) { +- PyErr_Format(PyExc_TypeError, &argparse[4]); +- Py_DECREF(restuple); +- return NULL; ++ PyErr_Format(PyExc_TypeError, &argparse[4]); ++ Py_DECREF(restuple); ++ return NULL; + } + if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, +- &resunicode, newpos)) { +- Py_DECREF(restuple); +- return NULL; ++ &resunicode, newpos)) { ++ Py_DECREF(restuple); ++ return NULL; + } + if (*newpos<0) +- *newpos = size+*newpos; ++ *newpos = size+*newpos; + if (*newpos<0 || *newpos>size) { +- PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos); +- Py_DECREF(restuple); +- return NULL; ++ PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos); ++ Py_DECREF(restuple); ++ return NULL; + } + Py_INCREF(resunicode); + Py_DECREF(restuple); +@@ -3460,9 +3462,9 @@ + } + + static PyObject *unicode_encode_ucs1(const Py_UNICODE *p, +- Py_ssize_t size, +- const char *errors, +- int limit) ++ Py_ssize_t size, ++ const char *errors, ++ int limit) + { + /* output object */ + PyObject *res; +@@ -3490,144 +3492,144 @@ + if (res == NULL) + goto onError; + if (size == 0) +- return res; ++ return res; + str = PyString_AS_STRING(res); + ressize = size; + + while (p=limit)) +- ++collend; +- /* cache callback name lookup (if not done yet, i.e. it's the first error) */ +- if (known_errorHandler==-1) { +- if ((errors==NULL) || (!strcmp(errors, "strict"))) +- known_errorHandler = 1; +- else if (!strcmp(errors, "replace")) +- known_errorHandler = 2; +- else if (!strcmp(errors, "ignore")) +- known_errorHandler = 3; +- else if (!strcmp(errors, "xmlcharrefreplace")) +- known_errorHandler = 4; +- else +- known_errorHandler = 0; +- } +- switch (known_errorHandler) { +- case 1: /* strict */ +- raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason); +- goto onError; +- case 2: /* replace */ +- while (collstart++=limit)) ++ ++collend; ++ /* cache callback name lookup (if not done yet, i.e. it's the first error) */ ++ if (known_errorHandler==-1) { ++ if ((errors==NULL) || (!strcmp(errors, "strict"))) ++ known_errorHandler = 1; ++ else if (!strcmp(errors, "replace")) ++ known_errorHandler = 2; ++ else if (!strcmp(errors, "ignore")) ++ known_errorHandler = 3; ++ else if (!strcmp(errors, "xmlcharrefreplace")) ++ known_errorHandler = 4; ++ else ++ known_errorHandler = 0; ++ } ++ switch (known_errorHandler) { ++ case 1: /* strict */ ++ raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason); ++ goto onError; ++ case 2: /* replace */ ++ while (collstart++ ressize) { +- if (requiredsize<2*ressize) +- requiredsize = 2*ressize; +- if (_PyString_Resize(&res, requiredsize)) +- goto onError; +- str = PyString_AS_STRING(res) + respos; +- ressize = requiredsize; +- } +- /* generate replacement (temporarily (mis)uses p) */ +- for (p = collstart; p < collend; ++p) { +- str += sprintf(str, "&#%d;", (int)*p); +- } +- p = collend; +- break; +- default: +- repunicode = unicode_encode_call_errorhandler(errors, &errorHandler, +- encoding, reason, startp, size, &exc, +- collstart-startp, collend-startp, &newpos); +- if (repunicode == NULL) +- goto onError; +- /* need more space? (at least enough for what we +- have+the replacement+the rest of the string, so +- we won't have to check space for encodable characters) */ +- respos = str-PyString_AS_STRING(res); +- repsize = PyUnicode_GET_SIZE(repunicode); +- requiredsize = respos+repsize+(endp-collend); +- if (requiredsize > ressize) { +- if (requiredsize<2*ressize) +- requiredsize = 2*ressize; +- if (_PyString_Resize(&res, requiredsize)) { +- Py_DECREF(repunicode); +- goto onError; +- } +- str = PyString_AS_STRING(res) + respos; +- ressize = requiredsize; +- } +- /* check if there is anything unencodable in the replacement +- and copy it to the output */ +- for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) { +- c = *uni2; +- if (c >= limit) { +- raise_encode_exception(&exc, encoding, startp, size, +- unicodepos, unicodepos+1, reason); +- Py_DECREF(repunicode); +- goto onError; +- } +- *str = (char)c; +- } +- p = startp + newpos; +- Py_DECREF(repunicode); +- } +- } ++ } ++ requiredsize = respos+repsize+(endp-collend); ++ if (requiredsize > ressize) { ++ if (requiredsize<2*ressize) ++ requiredsize = 2*ressize; ++ if (_PyString_Resize(&res, requiredsize)) ++ goto onError; ++ str = PyString_AS_STRING(res) + respos; ++ ressize = requiredsize; ++ } ++ /* generate replacement (temporarily (mis)uses p) */ ++ for (p = collstart; p < collend; ++p) { ++ str += sprintf(str, "&#%d;", (int)*p); ++ } ++ p = collend; ++ break; ++ default: ++ repunicode = unicode_encode_call_errorhandler(errors, &errorHandler, ++ encoding, reason, startp, size, &exc, ++ collstart-startp, collend-startp, &newpos); ++ if (repunicode == NULL) ++ goto onError; ++ /* need more space? (at least enough for what we ++ have+the replacement+the rest of the string, so ++ we won't have to check space for encodable characters) */ ++ respos = str-PyString_AS_STRING(res); ++ repsize = PyUnicode_GET_SIZE(repunicode); ++ requiredsize = respos+repsize+(endp-collend); ++ if (requiredsize > ressize) { ++ if (requiredsize<2*ressize) ++ requiredsize = 2*ressize; ++ if (_PyString_Resize(&res, requiredsize)) { ++ Py_DECREF(repunicode); ++ goto onError; ++ } ++ str = PyString_AS_STRING(res) + respos; ++ ressize = requiredsize; ++ } ++ /* check if there is anything unencodable in the replacement ++ and copy it to the output */ ++ for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) { ++ c = *uni2; ++ if (c >= limit) { ++ raise_encode_exception(&exc, encoding, startp, size, ++ unicodepos, unicodepos+1, reason); ++ Py_DECREF(repunicode); ++ goto onError; ++ } ++ *str = (char)c; ++ } ++ p = startp + newpos; ++ Py_DECREF(repunicode); ++ } ++ } + } + /* Resize if we allocated to much */ + respos = str-PyString_AS_STRING(res); + if (respos= 1 && is_dbcs_lead_byte(s, size - 1)) +- --size; ++ --size; + + /* First get the size of the result */ + if (size > 0) { +- usize = MultiByteToWideChar(CP_ACP, 0, s, size, NULL, 0); +- if (usize == 0) { +- PyErr_SetFromWindowsErrWithFilename(0, NULL); +- return -1; +- } ++ usize = MultiByteToWideChar(CP_ACP, 0, s, size, NULL, 0); ++ if (usize == 0) { ++ PyErr_SetFromWindowsErrWithFilename(0, NULL); ++ return -1; ++ } + } + + if (*v == NULL) { +- /* Create unicode object */ +- *v = _PyUnicode_New(usize); +- if (*v == NULL) +- return -1; ++ /* Create unicode object */ ++ *v = _PyUnicode_New(usize); ++ if (*v == NULL) ++ return -1; + } + else { +- /* Extend unicode object */ +- n = PyUnicode_GET_SIZE(*v); +- if (_PyUnicode_Resize(v, n + usize) < 0) +- return -1; ++ /* Extend unicode object */ ++ n = PyUnicode_GET_SIZE(*v); ++ if (_PyUnicode_Resize(v, n + usize) < 0) ++ return -1; + } + + /* Do the conversion */ + if (size > 0) { +- p = PyUnicode_AS_UNICODE(*v) + n; +- if (0 == MultiByteToWideChar(CP_ACP, 0, s, size, p, usize)) { +- PyErr_SetFromWindowsErrWithFilename(0, NULL); +- return -1; +- } ++ p = PyUnicode_AS_UNICODE(*v) + n; ++ if (0 == MultiByteToWideChar(CP_ACP, 0, s, size, p, usize)) { ++ PyErr_SetFromWindowsErrWithFilename(0, NULL); ++ return -1; ++ } + } + + return size; + } + + PyObject *PyUnicode_DecodeMBCSStateful(const char *s, +- Py_ssize_t size, +- const char *errors, +- Py_ssize_t *consumed) ++ Py_ssize_t size, ++ const char *errors, ++ Py_ssize_t *consumed) + { + PyUnicodeObject *v = NULL; + int done; + + if (consumed) +- *consumed = 0; ++ *consumed = 0; + + #ifdef NEED_RETRY + retry: + if (size > INT_MAX) +- done = decode_mbcs(&v, s, INT_MAX, 0); ++ done = decode_mbcs(&v, s, INT_MAX, 0); + else + #endif +- done = decode_mbcs(&v, s, (int)size, !consumed); ++ done = decode_mbcs(&v, s, (int)size, !consumed); + + if (done < 0) { + Py_XDECREF(v); +- return NULL; ++ return NULL; + } + + if (consumed) +- *consumed += done; ++ *consumed += done; + + #ifdef NEED_RETRY + if (size > INT_MAX) { +- s += done; +- size -= done; +- goto retry; ++ s += done; ++ size -= done; ++ goto retry; + } + #endif + +@@ -3847,8 +3849,8 @@ + } + + PyObject *PyUnicode_DecodeMBCS(const char *s, +- Py_ssize_t size, +- const char *errors) ++ Py_ssize_t size, ++ const char *errors) + { + return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL); + } +@@ -3858,8 +3860,8 @@ + * Returns 0 if succeed, -1 otherwise. + */ + static int encode_mbcs(PyObject **repr, +- const Py_UNICODE *p, /* unicode */ +- int size) /* size of unicode */ ++ const Py_UNICODE *p, /* unicode */ ++ int size) /* size of unicode */ + { + int mbcssize = 0; + Py_ssize_t n = 0; +@@ -3868,63 +3870,63 @@ + + /* First get the size of the result */ + if (size > 0) { +- mbcssize = WideCharToMultiByte(CP_ACP, 0, p, size, NULL, 0, NULL, NULL); +- if (mbcssize == 0) { +- PyErr_SetFromWindowsErrWithFilename(0, NULL); +- return -1; +- } ++ mbcssize = WideCharToMultiByte(CP_ACP, 0, p, size, NULL, 0, NULL, NULL); ++ if (mbcssize == 0) { ++ PyErr_SetFromWindowsErrWithFilename(0, NULL); ++ return -1; ++ } + } + + if (*repr == NULL) { +- /* Create string object */ +- *repr = PyString_FromStringAndSize(NULL, mbcssize); +- if (*repr == NULL) +- return -1; ++ /* Create string object */ ++ *repr = PyString_FromStringAndSize(NULL, mbcssize); ++ if (*repr == NULL) ++ return -1; + } + else { +- /* Extend string object */ +- n = PyString_Size(*repr); +- if (_PyString_Resize(repr, n + mbcssize) < 0) +- return -1; ++ /* Extend string object */ ++ n = PyString_Size(*repr); ++ if (_PyString_Resize(repr, n + mbcssize) < 0) ++ return -1; + } + + /* Do the conversion */ + if (size > 0) { +- char *s = PyString_AS_STRING(*repr) + n; +- if (0 == WideCharToMultiByte(CP_ACP, 0, p, size, s, mbcssize, NULL, NULL)) { +- PyErr_SetFromWindowsErrWithFilename(0, NULL); +- return -1; +- } ++ char *s = PyString_AS_STRING(*repr) + n; ++ if (0 == WideCharToMultiByte(CP_ACP, 0, p, size, s, mbcssize, NULL, NULL)) { ++ PyErr_SetFromWindowsErrWithFilename(0, NULL); ++ return -1; ++ } + } + + return 0; + } + + PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p, +- Py_ssize_t size, +- const char *errors) ++ Py_ssize_t size, ++ const char *errors) + { + PyObject *repr = NULL; + int ret; + + #ifdef NEED_RETRY +- retry: ++ retry: + if (size > INT_MAX) +- ret = encode_mbcs(&repr, p, INT_MAX); ++ ret = encode_mbcs(&repr, p, INT_MAX); + else + #endif +- ret = encode_mbcs(&repr, p, (int)size); ++ ret = encode_mbcs(&repr, p, (int)size); + + if (ret < 0) { +- Py_XDECREF(repr); +- return NULL; ++ Py_XDECREF(repr); ++ return NULL; + } + + #ifdef NEED_RETRY + if (size > INT_MAX) { +- p += INT_MAX; +- size -= INT_MAX; +- goto retry; ++ p += INT_MAX; ++ size -= INT_MAX; ++ goto retry; + } + #endif + +@@ -3938,8 +3940,8 @@ + return NULL; + } + return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode), +- PyUnicode_GET_SIZE(unicode), +- NULL); ++ PyUnicode_GET_SIZE(unicode), ++ NULL); + } + + #undef NEED_RETRY +@@ -3949,9 +3951,9 @@ + /* --- Character Mapping Codec -------------------------------------------- */ + + PyObject *PyUnicode_DecodeCharmap(const char *s, +- Py_ssize_t size, +- PyObject *mapping, +- const char *errors) ++ Py_ssize_t size, ++ PyObject *mapping, ++ const char *errors) + { + const char *starts = s; + Py_ssize_t startinpos; +@@ -3968,141 +3970,141 @@ + + /* Default to Latin-1 */ + if (mapping == NULL) +- return PyUnicode_DecodeLatin1(s, size, errors); ++ return PyUnicode_DecodeLatin1(s, size, errors); + + v = _PyUnicode_New(size); + if (v == NULL) +- goto onError; ++ goto onError; + if (size == 0) +- return (PyObject *)v; ++ return (PyObject *)v; + p = PyUnicode_AS_UNICODE(v); + e = s + size; + if (PyUnicode_CheckExact(mapping)) { +- mapstring = PyUnicode_AS_UNICODE(mapping); +- maplen = PyUnicode_GET_SIZE(mapping); +- while (s < e) { +- unsigned char ch = *s; +- Py_UNICODE x = 0xfffe; /* illegal value */ ++ mapstring = PyUnicode_AS_UNICODE(mapping); ++ maplen = PyUnicode_GET_SIZE(mapping); ++ while (s < e) { ++ unsigned char ch = *s; ++ Py_UNICODE x = 0xfffe; /* illegal value */ + +- if (ch < maplen) +- x = mapstring[ch]; ++ if (ch < maplen) ++ x = mapstring[ch]; + +- if (x == 0xfffe) { +- /* undefined mapping */ +- outpos = p-PyUnicode_AS_UNICODE(v); +- startinpos = s-starts; +- endinpos = startinpos+1; +- if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "charmap", "character maps to ", +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&v, &outpos, &p)) { +- goto onError; +- } +- continue; +- } +- *p++ = x; +- ++s; +- } ++ if (x == 0xfffe) { ++ /* undefined mapping */ ++ outpos = p-PyUnicode_AS_UNICODE(v); ++ startinpos = s-starts; ++ endinpos = startinpos+1; ++ if (unicode_decode_call_errorhandler( ++ errors, &errorHandler, ++ "charmap", "character maps to ", ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &v, &outpos, &p)) { ++ goto onError; ++ } ++ continue; ++ } ++ *p++ = x; ++ ++s; ++ } + } + else { +- while (s < e) { +- unsigned char ch = *s; +- PyObject *w, *x; ++ while (s < e) { ++ unsigned char ch = *s; ++ PyObject *w, *x; + +- /* Get mapping (char ordinal -> integer, Unicode char or None) */ +- w = PyInt_FromLong((long)ch); +- if (w == NULL) +- goto onError; +- x = PyObject_GetItem(mapping, w); +- Py_DECREF(w); +- if (x == NULL) { +- if (PyErr_ExceptionMatches(PyExc_LookupError)) { +- /* No mapping found means: mapping is undefined. */ +- PyErr_Clear(); +- x = Py_None; +- Py_INCREF(x); +- } else +- goto onError; +- } +- +- /* Apply mapping */ +- if (PyInt_Check(x)) { +- long value = PyInt_AS_LONG(x); +- if (value < 0 || value > 65535) { +- PyErr_SetString(PyExc_TypeError, +- "character mapping must be in range(65536)"); +- Py_DECREF(x); +- goto onError; +- } +- *p++ = (Py_UNICODE)value; +- } +- else if (x == Py_None) { +- /* undefined mapping */ +- outpos = p-PyUnicode_AS_UNICODE(v); +- startinpos = s-starts; +- endinpos = startinpos+1; +- if (unicode_decode_call_errorhandler( +- errors, &errorHandler, +- "charmap", "character maps to ", +- starts, size, &startinpos, &endinpos, &exc, &s, +- (PyObject **)&v, &outpos, &p)) { +- Py_DECREF(x); +- goto onError; +- } +- Py_DECREF(x); +- continue; +- } +- else if (PyUnicode_Check(x)) { +- Py_ssize_t targetsize = PyUnicode_GET_SIZE(x); +- +- if (targetsize == 1) +- /* 1-1 mapping */ +- *p++ = *PyUnicode_AS_UNICODE(x); +- +- else if (targetsize > 1) { +- /* 1-n mapping */ +- if (targetsize > extrachars) { +- /* resize first */ +- Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v); +- Py_ssize_t needed = (targetsize - extrachars) + \ +- (targetsize << 2); +- extrachars += needed; +- /* XXX overflow detection missing */ +- if (_PyUnicode_Resize(&v, +- PyUnicode_GET_SIZE(v) + needed) < 0) { +- Py_DECREF(x); +- goto onError; +- } +- p = PyUnicode_AS_UNICODE(v) + oldpos; +- } +- Py_UNICODE_COPY(p, +- PyUnicode_AS_UNICODE(x), +- targetsize); +- p += targetsize; +- extrachars -= targetsize; +- } +- /* 1-0 mapping: skip the character */ +- } +- else { +- /* wrong return value */ +- PyErr_SetString(PyExc_TypeError, +- "character mapping must return integer, None or unicode"); +- Py_DECREF(x); +- goto onError; +- } +- Py_DECREF(x); +- ++s; +- } ++ /* Get mapping (char ordinal -> integer, Unicode char or None) */ ++ w = PyInt_FromLong((long)ch); ++ if (w == NULL) ++ goto onError; ++ x = PyObject_GetItem(mapping, w); ++ Py_DECREF(w); ++ if (x == NULL) { ++ if (PyErr_ExceptionMatches(PyExc_LookupError)) { ++ /* No mapping found means: mapping is undefined. */ ++ PyErr_Clear(); ++ x = Py_None; ++ Py_INCREF(x); ++ } else ++ goto onError; ++ } ++ ++ /* Apply mapping */ ++ if (PyInt_Check(x)) { ++ long value = PyInt_AS_LONG(x); ++ if (value < 0 || value > 65535) { ++ PyErr_SetString(PyExc_TypeError, ++ "character mapping must be in range(65536)"); ++ Py_DECREF(x); ++ goto onError; ++ } ++ *p++ = (Py_UNICODE)value; ++ } ++ else if (x == Py_None) { ++ /* undefined mapping */ ++ outpos = p-PyUnicode_AS_UNICODE(v); ++ startinpos = s-starts; ++ endinpos = startinpos+1; ++ if (unicode_decode_call_errorhandler( ++ errors, &errorHandler, ++ "charmap", "character maps to ", ++ starts, size, &startinpos, &endinpos, &exc, &s, ++ &v, &outpos, &p)) { ++ Py_DECREF(x); ++ goto onError; ++ } ++ Py_DECREF(x); ++ continue; ++ } ++ else if (PyUnicode_Check(x)) { ++ Py_ssize_t targetsize = PyUnicode_GET_SIZE(x); ++ ++ if (targetsize == 1) ++ /* 1-1 mapping */ ++ *p++ = *PyUnicode_AS_UNICODE(x); ++ ++ else if (targetsize > 1) { ++ /* 1-n mapping */ ++ if (targetsize > extrachars) { ++ /* resize first */ ++ Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v); ++ Py_ssize_t needed = (targetsize - extrachars) + \ ++ (targetsize << 2); ++ extrachars += needed; ++ /* XXX overflow detection missing */ ++ if (_PyUnicode_Resize(&v, ++ PyUnicode_GET_SIZE(v) + needed) < 0) { ++ Py_DECREF(x); ++ goto onError; ++ } ++ p = PyUnicode_AS_UNICODE(v) + oldpos; ++ } ++ Py_UNICODE_COPY(p, ++ PyUnicode_AS_UNICODE(x), ++ targetsize); ++ p += targetsize; ++ extrachars -= targetsize; ++ } ++ /* 1-0 mapping: skip the character */ ++ } ++ else { ++ /* wrong return value */ ++ PyErr_SetString(PyExc_TypeError, ++ "character mapping must return integer, None or unicode"); ++ Py_DECREF(x); ++ goto onError; ++ } ++ Py_DECREF(x); ++ ++s; ++ } + } + if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v)) +- if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0) +- goto onError; ++ if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0) ++ goto onError; + Py_XDECREF(errorHandler); + Py_XDECREF(exc); + return (PyObject *)v; + +- onError: ++ onError: + Py_XDECREF(errorHandler); + Py_XDECREF(exc); + Py_XDECREF(v); +@@ -4112,74 +4114,74 @@ + /* Charmap encoding: the lookup table */ + + struct encoding_map{ +- PyObject_HEAD +- unsigned char level1[32]; +- int count2, count3; +- unsigned char level23[1]; ++ PyObject_HEAD ++ unsigned char level1[32]; ++ int count2, count3; ++ unsigned char level23[1]; + }; + + static PyObject* + encoding_map_size(PyObject *obj, PyObject* args) + { + struct encoding_map *map = (struct encoding_map*)obj; +- return PyInt_FromLong(sizeof(*map) - 1 + 16*map->count2 + ++ return PyInt_FromLong(sizeof(*map) - 1 + 16*map->count2 + + 128*map->count3); + } + + static PyMethodDef encoding_map_methods[] = { +- {"size", encoding_map_size, METH_NOARGS, +- PyDoc_STR("Return the size (in bytes) of this object") }, +- { 0 } ++ {"size", encoding_map_size, METH_NOARGS, ++ PyDoc_STR("Return the size (in bytes) of this object") }, ++ { 0 } + }; + + static void + encoding_map_dealloc(PyObject* o) + { +- PyObject_FREE(o); ++ PyObject_FREE(o); + } + + static PyTypeObject EncodingMapType = { +- PyVarObject_HEAD_INIT(NULL, 0) +- "EncodingMap", /*tp_name*/ +- sizeof(struct encoding_map), /*tp_basicsize*/ +- 0, /*tp_itemsize*/ +- /* methods */ +- encoding_map_dealloc, /*tp_dealloc*/ +- 0, /*tp_print*/ +- 0, /*tp_getattr*/ +- 0, /*tp_setattr*/ +- 0, /*tp_compare*/ +- 0, /*tp_repr*/ +- 0, /*tp_as_number*/ +- 0, /*tp_as_sequence*/ +- 0, /*tp_as_mapping*/ +- 0, /*tp_hash*/ +- 0, /*tp_call*/ +- 0, /*tp_str*/ +- 0, /*tp_getattro*/ +- 0, /*tp_setattro*/ +- 0, /*tp_as_buffer*/ +- Py_TPFLAGS_DEFAULT, /*tp_flags*/ +- 0, /*tp_doc*/ +- 0, /*tp_traverse*/ +- 0, /*tp_clear*/ +- 0, /*tp_richcompare*/ +- 0, /*tp_weaklistoffset*/ +- 0, /*tp_iter*/ +- 0, /*tp_iternext*/ +- encoding_map_methods, /*tp_methods*/ +- 0, /*tp_members*/ +- 0, /*tp_getset*/ +- 0, /*tp_base*/ +- 0, /*tp_dict*/ +- 0, /*tp_descr_get*/ +- 0, /*tp_descr_set*/ +- 0, /*tp_dictoffset*/ +- 0, /*tp_init*/ +- 0, /*tp_alloc*/ +- 0, /*tp_new*/ +- 0, /*tp_free*/ +- 0, /*tp_is_gc*/ ++ PyVarObject_HEAD_INIT(NULL, 0) ++ "EncodingMap", /*tp_name*/ ++ sizeof(struct encoding_map), /*tp_basicsize*/ ++ 0, /*tp_itemsize*/ ++ /* methods */ ++ encoding_map_dealloc, /*tp_dealloc*/ ++ 0, /*tp_print*/ ++ 0, /*tp_getattr*/ ++ 0, /*tp_setattr*/ ++ 0, /*tp_compare*/ ++ 0, /*tp_repr*/ ++ 0, /*tp_as_number*/ ++ 0, /*tp_as_sequence*/ ++ 0, /*tp_as_mapping*/ ++ 0, /*tp_hash*/ ++ 0, /*tp_call*/ ++ 0, /*tp_str*/ ++ 0, /*tp_getattro*/ ++ 0, /*tp_setattro*/ ++ 0, /*tp_as_buffer*/ ++ Py_TPFLAGS_DEFAULT, /*tp_flags*/ ++ 0, /*tp_doc*/ ++ 0, /*tp_traverse*/ ++ 0, /*tp_clear*/ ++ 0, /*tp_richcompare*/ ++ 0, /*tp_weaklistoffset*/ ++ 0, /*tp_iter*/ ++ 0, /*tp_iternext*/ ++ encoding_map_methods, /*tp_methods*/ ++ 0, /*tp_members*/ ++ 0, /*tp_getset*/ ++ 0, /*tp_base*/ ++ 0, /*tp_dict*/ ++ 0, /*tp_descr_get*/ ++ 0, /*tp_descr_set*/ ++ 0, /*tp_dictoffset*/ ++ 0, /*tp_init*/ ++ 0, /*tp_alloc*/ ++ 0, /*tp_new*/ ++ 0, /*tp_free*/ ++ 0, /*tp_is_gc*/ + }; + + PyObject* +@@ -4211,10 +4213,10 @@ + for (i = 1; i < 256; i++) { + int l1, l2; + if (decode[i] == 0 +- #ifdef Py_UNICODE_WIDE ++#ifdef Py_UNICODE_WIDE + || decode[i] > 0xFFFF +- #endif +- ) { ++#endif ++ ) { + need_dict = 1; + break; + } +@@ -4226,7 +4228,7 @@ + if (level1[l1] == 0xFF) + level1[l1] = count2++; + if (level2[l2] == 0xFF) +- level2[l2] = count3++; ++ level2[l2] = count3++; + } + + if (count2 >= 0xFF || count3 >= 0xFF) +@@ -4300,7 +4302,7 @@ + + #ifdef Py_UNICODE_WIDE + if (c > 0xFFFF) { +- return -1; ++ return -1; + } + #endif + if (c == 0) +@@ -4332,57 +4334,57 @@ + PyObject *x; + + if (w == NULL) +- return NULL; ++ return NULL; + x = PyObject_GetItem(mapping, w); + Py_DECREF(w); + if (x == NULL) { +- if (PyErr_ExceptionMatches(PyExc_LookupError)) { +- /* No mapping found means: mapping is undefined. */ +- PyErr_Clear(); +- x = Py_None; +- Py_INCREF(x); +- return x; +- } else +- return NULL; ++ if (PyErr_ExceptionMatches(PyExc_LookupError)) { ++ /* No mapping found means: mapping is undefined. */ ++ PyErr_Clear(); ++ x = Py_None; ++ Py_INCREF(x); ++ return x; ++ } else ++ return NULL; + } + else if (x == Py_None) +- return x; ++ return x; + else if (PyInt_Check(x)) { +- long value = PyInt_AS_LONG(x); +- if (value < 0 || value > 255) { +- PyErr_SetString(PyExc_TypeError, +- "character mapping must be in range(256)"); +- Py_DECREF(x); +- return NULL; +- } +- return x; ++ long value = PyInt_AS_LONG(x); ++ if (value < 0 || value > 255) { ++ PyErr_SetString(PyExc_TypeError, ++ "character mapping must be in range(256)"); ++ Py_DECREF(x); ++ return NULL; ++ } ++ return x; + } + else if (PyString_Check(x)) +- return x; ++ return x; + else { +- /* wrong return value */ +- PyErr_SetString(PyExc_TypeError, +- "character mapping must return integer, None or str"); +- Py_DECREF(x); +- return NULL; ++ /* wrong return value */ ++ PyErr_SetString(PyExc_TypeError, ++ "character mapping must return integer, None or str"); ++ Py_DECREF(x); ++ return NULL; + } + } + + static int + charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize) + { +- Py_ssize_t outsize = PyString_GET_SIZE(*outobj); +- /* exponentially overallocate to minimize reallocations */ +- if (requiredsize < 2*outsize) +- requiredsize = 2*outsize; +- if (_PyString_Resize(outobj, requiredsize)) { +- return 0; +- } +- return 1; ++ Py_ssize_t outsize = PyString_GET_SIZE(*outobj); ++ /* exponentially overallocate to minimize reallocations */ ++ if (requiredsize < 2*outsize) ++ requiredsize = 2*outsize; ++ if (_PyString_Resize(outobj, requiredsize)) { ++ return 0; ++ } ++ return 1; + } + +-typedef enum charmapencode_result { +- enc_SUCCESS, enc_FAILED, enc_EXCEPTION ++typedef enum charmapencode_result { ++ enc_SUCCESS, enc_FAILED, enc_EXCEPTION + }charmapencode_result; + /* lookup the character, put the result in the output string and adjust + various state variables. Reallocate the output string if not enough +@@ -4392,7 +4394,7 @@ + reallocation error occurred. The caller must decref the result */ + static + charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping, +- PyObject **outobj, Py_ssize_t *outpos) ++ PyObject **outobj, Py_ssize_t *outpos) + { + PyObject *rep; + char *outstart; +@@ -4400,47 +4402,47 @@ + + if (Py_TYPE(mapping) == &EncodingMapType) { + int res = encoding_map_lookup(c, mapping); +- Py_ssize_t requiredsize = *outpos+1; ++ Py_ssize_t requiredsize = *outpos+1; + if (res == -1) + return enc_FAILED; +- if (outsize0; ++uni2) { +- x = charmapencode_output(*uni2, mapping, res, respos); +- if (x==enc_EXCEPTION) { +- return -1; +- } +- else if (x==enc_FAILED) { +- Py_DECREF(repunicode); +- raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason); +- return -1; +- } +- } +- *inpos = newpos; +- Py_DECREF(repunicode); ++ case 1: /* strict */ ++ raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason); ++ return -1; ++ case 2: /* replace */ ++ for (collpos = collstartpos; collpos0; ++uni2) { ++ x = charmapencode_output(*uni2, mapping, res, respos); ++ if (x==enc_EXCEPTION) { ++ return -1; ++ } ++ else if (x==enc_FAILED) { ++ Py_DECREF(repunicode); ++ raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason); ++ return -1; ++ } ++ } ++ *inpos = newpos; ++ Py_DECREF(repunicode); + } + return 0; + } + + PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p, +- Py_ssize_t size, +- PyObject *mapping, +- const char *errors) ++ Py_ssize_t size, ++ PyObject *mapping, ++ const char *errors) + { + /* output object */ + PyObject *res = NULL; +@@ -4584,7 +4586,7 @@ + + /* Default to Latin-1 */ + if (mapping == NULL) +- return PyUnicode_EncodeLatin1(p, size, errors); ++ return PyUnicode_EncodeLatin1(p, size, errors); + + /* allocate enough for a simple encoding without + replacements, if we need more, we'll resize */ +@@ -4592,36 +4594,36 @@ + if (res == NULL) + goto onError; + if (size == 0) +- return res; ++ return res; + + while (inpos adjust input position */ +- ++inpos; ++ /* try to encode it */ ++ charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos); ++ if (x==enc_EXCEPTION) /* error */ ++ goto onError; ++ if (x==enc_FAILED) { /* unencodable character */ ++ if (charmap_encoding_error(p, size, &inpos, mapping, ++ &exc, ++ &known_errorHandler, &errorHandler, errors, ++ &res, &respos)) { ++ goto onError; ++ } ++ } ++ else ++ /* done with this character => adjust input position */ ++ ++inpos; + } + + /* Resize if we allocated to much */ + if (respossize) { +- PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos); +- Py_DECREF(restuple); +- return NULL; ++ PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos); ++ Py_DECREF(restuple); ++ return NULL; + } + Py_INCREF(resunicode); + Py_DECREF(restuple); +@@ -4743,63 +4745,63 @@ + PyObject *x; + + if (w == NULL) +- return -1; ++ return -1; + x = PyObject_GetItem(mapping, w); + Py_DECREF(w); + if (x == NULL) { +- if (PyErr_ExceptionMatches(PyExc_LookupError)) { +- /* No mapping found means: use 1:1 mapping. */ +- PyErr_Clear(); +- *result = NULL; +- return 0; +- } else +- return -1; ++ if (PyErr_ExceptionMatches(PyExc_LookupError)) { ++ /* No mapping found means: use 1:1 mapping. */ ++ PyErr_Clear(); ++ *result = NULL; ++ return 0; ++ } else ++ return -1; + } + else if (x == Py_None) { +- *result = x; +- return 0; ++ *result = x; ++ return 0; + } + else if (PyInt_Check(x)) { +- long value = PyInt_AS_LONG(x); +- long max = PyUnicode_GetMax(); +- if (value < 0 || value > max) { +- PyErr_Format(PyExc_TypeError, +- "character mapping must be in range(0x%lx)", max+1); +- Py_DECREF(x); +- return -1; +- } +- *result = x; +- return 0; ++ long value = PyInt_AS_LONG(x); ++ long max = PyUnicode_GetMax(); ++ if (value < 0 || value > max) { ++ PyErr_Format(PyExc_TypeError, ++ "character mapping must be in range(0x%lx)", max+1); ++ Py_DECREF(x); ++ return -1; ++ } ++ *result = x; ++ return 0; + } + else if (PyUnicode_Check(x)) { +- *result = x; +- return 0; ++ *result = x; ++ return 0; + } + else { +- /* wrong return value */ +- PyErr_SetString(PyExc_TypeError, +- "character mapping must return integer, None or unicode"); +- Py_DECREF(x); +- return -1; ++ /* wrong return value */ ++ PyErr_SetString(PyExc_TypeError, ++ "character mapping must return integer, None or unicode"); ++ Py_DECREF(x); ++ return -1; + } + } + /* ensure that *outobj is at least requiredsize characters long, +-if not reallocate and adjust various state variables. +-Return 0 on success, -1 on error */ ++ if not reallocate and adjust various state variables. ++ Return 0 on success, -1 on error */ + static + int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp, +- Py_ssize_t requiredsize) ++ Py_ssize_t requiredsize) + { + Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj); + if (requiredsize > oldsize) { +- /* remember old output position */ +- Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj); +- /* exponentially overallocate to minimize reallocations */ +- if (requiredsize < 2 * oldsize) +- requiredsize = 2 * oldsize; +- if (_PyUnicode_Resize(outobj, requiredsize) < 0) +- return -1; +- *outp = PyUnicode_AS_UNICODE(*outobj) + outpos; ++ /* remember old output position */ ++ Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj); ++ /* exponentially overallocate to minimize reallocations */ ++ if (requiredsize < 2 * oldsize) ++ requiredsize = 2 * oldsize; ++ if (PyUnicode_Resize(outobj, requiredsize) < 0) ++ return -1; ++ *outp = PyUnicode_AS_UNICODE(*outobj) + outpos; + } + return 0; + } +@@ -4811,47 +4813,47 @@ + Return 0 on success, -1 on error. */ + static + int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp, +- Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp, +- PyObject **res) ++ Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp, ++ PyObject **res) + { + if (charmaptranslate_lookup(*curinp, mapping, res)) +- return -1; ++ return -1; + if (*res==NULL) { +- /* not found => default to 1:1 mapping */ +- *(*outp)++ = *curinp; ++ /* not found => default to 1:1 mapping */ ++ *(*outp)++ = *curinp; + } + else if (*res==Py_None) +- ; ++ ; + else if (PyInt_Check(*res)) { +- /* no overflow check, because we know that the space is enough */ +- *(*outp)++ = (Py_UNICODE)PyInt_AS_LONG(*res); ++ /* no overflow check, because we know that the space is enough */ ++ *(*outp)++ = (Py_UNICODE)PyInt_AS_LONG(*res); + } + else if (PyUnicode_Check(*res)) { +- Py_ssize_t repsize = PyUnicode_GET_SIZE(*res); +- if (repsize==1) { +- /* no overflow check, because we know that the space is enough */ +- *(*outp)++ = *PyUnicode_AS_UNICODE(*res); +- } +- else if (repsize!=0) { +- /* more than one character */ +- Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) + +- (insize - (curinp-startinp)) + +- repsize - 1; +- if (charmaptranslate_makespace(outobj, outp, requiredsize)) +- return -1; +- memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize); +- *outp += repsize; +- } ++ Py_ssize_t repsize = PyUnicode_GET_SIZE(*res); ++ if (repsize==1) { ++ /* no overflow check, because we know that the space is enough */ ++ *(*outp)++ = *PyUnicode_AS_UNICODE(*res); ++ } ++ else if (repsize!=0) { ++ /* more than one character */ ++ Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) + ++ (insize - (curinp-startinp)) + ++ repsize - 1; ++ if (charmaptranslate_makespace(outobj, outp, requiredsize)) ++ return -1; ++ memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize); ++ *outp += repsize; ++ } + } + else +- return -1; ++ return -1; + return 0; + } + + PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p, +- Py_ssize_t size, +- PyObject *mapping, +- const char *errors) ++ Py_ssize_t size, ++ PyObject *mapping, ++ const char *errors) + { + /* output object */ + PyObject *res = NULL; +@@ -4871,119 +4873,119 @@ + int known_errorHandler = -1; + + if (mapping == NULL) { +- PyErr_BadArgument(); +- return NULL; ++ PyErr_BadArgument(); ++ return NULL; + } + + /* allocate enough for a simple 1:1 translation without + replacements, if we need more, we'll resize */ + res = PyUnicode_FromUnicode(NULL, size); + if (res == NULL) +- goto onError; ++ goto onError; + if (size == 0) +- return res; ++ return res; + str = PyUnicode_AS_UNICODE(res); + + while (p adjust input pointer */ +- ++p; +- else { /* untranslatable character */ +- PyObject *repunicode = NULL; /* initialize to prevent gcc warning */ +- Py_ssize_t repsize; +- Py_ssize_t newpos; +- Py_UNICODE *uni2; +- /* startpos for collecting untranslatable chars */ +- const Py_UNICODE *collstart = p; +- const Py_UNICODE *collend = p+1; +- const Py_UNICODE *coll; ++ /* try to encode it */ ++ PyObject *x = NULL; ++ if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) { ++ Py_XDECREF(x); ++ goto onError; ++ } ++ Py_XDECREF(x); ++ if (x!=Py_None) /* it worked => adjust input pointer */ ++ ++p; ++ else { /* untranslatable character */ ++ PyObject *repunicode = NULL; /* initialize to prevent gcc warning */ ++ Py_ssize_t repsize; ++ Py_ssize_t newpos; ++ Py_UNICODE *uni2; ++ /* startpos for collecting untranslatable chars */ ++ const Py_UNICODE *collstart = p; ++ const Py_UNICODE *collend = p+1; ++ const Py_UNICODE *coll; + +- /* find all untranslatable characters */ +- while (collend < endp) { +- if (charmaptranslate_lookup(*collend, mapping, &x)) +- goto onError; +- Py_XDECREF(x); +- if (x!=Py_None) +- break; +- ++collend; +- } +- /* cache callback name lookup +- * (if not done yet, i.e. it's the first error) */ +- if (known_errorHandler==-1) { +- if ((errors==NULL) || (!strcmp(errors, "strict"))) +- known_errorHandler = 1; +- else if (!strcmp(errors, "replace")) +- known_errorHandler = 2; +- else if (!strcmp(errors, "ignore")) +- known_errorHandler = 3; +- else if (!strcmp(errors, "xmlcharrefreplace")) +- known_errorHandler = 4; +- else +- known_errorHandler = 0; +- } +- switch (known_errorHandler) { +- case 1: /* strict */ +- raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason); +- goto onError; +- case 2: /* replace */ +- /* No need to check for space, this is a 1:1 replacement */ +- for (coll = collstart; coll0; ++uni2) +- *str++ = *uni2; +- p = startp + newpos; +- Py_DECREF(repunicode); +- } +- } ++ /* find all untranslatable characters */ ++ while (collend < endp) { ++ if (charmaptranslate_lookup(*collend, mapping, &x)) ++ goto onError; ++ Py_XDECREF(x); ++ if (x!=Py_None) ++ break; ++ ++collend; ++ } ++ /* cache callback name lookup ++ * (if not done yet, i.e. it's the first error) */ ++ if (known_errorHandler==-1) { ++ if ((errors==NULL) || (!strcmp(errors, "strict"))) ++ known_errorHandler = 1; ++ else if (!strcmp(errors, "replace")) ++ known_errorHandler = 2; ++ else if (!strcmp(errors, "ignore")) ++ known_errorHandler = 3; ++ else if (!strcmp(errors, "xmlcharrefreplace")) ++ known_errorHandler = 4; ++ else ++ known_errorHandler = 0; ++ } ++ switch (known_errorHandler) { ++ case 1: /* strict */ ++ raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason); ++ goto onError; ++ case 2: /* replace */ ++ /* No need to check for space, this is a 1:1 replacement */ ++ for (coll = collstart; coll0; ++uni2) ++ *str++ = *uni2; ++ p = startp + newpos; ++ Py_DECREF(repunicode); ++ } ++ } + } + /* Resize if we allocated to much */ + respos = str-PyUnicode_AS_UNICODE(res); + if (respos= 0) { +- *output++ = '0' + decimal; +- ++p; +- continue; +- } +- if (0 < ch && ch < 256) { +- *output++ = (char)ch; +- ++p; +- continue; +- } +- /* All other characters are considered unencodable */ +- collstart = p; +- collend = p+1; +- while (collend < end) { +- if ((0 < *collend && *collend < 256) || +- !Py_UNICODE_ISSPACE(*collend) || +- Py_UNICODE_TODECIMAL(*collend)) +- break; +- } +- /* cache callback name lookup +- * (if not done yet, i.e. it's the first error) */ +- if (known_errorHandler==-1) { +- if ((errors==NULL) || (!strcmp(errors, "strict"))) +- known_errorHandler = 1; +- else if (!strcmp(errors, "replace")) +- known_errorHandler = 2; +- else if (!strcmp(errors, "ignore")) +- known_errorHandler = 3; +- else if (!strcmp(errors, "xmlcharrefreplace")) +- known_errorHandler = 4; +- else +- known_errorHandler = 0; +- } +- switch (known_errorHandler) { +- case 1: /* strict */ +- raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason); +- goto onError; +- case 2: /* replace */ +- for (p = collstart; p < collend; ++p) +- *output++ = '?'; +- /* fall through */ +- case 3: /* ignore */ +- p = collend; +- break; +- case 4: /* xmlcharrefreplace */ +- /* generate replacement (temporarily (mis)uses p) */ +- for (p = collstart; p < collend; ++p) +- output += sprintf(output, "&#%d;", (int)*p); +- p = collend; +- break; +- default: +- repunicode = unicode_encode_call_errorhandler(errors, &errorHandler, +- encoding, reason, s, length, &exc, +- collstart-s, collend-s, &newpos); +- if (repunicode == NULL) +- goto onError; +- /* generate replacement */ +- repsize = PyUnicode_GET_SIZE(repunicode); +- for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) { +- Py_UNICODE ch = *uni2; +- if (Py_UNICODE_ISSPACE(ch)) +- *output++ = ' '; +- else { +- decimal = Py_UNICODE_TODECIMAL(ch); +- if (decimal >= 0) +- *output++ = '0' + decimal; +- else if (0 < ch && ch < 256) +- *output++ = (char)ch; +- else { +- Py_DECREF(repunicode); +- raise_encode_exception(&exc, encoding, +- s, length, collstart-s, collend-s, reason); +- goto onError; +- } +- } +- } +- p = s + newpos; +- Py_DECREF(repunicode); +- } ++ if (Py_UNICODE_ISSPACE(ch)) { ++ *output++ = ' '; ++ ++p; ++ continue; ++ } ++ decimal = Py_UNICODE_TODECIMAL(ch); ++ if (decimal >= 0) { ++ *output++ = '0' + decimal; ++ ++p; ++ continue; ++ } ++ if (0 < ch && ch < 256) { ++ *output++ = (char)ch; ++ ++p; ++ continue; ++ } ++ /* All other characters are considered unencodable */ ++ collstart = p; ++ collend = p+1; ++ while (collend < end) { ++ if ((0 < *collend && *collend < 256) || ++ !Py_UNICODE_ISSPACE(*collend) || ++ Py_UNICODE_TODECIMAL(*collend)) ++ break; ++ } ++ /* cache callback name lookup ++ * (if not done yet, i.e. it's the first error) */ ++ if (known_errorHandler==-1) { ++ if ((errors==NULL) || (!strcmp(errors, "strict"))) ++ known_errorHandler = 1; ++ else if (!strcmp(errors, "replace")) ++ known_errorHandler = 2; ++ else if (!strcmp(errors, "ignore")) ++ known_errorHandler = 3; ++ else if (!strcmp(errors, "xmlcharrefreplace")) ++ known_errorHandler = 4; ++ else ++ known_errorHandler = 0; ++ } ++ switch (known_errorHandler) { ++ case 1: /* strict */ ++ raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason); ++ goto onError; ++ case 2: /* replace */ ++ for (p = collstart; p < collend; ++p) ++ *output++ = '?'; ++ /* fall through */ ++ case 3: /* ignore */ ++ p = collend; ++ break; ++ case 4: /* xmlcharrefreplace */ ++ /* generate replacement (temporarily (mis)uses p) */ ++ for (p = collstart; p < collend; ++p) ++ output += sprintf(output, "&#%d;", (int)*p); ++ p = collend; ++ break; ++ default: ++ repunicode = unicode_encode_call_errorhandler(errors, &errorHandler, ++ encoding, reason, s, length, &exc, ++ collstart-s, collend-s, &newpos); ++ if (repunicode == NULL) ++ goto onError; ++ /* generate replacement */ ++ repsize = PyUnicode_GET_SIZE(repunicode); ++ for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) { ++ Py_UNICODE ch = *uni2; ++ if (Py_UNICODE_ISSPACE(ch)) ++ *output++ = ' '; ++ else { ++ decimal = Py_UNICODE_TODECIMAL(ch); ++ if (decimal >= 0) ++ *output++ = '0' + decimal; ++ else if (0 < ch && ch < 256) ++ *output++ = (char)ch; ++ else { ++ Py_DECREF(repunicode); ++ raise_encode_exception(&exc, encoding, ++ s, length, collstart-s, collend-s, reason); ++ goto onError; ++ } ++ } ++ } ++ p = s + newpos; ++ Py_DECREF(repunicode); ++ } + } + /* 0-terminate the output string */ + *output++ = '\0'; +@@ -5136,7 +5138,7 @@ + Py_XDECREF(errorHandler); + return 0; + +- onError: ++ onError: + Py_XDECREF(exc); + Py_XDECREF(errorHandler); + return -1; +@@ -5178,11 +5180,11 @@ + + str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str); + if (!str_obj) +- return -1; ++ return -1; + sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr); + if (!sub_obj) { +- Py_DECREF(str_obj); +- return -1; ++ Py_DECREF(str_obj); ++ return -1; + } + + FIX_START_END(str_obj); +@@ -5207,11 +5209,11 @@ + + str = PyUnicode_FromObject(str); + if (!str) +- return -2; ++ return -2; + sub = PyUnicode_FromObject(sub); + if (!sub) { +- Py_DECREF(str); +- return -2; ++ Py_DECREF(str); ++ return -2; + } + + if (direction > 0) +@@ -5235,10 +5237,10 @@ + + static + int tailmatch(PyUnicodeObject *self, +- PyUnicodeObject *substring, +- Py_ssize_t start, +- Py_ssize_t end, +- int direction) ++ PyUnicodeObject *substring, ++ Py_ssize_t start, ++ Py_ssize_t end, ++ int direction) + { + if (substring->length == 0) + return 1; +@@ -5247,39 +5249,39 @@ + + end -= substring->length; + if (end < start) +- return 0; ++ return 0; + + if (direction > 0) { +- if (Py_UNICODE_MATCH(self, end, substring)) +- return 1; ++ if (Py_UNICODE_MATCH(self, end, substring)) ++ return 1; + } else { + if (Py_UNICODE_MATCH(self, start, substring)) +- return 1; ++ return 1; + } + + return 0; + } + + Py_ssize_t PyUnicode_Tailmatch(PyObject *str, +- PyObject *substr, +- Py_ssize_t start, +- Py_ssize_t end, +- int direction) ++ PyObject *substr, ++ Py_ssize_t start, ++ Py_ssize_t end, ++ int direction) + { + Py_ssize_t result; + + str = PyUnicode_FromObject(str); + if (str == NULL) +- return -1; ++ return -1; + substr = PyUnicode_FromObject(substr); + if (substr == NULL) { +- Py_DECREF(str); +- return -1; ++ Py_DECREF(str); ++ return -1; + } + + result = tailmatch((PyUnicodeObject *)str, +- (PyUnicodeObject *)substr, +- start, end, direction); ++ (PyUnicodeObject *)substr, ++ start, end, direction); + Py_DECREF(str); + Py_DECREF(substr); + return result; +@@ -5290,24 +5292,24 @@ + + static + PyObject *fixup(PyUnicodeObject *self, +- int (*fixfct)(PyUnicodeObject *s)) ++ int (*fixfct)(PyUnicodeObject *s)) + { + + PyUnicodeObject *u; + + u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length); + if (u == NULL) +- return NULL; ++ return NULL; + + Py_UNICODE_COPY(u->str, self->str, self->length); + + if (!fixfct(u) && PyUnicode_CheckExact(self)) { +- /* fixfct should return TRUE if it modified the buffer. If +- FALSE, return a reference to the original buffer instead +- (to save space, not time) */ +- Py_INCREF(self); +- Py_DECREF(u); +- return (PyObject*) self; ++ /* fixfct should return TRUE if it modified the buffer. If ++ FALSE, return a reference to the original buffer instead ++ (to save space, not time) */ ++ Py_INCREF(self); ++ Py_DECREF(u); ++ return (PyObject*) self; + } + return (PyObject*) u; + } +@@ -5320,13 +5322,13 @@ + int status = 0; + + while (len-- > 0) { +- register Py_UNICODE ch; ++ register Py_UNICODE ch; + +- ch = Py_UNICODE_TOUPPER(*s); +- if (ch != *s) { ++ ch = Py_UNICODE_TOUPPER(*s); ++ if (ch != *s) { + status = 1; +- *s = ch; +- } ++ *s = ch; ++ } + s++; + } + +@@ -5341,13 +5343,13 @@ + int status = 0; + + while (len-- > 0) { +- register Py_UNICODE ch; ++ register Py_UNICODE ch; + +- ch = Py_UNICODE_TOLOWER(*s); +- if (ch != *s) { ++ ch = Py_UNICODE_TOLOWER(*s); ++ if (ch != *s) { + status = 1; +- *s = ch; +- } ++ *s = ch; ++ } + s++; + } + +@@ -5383,10 +5385,10 @@ + int status = 0; + + if (len == 0) +- return 0; ++ return 0; + if (Py_UNICODE_ISLOWER(*s)) { +- *s = Py_UNICODE_TOUPPER(*s); +- status = 1; ++ *s = Py_UNICODE_TOUPPER(*s); ++ status = 1; + } + s++; + while (--len > 0) { +@@ -5408,31 +5410,31 @@ + + /* Shortcut for single character strings */ + if (PyUnicode_GET_SIZE(self) == 1) { +- Py_UNICODE ch = Py_UNICODE_TOTITLE(*p); +- if (*p != ch) { +- *p = ch; +- return 1; +- } +- else +- return 0; ++ Py_UNICODE ch = Py_UNICODE_TOTITLE(*p); ++ if (*p != ch) { ++ *p = ch; ++ return 1; ++ } ++ else ++ return 0; + } + + e = p + PyUnicode_GET_SIZE(self); + previous_is_cased = 0; + for (; p < e; p++) { +- register const Py_UNICODE ch = *p; ++ register const Py_UNICODE ch = *p; + +- if (previous_is_cased) +- *p = Py_UNICODE_TOLOWER(ch); +- else +- *p = Py_UNICODE_TOTITLE(ch); ++ if (previous_is_cased) ++ *p = Py_UNICODE_TOLOWER(ch); ++ else ++ *p = Py_UNICODE_TOTITLE(ch); + +- if (Py_UNICODE_ISLOWER(ch) || +- Py_UNICODE_ISUPPER(ch) || +- Py_UNICODE_ISTITLE(ch)) +- previous_is_cased = 1; +- else +- previous_is_cased = 0; ++ if (Py_UNICODE_ISLOWER(ch) || ++ Py_UNICODE_ISUPPER(ch) || ++ Py_UNICODE_ISTITLE(ch)) ++ previous_is_cased = 1; ++ else ++ previous_is_cased = 0; + } + return 1; + } +@@ -5455,7 +5457,7 @@ + + fseq = PySequence_Fast(seq, ""); + if (fseq == NULL) { +- return NULL; ++ return NULL; + } + + /* Grrrr. A codec may be invoked to convert str objects to +@@ -5468,34 +5470,34 @@ + seqlen = PySequence_Fast_GET_SIZE(fseq); + /* If empty sequence, return u"". */ + if (seqlen == 0) { +- res = _PyUnicode_New(0); /* empty sequence; return u"" */ +- goto Done; ++ res = _PyUnicode_New(0); /* empty sequence; return u"" */ ++ goto Done; + } + /* If singleton sequence with an exact Unicode, return that. */ + if (seqlen == 1) { +- item = PySequence_Fast_GET_ITEM(fseq, 0); +- if (PyUnicode_CheckExact(item)) { +- Py_INCREF(item); +- res = (PyUnicodeObject *)item; +- goto Done; +- } ++ item = PySequence_Fast_GET_ITEM(fseq, 0); ++ if (PyUnicode_CheckExact(item)) { ++ Py_INCREF(item); ++ res = (PyUnicodeObject *)item; ++ goto Done; ++ } + } + + /* At least two items to join, or one that isn't exact Unicode. */ + if (seqlen > 1) { + /* Set up sep and seplen -- they're needed. */ +- if (separator == NULL) { +- sep = ␣ +- seplen = 1; ++ if (separator == NULL) { ++ sep = ␣ ++ seplen = 1; + } +- else { +- internal_separator = PyUnicode_FromObject(separator); +- if (internal_separator == NULL) +- goto onError; +- sep = PyUnicode_AS_UNICODE(internal_separator); +- seplen = PyUnicode_GET_SIZE(internal_separator); +- /* In case PyUnicode_FromObject() mutated seq. */ +- seqlen = PySequence_Fast_GET_SIZE(fseq); ++ else { ++ internal_separator = PyUnicode_FromObject(separator); ++ if (internal_separator == NULL) ++ goto onError; ++ sep = PyUnicode_AS_UNICODE(internal_separator); ++ seplen = PyUnicode_GET_SIZE(internal_separator); ++ /* In case PyUnicode_FromObject() mutated seq. */ ++ seqlen = PySequence_Fast_GET_SIZE(fseq); + } + } + +@@ -5507,79 +5509,79 @@ + res_used = 0; + + for (i = 0; i < seqlen; ++i) { +- Py_ssize_t itemlen; +- Py_ssize_t new_res_used; ++ Py_ssize_t itemlen; ++ Py_ssize_t new_res_used; + +- item = PySequence_Fast_GET_ITEM(fseq, i); +- /* Convert item to Unicode. */ +- if (! PyUnicode_Check(item) && ! PyString_Check(item)) { +- PyErr_Format(PyExc_TypeError, +- "sequence item %zd: expected string or Unicode," +- " %.80s found", +- i, Py_TYPE(item)->tp_name); +- goto onError; +- } +- item = PyUnicode_FromObject(item); +- if (item == NULL) +- goto onError; +- /* We own a reference to item from here on. */ ++ item = PySequence_Fast_GET_ITEM(fseq, i); ++ /* Convert item to Unicode. */ ++ if (! PyUnicode_Check(item) && ! PyString_Check(item)) { ++ PyErr_Format(PyExc_TypeError, ++ "sequence item %zd: expected string or Unicode," ++ " %.80s found", ++ i, Py_TYPE(item)->tp_name); ++ goto onError; ++ } ++ item = PyUnicode_FromObject(item); ++ if (item == NULL) ++ goto onError; ++ /* We own a reference to item from here on. */ + +- /* In case PyUnicode_FromObject() mutated seq. */ +- seqlen = PySequence_Fast_GET_SIZE(fseq); ++ /* In case PyUnicode_FromObject() mutated seq. */ ++ seqlen = PySequence_Fast_GET_SIZE(fseq); + + /* Make sure we have enough space for the separator and the item. */ +- itemlen = PyUnicode_GET_SIZE(item); +- new_res_used = res_used + itemlen; +- if (new_res_used < 0) +- goto Overflow; +- if (i < seqlen - 1) { +- new_res_used += seplen; +- if (new_res_used < 0) +- goto Overflow; +- } +- if (new_res_used > res_alloc) { +- /* double allocated size until it's big enough */ +- do { +- res_alloc += res_alloc; +- if (res_alloc <= 0) +- goto Overflow; +- } while (new_res_used > res_alloc); +- if (_PyUnicode_Resize(&res, res_alloc) < 0) { +- Py_DECREF(item); +- goto onError; +- } ++ itemlen = PyUnicode_GET_SIZE(item); ++ new_res_used = res_used + itemlen; ++ if (new_res_used < 0) ++ goto Overflow; ++ if (i < seqlen - 1) { ++ new_res_used += seplen; ++ if (new_res_used < 0) ++ goto Overflow; ++ } ++ if (new_res_used > res_alloc) { ++ /* double allocated size until it's big enough */ ++ do { ++ res_alloc += res_alloc; ++ if (res_alloc <= 0) ++ goto Overflow; ++ } while (new_res_used > res_alloc); ++ if (_PyUnicode_Resize(&res, res_alloc) < 0) { ++ Py_DECREF(item); ++ goto onError; ++ } + res_p = PyUnicode_AS_UNICODE(res) + res_used; +- } ++ } + +- /* Copy item, and maybe the separator. */ +- Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen); +- res_p += itemlen; +- if (i < seqlen - 1) { +- Py_UNICODE_COPY(res_p, sep, seplen); +- res_p += seplen; +- } +- Py_DECREF(item); +- res_used = new_res_used; ++ /* Copy item, and maybe the separator. */ ++ Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen); ++ res_p += itemlen; ++ if (i < seqlen - 1) { ++ Py_UNICODE_COPY(res_p, sep, seplen); ++ res_p += seplen; ++ } ++ Py_DECREF(item); ++ res_used = new_res_used; + } + + /* Shrink res to match the used area; this probably can't fail, + * but it's cheap to check. + */ + if (_PyUnicode_Resize(&res, res_used) < 0) +- goto onError; ++ goto onError; + +- Done: ++ Done: + Py_XDECREF(internal_separator); + Py_DECREF(fseq); + return (PyObject *)res; + +- Overflow: ++ Overflow: + PyErr_SetString(PyExc_OverflowError, + "join() result is too long for a Python string"); + Py_DECREF(item); + /* fall through */ + +- onError: ++ onError: + Py_XDECREF(internal_separator); + Py_DECREF(fseq); + Py_XDECREF(res); +@@ -5588,9 +5590,9 @@ + + static + PyUnicodeObject *pad(PyUnicodeObject *self, +- Py_ssize_t left, +- Py_ssize_t right, +- Py_UNICODE fill) ++ Py_ssize_t left, ++ Py_ssize_t right, ++ Py_UNICODE fill) + { + PyUnicodeObject *u; + +@@ -5621,21 +5623,21 @@ + return u; + } + +-#define SPLIT_APPEND(data, left, right) \ +- str = PyUnicode_FromUnicode((data) + (left), (right) - (left)); \ +- if (!str) \ +- goto onError; \ +- if (PyList_Append(list, str)) { \ +- Py_DECREF(str); \ +- goto onError; \ +- } \ +- else \ +- Py_DECREF(str); ++#define SPLIT_APPEND(data, left, right) \ ++ str = PyUnicode_FromUnicode((data) + (left), (right) - (left)); \ ++ if (!str) \ ++ goto onError; \ ++ if (PyList_Append(list, str)) { \ ++ Py_DECREF(str); \ ++ goto onError; \ ++ } \ ++ else \ ++ Py_DECREF(str); + + static + PyObject *split_whitespace(PyUnicodeObject *self, +- PyObject *list, +- Py_ssize_t maxcount) ++ PyObject *list, ++ Py_ssize_t maxcount) + { + register Py_ssize_t i; + register Py_ssize_t j; +@@ -5644,33 +5646,33 @@ + register const Py_UNICODE *buf = self->str; + + for (i = j = 0; i < len; ) { +- /* find a token */ +- while (i < len && Py_UNICODE_ISSPACE(buf[i])) +- i++; +- j = i; +- while (i < len && !Py_UNICODE_ISSPACE(buf[i])) +- i++; +- if (j < i) { +- if (maxcount-- <= 0) +- break; +- SPLIT_APPEND(buf, j, i); +- while (i < len && Py_UNICODE_ISSPACE(buf[i])) +- i++; +- j = i; +- } ++ /* find a token */ ++ while (i < len && Py_UNICODE_ISSPACE(buf[i])) ++ i++; ++ j = i; ++ while (i < len && !Py_UNICODE_ISSPACE(buf[i])) ++ i++; ++ if (j < i) { ++ if (maxcount-- <= 0) ++ break; ++ SPLIT_APPEND(buf, j, i); ++ while (i < len && Py_UNICODE_ISSPACE(buf[i])) ++ i++; ++ j = i; ++ } + } + if (j < len) { +- SPLIT_APPEND(buf, j, len); ++ SPLIT_APPEND(buf, j, len); + } + return list; + +- onError: ++ onError: + Py_DECREF(list); + return NULL; + } + + PyObject *PyUnicode_Splitlines(PyObject *string, +- int keepends) ++ int keepends) + { + register Py_ssize_t i; + register Py_ssize_t j; +@@ -5681,7 +5683,7 @@ + + string = PyUnicode_FromObject(string); + if (string == NULL) +- return NULL; ++ return NULL; + data = PyUnicode_AS_UNICODE(string); + len = PyUnicode_GET_SIZE(string); + +@@ -5690,34 +5692,34 @@ + goto onError; + + for (i = j = 0; i < len; ) { +- Py_ssize_t eol; ++ Py_ssize_t eol; + +- /* Find a line and append it */ +- while (i < len && !BLOOM_LINEBREAK(data[i])) +- i++; ++ /* Find a line and append it */ ++ while (i < len && !BLOOM_LINEBREAK(data[i])) ++ i++; + +- /* Skip the line break reading CRLF as one line break */ +- eol = i; +- if (i < len) { +- if (data[i] == '\r' && i + 1 < len && +- data[i+1] == '\n') +- i += 2; +- else +- i++; +- if (keepends) +- eol = i; +- } +- SPLIT_APPEND(data, j, eol); +- j = i; ++ /* Skip the line break reading CRLF as one line break */ ++ eol = i; ++ if (i < len) { ++ if (data[i] == '\r' && i + 1 < len && ++ data[i+1] == '\n') ++ i += 2; ++ else ++ i++; ++ if (keepends) ++ eol = i; ++ } ++ SPLIT_APPEND(data, j, eol); ++ j = i; + } + if (j < len) { +- SPLIT_APPEND(data, j, len); ++ SPLIT_APPEND(data, j, len); + } + + Py_DECREF(string); + return list; + +- onError: ++ onError: + Py_XDECREF(list); + Py_DECREF(string); + return NULL; +@@ -5725,9 +5727,9 @@ + + static + PyObject *split_char(PyUnicodeObject *self, +- PyObject *list, +- Py_UNICODE ch, +- Py_ssize_t maxcount) ++ PyObject *list, ++ Py_UNICODE ch, ++ Py_ssize_t maxcount) + { + register Py_ssize_t i; + register Py_ssize_t j; +@@ -5736,29 +5738,29 @@ + register const Py_UNICODE *buf = self->str; + + for (i = j = 0; i < len; ) { +- if (buf[i] == ch) { +- if (maxcount-- <= 0) +- break; +- SPLIT_APPEND(buf, j, i); +- i = j = i + 1; +- } else +- i++; ++ if (buf[i] == ch) { ++ if (maxcount-- <= 0) ++ break; ++ SPLIT_APPEND(buf, j, i); ++ i = j = i + 1; ++ } else ++ i++; + } + if (j <= len) { +- SPLIT_APPEND(buf, j, len); ++ SPLIT_APPEND(buf, j, len); + } + return list; + +- onError: ++ onError: + Py_DECREF(list); + return NULL; + } + + static + PyObject *split_substring(PyUnicodeObject *self, +- PyObject *list, +- PyUnicodeObject *substring, +- Py_ssize_t maxcount) ++ PyObject *list, ++ PyUnicodeObject *substring, ++ Py_ssize_t maxcount) + { + register Py_ssize_t i; + register Py_ssize_t j; +@@ -5767,28 +5769,28 @@ + PyObject *str; + + for (i = j = 0; i <= len - sublen; ) { +- if (Py_UNICODE_MATCH(self, i, substring)) { +- if (maxcount-- <= 0) +- break; +- SPLIT_APPEND(self->str, j, i); +- i = j = i + sublen; +- } else +- i++; ++ if (Py_UNICODE_MATCH(self, i, substring)) { ++ if (maxcount-- <= 0) ++ break; ++ SPLIT_APPEND(self->str, j, i); ++ i = j = i + sublen; ++ } else ++ i++; + } + if (j <= len) { +- SPLIT_APPEND(self->str, j, len); ++ SPLIT_APPEND(self->str, j, len); + } + return list; + +- onError: ++ onError: + Py_DECREF(list); + return NULL; + } + + static + PyObject *rsplit_whitespace(PyUnicodeObject *self, +- PyObject *list, +- Py_ssize_t maxcount) ++ PyObject *list, ++ Py_ssize_t maxcount) + { + register Py_ssize_t i; + register Py_ssize_t j; +@@ -5797,38 +5799,38 @@ + register const Py_UNICODE *buf = self->str; + + for (i = j = len - 1; i >= 0; ) { +- /* find a token */ +- while (i >= 0 && Py_UNICODE_ISSPACE(buf[i])) +- i--; +- j = i; +- while (i >= 0 && !Py_UNICODE_ISSPACE(buf[i])) +- i--; +- if (j > i) { +- if (maxcount-- <= 0) +- break; +- SPLIT_APPEND(buf, i + 1, j + 1); +- while (i >= 0 && Py_UNICODE_ISSPACE(buf[i])) +- i--; +- j = i; +- } ++ /* find a token */ ++ while (i >= 0 && Py_UNICODE_ISSPACE(buf[i])) ++ i--; ++ j = i; ++ while (i >= 0 && !Py_UNICODE_ISSPACE(buf[i])) ++ i--; ++ if (j > i) { ++ if (maxcount-- <= 0) ++ break; ++ SPLIT_APPEND(buf, i + 1, j + 1); ++ while (i >= 0 && Py_UNICODE_ISSPACE(buf[i])) ++ i--; ++ j = i; ++ } + } + if (j >= 0) { +- SPLIT_APPEND(buf, 0, j + 1); ++ SPLIT_APPEND(buf, 0, j + 1); + } + if (PyList_Reverse(list) < 0) + goto onError; + return list; + +- onError: ++ onError: + Py_DECREF(list); + return NULL; + } + +-static ++static + PyObject *rsplit_char(PyUnicodeObject *self, +- PyObject *list, +- Py_UNICODE ch, +- Py_ssize_t maxcount) ++ PyObject *list, ++ Py_UNICODE ch, ++ Py_ssize_t maxcount) + { + register Py_ssize_t i; + register Py_ssize_t j; +@@ -5837,31 +5839,31 @@ + register const Py_UNICODE *buf = self->str; + + for (i = j = len - 1; i >= 0; ) { +- if (buf[i] == ch) { +- if (maxcount-- <= 0) +- break; +- SPLIT_APPEND(buf, i + 1, j + 1); +- j = i = i - 1; +- } else +- i--; ++ if (buf[i] == ch) { ++ if (maxcount-- <= 0) ++ break; ++ SPLIT_APPEND(buf, i + 1, j + 1); ++ j = i = i - 1; ++ } else ++ i--; + } + if (j >= -1) { +- SPLIT_APPEND(buf, 0, j + 1); ++ SPLIT_APPEND(buf, 0, j + 1); + } + if (PyList_Reverse(list) < 0) + goto onError; + return list; + +- onError: ++ onError: + Py_DECREF(list); + return NULL; + } + +-static ++static + PyObject *rsplit_substring(PyUnicodeObject *self, +- PyObject *list, +- PyUnicodeObject *substring, +- Py_ssize_t maxcount) ++ PyObject *list, ++ PyUnicodeObject *substring, ++ Py_ssize_t maxcount) + { + register Py_ssize_t i; + register Py_ssize_t j; +@@ -5870,23 +5872,23 @@ + PyObject *str; + + for (i = len - sublen, j = len; i >= 0; ) { +- if (Py_UNICODE_MATCH(self, i, substring)) { +- if (maxcount-- <= 0) +- break; +- SPLIT_APPEND(self->str, i + sublen, j); +- j = i; +- i -= sublen; +- } else +- i--; ++ if (Py_UNICODE_MATCH(self, i, substring)) { ++ if (maxcount-- <= 0) ++ break; ++ SPLIT_APPEND(self->str, i + sublen, j); ++ j = i; ++ i -= sublen; ++ } else ++ i--; + } + if (j >= 0) { +- SPLIT_APPEND(self->str, 0, j); ++ SPLIT_APPEND(self->str, 0, j); + } + if (PyList_Reverse(list) < 0) + goto onError; + return list; + +- onError: ++ onError: + Py_DECREF(list); + return NULL; + } +@@ -5895,8 +5897,8 @@ + + static + PyObject *split(PyUnicodeObject *self, +- PyUnicodeObject *substring, +- Py_ssize_t maxcount) ++ PyUnicodeObject *substring, ++ Py_ssize_t maxcount) + { + PyObject *list; + +@@ -5908,24 +5910,24 @@ + return NULL; + + if (substring == NULL) +- return split_whitespace(self,list,maxcount); ++ return split_whitespace(self,list,maxcount); + + else if (substring->length == 1) +- return split_char(self,list,substring->str[0],maxcount); ++ return split_char(self,list,substring->str[0],maxcount); + + else if (substring->length == 0) { +- Py_DECREF(list); +- PyErr_SetString(PyExc_ValueError, "empty separator"); +- return NULL; ++ Py_DECREF(list); ++ PyErr_SetString(PyExc_ValueError, "empty separator"); ++ return NULL; + } + else +- return split_substring(self,list,substring,maxcount); ++ return split_substring(self,list,substring,maxcount); + } + + static + PyObject *rsplit(PyUnicodeObject *self, +- PyUnicodeObject *substring, +- Py_ssize_t maxcount) ++ PyUnicodeObject *substring, ++ Py_ssize_t maxcount) + { + PyObject *list; + +@@ -5937,30 +5939,30 @@ + return NULL; + + if (substring == NULL) +- return rsplit_whitespace(self,list,maxcount); ++ return rsplit_whitespace(self,list,maxcount); + + else if (substring->length == 1) +- return rsplit_char(self,list,substring->str[0],maxcount); ++ return rsplit_char(self,list,substring->str[0],maxcount); + + else if (substring->length == 0) { +- Py_DECREF(list); +- PyErr_SetString(PyExc_ValueError, "empty separator"); +- return NULL; ++ Py_DECREF(list); ++ PyErr_SetString(PyExc_ValueError, "empty separator"); ++ return NULL; + } + else +- return rsplit_substring(self,list,substring,maxcount); ++ return rsplit_substring(self,list,substring,maxcount); + } + + static + PyObject *replace(PyUnicodeObject *self, +- PyUnicodeObject *str1, +- PyUnicodeObject *str2, +- Py_ssize_t maxcount) ++ PyUnicodeObject *str1, ++ PyUnicodeObject *str2, ++ Py_ssize_t maxcount) + { + PyUnicodeObject *u; + + if (maxcount < 0) +- maxcount = PY_SSIZE_T_MAX; ++ maxcount = PY_SSIZE_T_MAX; + + if (str1->length == str2->length) { + /* same length */ +@@ -6046,7 +6048,7 @@ + break; + j++; + } +- if (j > i) { ++ if (j > i) { + if (j > e) + break; + /* copy unchanged part [i:j] */ +@@ -6077,7 +6079,7 @@ + } + return (PyObject *) u; + +-nothing: ++ nothing: + /* nothing to replace; return original string (when possible) */ + if (PyUnicode_CheckExact(self)) { + Py_INCREF(self); +@@ -6089,7 +6091,7 @@ + /* --- Unicode Object Methods --------------------------------------------- */ + + PyDoc_STRVAR(title__doc__, +-"S.title() -> unicode\n\ ++ "S.title() -> unicode\n\ + \n\ + Return a titlecased version of S, i.e. words start with title case\n\ + characters, all remaining cased characters have lower case."); +@@ -6101,7 +6103,7 @@ + } + + PyDoc_STRVAR(capitalize__doc__, +-"S.capitalize() -> unicode\n\ ++ "S.capitalize() -> unicode\n\ + \n\ + Return a capitalized version of S, i.e. make the first character\n\ + have upper case."); +@@ -6114,7 +6116,7 @@ + + #if 0 + PyDoc_STRVAR(capwords__doc__, +-"S.capwords() -> unicode\n\ ++ "S.capwords() -> unicode\n\ + \n\ + Apply .capitalize() to all words in S and return the result with\n\ + normalized whitespace (all whitespace strings are replaced by ' ')."); +@@ -6134,7 +6136,7 @@ + /* Capitalize each word */ + for (i = 0; i < PyList_GET_SIZE(list); i++) { + item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i), +- fixcapitalize); ++ fixcapitalize); + if (item == NULL) + goto onError; + Py_DECREF(PyList_GET_ITEM(list, i)); +@@ -6144,7 +6146,7 @@ + /* Join the words to form a new string */ + item = PyUnicode_Join(NULL, list); + +-onError: ++ onError: + Py_DECREF(list); + return (PyObject *)item; + } +@@ -6155,30 +6157,30 @@ + static int + convert_uc(PyObject *obj, void *addr) + { +- Py_UNICODE *fillcharloc = (Py_UNICODE *)addr; +- PyObject *uniobj; +- Py_UNICODE *unistr; ++ Py_UNICODE *fillcharloc = (Py_UNICODE *)addr; ++ PyObject *uniobj; ++ Py_UNICODE *unistr; + +- uniobj = PyUnicode_FromObject(obj); +- if (uniobj == NULL) { +- PyErr_SetString(PyExc_TypeError, +- "The fill character cannot be converted to Unicode"); +- return 0; +- } +- if (PyUnicode_GET_SIZE(uniobj) != 1) { +- PyErr_SetString(PyExc_TypeError, +- "The fill character must be exactly one character long"); +- Py_DECREF(uniobj); +- return 0; +- } +- unistr = PyUnicode_AS_UNICODE(uniobj); +- *fillcharloc = unistr[0]; +- Py_DECREF(uniobj); +- return 1; ++ uniobj = PyUnicode_FromObject(obj); ++ if (uniobj == NULL) { ++ PyErr_SetString(PyExc_TypeError, ++ "The fill character cannot be converted to Unicode"); ++ return 0; ++ } ++ if (PyUnicode_GET_SIZE(uniobj) != 1) { ++ PyErr_SetString(PyExc_TypeError, ++ "The fill character must be exactly one character long"); ++ Py_DECREF(uniobj); ++ return 0; ++ } ++ unistr = PyUnicode_AS_UNICODE(uniobj); ++ *fillcharloc = unistr[0]; ++ Py_DECREF(uniobj); ++ return 1; + } + + PyDoc_STRVAR(center__doc__, +-"S.center(width[, fillchar]) -> unicode\n\ ++ "S.center(width[, fillchar]) -> unicode\n\ + \n\ + Return S centered in a Unicode string of length width. Padding is\n\ + done using the specified fill character (default is a space)"); +@@ -6239,9 +6241,9 @@ + c1 = *s1++; + c2 = *s2++; + +- if (c1 > (1<<11) * 26) +- c1 += utf16Fixup[c1>>11]; +- if (c2 > (1<<11) * 26) ++ if (c1 > (1<<11) * 26) ++ c1 += utf16Fixup[c1>>11]; ++ if (c2 > (1<<11) * 26) + c2 += utf16Fixup[c2>>11]; + /* now c1 and c2 are in UTF-32-compatible order */ + +@@ -6285,7 +6287,7 @@ + #endif + + int PyUnicode_Compare(PyObject *left, +- PyObject *right) ++ PyObject *right) + { + PyUnicodeObject *u = NULL, *v = NULL; + int result; +@@ -6293,16 +6295,16 @@ + /* Coerce the two arguments */ + u = (PyUnicodeObject *)PyUnicode_FromObject(left); + if (u == NULL) +- goto onError; ++ goto onError; + v = (PyUnicodeObject *)PyUnicode_FromObject(right); + if (v == NULL) +- goto onError; ++ goto onError; + + /* Shortcut for empty or interned objects */ + if (v == u) { +- Py_DECREF(u); +- Py_DECREF(v); +- return 0; ++ Py_DECREF(u); ++ Py_DECREF(v); ++ return 0; + } + + result = unicode_compare(u, v); +@@ -6311,7 +6313,7 @@ + Py_DECREF(v); + return result; + +-onError: ++ onError: + Py_XDECREF(u); + Py_XDECREF(v); + return -1; +@@ -6350,7 +6352,7 @@ + } + return PyBool_FromLong(result); + +- onError: ++ onError: + + /* Standard case + +@@ -6379,22 +6381,22 @@ + if (!PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) + return NULL; + PyErr_Clear(); +- if (PyErr_Warn(PyExc_UnicodeWarning, +- (op == Py_EQ) ? ++ if (PyErr_Warn(PyExc_UnicodeWarning, ++ (op == Py_EQ) ? + "Unicode equal comparison " + "failed to convert both arguments to Unicode - " + "interpreting them as being unequal" : + "Unicode unequal comparison " + "failed to convert both arguments to Unicode - " + "interpreting them as being unequal" +- ) < 0) ++ ) < 0) + return NULL; + result = (op == Py_NE); + return PyBool_FromLong(result); + } + + int PyUnicode_Contains(PyObject *container, +- PyObject *element) ++ PyObject *element) + { + PyObject *str, *sub; + int result; +@@ -6402,8 +6404,8 @@ + /* Coerce the two arguments */ + sub = PyUnicode_FromObject(element); + if (!sub) { +- PyErr_SetString(PyExc_TypeError, +- "'in ' requires string as left operand"); ++ PyErr_SetString(PyExc_TypeError, ++ "'in ' requires string as left operand"); + return -1; + } + +@@ -6424,32 +6426,32 @@ + /* Concat to string or Unicode object giving a new Unicode object. */ + + PyObject *PyUnicode_Concat(PyObject *left, +- PyObject *right) ++ PyObject *right) + { + PyUnicodeObject *u = NULL, *v = NULL, *w; + + /* Coerce the two arguments */ + u = (PyUnicodeObject *)PyUnicode_FromObject(left); + if (u == NULL) +- goto onError; ++ goto onError; + v = (PyUnicodeObject *)PyUnicode_FromObject(right); + if (v == NULL) +- goto onError; ++ goto onError; + + /* Shortcuts */ + if (v == unicode_empty) { +- Py_DECREF(v); +- return (PyObject *)u; ++ Py_DECREF(v); ++ return (PyObject *)u; + } + if (u == unicode_empty) { +- Py_DECREF(u); +- return (PyObject *)v; ++ Py_DECREF(u); ++ return (PyObject *)v; + } + + /* Concat the two Unicode strings */ + w = _PyUnicode_New(u->length + v->length); + if (w == NULL) +- goto onError; ++ goto onError; + Py_UNICODE_COPY(w->str, u->str, u->length); + Py_UNICODE_COPY(w->str + u->length, v->str, v->length); + +@@ -6457,14 +6459,14 @@ + Py_DECREF(v); + return (PyObject *)w; + +-onError: ++ onError: + Py_XDECREF(u); + Py_XDECREF(v); + return NULL; + } + + PyDoc_STRVAR(count__doc__, +-"S.count(sub[, start[, end]]) -> int\n\ ++ "S.count(sub[, start[, end]]) -> int\n\ + \n\ + Return the number of non-overlapping occurrences of substring sub in\n\ + Unicode string S[start:end]. Optional arguments start and end are\n\ +@@ -6479,13 +6481,13 @@ + PyObject *result; + + if (!PyArg_ParseTuple(args, "O|O&O&:count", &substring, +- _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) ++ _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + + substring = (PyUnicodeObject *)PyUnicode_FromObject( + (PyObject *)substring); + if (substring == NULL) +- return NULL; ++ return NULL; + + FIX_START_END(self); + +@@ -6500,7 +6502,7 @@ + } + + PyDoc_STRVAR(encode__doc__, +-"S.encode([encoding[,errors]]) -> string or unicode\n\ ++ "S.encode([encoding[,errors]]) -> string or unicode\n\ + \n\ + Encodes S using the codec registered for encoding. encoding defaults\n\ + to the default encoding. errors may be given to set a different error\n\ +@@ -6515,7 +6517,7 @@ + char *encoding = NULL; + char *errors = NULL; + PyObject *v; +- ++ + if (!PyArg_ParseTuple(args, "|ss:encode", &encoding, &errors)) + return NULL; + v = PyUnicode_AsEncodedObject((PyObject *)self, encoding, errors); +@@ -6531,12 +6533,12 @@ + } + return v; + +- onError: ++ onError: + return NULL; + } + + PyDoc_STRVAR(decode__doc__, +-"S.decode([encoding[,errors]]) -> string or unicode\n\ ++ "S.decode([encoding[,errors]]) -> string or unicode\n\ + \n\ + Decodes S using the codec registered for encoding. encoding defaults\n\ + to the default encoding. errors may be given to set a different error\n\ +@@ -6551,7 +6553,7 @@ + char *encoding = NULL; + char *errors = NULL; + PyObject *v; +- ++ + if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors)) + return NULL; + v = PyUnicode_AsDecodedObject((PyObject *)self, encoding, errors); +@@ -6567,12 +6569,12 @@ + } + return v; + +- onError: ++ onError: + return NULL; + } + + PyDoc_STRVAR(expandtabs__doc__, +-"S.expandtabs([tabsize]) -> unicode\n\ ++ "S.expandtabs([tabsize]) -> unicode\n\ + \n\ + Return a copy of S where all tab characters are expanded using spaces.\n\ + If tabsize is not given, a tab size of 8 characters is assumed."); +@@ -6589,7 +6591,7 @@ + int tabsize = 8; + + if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize)) +- return NULL; ++ return NULL; + + /* First pass: determine size of output string */ + i = 0; /* chars up to and including most recent \n or \r */ +@@ -6597,27 +6599,27 @@ + e = self->str + self->length; /* end of input */ + for (p = self->str; p < e; p++) + if (*p == '\t') { +- if (tabsize > 0) { +- incr = tabsize - (j % tabsize); /* cannot overflow */ +- if (j > PY_SSIZE_T_MAX - incr) +- goto overflow1; +- j += incr; ++ if (tabsize > 0) { ++ incr = tabsize - (j % tabsize); /* cannot overflow */ ++ if (j > PY_SSIZE_T_MAX - incr) ++ goto overflow1; ++ j += incr; + } +- } ++ } + else { +- if (j > PY_SSIZE_T_MAX - 1) +- goto overflow1; ++ if (j > PY_SSIZE_T_MAX - 1) ++ goto overflow1; + j++; + if (*p == '\n' || *p == '\r') { +- if (i > PY_SSIZE_T_MAX - j) +- goto overflow1; ++ if (i > PY_SSIZE_T_MAX - j) ++ goto overflow1; + i += j; + j = 0; + } + } + + if (i > PY_SSIZE_T_MAX - j) +- goto overflow1; ++ goto overflow1; + + /* Second pass: create output string and fill it */ + u = _PyUnicode_New(i + j); +@@ -6630,20 +6632,20 @@ + + for (p = self->str; p < e; p++) + if (*p == '\t') { +- if (tabsize > 0) { +- i = tabsize - (j % tabsize); +- j += i; +- while (i--) { +- if (q >= qe) +- goto overflow2; +- *q++ = ' '; ++ if (tabsize > 0) { ++ i = tabsize - (j % tabsize); ++ j += i; ++ while (i--) { ++ if (q >= qe) ++ goto overflow2; ++ *q++ = ' '; + } +- } +- } +- else { +- if (q >= qe) +- goto overflow2; +- *q++ = *p; ++ } ++ } ++ else { ++ if (q >= qe) ++ goto overflow2; ++ *q++ = *p; + j++; + if (*p == '\n' || *p == '\r') + j = 0; +@@ -6659,7 +6661,7 @@ + } + + PyDoc_STRVAR(find__doc__, +-"S.find(sub [,start [,end]]) -> int\n\ ++ "S.find(sub [,start [,end]]) -> int\n\ + \n\ + Return the lowest index in S where substring sub is found,\n\ + such that sub is contained within s[start:end]. Optional\n\ +@@ -6714,21 +6716,21 @@ + register long x; + + if (self->hash != -1) +- return self->hash; ++ return self->hash; + len = PyUnicode_GET_SIZE(self); + p = PyUnicode_AS_UNICODE(self); + x = *p << 7; + while (--len >= 0) +- x = (1000003*x) ^ *p++; ++ x = (1000003*x) ^ *p++; + x ^= PyUnicode_GET_SIZE(self); + if (x == -1) +- x = -2; ++ x = -2; + self->hash = x; + return x; + } + + PyDoc_STRVAR(index__doc__, +-"S.index(sub [,start [,end]]) -> int\n\ ++ "S.index(sub [,start [,end]]) -> int\n\ + \n\ + Like S.find() but raise ValueError when the substring is not found."); + +@@ -6760,7 +6762,7 @@ + } + + PyDoc_STRVAR(islower__doc__, +-"S.islower() -> bool\n\ ++ "S.islower() -> bool\n\ + \n\ + Return True if all cased characters in S are lowercase and there is\n\ + at least one cased character in S, False otherwise."); +@@ -6774,27 +6776,27 @@ + + /* Shortcut for single character strings */ + if (PyUnicode_GET_SIZE(self) == 1) +- return PyBool_FromLong(Py_UNICODE_ISLOWER(*p)); ++ return PyBool_FromLong(Py_UNICODE_ISLOWER(*p)); + + /* Special case for empty strings */ + if (PyUnicode_GET_SIZE(self) == 0) +- return PyBool_FromLong(0); ++ return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); + cased = 0; + for (; p < e; p++) { +- register const Py_UNICODE ch = *p; ++ register const Py_UNICODE ch = *p; + +- if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) +- return PyBool_FromLong(0); +- else if (!cased && Py_UNICODE_ISLOWER(ch)) +- cased = 1; ++ if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) ++ return PyBool_FromLong(0); ++ else if (!cased && Py_UNICODE_ISLOWER(ch)) ++ cased = 1; + } + return PyBool_FromLong(cased); + } + + PyDoc_STRVAR(isupper__doc__, +-"S.isupper() -> bool\n\ ++ "S.isupper() -> bool\n\ + \n\ + Return True if all cased characters in S are uppercase and there is\n\ + at least one cased character in S, False otherwise."); +@@ -6808,27 +6810,27 @@ + + /* Shortcut for single character strings */ + if (PyUnicode_GET_SIZE(self) == 1) +- return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0); ++ return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0); + + /* Special case for empty strings */ + if (PyUnicode_GET_SIZE(self) == 0) +- return PyBool_FromLong(0); ++ return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); + cased = 0; + for (; p < e; p++) { +- register const Py_UNICODE ch = *p; ++ register const Py_UNICODE ch = *p; + +- if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch)) +- return PyBool_FromLong(0); +- else if (!cased && Py_UNICODE_ISUPPER(ch)) +- cased = 1; ++ if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch)) ++ return PyBool_FromLong(0); ++ else if (!cased && Py_UNICODE_ISUPPER(ch)) ++ cased = 1; + } + return PyBool_FromLong(cased); + } + + PyDoc_STRVAR(istitle__doc__, +-"S.istitle() -> bool\n\ ++ "S.istitle() -> bool\n\ + \n\ + Return True if S is a titlecased string and there is at least one\n\ + character in S, i.e. upper- and titlecase characters may only\n\ +@@ -6844,39 +6846,39 @@ + + /* Shortcut for single character strings */ + if (PyUnicode_GET_SIZE(self) == 1) +- return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) || +- (Py_UNICODE_ISUPPER(*p) != 0)); ++ return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) || ++ (Py_UNICODE_ISUPPER(*p) != 0)); + + /* Special case for empty strings */ + if (PyUnicode_GET_SIZE(self) == 0) +- return PyBool_FromLong(0); ++ return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); + cased = 0; + previous_is_cased = 0; + for (; p < e; p++) { +- register const Py_UNICODE ch = *p; ++ register const Py_UNICODE ch = *p; + +- if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) { +- if (previous_is_cased) +- return PyBool_FromLong(0); +- previous_is_cased = 1; +- cased = 1; +- } +- else if (Py_UNICODE_ISLOWER(ch)) { +- if (!previous_is_cased) +- return PyBool_FromLong(0); +- previous_is_cased = 1; +- cased = 1; +- } +- else +- previous_is_cased = 0; ++ if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) { ++ if (previous_is_cased) ++ return PyBool_FromLong(0); ++ previous_is_cased = 1; ++ cased = 1; ++ } ++ else if (Py_UNICODE_ISLOWER(ch)) { ++ if (!previous_is_cased) ++ return PyBool_FromLong(0); ++ previous_is_cased = 1; ++ cased = 1; ++ } ++ else ++ previous_is_cased = 0; + } + return PyBool_FromLong(cased); + } + + PyDoc_STRVAR(isspace__doc__, +-"S.isspace() -> bool\n\ ++ "S.isspace() -> bool\n\ + \n\ + Return True if all characters in S are whitespace\n\ + and there is at least one character in S, False otherwise."); +@@ -6889,23 +6891,23 @@ + + /* Shortcut for single character strings */ + if (PyUnicode_GET_SIZE(self) == 1 && +- Py_UNICODE_ISSPACE(*p)) +- return PyBool_FromLong(1); ++ Py_UNICODE_ISSPACE(*p)) ++ return PyBool_FromLong(1); + + /* Special case for empty strings */ + if (PyUnicode_GET_SIZE(self) == 0) +- return PyBool_FromLong(0); ++ return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); + for (; p < e; p++) { +- if (!Py_UNICODE_ISSPACE(*p)) +- return PyBool_FromLong(0); ++ if (!Py_UNICODE_ISSPACE(*p)) ++ return PyBool_FromLong(0); + } + return PyBool_FromLong(1); + } + + PyDoc_STRVAR(isalpha__doc__, +-"S.isalpha() -> bool\n\ ++ "S.isalpha() -> bool\n\ + \n\ + Return True if all characters in S are alphabetic\n\ + and there is at least one character in S, False otherwise."); +@@ -6918,23 +6920,23 @@ + + /* Shortcut for single character strings */ + if (PyUnicode_GET_SIZE(self) == 1 && +- Py_UNICODE_ISALPHA(*p)) +- return PyBool_FromLong(1); ++ Py_UNICODE_ISALPHA(*p)) ++ return PyBool_FromLong(1); + + /* Special case for empty strings */ + if (PyUnicode_GET_SIZE(self) == 0) +- return PyBool_FromLong(0); ++ return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); + for (; p < e; p++) { +- if (!Py_UNICODE_ISALPHA(*p)) +- return PyBool_FromLong(0); ++ if (!Py_UNICODE_ISALPHA(*p)) ++ return PyBool_FromLong(0); + } + return PyBool_FromLong(1); + } + + PyDoc_STRVAR(isalnum__doc__, +-"S.isalnum() -> bool\n\ ++ "S.isalnum() -> bool\n\ + \n\ + Return True if all characters in S are alphanumeric\n\ + and there is at least one character in S, False otherwise."); +@@ -6947,23 +6949,23 @@ + + /* Shortcut for single character strings */ + if (PyUnicode_GET_SIZE(self) == 1 && +- Py_UNICODE_ISALNUM(*p)) +- return PyBool_FromLong(1); ++ Py_UNICODE_ISALNUM(*p)) ++ return PyBool_FromLong(1); + + /* Special case for empty strings */ + if (PyUnicode_GET_SIZE(self) == 0) +- return PyBool_FromLong(0); ++ return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); + for (; p < e; p++) { +- if (!Py_UNICODE_ISALNUM(*p)) +- return PyBool_FromLong(0); ++ if (!Py_UNICODE_ISALNUM(*p)) ++ return PyBool_FromLong(0); + } + return PyBool_FromLong(1); + } + + PyDoc_STRVAR(isdecimal__doc__, +-"S.isdecimal() -> bool\n\ ++ "S.isdecimal() -> bool\n\ + \n\ + Return True if there are only decimal characters in S,\n\ + False otherwise."); +@@ -6976,23 +6978,23 @@ + + /* Shortcut for single character strings */ + if (PyUnicode_GET_SIZE(self) == 1 && +- Py_UNICODE_ISDECIMAL(*p)) +- return PyBool_FromLong(1); ++ Py_UNICODE_ISDECIMAL(*p)) ++ return PyBool_FromLong(1); + + /* Special case for empty strings */ + if (PyUnicode_GET_SIZE(self) == 0) +- return PyBool_FromLong(0); ++ return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); + for (; p < e; p++) { +- if (!Py_UNICODE_ISDECIMAL(*p)) +- return PyBool_FromLong(0); ++ if (!Py_UNICODE_ISDECIMAL(*p)) ++ return PyBool_FromLong(0); + } + return PyBool_FromLong(1); + } + + PyDoc_STRVAR(isdigit__doc__, +-"S.isdigit() -> bool\n\ ++ "S.isdigit() -> bool\n\ + \n\ + Return True if all characters in S are digits\n\ + and there is at least one character in S, False otherwise."); +@@ -7005,23 +7007,23 @@ + + /* Shortcut for single character strings */ + if (PyUnicode_GET_SIZE(self) == 1 && +- Py_UNICODE_ISDIGIT(*p)) +- return PyBool_FromLong(1); ++ Py_UNICODE_ISDIGIT(*p)) ++ return PyBool_FromLong(1); + + /* Special case for empty strings */ + if (PyUnicode_GET_SIZE(self) == 0) +- return PyBool_FromLong(0); ++ return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); + for (; p < e; p++) { +- if (!Py_UNICODE_ISDIGIT(*p)) +- return PyBool_FromLong(0); ++ if (!Py_UNICODE_ISDIGIT(*p)) ++ return PyBool_FromLong(0); + } + return PyBool_FromLong(1); + } + + PyDoc_STRVAR(isnumeric__doc__, +-"S.isnumeric() -> bool\n\ ++ "S.isnumeric() -> bool\n\ + \n\ + Return True if there are only numeric characters in S,\n\ + False otherwise."); +@@ -7034,23 +7036,23 @@ + + /* Shortcut for single character strings */ + if (PyUnicode_GET_SIZE(self) == 1 && +- Py_UNICODE_ISNUMERIC(*p)) +- return PyBool_FromLong(1); ++ Py_UNICODE_ISNUMERIC(*p)) ++ return PyBool_FromLong(1); + + /* Special case for empty strings */ + if (PyUnicode_GET_SIZE(self) == 0) +- return PyBool_FromLong(0); ++ return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); + for (; p < e; p++) { +- if (!Py_UNICODE_ISNUMERIC(*p)) +- return PyBool_FromLong(0); ++ if (!Py_UNICODE_ISNUMERIC(*p)) ++ return PyBool_FromLong(0); + } + return PyBool_FromLong(1); + } + + PyDoc_STRVAR(join__doc__, +-"S.join(sequence) -> unicode\n\ ++ "S.join(sequence) -> unicode\n\ + \n\ + Return a string which is the concatenation of the strings in the\n\ + sequence. The separator between elements is S."); +@@ -7068,7 +7070,7 @@ + } + + PyDoc_STRVAR(ljust__doc__, +-"S.ljust(width[, fillchar]) -> int\n\ ++ "S.ljust(width[, fillchar]) -> int\n\ + \n\ + Return S left-justified in a Unicode string of length width. Padding is\n\ + done using the specified fill character (default is a space)."); +@@ -7091,7 +7093,7 @@ + } + + PyDoc_STRVAR(lower__doc__, +-"S.lower() -> unicode\n\ ++ "S.lower() -> unicode\n\ + \n\ + Return a copy of the string S converted to lowercase."); + +@@ -7114,102 +7116,102 @@ + PyObject * + _PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj) + { +- Py_UNICODE *s = PyUnicode_AS_UNICODE(self); +- Py_ssize_t len = PyUnicode_GET_SIZE(self); +- Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj); +- Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj); +- Py_ssize_t i, j; ++ Py_UNICODE *s = PyUnicode_AS_UNICODE(self); ++ Py_ssize_t len = PyUnicode_GET_SIZE(self); ++ Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj); ++ Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj); ++ Py_ssize_t i, j; + +- BLOOM_MASK sepmask = make_bloom_mask(sep, seplen); ++ BLOOM_MASK sepmask = make_bloom_mask(sep, seplen); + +- i = 0; +- if (striptype != RIGHTSTRIP) { +- while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) { +- i++; +- } +- } ++ i = 0; ++ if (striptype != RIGHTSTRIP) { ++ while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) { ++ i++; ++ } ++ } + +- j = len; +- if (striptype != LEFTSTRIP) { +- do { +- j--; +- } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen)); +- j++; +- } ++ j = len; ++ if (striptype != LEFTSTRIP) { ++ do { ++ j--; ++ } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen)); ++ j++; ++ } + +- if (i == 0 && j == len && PyUnicode_CheckExact(self)) { +- Py_INCREF(self); +- return (PyObject*)self; +- } +- else +- return PyUnicode_FromUnicode(s+i, j-i); ++ if (i == 0 && j == len && PyUnicode_CheckExact(self)) { ++ Py_INCREF(self); ++ return (PyObject*)self; ++ } ++ else ++ return PyUnicode_FromUnicode(s+i, j-i); + } + + + static PyObject * + do_strip(PyUnicodeObject *self, int striptype) + { +- Py_UNICODE *s = PyUnicode_AS_UNICODE(self); +- Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j; ++ Py_UNICODE *s = PyUnicode_AS_UNICODE(self); ++ Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j; + +- i = 0; +- if (striptype != RIGHTSTRIP) { +- while (i < len && Py_UNICODE_ISSPACE(s[i])) { +- i++; +- } +- } ++ i = 0; ++ if (striptype != RIGHTSTRIP) { ++ while (i < len && Py_UNICODE_ISSPACE(s[i])) { ++ i++; ++ } ++ } + +- j = len; +- if (striptype != LEFTSTRIP) { +- do { +- j--; +- } while (j >= i && Py_UNICODE_ISSPACE(s[j])); +- j++; +- } ++ j = len; ++ if (striptype != LEFTSTRIP) { ++ do { ++ j--; ++ } while (j >= i && Py_UNICODE_ISSPACE(s[j])); ++ j++; ++ } + +- if (i == 0 && j == len && PyUnicode_CheckExact(self)) { +- Py_INCREF(self); +- return (PyObject*)self; +- } +- else +- return PyUnicode_FromUnicode(s+i, j-i); ++ if (i == 0 && j == len && PyUnicode_CheckExact(self)) { ++ Py_INCREF(self); ++ return (PyObject*)self; ++ } ++ else ++ return PyUnicode_FromUnicode(s+i, j-i); + } + + + static PyObject * + do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args) + { +- PyObject *sep = NULL; ++ PyObject *sep = NULL; + +- if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep)) +- return NULL; ++ if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep)) ++ return NULL; + +- if (sep != NULL && sep != Py_None) { +- if (PyUnicode_Check(sep)) +- return _PyUnicode_XStrip(self, striptype, sep); +- else if (PyString_Check(sep)) { +- PyObject *res; +- sep = PyUnicode_FromObject(sep); +- if (sep==NULL) +- return NULL; +- res = _PyUnicode_XStrip(self, striptype, sep); +- Py_DECREF(sep); +- return res; +- } +- else { +- PyErr_Format(PyExc_TypeError, +- "%s arg must be None, unicode or str", +- STRIPNAME(striptype)); +- return NULL; +- } +- } ++ if (sep != NULL && sep != Py_None) { ++ if (PyUnicode_Check(sep)) ++ return _PyUnicode_XStrip(self, striptype, sep); ++ else if (PyString_Check(sep)) { ++ PyObject *res; ++ sep = PyUnicode_FromObject(sep); ++ if (sep==NULL) ++ return NULL; ++ res = _PyUnicode_XStrip(self, striptype, sep); ++ Py_DECREF(sep); ++ return res; ++ } ++ else { ++ PyErr_Format(PyExc_TypeError, ++ "%s arg must be None, unicode or str", ++ STRIPNAME(striptype)); ++ return NULL; ++ } ++ } + +- return do_strip(self, striptype); ++ return do_strip(self, striptype); + } + + + PyDoc_STRVAR(strip__doc__, +-"S.strip([chars]) -> unicode\n\ ++ "S.strip([chars]) -> unicode\n\ + \n\ + Return a copy of the string S with leading and trailing\n\ + whitespace removed.\n\ +@@ -7219,15 +7221,15 @@ + static PyObject * + unicode_strip(PyUnicodeObject *self, PyObject *args) + { +- if (PyTuple_GET_SIZE(args) == 0) +- return do_strip(self, BOTHSTRIP); /* Common case */ +- else +- return do_argstrip(self, BOTHSTRIP, args); ++ if (PyTuple_GET_SIZE(args) == 0) ++ return do_strip(self, BOTHSTRIP); /* Common case */ ++ else ++ return do_argstrip(self, BOTHSTRIP, args); + } + + + PyDoc_STRVAR(lstrip__doc__, +-"S.lstrip([chars]) -> unicode\n\ ++ "S.lstrip([chars]) -> unicode\n\ + \n\ + Return a copy of the string S with leading whitespace removed.\n\ + If chars is given and not None, remove characters in chars instead.\n\ +@@ -7236,15 +7238,15 @@ + static PyObject * + unicode_lstrip(PyUnicodeObject *self, PyObject *args) + { +- if (PyTuple_GET_SIZE(args) == 0) +- return do_strip(self, LEFTSTRIP); /* Common case */ +- else +- return do_argstrip(self, LEFTSTRIP, args); ++ if (PyTuple_GET_SIZE(args) == 0) ++ return do_strip(self, LEFTSTRIP); /* Common case */ ++ else ++ return do_argstrip(self, LEFTSTRIP, args); + } + + + PyDoc_STRVAR(rstrip__doc__, +-"S.rstrip([chars]) -> unicode\n\ ++ "S.rstrip([chars]) -> unicode\n\ + \n\ + Return a copy of the string S with trailing whitespace removed.\n\ + If chars is given and not None, remove characters in chars instead.\n\ +@@ -7253,10 +7255,10 @@ + static PyObject * + unicode_rstrip(PyUnicodeObject *self, PyObject *args) + { +- if (PyTuple_GET_SIZE(args) == 0) +- return do_strip(self, RIGHTSTRIP); /* Common case */ +- else +- return do_argstrip(self, RIGHTSTRIP, args); ++ if (PyTuple_GET_SIZE(args) == 0) ++ return do_strip(self, RIGHTSTRIP); /* Common case */ ++ else ++ return do_argstrip(self, RIGHTSTRIP, args); + } + + +@@ -7301,25 +7303,25 @@ + if (str->length == 1 && len > 0) { + Py_UNICODE_FILL(p, str->str[0], len); + } else { +- Py_ssize_t done = 0; /* number of characters copied this far */ +- if (done < nchars) { ++ Py_ssize_t done = 0; /* number of characters copied this far */ ++ if (done < nchars) { + Py_UNICODE_COPY(p, str->str, str->length); + done = str->length; +- } +- while (done < nchars) { ++ } ++ while (done < nchars) { + Py_ssize_t n = (done <= nchars-done) ? done : nchars-done; + Py_UNICODE_COPY(p+done, p, n); + done += n; +- } ++ } + } + + return (PyObject*) u; + } + + PyObject *PyUnicode_Replace(PyObject *obj, +- PyObject *subobj, +- PyObject *replobj, +- Py_ssize_t maxcount) ++ PyObject *subobj, ++ PyObject *replobj, ++ Py_ssize_t maxcount) + { + PyObject *self; + PyObject *str1; +@@ -7328,22 +7330,22 @@ + + self = PyUnicode_FromObject(obj); + if (self == NULL) +- return NULL; ++ return NULL; + str1 = PyUnicode_FromObject(subobj); + if (str1 == NULL) { +- Py_DECREF(self); +- return NULL; ++ Py_DECREF(self); ++ return NULL; + } + str2 = PyUnicode_FromObject(replobj); + if (str2 == NULL) { +- Py_DECREF(self); +- Py_DECREF(str1); +- return NULL; ++ Py_DECREF(self); ++ Py_DECREF(str1); ++ return NULL; + } + result = replace((PyUnicodeObject *)self, +- (PyUnicodeObject *)str1, +- (PyUnicodeObject *)str2, +- maxcount); ++ (PyUnicodeObject *)str1, ++ (PyUnicodeObject *)str2, ++ maxcount); + Py_DECREF(self); + Py_DECREF(str1); + Py_DECREF(str2); +@@ -7351,7 +7353,7 @@ + } + + PyDoc_STRVAR(replace__doc__, +-"S.replace (old, new[, count]) -> unicode\n\ ++ "S.replace (old, new[, count]) -> unicode\n\ + \n\ + Return a copy of S with all occurrences of substring\n\ + old replaced by new. If the optional argument count is\n\ +@@ -7369,11 +7371,11 @@ + return NULL; + str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1); + if (str1 == NULL) +- return NULL; ++ return NULL; + str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2); + if (str2 == NULL) { +- Py_DECREF(str1); +- return NULL; ++ Py_DECREF(str1); ++ return NULL; + } + + result = replace(self, str1, str2, maxcount); +@@ -7387,12 +7389,12 @@ + PyObject *unicode_repr(PyObject *unicode) + { + return unicodeescape_string(PyUnicode_AS_UNICODE(unicode), +- PyUnicode_GET_SIZE(unicode), +- 1); ++ PyUnicode_GET_SIZE(unicode), ++ 1); + } + + PyDoc_STRVAR(rfind__doc__, +-"S.rfind(sub [,start [,end]]) -> int\n\ ++ "S.rfind(sub [,start [,end]]) -> int\n\ + \n\ + Return the highest index in S where substring sub is found,\n\ + such that sub is contained within s[start:end]. Optional\n\ +@@ -7409,7 +7411,7 @@ + Py_ssize_t result; + + if (!_ParseTupleFinds(args, &substring, &start, &end)) +- return NULL; ++ return NULL; + + result = stringlib_rfind_slice( + PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self), +@@ -7423,7 +7425,7 @@ + } + + PyDoc_STRVAR(rindex__doc__, +-"S.rindex(sub [,start [,end]]) -> int\n\ ++ "S.rindex(sub [,start [,end]]) -> int\n\ + \n\ + Like S.rfind() but raise ValueError when the substring is not found."); + +@@ -7436,7 +7438,7 @@ + Py_ssize_t result; + + if (!_ParseTupleFinds(args, &substring, &start, &end)) +- return NULL; ++ return NULL; + + result = stringlib_rfind_slice( + PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self), +@@ -7454,7 +7456,7 @@ + } + + PyDoc_STRVAR(rjust__doc__, +-"S.rjust(width[, fillchar]) -> unicode\n\ ++ "S.rjust(width[, fillchar]) -> unicode\n\ + \n\ + Return S right-justified in a Unicode string of length width. Padding is\n\ + done using the specified fill character (default is a space)."); +@@ -7495,24 +7497,24 @@ + start = end; + /* copy slice */ + return (PyObject*) PyUnicode_FromUnicode(self->str + start, +- end - start); ++ end - start); + } + + PyObject *PyUnicode_Split(PyObject *s, +- PyObject *sep, +- Py_ssize_t maxsplit) ++ PyObject *sep, ++ Py_ssize_t maxsplit) + { + PyObject *result; + + s = PyUnicode_FromObject(s); + if (s == NULL) +- return NULL; ++ return NULL; + if (sep != NULL) { +- sep = PyUnicode_FromObject(sep); +- if (sep == NULL) { +- Py_DECREF(s); +- return NULL; +- } ++ sep = PyUnicode_FromObject(sep); ++ if (sep == NULL) { ++ Py_DECREF(s); ++ return NULL; ++ } + } + + result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit); +@@ -7523,7 +7525,7 @@ + } + + PyDoc_STRVAR(split__doc__, +-"S.split([sep [,maxsplit]]) -> list of strings\n\ ++ "S.split([sep [,maxsplit]]) -> list of strings\n\ + \n\ + Return a list of the words in S, using sep as the\n\ + delimiter string. If maxsplit is given, at most maxsplit\n\ +@@ -7541,11 +7543,11 @@ + return NULL; + + if (substring == Py_None) +- return split(self, NULL, maxcount); ++ return split(self, NULL, maxcount); + else if (PyUnicode_Check(substring)) +- return split(self, (PyUnicodeObject *)substring, maxcount); ++ return split(self, (PyUnicodeObject *)substring, maxcount); + else +- return PyUnicode_Split((PyObject *)self, substring, maxcount); ++ return PyUnicode_Split((PyObject *)self, substring, maxcount); + } + + PyObject * +@@ -7557,7 +7559,7 @@ + + str_obj = PyUnicode_FromObject(str_in); + if (!str_obj) +- return NULL; ++ return NULL; + sep_obj = PyUnicode_FromObject(sep_in); + if (!sep_obj) { + Py_DECREF(str_obj); +@@ -7585,7 +7587,7 @@ + + str_obj = PyUnicode_FromObject(str_in); + if (!str_obj) +- return NULL; ++ return NULL; + sep_obj = PyUnicode_FromObject(sep_in); + if (!sep_obj) { + Py_DECREF(str_obj); +@@ -7604,7 +7606,7 @@ + } + + PyDoc_STRVAR(partition__doc__, +-"S.partition(sep) -> (head, sep, tail)\n\ ++ "S.partition(sep) -> (head, sep, tail)\n\ + \n\ + Search for the separator sep in S, and return the part before it,\n\ + the separator itself, and the part after it. If the separator is not\n\ +@@ -7617,7 +7619,7 @@ + } + + PyDoc_STRVAR(rpartition__doc__, +-"S.rpartition(sep) -> (tail, sep, head)\n\ ++ "S.rpartition(sep) -> (tail, sep, head)\n\ + \n\ + Search for the separator sep in S, starting at the end of S, and return\n\ + the part before it, the separator itself, and the part after it. If the\n\ +@@ -7630,20 +7632,20 @@ + } + + PyObject *PyUnicode_RSplit(PyObject *s, +- PyObject *sep, +- Py_ssize_t maxsplit) ++ PyObject *sep, ++ Py_ssize_t maxsplit) + { + PyObject *result; +- ++ + s = PyUnicode_FromObject(s); + if (s == NULL) +- return NULL; ++ return NULL; + if (sep != NULL) { +- sep = PyUnicode_FromObject(sep); +- if (sep == NULL) { +- Py_DECREF(s); +- return NULL; +- } ++ sep = PyUnicode_FromObject(sep); ++ if (sep == NULL) { ++ Py_DECREF(s); ++ return NULL; ++ } + } + + result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit); +@@ -7654,7 +7656,7 @@ + } + + PyDoc_STRVAR(rsplit__doc__, +-"S.rsplit([sep [,maxsplit]]) -> list of strings\n\ ++ "S.rsplit([sep [,maxsplit]]) -> list of strings\n\ + \n\ + Return a list of the words in S, using sep as the\n\ + delimiter string, starting at the end of the string and\n\ +@@ -7672,15 +7674,15 @@ + return NULL; + + if (substring == Py_None) +- return rsplit(self, NULL, maxcount); ++ return rsplit(self, NULL, maxcount); + else if (PyUnicode_Check(substring)) +- return rsplit(self, (PyUnicodeObject *)substring, maxcount); ++ return rsplit(self, (PyUnicodeObject *)substring, maxcount); + else +- return PyUnicode_RSplit((PyObject *)self, substring, maxcount); ++ return PyUnicode_RSplit((PyObject *)self, substring, maxcount); + } + + PyDoc_STRVAR(splitlines__doc__, +-"S.splitlines([keepends]]) -> list of strings\n\ ++ "S.splitlines([keepends]) -> list of strings\n\ + \n\ + Return a list of the lines in S, breaking at line boundaries.\n\ + Line breaks are not included in the resulting list unless keepends\n\ +@@ -7704,7 +7706,7 @@ + } + + PyDoc_STRVAR(swapcase__doc__, +-"S.swapcase() -> unicode\n\ ++ "S.swapcase() -> unicode\n\ + \n\ + Return a copy of S with uppercase characters converted to lowercase\n\ + and vice versa."); +@@ -7716,7 +7718,7 @@ + } + + PyDoc_STRVAR(translate__doc__, +-"S.translate(table) -> unicode\n\ ++ "S.translate(table) -> unicode\n\ + \n\ + Return a copy of the string S, where all characters have been mapped\n\ + through the given translation table, which must be a mapping of\n\ +@@ -7728,13 +7730,13 @@ + unicode_translate(PyUnicodeObject *self, PyObject *table) + { + return PyUnicode_TranslateCharmap(self->str, +- self->length, +- table, +- "ignore"); ++ self->length, ++ table, ++ "ignore"); + } + + PyDoc_STRVAR(upper__doc__, +-"S.upper() -> unicode\n\ ++ "S.upper() -> unicode\n\ + \n\ + Return a copy of S converted to uppercase."); + +@@ -7745,7 +7747,7 @@ + } + + PyDoc_STRVAR(zfill__doc__, +-"S.zfill(width) -> unicode\n\ ++ "S.zfill(width) -> unicode\n\ + \n\ + Pad a numeric string S with zeros on the left, to fill a field\n\ + of the specified width. The string S is never truncated."); +@@ -7769,7 +7771,7 @@ + return PyUnicode_FromUnicode( + PyUnicode_AS_UNICODE(self), + PyUnicode_GET_SIZE(self) +- ); ++ ); + } + + fill = width - self->length; +@@ -7797,7 +7799,7 @@ + #endif + + PyDoc_STRVAR(startswith__doc__, +-"S.startswith(prefix[, start[, end]]) -> bool\n\ ++ "S.startswith(prefix[, start[, end]]) -> bool\n\ + \n\ + Return True if S starts with the specified prefix, False otherwise.\n\ + With optional start, test S beginning at that position.\n\ +@@ -7806,7 +7808,7 @@ + + static PyObject * + unicode_startswith(PyUnicodeObject *self, +- PyObject *args) ++ PyObject *args) + { + PyObject *subobj; + PyUnicodeObject *substring; +@@ -7815,13 +7817,13 @@ + int result; + + if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj, +- _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) +- return NULL; ++ _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) ++ return NULL; + if (PyTuple_Check(subobj)) { + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { + substring = (PyUnicodeObject *)PyUnicode_FromObject( +- PyTuple_GET_ITEM(subobj, i)); ++ PyTuple_GET_ITEM(subobj, i)); + if (substring == NULL) + return NULL; + result = tailmatch(self, substring, start, end, -1); +@@ -7835,7 +7837,7 @@ + } + substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj); + if (substring == NULL) +- return NULL; ++ return NULL; + result = tailmatch(self, substring, start, end, -1); + Py_DECREF(substring); + return PyBool_FromLong(result); +@@ -7843,7 +7845,7 @@ + + + PyDoc_STRVAR(endswith__doc__, +-"S.endswith(suffix[, start[, end]]) -> bool\n\ ++ "S.endswith(suffix[, start[, end]]) -> bool\n\ + \n\ + Return True if S ends with the specified suffix, False otherwise.\n\ + With optional start, test S beginning at that position.\n\ +@@ -7852,7 +7854,7 @@ + + static PyObject * + unicode_endswith(PyUnicodeObject *self, +- PyObject *args) ++ PyObject *args) + { + PyObject *subobj; + PyUnicodeObject *substring; +@@ -7861,15 +7863,15 @@ + int result; + + if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj, +- _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) +- return NULL; ++ _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) ++ return NULL; + if (PyTuple_Check(subobj)) { + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { + substring = (PyUnicodeObject *)PyUnicode_FromObject( +- PyTuple_GET_ITEM(subobj, i)); ++ PyTuple_GET_ITEM(subobj, i)); + if (substring == NULL) +- return NULL; ++ return NULL; + result = tailmatch(self, substring, start, end, +1); + Py_DECREF(substring); + if (result) { +@@ -7880,7 +7882,7 @@ + } + substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj); + if (substring == NULL) +- return NULL; ++ return NULL; + + result = tailmatch(self, substring, start, end, +1); + Py_DECREF(substring); +@@ -7892,7 +7894,7 @@ + #include "stringlib/string_format.h" + + PyDoc_STRVAR(format__doc__, +-"S.format(*args, **kwargs) -> unicode\n\ ++ "S.format(*args, **kwargs) -> unicode\n\ + \n\ + "); + +@@ -7909,7 +7911,7 @@ + goto done; + if (!(PyBytes_Check(format_spec) || PyUnicode_Check(format_spec))) { + PyErr_Format(PyExc_TypeError, "__format__ arg must be str " +- "or unicode, not %s", Py_TYPE(format_spec)->tp_name); ++ "or unicode, not %s", Py_TYPE(format_spec)->tp_name); + goto done; + } + tmp = PyObject_Unicode(format_spec); +@@ -7920,13 +7922,13 @@ + result = _PyUnicode_FormatAdvanced(self, + PyUnicode_AS_UNICODE(format_spec), + PyUnicode_GET_SIZE(format_spec)); +-done: ++ done: + Py_XDECREF(tmp); + return result; + } + + PyDoc_STRVAR(p_format__doc__, +-"S.__format__(format_spec) -> unicode\n\ ++ "S.__format__(format_spec) -> unicode\n\ + \n\ + "); + +@@ -7938,14 +7940,14 @@ + } + + PyDoc_STRVAR(sizeof__doc__, +-"S.__sizeof__() -> size of S in memory, in bytes\n\ ++ "S.__sizeof__() -> size of S in memory, in bytes\n\ + \n\ + "); + + static PyObject * + unicode_getnewargs(PyUnicodeObject *v) + { +- return Py_BuildValue("(u#)", v->str, v->length); ++ return Py_BuildValue("(u#)", v->str, v->length); + } + + +@@ -8008,37 +8010,37 @@ + {"freelistsize", (PyCFunction) free_listsize, METH_NOARGS}, + #endif + +- {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS}, ++ {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS}, + {NULL, NULL} + }; + + static PyObject * + unicode_mod(PyObject *v, PyObject *w) + { +- if (!PyUnicode_Check(v)) { +- Py_INCREF(Py_NotImplemented); +- return Py_NotImplemented; +- } +- return PyUnicode_Format(v, w); ++ if (!PyUnicode_Check(v)) { ++ Py_INCREF(Py_NotImplemented); ++ return Py_NotImplemented; ++ } ++ return PyUnicode_Format(v, w); + } + + static PyNumberMethods unicode_as_number = { +- 0, /*nb_add*/ +- 0, /*nb_subtract*/ +- 0, /*nb_multiply*/ +- 0, /*nb_divide*/ +- unicode_mod, /*nb_remainder*/ ++ 0, /*nb_add*/ ++ 0, /*nb_subtract*/ ++ 0, /*nb_multiply*/ ++ 0, /*nb_divide*/ ++ unicode_mod, /*nb_remainder*/ + }; + + static PySequenceMethods unicode_as_sequence = { +- (lenfunc) unicode_length, /* sq_length */ +- PyUnicode_Concat, /* sq_concat */ +- (ssizeargfunc) unicode_repeat, /* sq_repeat */ +- (ssizeargfunc) unicode_getitem, /* sq_item */ +- (ssizessizeargfunc) unicode_slice, /* sq_slice */ +- 0, /* sq_ass_item */ +- 0, /* sq_ass_slice */ +- PyUnicode_Contains, /* sq_contains */ ++ (lenfunc) unicode_length, /* sq_length */ ++ PyUnicode_Concat, /* sq_concat */ ++ (ssizeargfunc) unicode_repeat, /* sq_repeat */ ++ (ssizeargfunc) unicode_getitem, /* sq_item */ ++ (ssizessizeargfunc) unicode_slice, /* sq_slice */ ++ 0, /* sq_ass_item */ ++ 0, /* sq_ass_slice */ ++ PyUnicode_Contains, /* sq_contains */ + }; + + static PyObject* +@@ -8058,7 +8060,7 @@ + PyObject* result; + + if (PySlice_GetIndicesEx((PySliceObject*)item, PyUnicode_GET_SIZE(self), +- &start, &stop, &step, &slicelength) < 0) { ++ &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + +@@ -8074,10 +8076,10 @@ + source_buf = PyUnicode_AS_UNICODE((PyObject*)self); + result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength* + sizeof(Py_UNICODE)); +- +- if (result_buf == NULL) +- return PyErr_NoMemory(); + ++ if (result_buf == NULL) ++ return PyErr_NoMemory(); ++ + for (cur = start, i = 0; i < slicelength; cur += step, i++) { + result_buf[i] = source_buf[cur]; + } +@@ -8093,19 +8095,19 @@ + } + + static PyMappingMethods unicode_as_mapping = { +- (lenfunc)unicode_length, /* mp_length */ +- (binaryfunc)unicode_subscript, /* mp_subscript */ +- (objobjargproc)0, /* mp_ass_subscript */ ++ (lenfunc)unicode_length, /* mp_length */ ++ (binaryfunc)unicode_subscript, /* mp_subscript */ ++ (objobjargproc)0, /* mp_ass_subscript */ + }; + + static Py_ssize_t + unicode_buffer_getreadbuf(PyUnicodeObject *self, +- Py_ssize_t index, +- const void **ptr) ++ Py_ssize_t index, ++ const void **ptr) + { + if (index != 0) { + PyErr_SetString(PyExc_SystemError, +- "accessing non-existent unicode segment"); ++ "accessing non-existent unicode segment"); + return -1; + } + *ptr = (void *) self->str; +@@ -8114,16 +8116,16 @@ + + static Py_ssize_t + unicode_buffer_getwritebuf(PyUnicodeObject *self, Py_ssize_t index, +- const void **ptr) ++ const void **ptr) + { + PyErr_SetString(PyExc_TypeError, +- "cannot use unicode as modifiable buffer"); ++ "cannot use unicode as modifiable buffer"); + return -1; + } + + static int + unicode_buffer_getsegcount(PyUnicodeObject *self, +- Py_ssize_t *lenp) ++ Py_ssize_t *lenp) + { + if (lenp) + *lenp = PyUnicode_GET_DATA_SIZE(self); +@@ -8132,19 +8134,19 @@ + + static Py_ssize_t + unicode_buffer_getcharbuf(PyUnicodeObject *self, +- Py_ssize_t index, +- const void **ptr) ++ Py_ssize_t index, ++ const void **ptr) + { + PyObject *str; + + if (index != 0) { + PyErr_SetString(PyExc_SystemError, +- "accessing non-existent unicode segment"); ++ "accessing non-existent unicode segment"); + return -1; + } + str = _PyUnicode_AsDefaultEncodedString((PyObject *)self, NULL); + if (str == NULL) +- return -1; ++ return -1; + *ptr = (void *) PyString_AS_STRING(str); + return PyString_GET_SIZE(str); + } +@@ -8156,22 +8158,22 @@ + { + Py_ssize_t argidx = *p_argidx; + if (argidx < arglen) { +- (*p_argidx)++; +- if (arglen < 0) +- return args; +- else +- return PyTuple_GetItem(args, argidx); ++ (*p_argidx)++; ++ if (arglen < 0) ++ return args; ++ else ++ return PyTuple_GetItem(args, argidx); + } + PyErr_SetString(PyExc_TypeError, +- "not enough arguments for format string"); ++ "not enough arguments for format string"); + return NULL; + } + + #define F_LJUST (1<<0) +-#define F_SIGN (1<<1) ++#define F_SIGN (1<<1) + #define F_BLANK (1<<2) +-#define F_ALT (1<<3) +-#define F_ZERO (1<<4) ++#define F_ALT (1<<3) ++#define F_ZERO (1<<4) + + static Py_ssize_t + strtounicode(Py_UNICODE *buffer, const char *charbuffer) +@@ -8179,7 +8181,7 @@ + register Py_ssize_t i; + Py_ssize_t len = strlen(charbuffer); + for (i = len - 1; i >= 0; i--) +- buffer[i] = (Py_UNICODE) charbuffer[i]; ++ buffer[i] = (Py_UNICODE) charbuffer[i]; + + return len; + } +@@ -8210,11 +8212,11 @@ + + static int + formatfloat(Py_UNICODE *buf, +- size_t buflen, +- int flags, +- int prec, +- int type, +- PyObject *v) ++ size_t buflen, ++ int flags, ++ int prec, ++ int type, ++ PyObject *v) + { + /* fmt = '%#.' + `prec` + `type` + worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/ +@@ -8223,70 +8225,70 @@ + + x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) +- return -1; ++ return -1; + if (prec < 0) +- prec = 6; ++ prec = 6; + if (type == 'f' && (fabs(x) / 1e25) >= 1e25) +- type = 'g'; ++ type = 'g'; + /* Worst case length calc to ensure no buffer overrun: + + 'g' formats: +- fmt = %#.g +- buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp +- for any double rep.) +- len = 1 + prec + 1 + 2 + 5 = 9 + prec ++ fmt = %#.g ++ buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp ++ for any double rep.) ++ len = 1 + prec + 1 + 2 + 5 = 9 + prec + + 'f' formats: +- buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50) +- len = 1 + 50 + 1 + prec = 52 + prec ++ buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50) ++ len = 1 + 50 + 1 + prec = 52 + prec + + If prec=0 the effective precision is 1 (the leading digit is + always given), therefore increase the length by one. + + */ +- if (((type == 'g' || type == 'G') && +- buflen <= (size_t)10 + (size_t)prec) || +- (type == 'f' && buflen <= (size_t)53 + (size_t)prec)) { +- PyErr_SetString(PyExc_OverflowError, +- "formatted float is too long (precision too large?)"); +- return -1; ++ if (((type == 'g' || type == 'G') && ++ buflen <= (size_t)10 + (size_t)prec) || ++ (type == 'f' && buflen <= (size_t)53 + (size_t)prec)) { ++ PyErr_SetString(PyExc_OverflowError, ++ "formatted float is too long (precision too large?)"); ++ return -1; + } + PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c", +- (flags&F_ALT) ? "#" : "", +- prec, type); ++ (flags&F_ALT) ? "#" : "", ++ prec, type); + return doubletounicode(buf, buflen, fmt, x); + } + + static PyObject* + formatlong(PyObject *val, int flags, int prec, int type) + { +- char *buf; +- int i, len; +- PyObject *str; /* temporary string object. */ +- PyUnicodeObject *result; ++ char *buf; ++ int i, len; ++ PyObject *str; /* temporary string object. */ ++ PyUnicodeObject *result; + +- str = _PyString_FormatLong(val, flags, prec, type, &buf, &len); +- if (!str) +- return NULL; +- result = _PyUnicode_New(len); +- if (!result) { +- Py_DECREF(str); +- return NULL; +- } +- for (i = 0; i < len; i++) +- result->str[i] = buf[i]; +- result->str[len] = 0; +- Py_DECREF(str); +- return (PyObject*)result; ++ str = _PyString_FormatLong(val, flags, prec, type, &buf, &len); ++ if (!str) ++ return NULL; ++ result = _PyUnicode_New(len); ++ if (!result) { ++ Py_DECREF(str); ++ return NULL; ++ } ++ for (i = 0; i < len; i++) ++ result->str[i] = buf[i]; ++ result->str[len] = 0; ++ Py_DECREF(str); ++ return (PyObject*)result; + } + + static int + formatint(Py_UNICODE *buf, +- size_t buflen, +- int flags, +- int prec, +- int type, +- PyObject *v) ++ size_t buflen, ++ int flags, ++ int prec, ++ int type, ++ PyObject *v) + { + /* fmt = '%#.' + `prec` + 'l' + `type` + * worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine) +@@ -8315,7 +8317,7 @@ + */ + if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) { + PyErr_SetString(PyExc_OverflowError, +- "formatted integer is too long (precision too large?)"); ++ "formatted integer is too long (precision too large?)"); + return -1; + } + +@@ -8362,46 +8364,46 @@ + { + /* presume that the buffer is at least 2 characters long */ + if (PyUnicode_Check(v)) { +- if (PyUnicode_GET_SIZE(v) != 1) +- goto onError; +- buf[0] = PyUnicode_AS_UNICODE(v)[0]; ++ if (PyUnicode_GET_SIZE(v) != 1) ++ goto onError; ++ buf[0] = PyUnicode_AS_UNICODE(v)[0]; + } + + else if (PyString_Check(v)) { +- if (PyString_GET_SIZE(v) != 1) +- goto onError; +- buf[0] = (Py_UNICODE)PyString_AS_STRING(v)[0]; ++ if (PyString_GET_SIZE(v) != 1) ++ goto onError; ++ buf[0] = (Py_UNICODE)PyString_AS_STRING(v)[0]; + } + + else { +- /* Integer input truncated to a character */ ++ /* Integer input truncated to a character */ + long x; +- x = PyInt_AsLong(v); +- if (x == -1 && PyErr_Occurred()) +- goto onError; ++ x = PyInt_AsLong(v); ++ if (x == -1 && PyErr_Occurred()) ++ goto onError; + #ifdef Py_UNICODE_WIDE +- if (x < 0 || x > 0x10ffff) { +- PyErr_SetString(PyExc_OverflowError, +- "%c arg not in range(0x110000) " +- "(wide Python build)"); +- return -1; +- } ++ if (x < 0 || x > 0x10ffff) { ++ PyErr_SetString(PyExc_OverflowError, ++ "%c arg not in range(0x110000) " ++ "(wide Python build)"); ++ return -1; ++ } + #else +- if (x < 0 || x > 0xffff) { +- PyErr_SetString(PyExc_OverflowError, +- "%c arg not in range(0x10000) " +- "(narrow Python build)"); +- return -1; +- } ++ if (x < 0 || x > 0xffff) { ++ PyErr_SetString(PyExc_OverflowError, ++ "%c arg not in range(0x10000) " ++ "(narrow Python build)"); ++ return -1; ++ } + #endif +- buf[0] = (Py_UNICODE) x; ++ buf[0] = (Py_UNICODE) x; + } + buf[1] = '\0'; + return 1; + +- onError: ++ onError: + PyErr_SetString(PyExc_TypeError, +- "%c requires int or char"); ++ "%c requires int or char"); + return -1; + } + +@@ -8416,7 +8418,7 @@ + #define FORMATBUFLEN (size_t)120 + + PyObject *PyUnicode_Format(PyObject *format, +- PyObject *args) ++ PyObject *args) + { + Py_UNICODE *fmt, *res; + Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx; +@@ -8426,449 +8428,449 @@ + PyObject *uformat; + + if (format == NULL || args == NULL) { +- PyErr_BadInternalCall(); +- return NULL; ++ PyErr_BadInternalCall(); ++ return NULL; + } + uformat = PyUnicode_FromObject(format); + if (uformat == NULL) +- return NULL; ++ return NULL; + fmt = PyUnicode_AS_UNICODE(uformat); + fmtcnt = PyUnicode_GET_SIZE(uformat); + + reslen = rescnt = fmtcnt + 100; + result = _PyUnicode_New(reslen); + if (result == NULL) +- goto onError; ++ goto onError; + res = PyUnicode_AS_UNICODE(result); + + if (PyTuple_Check(args)) { +- arglen = PyTuple_Size(args); +- argidx = 0; ++ arglen = PyTuple_Size(args); ++ argidx = 0; + } + else { +- arglen = -1; +- argidx = -2; ++ arglen = -1; ++ argidx = -2; + } + if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) && + !PyObject_TypeCheck(args, &PyBaseString_Type)) +- dict = args; ++ dict = args; + + while (--fmtcnt >= 0) { +- if (*fmt != '%') { +- if (--rescnt < 0) { +- rescnt = fmtcnt + 100; +- reslen += rescnt; +- if (_PyUnicode_Resize(&result, reslen) < 0) +- goto onError; +- res = PyUnicode_AS_UNICODE(result) + reslen - rescnt; +- --rescnt; +- } +- *res++ = *fmt++; +- } +- else { +- /* Got a format specifier */ +- int flags = 0; +- Py_ssize_t width = -1; +- int prec = -1; +- Py_UNICODE c = '\0'; +- Py_UNICODE fill; +- int isnumok; +- PyObject *v = NULL; +- PyObject *temp = NULL; +- Py_UNICODE *pbuf; +- Py_UNICODE sign; +- Py_ssize_t len; +- Py_UNICODE formatbuf[FORMATBUFLEN]; /* For format{float,int,char}() */ ++ if (*fmt != '%') { ++ if (--rescnt < 0) { ++ rescnt = fmtcnt + 100; ++ reslen += rescnt; ++ if (_PyUnicode_Resize(&result, reslen) < 0) ++ goto onError; ++ res = PyUnicode_AS_UNICODE(result) + reslen - rescnt; ++ --rescnt; ++ } ++ *res++ = *fmt++; ++ } ++ else { ++ /* Got a format specifier */ ++ int flags = 0; ++ Py_ssize_t width = -1; ++ int prec = -1; ++ Py_UNICODE c = '\0'; ++ Py_UNICODE fill; ++ int isnumok; ++ PyObject *v = NULL; ++ PyObject *temp = NULL; ++ Py_UNICODE *pbuf; ++ Py_UNICODE sign; ++ Py_ssize_t len; ++ Py_UNICODE formatbuf[FORMATBUFLEN]; /* For format{float,int,char}() */ + +- fmt++; +- if (*fmt == '(') { +- Py_UNICODE *keystart; +- Py_ssize_t keylen; +- PyObject *key; +- int pcount = 1; ++ fmt++; ++ if (*fmt == '(') { ++ Py_UNICODE *keystart; ++ Py_ssize_t keylen; ++ PyObject *key; ++ int pcount = 1; + +- if (dict == NULL) { +- PyErr_SetString(PyExc_TypeError, +- "format requires a mapping"); +- goto onError; +- } +- ++fmt; +- --fmtcnt; +- keystart = fmt; +- /* Skip over balanced parentheses */ +- while (pcount > 0 && --fmtcnt >= 0) { +- if (*fmt == ')') +- --pcount; +- else if (*fmt == '(') +- ++pcount; +- fmt++; +- } +- keylen = fmt - keystart - 1; +- if (fmtcnt < 0 || pcount > 0) { +- PyErr_SetString(PyExc_ValueError, +- "incomplete format key"); +- goto onError; +- } ++ if (dict == NULL) { ++ PyErr_SetString(PyExc_TypeError, ++ "format requires a mapping"); ++ goto onError; ++ } ++ ++fmt; ++ --fmtcnt; ++ keystart = fmt; ++ /* Skip over balanced parentheses */ ++ while (pcount > 0 && --fmtcnt >= 0) { ++ if (*fmt == ')') ++ --pcount; ++ else if (*fmt == '(') ++ ++pcount; ++ fmt++; ++ } ++ keylen = fmt - keystart - 1; ++ if (fmtcnt < 0 || pcount > 0) { ++ PyErr_SetString(PyExc_ValueError, ++ "incomplete format key"); ++ goto onError; ++ } + #if 0 +- /* keys are converted to strings using UTF-8 and +- then looked up since Python uses strings to hold +- variables names etc. in its namespaces and we +- wouldn't want to break common idioms. */ +- key = PyUnicode_EncodeUTF8(keystart, +- keylen, +- NULL); ++ /* keys are converted to strings using UTF-8 and ++ then looked up since Python uses strings to hold ++ variables names etc. in its namespaces and we ++ wouldn't want to break common idioms. */ ++ key = PyUnicode_EncodeUTF8(keystart, ++ keylen, ++ NULL); + #else +- key = PyUnicode_FromUnicode(keystart, keylen); ++ key = PyUnicode_FromUnicode(keystart, keylen); + #endif +- if (key == NULL) +- goto onError; +- if (args_owned) { +- Py_DECREF(args); +- args_owned = 0; +- } +- args = PyObject_GetItem(dict, key); +- Py_DECREF(key); +- if (args == NULL) { +- goto onError; +- } +- args_owned = 1; +- arglen = -1; +- argidx = -2; +- } +- while (--fmtcnt >= 0) { +- switch (c = *fmt++) { +- case '-': flags |= F_LJUST; continue; +- case '+': flags |= F_SIGN; continue; +- case ' ': flags |= F_BLANK; continue; +- case '#': flags |= F_ALT; continue; +- case '0': flags |= F_ZERO; continue; +- } +- break; +- } +- if (c == '*') { +- v = getnextarg(args, arglen, &argidx); +- if (v == NULL) +- goto onError; +- if (!PyInt_Check(v)) { +- PyErr_SetString(PyExc_TypeError, +- "* wants int"); +- goto onError; +- } +- width = PyInt_AsLong(v); +- if (width < 0) { +- flags |= F_LJUST; +- width = -width; +- } +- if (--fmtcnt >= 0) +- c = *fmt++; +- } +- else if (c >= '0' && c <= '9') { +- width = c - '0'; +- while (--fmtcnt >= 0) { +- c = *fmt++; +- if (c < '0' || c > '9') +- break; +- if ((width*10) / 10 != width) { +- PyErr_SetString(PyExc_ValueError, +- "width too big"); +- goto onError; +- } +- width = width*10 + (c - '0'); +- } +- } +- if (c == '.') { +- prec = 0; +- if (--fmtcnt >= 0) +- c = *fmt++; +- if (c == '*') { +- v = getnextarg(args, arglen, &argidx); +- if (v == NULL) +- goto onError; +- if (!PyInt_Check(v)) { +- PyErr_SetString(PyExc_TypeError, +- "* wants int"); +- goto onError; +- } +- prec = PyInt_AsLong(v); +- if (prec < 0) +- prec = 0; +- if (--fmtcnt >= 0) +- c = *fmt++; +- } +- else if (c >= '0' && c <= '9') { +- prec = c - '0'; +- while (--fmtcnt >= 0) { +- c = Py_CHARMASK(*fmt++); +- if (c < '0' || c > '9') +- break; +- if ((prec*10) / 10 != prec) { +- PyErr_SetString(PyExc_ValueError, +- "prec too big"); +- goto onError; +- } +- prec = prec*10 + (c - '0'); +- } +- } +- } /* prec */ +- if (fmtcnt >= 0) { +- if (c == 'h' || c == 'l' || c == 'L') { +- if (--fmtcnt >= 0) +- c = *fmt++; +- } +- } +- if (fmtcnt < 0) { +- PyErr_SetString(PyExc_ValueError, +- "incomplete format"); +- goto onError; +- } +- if (c != '%') { +- v = getnextarg(args, arglen, &argidx); +- if (v == NULL) +- goto onError; +- } +- sign = 0; +- fill = ' '; +- switch (c) { ++ if (key == NULL) ++ goto onError; ++ if (args_owned) { ++ Py_DECREF(args); ++ args_owned = 0; ++ } ++ args = PyObject_GetItem(dict, key); ++ Py_DECREF(key); ++ if (args == NULL) { ++ goto onError; ++ } ++ args_owned = 1; ++ arglen = -1; ++ argidx = -2; ++ } ++ while (--fmtcnt >= 0) { ++ switch (c = *fmt++) { ++ case '-': flags |= F_LJUST; continue; ++ case '+': flags |= F_SIGN; continue; ++ case ' ': flags |= F_BLANK; continue; ++ case '#': flags |= F_ALT; continue; ++ case '0': flags |= F_ZERO; continue; ++ } ++ break; ++ } ++ if (c == '*') { ++ v = getnextarg(args, arglen, &argidx); ++ if (v == NULL) ++ goto onError; ++ if (!PyInt_Check(v)) { ++ PyErr_SetString(PyExc_TypeError, ++ "* wants int"); ++ goto onError; ++ } ++ width = PyInt_AsLong(v); ++ if (width < 0) { ++ flags |= F_LJUST; ++ width = -width; ++ } ++ if (--fmtcnt >= 0) ++ c = *fmt++; ++ } ++ else if (c >= '0' && c <= '9') { ++ width = c - '0'; ++ while (--fmtcnt >= 0) { ++ c = *fmt++; ++ if (c < '0' || c > '9') ++ break; ++ if ((width*10) / 10 != width) { ++ PyErr_SetString(PyExc_ValueError, ++ "width too big"); ++ goto onError; ++ } ++ width = width*10 + (c - '0'); ++ } ++ } ++ if (c == '.') { ++ prec = 0; ++ if (--fmtcnt >= 0) ++ c = *fmt++; ++ if (c == '*') { ++ v = getnextarg(args, arglen, &argidx); ++ if (v == NULL) ++ goto onError; ++ if (!PyInt_Check(v)) { ++ PyErr_SetString(PyExc_TypeError, ++ "* wants int"); ++ goto onError; ++ } ++ prec = PyInt_AsLong(v); ++ if (prec < 0) ++ prec = 0; ++ if (--fmtcnt >= 0) ++ c = *fmt++; ++ } ++ else if (c >= '0' && c <= '9') { ++ prec = c - '0'; ++ while (--fmtcnt >= 0) { ++ c = Py_CHARMASK(*fmt++); ++ if (c < '0' || c > '9') ++ break; ++ if ((prec*10) / 10 != prec) { ++ PyErr_SetString(PyExc_ValueError, ++ "prec too big"); ++ goto onError; ++ } ++ prec = prec*10 + (c - '0'); ++ } ++ } ++ } /* prec */ ++ if (fmtcnt >= 0) { ++ if (c == 'h' || c == 'l' || c == 'L') { ++ if (--fmtcnt >= 0) ++ c = *fmt++; ++ } ++ } ++ if (fmtcnt < 0) { ++ PyErr_SetString(PyExc_ValueError, ++ "incomplete format"); ++ goto onError; ++ } ++ if (c != '%') { ++ v = getnextarg(args, arglen, &argidx); ++ if (v == NULL) ++ goto onError; ++ } ++ sign = 0; ++ fill = ' '; ++ switch (c) { + +- case '%': +- pbuf = formatbuf; +- /* presume that buffer length is at least 1 */ +- pbuf[0] = '%'; +- len = 1; +- break; ++ case '%': ++ pbuf = formatbuf; ++ /* presume that buffer length is at least 1 */ ++ pbuf[0] = '%'; ++ len = 1; ++ break; + +- case 's': +- case 'r': +- if (PyUnicode_Check(v) && c == 's') { +- temp = v; +- Py_INCREF(temp); +- } +- else { +- PyObject *unicode; +- if (c == 's') +- temp = PyObject_Unicode(v); +- else +- temp = PyObject_Repr(v); +- if (temp == NULL) +- goto onError; ++ case 's': ++ case 'r': ++ if (PyUnicode_Check(v) && c == 's') { ++ temp = v; ++ Py_INCREF(temp); ++ } ++ else { ++ PyObject *unicode; ++ if (c == 's') ++ temp = PyObject_Unicode(v); ++ else ++ temp = PyObject_Repr(v); ++ if (temp == NULL) ++ goto onError; + if (PyUnicode_Check(temp)) + /* nothing to do */; + else if (PyString_Check(temp)) { + /* convert to string to Unicode */ +- unicode = PyUnicode_Decode(PyString_AS_STRING(temp), +- PyString_GET_SIZE(temp), +- NULL, +- "strict"); +- Py_DECREF(temp); +- temp = unicode; +- if (temp == NULL) +- goto onError; +- } +- else { +- Py_DECREF(temp); +- PyErr_SetString(PyExc_TypeError, +- "%s argument has non-string str()"); +- goto onError; +- } +- } +- pbuf = PyUnicode_AS_UNICODE(temp); +- len = PyUnicode_GET_SIZE(temp); +- if (prec >= 0 && len > prec) +- len = prec; +- break; ++ unicode = PyUnicode_Decode(PyString_AS_STRING(temp), ++ PyString_GET_SIZE(temp), ++ NULL, ++ "strict"); ++ Py_DECREF(temp); ++ temp = unicode; ++ if (temp == NULL) ++ goto onError; ++ } ++ else { ++ Py_DECREF(temp); ++ PyErr_SetString(PyExc_TypeError, ++ "%s argument has non-string str()"); ++ goto onError; ++ } ++ } ++ pbuf = PyUnicode_AS_UNICODE(temp); ++ len = PyUnicode_GET_SIZE(temp); ++ if (prec >= 0 && len > prec) ++ len = prec; ++ break; + +- case 'i': +- case 'd': +- case 'u': +- case 'o': +- case 'x': +- case 'X': +- if (c == 'i') +- c = 'd'; +- isnumok = 0; +- if (PyNumber_Check(v)) { +- PyObject *iobj=NULL; ++ case 'i': ++ case 'd': ++ case 'u': ++ case 'o': ++ case 'x': ++ case 'X': ++ if (c == 'i') ++ c = 'd'; ++ isnumok = 0; ++ if (PyNumber_Check(v)) { ++ PyObject *iobj=NULL; + +- if (PyInt_Check(v) || (PyLong_Check(v))) { +- iobj = v; +- Py_INCREF(iobj); +- } +- else { +- iobj = PyNumber_Int(v); +- if (iobj==NULL) iobj = PyNumber_Long(v); +- } +- if (iobj!=NULL) { +- if (PyInt_Check(iobj)) { +- isnumok = 1; +- pbuf = formatbuf; +- len = formatint(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), +- flags, prec, c, iobj); +- Py_DECREF(iobj); +- if (len < 0) +- goto onError; +- sign = 1; +- } +- else if (PyLong_Check(iobj)) { +- isnumok = 1; +- temp = formatlong(iobj, flags, prec, c); +- Py_DECREF(iobj); +- if (!temp) +- goto onError; +- pbuf = PyUnicode_AS_UNICODE(temp); +- len = PyUnicode_GET_SIZE(temp); +- sign = 1; +- } +- else { +- Py_DECREF(iobj); +- } +- } +- } +- if (!isnumok) { +- PyErr_Format(PyExc_TypeError, +- "%%%c format: a number is required, " +- "not %.200s", (char)c, Py_TYPE(v)->tp_name); +- goto onError; +- } +- if (flags & F_ZERO) +- fill = '0'; +- break; ++ if (PyInt_Check(v) || (PyLong_Check(v))) { ++ iobj = v; ++ Py_INCREF(iobj); ++ } ++ else { ++ iobj = PyNumber_Int(v); ++ if (iobj==NULL) iobj = PyNumber_Long(v); ++ } ++ if (iobj!=NULL) { ++ if (PyInt_Check(iobj)) { ++ isnumok = 1; ++ pbuf = formatbuf; ++ len = formatint(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), ++ flags, prec, c, iobj); ++ Py_DECREF(iobj); ++ if (len < 0) ++ goto onError; ++ sign = 1; ++ } ++ else if (PyLong_Check(iobj)) { ++ isnumok = 1; ++ temp = formatlong(iobj, flags, prec, c); ++ Py_DECREF(iobj); ++ if (!temp) ++ goto onError; ++ pbuf = PyUnicode_AS_UNICODE(temp); ++ len = PyUnicode_GET_SIZE(temp); ++ sign = 1; ++ } ++ else { ++ Py_DECREF(iobj); ++ } ++ } ++ } ++ if (!isnumok) { ++ PyErr_Format(PyExc_TypeError, ++ "%%%c format: a number is required, " ++ "not %.200s", (char)c, Py_TYPE(v)->tp_name); ++ goto onError; ++ } ++ if (flags & F_ZERO) ++ fill = '0'; ++ break; + +- case 'e': +- case 'E': +- case 'f': +- case 'F': +- case 'g': +- case 'G': +- if (c == 'F') +- c = 'f'; +- pbuf = formatbuf; +- len = formatfloat(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), +- flags, prec, c, v); +- if (len < 0) +- goto onError; +- sign = 1; +- if (flags & F_ZERO) +- fill = '0'; +- break; ++ case 'e': ++ case 'E': ++ case 'f': ++ case 'F': ++ case 'g': ++ case 'G': ++ if (c == 'F') ++ c = 'f'; ++ pbuf = formatbuf; ++ len = formatfloat(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), ++ flags, prec, c, v); ++ if (len < 0) ++ goto onError; ++ sign = 1; ++ if (flags & F_ZERO) ++ fill = '0'; ++ break; + +- case 'c': +- pbuf = formatbuf; +- len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v); +- if (len < 0) +- goto onError; +- break; ++ case 'c': ++ pbuf = formatbuf; ++ len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v); ++ if (len < 0) ++ goto onError; ++ break; + +- default: +- PyErr_Format(PyExc_ValueError, +- "unsupported format character '%c' (0x%x) " +- "at index %zd", +- (31<=c && c<=126) ? (char)c : '?', ++ default: ++ PyErr_Format(PyExc_ValueError, ++ "unsupported format character '%c' (0x%x) " ++ "at index %zd", ++ (31<=c && c<=126) ? (char)c : '?', + (int)c, +- (Py_ssize_t)(fmt - 1 - +- PyUnicode_AS_UNICODE(uformat))); +- goto onError; +- } +- if (sign) { +- if (*pbuf == '-' || *pbuf == '+') { +- sign = *pbuf++; +- len--; +- } +- else if (flags & F_SIGN) +- sign = '+'; +- else if (flags & F_BLANK) +- sign = ' '; +- else +- sign = 0; +- } +- if (width < len) +- width = len; +- if (rescnt - (sign != 0) < width) { +- reslen -= rescnt; +- rescnt = width + fmtcnt + 100; +- reslen += rescnt; +- if (reslen < 0) { +- Py_XDECREF(temp); +- PyErr_NoMemory(); +- goto onError; +- } +- if (_PyUnicode_Resize(&result, reslen) < 0) { +- Py_XDECREF(temp); +- goto onError; +- } +- res = PyUnicode_AS_UNICODE(result) +- + reslen - rescnt; +- } +- if (sign) { +- if (fill != ' ') +- *res++ = sign; +- rescnt--; +- if (width > len) +- width--; +- } +- if ((flags & F_ALT) && (c == 'x' || c == 'X')) { +- assert(pbuf[0] == '0'); +- assert(pbuf[1] == c); +- if (fill != ' ') { +- *res++ = *pbuf++; +- *res++ = *pbuf++; +- } +- rescnt -= 2; +- width -= 2; +- if (width < 0) +- width = 0; +- len -= 2; +- } +- if (width > len && !(flags & F_LJUST)) { +- do { +- --rescnt; +- *res++ = fill; +- } while (--width > len); +- } +- if (fill == ' ') { +- if (sign) +- *res++ = sign; +- if ((flags & F_ALT) && (c == 'x' || c == 'X')) { +- assert(pbuf[0] == '0'); +- assert(pbuf[1] == c); +- *res++ = *pbuf++; +- *res++ = *pbuf++; +- } +- } +- Py_UNICODE_COPY(res, pbuf, len); +- res += len; +- rescnt -= len; +- while (--width >= len) { +- --rescnt; +- *res++ = ' '; +- } +- if (dict && (argidx < arglen) && c != '%') { +- PyErr_SetString(PyExc_TypeError, +- "not all arguments converted during string formatting"); ++ (Py_ssize_t)(fmt - 1 - ++ PyUnicode_AS_UNICODE(uformat))); ++ goto onError; ++ } ++ if (sign) { ++ if (*pbuf == '-' || *pbuf == '+') { ++ sign = *pbuf++; ++ len--; ++ } ++ else if (flags & F_SIGN) ++ sign = '+'; ++ else if (flags & F_BLANK) ++ sign = ' '; ++ else ++ sign = 0; ++ } ++ if (width < len) ++ width = len; ++ if (rescnt - (sign != 0) < width) { ++ reslen -= rescnt; ++ rescnt = width + fmtcnt + 100; ++ reslen += rescnt; ++ if (reslen < 0) { ++ Py_XDECREF(temp); ++ PyErr_NoMemory(); ++ goto onError; ++ } ++ if (_PyUnicode_Resize(&result, reslen) < 0) { ++ Py_XDECREF(temp); ++ goto onError; ++ } ++ res = PyUnicode_AS_UNICODE(result) ++ + reslen - rescnt; ++ } ++ if (sign) { ++ if (fill != ' ') ++ *res++ = sign; ++ rescnt--; ++ if (width > len) ++ width--; ++ } ++ if ((flags & F_ALT) && (c == 'x' || c == 'X')) { ++ assert(pbuf[0] == '0'); ++ assert(pbuf[1] == c); ++ if (fill != ' ') { ++ *res++ = *pbuf++; ++ *res++ = *pbuf++; ++ } ++ rescnt -= 2; ++ width -= 2; ++ if (width < 0) ++ width = 0; ++ len -= 2; ++ } ++ if (width > len && !(flags & F_LJUST)) { ++ do { ++ --rescnt; ++ *res++ = fill; ++ } while (--width > len); ++ } ++ if (fill == ' ') { ++ if (sign) ++ *res++ = sign; ++ if ((flags & F_ALT) && (c == 'x' || c == 'X')) { ++ assert(pbuf[0] == '0'); ++ assert(pbuf[1] == c); ++ *res++ = *pbuf++; ++ *res++ = *pbuf++; ++ } ++ } ++ Py_UNICODE_COPY(res, pbuf, len); ++ res += len; ++ rescnt -= len; ++ while (--width >= len) { ++ --rescnt; ++ *res++ = ' '; ++ } ++ if (dict && (argidx < arglen) && c != '%') { ++ PyErr_SetString(PyExc_TypeError, ++ "not all arguments converted during string formatting"); + Py_XDECREF(temp); +- goto onError; +- } +- Py_XDECREF(temp); +- } /* '%' */ ++ goto onError; ++ } ++ Py_XDECREF(temp); ++ } /* '%' */ + } /* until end */ + if (argidx < arglen && !dict) { +- PyErr_SetString(PyExc_TypeError, +- "not all arguments converted during string formatting"); +- goto onError; ++ PyErr_SetString(PyExc_TypeError, ++ "not all arguments converted during string formatting"); ++ goto onError; + } + + if (_PyUnicode_Resize(&result, reslen - rescnt) < 0) +- goto onError; ++ goto onError; + if (args_owned) { +- Py_DECREF(args); ++ Py_DECREF(args); + } + Py_DECREF(uformat); + return (PyObject *)result; + +- onError: ++ onError: + Py_XDECREF(result); + Py_DECREF(uformat); + if (args_owned) { +- Py_DECREF(args); ++ Py_DECREF(args); + } + return NULL; + } +@@ -8886,56 +8888,56 @@ + static PyObject * + unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { +- PyObject *x = NULL; +- static char *kwlist[] = {"string", "encoding", "errors", 0}; +- char *encoding = NULL; +- char *errors = NULL; ++ PyObject *x = NULL; ++ static char *kwlist[] = {"string", "encoding", "errors", 0}; ++ char *encoding = NULL; ++ char *errors = NULL; + +- if (type != &PyUnicode_Type) +- return unicode_subtype_new(type, args, kwds); +- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:unicode", +- kwlist, &x, &encoding, &errors)) +- return NULL; +- if (x == NULL) +- return (PyObject *)_PyUnicode_New(0); +- if (encoding == NULL && errors == NULL) +- return PyObject_Unicode(x); +- else +- return PyUnicode_FromEncodedObject(x, encoding, errors); ++ if (type != &PyUnicode_Type) ++ return unicode_subtype_new(type, args, kwds); ++ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:unicode", ++ kwlist, &x, &encoding, &errors)) ++ return NULL; ++ if (x == NULL) ++ return (PyObject *)_PyUnicode_New(0); ++ if (encoding == NULL && errors == NULL) ++ return PyObject_Unicode(x); ++ else ++ return PyUnicode_FromEncodedObject(x, encoding, errors); + } + + static PyObject * + unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { +- PyUnicodeObject *tmp, *pnew; +- Py_ssize_t n; ++ PyUnicodeObject *tmp, *pnew; ++ Py_ssize_t n; + +- assert(PyType_IsSubtype(type, &PyUnicode_Type)); +- tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds); +- if (tmp == NULL) +- return NULL; +- assert(PyUnicode_Check(tmp)); +- pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length); +- if (pnew == NULL) { +- Py_DECREF(tmp); +- return NULL; +- } +- pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1)); +- if (pnew->str == NULL) { +- _Py_ForgetReference((PyObject *)pnew); +- PyObject_Del(pnew); +- Py_DECREF(tmp); +- return PyErr_NoMemory(); +- } +- Py_UNICODE_COPY(pnew->str, tmp->str, n+1); +- pnew->length = n; +- pnew->hash = tmp->hash; +- Py_DECREF(tmp); +- return (PyObject *)pnew; ++ assert(PyType_IsSubtype(type, &PyUnicode_Type)); ++ tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds); ++ if (tmp == NULL) ++ return NULL; ++ assert(PyUnicode_Check(tmp)); ++ pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length); ++ if (pnew == NULL) { ++ Py_DECREF(tmp); ++ return NULL; ++ } ++ pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1)); ++ if (pnew->str == NULL) { ++ _Py_ForgetReference((PyObject *)pnew); ++ PyObject_Del(pnew); ++ Py_DECREF(tmp); ++ return PyErr_NoMemory(); ++ } ++ Py_UNICODE_COPY(pnew->str, tmp->str, n+1); ++ pnew->length = n; ++ pnew->hash = tmp->hash; ++ Py_DECREF(tmp); ++ return (PyObject *)pnew; + } + + PyDoc_STRVAR(unicode_doc, +-"unicode(string [, encoding[, errors]]) -> object\n\ ++ "unicode(string [, encoding[, errors]]) -> object\n\ + \n\ + Create a new Unicode object from the given encoded string.\n\ + encoding defaults to the current default string encoding.\n\ +@@ -8943,46 +8945,46 @@ + + PyTypeObject PyUnicode_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) +- "unicode", /* tp_name */ +- sizeof(PyUnicodeObject), /* tp_size */ +- 0, /* tp_itemsize */ ++ "unicode", /* tp_name */ ++ sizeof(PyUnicodeObject), /* tp_size */ ++ 0, /* tp_itemsize */ + /* Slots */ +- (destructor)unicode_dealloc, /* tp_dealloc */ +- 0, /* tp_print */ +- 0, /* tp_getattr */ +- 0, /* tp_setattr */ +- 0, /* tp_compare */ +- unicode_repr, /* tp_repr */ +- &unicode_as_number, /* tp_as_number */ +- &unicode_as_sequence, /* tp_as_sequence */ +- &unicode_as_mapping, /* tp_as_mapping */ +- (hashfunc) unicode_hash, /* tp_hash*/ +- 0, /* tp_call*/ +- (reprfunc) unicode_str, /* tp_str */ +- PyObject_GenericGetAttr, /* tp_getattro */ +- 0, /* tp_setattro */ +- &unicode_as_buffer, /* tp_as_buffer */ ++ (destructor)unicode_dealloc, /* tp_dealloc */ ++ 0, /* tp_print */ ++ 0, /* tp_getattr */ ++ 0, /* tp_setattr */ ++ 0, /* tp_compare */ ++ unicode_repr, /* tp_repr */ ++ &unicode_as_number, /* tp_as_number */ ++ &unicode_as_sequence, /* tp_as_sequence */ ++ &unicode_as_mapping, /* tp_as_mapping */ ++ (hashfunc) unicode_hash, /* tp_hash*/ ++ 0, /* tp_call*/ ++ (reprfunc) unicode_str, /* tp_str */ ++ PyObject_GenericGetAttr, /* tp_getattro */ ++ 0, /* tp_setattro */ ++ &unicode_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | +- Py_TPFLAGS_BASETYPE | Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */ +- unicode_doc, /* tp_doc */ +- 0, /* tp_traverse */ +- 0, /* tp_clear */ +- PyUnicode_RichCompare, /* tp_richcompare */ +- 0, /* tp_weaklistoffset */ +- 0, /* tp_iter */ +- 0, /* tp_iternext */ +- unicode_methods, /* tp_methods */ +- 0, /* tp_members */ +- 0, /* tp_getset */ +- &PyBaseString_Type, /* tp_base */ +- 0, /* tp_dict */ +- 0, /* tp_descr_get */ +- 0, /* tp_descr_set */ +- 0, /* tp_dictoffset */ +- 0, /* tp_init */ +- 0, /* tp_alloc */ +- unicode_new, /* tp_new */ +- PyObject_Del, /* tp_free */ ++ Py_TPFLAGS_BASETYPE | Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */ ++ unicode_doc, /* tp_doc */ ++ 0, /* tp_traverse */ ++ 0, /* tp_clear */ ++ PyUnicode_RichCompare, /* tp_richcompare */ ++ 0, /* tp_weaklistoffset */ ++ 0, /* tp_iter */ ++ 0, /* tp_iternext */ ++ unicode_methods, /* tp_methods */ ++ 0, /* tp_members */ ++ 0, /* tp_getset */ ++ &PyBaseString_Type, /* tp_base */ ++ 0, /* tp_dict */ ++ 0, /* tp_descr_get */ ++ 0, /* tp_descr_set */ ++ 0, /* tp_dictoffset */ ++ 0, /* tp_init */ ++ 0, /* tp_alloc */ ++ unicode_new, /* tp_new */ ++ PyObject_Del, /* tp_free */ + }; + + /* Initialize the Unicode implementation */ +@@ -9008,13 +9010,13 @@ + numfree = 0; + unicode_empty = _PyUnicode_New(0); + if (!unicode_empty) +- return; ++ return; + + strcpy(unicode_default_encoding, "ascii"); + for (i = 0; i < 256; i++) +- unicode_latin1[i] = NULL; ++ unicode_latin1[i] = NULL; + if (PyType_Ready(&PyUnicode_Type) < 0) +- Py_FatalError("Can't initialize 'unicode'"); ++ Py_FatalError("Can't initialize 'unicode'"); + + /* initialize the linebreak bloom filter */ + bloom_linebreak = make_bloom_mask( +@@ -9033,13 +9035,13 @@ + PyUnicodeObject *u; + + for (u = free_list; u != NULL;) { +- PyUnicodeObject *v = u; +- u = *(PyUnicodeObject **)u; +- if (v->str) +- PyObject_DEL(v->str); +- Py_XDECREF(v->defenc); +- PyObject_Del(v); +- numfree--; ++ PyUnicodeObject *v = u; ++ u = *(PyUnicodeObject **)u; ++ if (v->str) ++ PyObject_DEL(v->str); ++ Py_XDECREF(v->defenc); ++ PyObject_Del(v); ++ numfree--; + } + free_list = NULL; + assert(numfree == 0); +@@ -9055,10 +9057,10 @@ + unicode_empty = NULL; + + for (i = 0; i < 256; i++) { +- if (unicode_latin1[i]) { +- Py_DECREF(unicode_latin1[i]); +- unicode_latin1[i] = NULL; +- } ++ if (unicode_latin1[i]) { ++ Py_DECREF(unicode_latin1[i]); ++ unicode_latin1[i] = NULL; ++ } + } + (void)PyUnicode_ClearFreeList(); + } +@@ -9069,8 +9071,8 @@ + + + /* +-Local variables: +-c-basic-offset: 4 +-indent-tabs-mode: nil +-End: ++ Local variables: ++ c-basic-offset: 4 ++ indent-tabs-mode: nil ++ End: + */ +Index: Objects/listobject.c +=================================================================== +--- Objects/listobject.c (.../tags/r261) (Revision 70449) ++++ Objects/listobject.c (.../branches/release26-maint) (Revision 70449) +@@ -838,6 +838,10 @@ + + /* Guess a result list size. */ + n = _PyObject_LengthHint(b, 8); ++ if (n == -1) { ++ Py_DECREF(it); ++ return NULL; ++ } + m = Py_SIZE(self); + mn = m + n; + if (mn >= m) { +@@ -2911,11 +2915,11 @@ + static void listreviter_dealloc(listreviterobject *); + static int listreviter_traverse(listreviterobject *, visitproc, void *); + static PyObject *listreviter_next(listreviterobject *); +-static Py_ssize_t listreviter_len(listreviterobject *); ++static PyObject *listreviter_len(listreviterobject *); + +-static PySequenceMethods listreviter_as_sequence = { +- (lenfunc)listreviter_len, /* sq_length */ +- 0, /* sq_concat */ ++static PyMethodDef listreviter_methods[] = { ++ {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc}, ++ {NULL, NULL} /* sentinel */ + }; + + PyTypeObject PyListRevIter_Type = { +@@ -2931,7 +2935,7 @@ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ +- &listreviter_as_sequence, /* tp_as_sequence */ ++ 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ +@@ -2947,6 +2951,7 @@ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)listreviter_next, /* tp_iternext */ ++ listreviter_methods, /* tp_methods */ + 0, + }; + +@@ -3002,11 +3007,11 @@ + return NULL; + } + +-static Py_ssize_t ++static PyObject * + listreviter_len(listreviterobject *it) + { + Py_ssize_t len = it->it_index + 1; + if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len) +- return 0; +- return len; ++ len = 0; ++ return PyLong_FromSsize_t(len); + } +Index: Objects/fileobject.c +=================================================================== +--- Objects/fileobject.c (.../tags/r261) (Revision 70449) ++++ Objects/fileobject.c (.../branches/release26-maint) (Revision 70449) +@@ -132,8 +132,8 @@ + if (fstat(fileno(f->f_fp), &buf) == 0 && + S_ISDIR(buf.st_mode)) { + char *msg = strerror(EISDIR); +- PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)", +- EISDIR, msg); ++ PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)", ++ EISDIR, msg, f->f_name); + PyErr_SetObject(PyExc_IOError, exc); + Py_XDECREF(exc); + return NULL; +Index: Objects/stringlib/formatter.h +=================================================================== +--- Objects/stringlib/formatter.h (.../tags/r261) (Revision 70449) ++++ Objects/stringlib/formatter.h (.../branches/release26-maint) (Revision 70449) +@@ -15,6 +15,34 @@ + + #define ALLOW_PARENS_FOR_SIGN 0 + ++/* Raises an exception about an unknown presentation type for this ++ * type. */ ++ ++static void ++unknown_presentation_type(STRINGLIB_CHAR presentation_type, ++ const char* type_name) ++{ ++#if STRINGLIB_IS_UNICODE ++ /* If STRINGLIB_CHAR is Py_UNICODE, %c might be out-of-range, ++ hence the two cases. If it is char, gcc complains that the ++ condition below is always true, hence the ifdef. */ ++ if (presentation_type > 32 && presentation_type < 128) ++#endif ++ PyErr_Format(PyExc_ValueError, ++ "Unknown format code '%c' " ++ "for object of type '%.200s'", ++ presentation_type, ++ type_name); ++#if STRINGLIB_IS_UNICODE ++ else ++ PyErr_Format(PyExc_ValueError, ++ "Unknown format code '\\x%x' " ++ "for object of type '%.200s'", ++ (unsigned int)presentation_type, ++ type_name); ++#endif ++} ++ + /* + get_integer consumes 0 or more decimal digit characters from an + input string, updates *result with the corresponding positive +@@ -854,19 +882,7 @@ + break; + default: + /* unknown */ +- #if STRINGLIB_IS_UNICODE +- /* If STRINGLIB_CHAR is Py_UNICODE, %c might be out-of-range, +- hence the two cases. If it is char, gcc complains that the +- condition below is always true, hence the ifdef. */ +- if (format.type > 32 && format.type <128) +- #endif +- PyErr_Format(PyExc_ValueError, "Unknown conversion type %c", +- (char)format.type); +- #if STRINGLIB_IS_UNICODE +- else +- PyErr_Format(PyExc_ValueError, "Unknown conversion type '\\x%x'", +- (unsigned int)format.type); +- #endif ++ unknown_presentation_type(format.type, obj->ob_type->tp_name); + goto done; + } + +@@ -928,8 +944,7 @@ + + default: + /* unknown */ +- PyErr_Format(PyExc_ValueError, "Unknown conversion type %c", +- format.type); ++ unknown_presentation_type(format.type, obj->ob_type->tp_name); + goto done; + } + +@@ -1031,8 +1046,7 @@ + + default: + /* unknown */ +- PyErr_Format(PyExc_ValueError, "Unknown conversion type %c", +- format.type); ++ unknown_presentation_type(format.type, obj->ob_type->tp_name); + goto done; + } + +Index: Objects/stringlib/transmogrify.h +=================================================================== +--- Objects/stringlib/transmogrify.h (.../tags/r261) (Revision 70449) ++++ Objects/stringlib/transmogrify.h (.../branches/release26-maint) (Revision 70449) +@@ -22,76 +22,69 @@ + { + const char *e, *p; + char *q; +- Py_ssize_t i, j, old_j; ++ size_t i, j; + PyObject *u; + int tabsize = 8; +- ++ + if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize)) +- return NULL; +- ++ return NULL; ++ + /* First pass: determine size of output string */ +- i = j = old_j = 0; ++ i = j = 0; + e = STRINGLIB_STR(self) + STRINGLIB_LEN(self); + for (p = STRINGLIB_STR(self); p < e; p++) + if (*p == '\t') { +- if (tabsize > 0) { +- j += tabsize - (j % tabsize); +- /* XXX: this depends on a signed integer overflow to < 0 */ +- /* C compilers, including gcc, do -NOT- guarantee this. */ +- if (old_j > j) { +- PyErr_SetString(PyExc_OverflowError, +- "result is too long"); +- return NULL; +- } +- old_j = j; ++ if (tabsize > 0) { ++ j += tabsize - (j % tabsize); ++ if (j > PY_SSIZE_T_MAX) { ++ PyErr_SetString(PyExc_OverflowError, ++ "result is too long"); ++ return NULL; ++ } + } +- } ++ } + else { + j++; + if (*p == '\n' || *p == '\r') { + i += j; +- old_j = j = 0; +- /* XXX: this depends on a signed integer overflow to < 0 */ +- /* C compilers, including gcc, do -NOT- guarantee this. */ +- if (i < 0) { ++ j = 0; ++ if (i > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "result is too long"); + return NULL; + } + } + } +- +- if ((i + j) < 0) { +- /* XXX: this depends on a signed integer overflow to < 0 */ +- /* C compilers, including gcc, do -NOT- guarantee this. */ ++ ++ if ((i + j) > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, "result is too long"); + return NULL; + } +- ++ + /* Second pass: create output string and fill it */ + u = STRINGLIB_NEW(NULL, i + j); + if (!u) + return NULL; +- ++ + j = 0; + q = STRINGLIB_STR(u); +- ++ + for (p = STRINGLIB_STR(self); p < e; p++) + if (*p == '\t') { +- if (tabsize > 0) { +- i = tabsize - (j % tabsize); +- j += i; +- while (i--) +- *q++ = ' '; +- } +- } +- else { ++ if (tabsize > 0) { ++ i = tabsize - (j % tabsize); ++ j += i; ++ while (i--) ++ *q++ = ' '; ++ } ++ } ++ else { + j++; +- *q++ = *p; ++ *q++ = *p; + if (*p == '\n' || *p == '\r') + j = 0; + } +- ++ + return u; + } + +Index: Objects/setobject.c +=================================================================== +--- Objects/setobject.c (.../tags/r261) (Revision 70449) ++++ Objects/setobject.c (.../branches/release26-maint) (Revision 70449) +@@ -810,9 +810,16 @@ + setiter_dealloc(setiterobject *si) + { + Py_XDECREF(si->si_set); +- PyObject_Del(si); ++ PyObject_GC_Del(si); + } + ++static int ++setiter_traverse(setiterobject *si, visitproc visit, void *arg) ++{ ++ Py_VISIT(si->si_set); ++ return 0; ++} ++ + static PyObject * + setiter_len(setiterobject *si) + { +@@ -888,9 +895,9 @@ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ +- Py_TPFLAGS_DEFAULT, /* tp_flags */ ++ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ +- 0, /* tp_traverse */ ++ (traverseproc)setiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +@@ -903,7 +910,7 @@ + static PyObject * + set_iter(PySetObject *so) + { +- setiterobject *si = PyObject_New(setiterobject, &PySetIter_Type); ++ setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type); + if (si == NULL) + return NULL; + Py_INCREF(so); +@@ -911,6 +918,7 @@ + si->si_used = so->used; + si->si_pos = 0; + si->len = so->used; ++ _PyObject_GC_TRACK(si); + return (PyObject *)si; + } + +Index: Objects/longobject.c +=================================================================== +--- Objects/longobject.c (.../tags/r261) (Revision 70449) ++++ Objects/longobject.c (.../branches/release26-maint) (Revision 70449) +@@ -513,7 +513,7 @@ + /* Because we're going LSB to MSB, thisbyte is + more significant than what's already in accum, + so needs to be prepended to accum. */ +- accum |= thisbyte << accumbits; ++ accum |= (twodigits)thisbyte << accumbits; + accumbits += 8; + if (accumbits >= PyLong_SHIFT) { + /* There's enough to fill a Python digit. */ +@@ -542,12 +542,12 @@ + unsigned char* bytes, size_t n, + int little_endian, int is_signed) + { +- int i; /* index into v->ob_digit */ ++ Py_ssize_t i; /* index into v->ob_digit */ + Py_ssize_t ndigits; /* |v->ob_size| */ + twodigits accum; /* sliding register */ + unsigned int accumbits; /* # bits in accum */ + int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ +- twodigits carry; /* for computing 2's-comp */ ++ digit carry; /* for computing 2's-comp */ + size_t j; /* # bytes filled */ + unsigned char* p; /* pointer to next byte in bytes */ + int pincr; /* direction to move p */ +@@ -587,7 +587,7 @@ + accumbits = 0; + carry = do_twos_comp ? 1 : 0; + for (i = 0; i < ndigits; ++i) { +- twodigits thisdigit = v->ob_digit[i]; ++ digit thisdigit = v->ob_digit[i]; + if (do_twos_comp) { + thisdigit = (thisdigit ^ PyLong_MASK) + carry; + carry = thisdigit >> PyLong_SHIFT; +@@ -596,26 +596,23 @@ + /* Because we're going LSB to MSB, thisdigit is more + significant than what's already in accum, so needs to be + prepended to accum. */ +- accum |= thisdigit << accumbits; +- accumbits += PyLong_SHIFT; ++ accum |= (twodigits)thisdigit << accumbits; + + /* The most-significant digit may be (probably is) at least + partly empty. */ + if (i == ndigits - 1) { + /* Count # of sign bits -- they needn't be stored, + * although for signed conversion we need later to +- * make sure at least one sign bit gets stored. +- * First shift conceptual sign bit to real sign bit. +- */ +- stwodigits s = (stwodigits)(thisdigit << +- (8*sizeof(stwodigits) - PyLong_SHIFT)); +- unsigned int nsignbits = 0; +- while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) { +- ++nsignbits; +- s <<= 1; ++ * make sure at least one sign bit gets stored. */ ++ digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : ++ thisdigit; ++ while (s != 0) { ++ s >>= 1; ++ accumbits++; + } +- accumbits -= nsignbits; + } ++ else ++ accumbits += PyLong_SHIFT; + + /* Store as many bytes as possible. */ + while (accumbits >= 8) { +@@ -1079,7 +1076,7 @@ + static digit + v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) + { +- int i; ++ Py_ssize_t i; + digit carry = 0; + + assert(m >= n); +@@ -1105,7 +1102,7 @@ + static digit + v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) + { +- int i; ++ Py_ssize_t i; + digit borrow = 0; + + assert(m >= n); +@@ -1171,7 +1168,7 @@ + digit hi; + rem = (rem << PyLong_SHIFT) + *--pin; + *--pout = hi = (digit)(rem / n); +- rem -= hi * n; ++ rem -= (twodigits)hi * n; + } + return (digit)rem; + } +@@ -1436,11 +1433,11 @@ + while (--p >= start) { + int k = _PyLong_DigitValue[Py_CHARMASK(*p)]; + assert(k >= 0 && k < base); +- accum |= (twodigits)(k << bits_in_accum); ++ accum |= (twodigits)k << bits_in_accum; + bits_in_accum += bits_per_char; + if (bits_in_accum >= PyLong_SHIFT) { + *pdigit++ = (digit)(accum & PyLong_MASK); +- assert(pdigit - z->ob_digit <= (int)n); ++ assert(pdigit - z->ob_digit <= n); + accum >>= PyLong_SHIFT; + bits_in_accum -= PyLong_SHIFT; + assert(bits_in_accum < PyLong_SHIFT); +@@ -1449,7 +1446,7 @@ + if (bits_in_accum) { + assert(bits_in_accum <= PyLong_SHIFT); + *pdigit++ = (digit)accum; +- assert(pdigit - z->ob_digit <= (int)n); ++ assert(pdigit - z->ob_digit <= n); + } + while (pdigit - z->ob_digit < n) + *pdigit++ = 0; +@@ -1846,7 +1843,7 @@ + digit vj = (j >= size_v) ? 0 : v->ob_digit[j]; + twodigits q; + stwodigits carry = 0; +- int i; ++ Py_ssize_t i; + + SIGCHECK({ + Py_DECREF(a); +@@ -1965,7 +1962,7 @@ + static long + long_hash(PyLongObject *v) + { +- long x; ++ unsigned long x; + Py_ssize_t i; + int sign; + +@@ -1980,17 +1977,18 @@ + i = -(i); + } + #define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT) +- /* The following loop produces a C long x such that (unsigned long)x +- is congruent to the absolute value of v modulo ULONG_MAX. The ++ /* The following loop produces a C unsigned long x such that x is ++ congruent to the absolute value of v modulo ULONG_MAX. The + resulting x is nonzero if and only if v is. */ + while (--i >= 0) { + /* Force a native long #-bits (32 or 64) circular shift */ +- x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK); ++ x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ++ ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK); + x += v->ob_digit[i]; +- /* If the addition above overflowed (thinking of x as +- unsigned), we compensate by incrementing. This preserves +- the value modulo ULONG_MAX. */ +- if ((unsigned long)x < v->ob_digit[i]) ++ /* If the addition above overflowed we compensate by ++ incrementing. This preserves the value modulo ++ ULONG_MAX. */ ++ if (x < v->ob_digit[i]) + x++; + } + #undef LONG_BIT_PyLong_SHIFT +@@ -2008,7 +2006,7 @@ + { + Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); + PyLongObject *z; +- int i; ++ Py_ssize_t i; + digit carry = 0; + + /* Ensure a is the larger of the two: */ +Index: Objects/bytearrayobject.c +=================================================================== +--- Objects/bytearrayobject.c (.../tags/r261) (Revision 70449) ++++ Objects/bytearrayobject.c (.../branches/release26-maint) (Revision 70449) +@@ -154,6 +154,17 @@ + return view->len; + } + ++static int ++_canresize(PyByteArrayObject *self) ++{ ++ if (self->ob_exports > 0) { ++ PyErr_SetString(PyExc_BufferError, ++ "Existing exports of data: object cannot be re-sized"); ++ return 0; ++ } ++ return 1; ++} ++ + /* Direct API functions */ + + PyObject * +@@ -229,6 +240,13 @@ + assert(PyByteArray_Check(self)); + assert(size >= 0); + ++ if (size == Py_SIZE(self)) { ++ return 0; ++ } ++ if (!_canresize((PyByteArrayObject *)self)) { ++ return -1; ++ } ++ + if (size < alloc / 2) { + /* Major downsize; resize down to exact size */ + alloc = size + 1; +@@ -248,16 +266,6 @@ + alloc = size + 1; + } + +- if (((PyByteArrayObject *)self)->ob_exports > 0) { +- /* +- fprintf(stderr, "%d: %s", ((PyByteArrayObject *)self)->ob_exports, +- ((PyByteArrayObject *)self)->ob_bytes); +- */ +- PyErr_SetString(PyExc_BufferError, +- "Existing exports of data: object cannot be re-sized"); +- return -1; +- } +- + sval = PyMem_Realloc(((PyByteArrayObject *)self)->ob_bytes, alloc); + if (sval == NULL) { + PyErr_NoMemory(); +@@ -522,6 +530,10 @@ + + if (avail != needed) { + if (avail > needed) { ++ if (!_canresize(self)) { ++ res = -1; ++ goto finish; ++ } + /* + 0 lo hi old_size + | |<----avail----->|<-----tomove------>| +@@ -654,6 +666,8 @@ + stop = start; + if (step == 1) { + if (slicelen != needed) { ++ if (!_canresize(self)) ++ return -1; + if (slicelen > needed) { + /* + 0 start stop old_size +@@ -689,6 +703,8 @@ + /* Delete slice */ + Py_ssize_t cur, i; + ++ if (!_canresize(self)) ++ return -1; + if (step < 0) { + stop = start + 1; + start = stop + step * (slicelen - 1) - 1; +@@ -1449,6 +1465,7 @@ + if (delobj != NULL) { + if (_getbuffer(delobj, &vdel) < 0) { + result = NULL; ++ delobj = NULL; /* don't try to release vdel buffer on exit */ + goto done; + } + } +@@ -1473,7 +1490,7 @@ + } + goto done; + } +- ++ + for (i = 0; i < 256; i++) + trans_table[i] = Py_CHARMASK(table[i]); + +@@ -2662,6 +2679,10 @@ + + /* Try to determine the length of the argument. 32 is abitrary. */ + buf_size = _PyObject_LengthHint(arg, 32); ++ if (buf_size == -1) { ++ Py_DECREF(it); ++ return NULL; ++ } + + bytes_obj = PyByteArray_FromStringAndSize(NULL, buf_size); + if (bytes_obj == NULL) +@@ -2730,6 +2751,8 @@ + PyErr_SetString(PyExc_IndexError, "pop index out of range"); + return NULL; + } ++ if (!_canresize(self)) ++ return NULL; + + value = self->ob_bytes[where]; + memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where); +@@ -2760,6 +2783,8 @@ + PyErr_SetString(PyExc_ValueError, "value not found in bytes"); + return NULL; + } ++ if (!_canresize(self)) ++ return NULL; + + memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where); + if (PyByteArray_Resize((PyObject *)self, n - 1) < 0) +Index: Misc/developers.txt +=================================================================== +--- Misc/developers.txt (.../tags/r261) (Revision 70449) ++++ Misc/developers.txt (.../branches/release26-maint) (Revision 70449) +@@ -17,6 +17,9 @@ + Permissions History + ------------------- + ++- Tarek Ziadé as given SVN access on Decmeber 21 2008 by NCN, ++ for maintenance of distutils. ++ + - Hirokazu Yamamoto was given SVN access on August 12 2008 by MvL, + for contributions to the Windows build. + +Index: Misc/python.man +=================================================================== +--- Misc/python.man (.../tags/r261) (Revision 70449) ++++ Misc/python.man (.../branches/release26-maint) (Revision 70449) +@@ -54,6 +54,9 @@ + [ + .B \-x + ] ++[ ++.B \-3 ++] + .br + [ + .B \-c +@@ -236,6 +239,9 @@ + Skip the first line of the source. This is intended for a DOS + specific hack only. Warning: the line numbers in error messages will + be off by one! ++.TP ++.B \-3 ++Warn about Python 3.x incompatibilities that 2to3 cannot trivially fix. + .SH INTERPRETER INTERFACE + The interpreter interface resembles that of the UNIX shell: when + called with standard input connected to a tty device, it prompts for +Index: Misc/build.sh +=================================================================== +--- Misc/build.sh (.../tags/r261) (Revision 70449) ++++ Misc/build.sh (.../branches/release26-maint) (Revision 70449) +@@ -263,7 +263,7 @@ + echo "Conflict detected in $CONFLICTED_FILE. Doc build skipped." > ../build/$F + err=1 + else +- make update html >& ../build/$F ++ make checkout update html >& ../build/$F + err=$? + fi + update_status "Making doc" "$F" $start +Index: Misc/NEWS +=================================================================== +--- Misc/NEWS (.../tags/r261) (Revision 70449) ++++ Misc/NEWS (.../branches/release26-maint) (Revision 70449) +@@ -4,6 +4,239 @@ + + (editors: check NEWS.help for information about editing NEWS using ReST.) + ++What's New in Python 2.6.2 ++========================== ++ ++*Release date: XX-XXX-200X* ++ ++Core and Builtins ++----------------- ++ ++- xrange() is now registered as a Sequence. ++ ++- Issue #5247: Improve error message when unknown format codes are ++ used when using str.format() with str, unicode, long, int, and ++ float arguments. ++ ++- Running Python with the -3 option now also warns about classic division ++ for ints and longs. ++ ++- Issue #5013: Fixed a bug in FileHandler which occurred when the delay ++ parameter was set. ++ ++- Issue 1242657: the __len__() and __length_hint__() calls in several tools ++ were suppressing all exceptions. These include list(), filter(), map(), ++ zip(), and bytearray(). ++ ++- Issue #4935: The overflow checking code in the expandtabs() method common ++ to str, bytes and bytearray could be optimized away by the compiler, letting ++ the interpreter segfault instead of raising an error. ++ ++- Issue #4915: Port sysmodule to Windows CE. ++ ++- Issue #1180193: When importing a module from a .pyc (or .pyo) file with ++ an existing .py counterpart, override the co_filename attributes of all ++ code objects if the original filename is obsolete (which can happen if the ++ file has been renamed, moved, or if it is accessed through different paths). ++ Patch by Ziga Seilnacht and Jean-Paul Calderone. ++ ++- Issue #4075: Use OutputDebugStringW in Py_FatalError. ++ ++- Issue #4797: IOError.filename was not set when _fileio.FileIO failed to open ++ file with `str' filename on Windows. ++ ++- Issue #3680: Reference cycles created through a dict, set or deque iterator ++ did not get collected. ++ ++- Issue #4701: PyObject_Hash now implicitly calls PyType_Ready on types ++ where the tp_hash and tp_dict slots are both NULL. ++ ++- Issue #4764: With io.open, IOError.filename is set when trying to open a ++ directory on POSIX systems. ++ ++- Issue #4764: IOError.filename is set when trying to open a directory on POSIX ++ systems. ++ ++- Issue #4759: None is now allowed as the first argument of ++ bytearray.translate(). It was always allowed for bytes.translate(). ++ ++- Issue #4759: fix a segfault for bytearray.translate(x, None). ++ ++- Added test case to ensure attempts to read from a file opened for writing ++ fail. ++ ++- Issue #4597: Fixed several opcodes that weren't always propagating ++ exceptions. ++ ++- Issue #2467: gc.DEBUG_STATS reported invalid elapsed times. Also, always ++ print elapsed times, not only when some objects are uncollectable / ++ unreachable. Original patch by Neil Schemenauer. ++ ++- Issue #4589: Fixed exception handling when the __exit__ function of a ++ context manager returns a value that cannot be converted to a bool. ++ ++- Issue #4233: Changed semantic of ``_fileio.FileIO``'s ``close()`` ++ method on file objects with closefd=False. The file descriptor is still ++ kept open but the file object behaves like a closed file. The ``FileIO`` ++ object also got a new readonly attribute ``closefd``. ++ ++- Issue #3689: The list reversed iterator now supports __length_hint__ ++ instead of __len__. Behavior now matches other reversed iterators. ++ ++- Issue #4509: Various issues surrounding resize of bytearray objects to ++ which there are buffer exports. ++ ++Library ++------- ++ ++- Fix Decimal.__format__ bug that swapped the meanings of the '<' and ++ '>' alignment characters. ++ ++- Issue #1222: locale.format() bug when the thousands separator is a space ++ character. ++ ++- Issue #4792: Prevent a segfault in _tkinter by using the ++ guaranteed to be safe interp argument given to the PythonCmd in place of ++ the Tcl interpreter taken from a PythonCmd_ClientData. ++ ++- Issue #5193: Guarantee that Tkinter.Text.search returns a string. ++ ++- Issue #5385: Fixed mmap crash after resize failure on windows. ++ ++- Issue #5179: Fixed subprocess handle leak on failure on windows. ++ ++- Issue #4308: httplib.IncompleteRead's repr doesn't include all of the data all ++ ready received. ++ ++- Issue #5401: Fixed a performance problem in mimetypes when ``from mimetypes ++ import guess_extension`` was used. ++ ++- Issue #1733986: Fixed mmap crash in accessing elements of second map object ++ with same tagname but larger size than first map. (Windows) ++ ++- Issue #5386: mmap.write_byte didn't check map size, so it could cause buffer ++ overrun. ++ ++- Issue #5292: Fixed mmap crash on its boundary access m[len(m)]. ++ ++- Issue #5282: Fixed mmap resize on 32bit windows and unix. When offset > 0, ++ The file was resized to wrong size. ++ ++- Issue #5287: Add exception handling around findCaller() call in logging to ++ help out IronPython. ++ ++- Issue #4524: distutils build_script command failed with --with-suffix=3. ++ Initial patch by Amaury Forgeot d'Arc. ++ ++- Issue #4998: The memory saving effect of __slots__ had been lost on Fractions ++ which inherited from numbers.py which did not have __slots__ defined. The ++ numbers hierarchy now has its own __slots__ declarations. ++ ++- Issue #5203: Fixed ctypes segfaults when passing a unicode string to a ++ function without argtypes (only occurs if HAVE_USABLE_WCHAR_T is false). ++ ++- Issue #3386: distutils.sysconfig.get_python_lib prefix argument was ignored ++ under NT and OS2. Patch by Philip Jenvey. ++ ++- Issue #4890: Handle empty text search pattern in Tkinter.Text.search. ++ ++- Issue #5170: Fixed Unicode output bug in logging and added test case. ++ This is a regression which did not occur in 2.5. ++ ++- Partial fix to issue #1731706: memory leak in Tkapp_Call when calling ++ from a thread different than the one that created the Tcl interpreter. ++ Patch by Robert Hancock. ++ ++- Issue #5132: Fixed trouble building extensions under Solaris with ++ --enabled-shared activated. Initial patch by Dave Peterson. ++ ++- Issue #1581476: Always use the Tcl global namespace when calling into Tcl. ++ ++- Issue #2047: shutil.move() could believe that its destination path was ++ inside its source path if it began with the same letters (e.g. "src" vs. ++ "src.new"). ++ ++- Issue 4920: Fixed .next() vs .__next__() issues in the ABCs for ++ Iterator and MutableSet. ++ ++- Issue 5021: doctest.testfile() did not create __name__ and ++ collections.namedtuple() relied on __name__ being defined. ++ ++- Issue #3881: Help Tcl to load even when started through the ++ unreadable local symlink to "Program Files" on Vista. ++ ++- Issue #4710: Extract directories properly in the zipfile module; ++ allow adding directories to a zipfile. ++ ++- Issue #5008: When a file is opened in append mode with the new IO library, ++ do an explicit seek to the end of file (so that e.g. tell() returns the ++ file size rather than 0). This is consistent with the behaviour of the ++ traditional 2.x file object. ++ ++- Issue #3997: zipfiles generated with more than 65536 files could not be ++ opened with other applications. ++ ++- Issue 4816: itertools.combinations() and itertools.product were raising ++ a ValueError for values of *r* larger than the input iterable. They now ++ correctly return an empty iterator. ++ ++- Fractions.from_float() no longer loses precision for integers too big to ++ cast as floats. ++ ++- Issue 4790: The nsmallest() and nlargest() functions in the heapq module ++ did unnecessary work in the common case where no key function was specified. ++ ++- Issue #3767: Convert Tk object to string in tkColorChooser. ++ ++- Issue #3248: Allow placing ScrolledText in a PanedWindow. ++ ++- Issue #3954: Fix a potential SystemError in _hotshot.logreader error ++ handling. ++ ++- Issue #4574: fix a crash in io.IncrementalNewlineDecoder when a carriage ++ return encodes to more than one byte in the source encoding (e.g. UTF-16) ++ and gets split on a chunk boundary. ++ ++- Issue #4223: inspect.getsource() will now correctly display source code ++ for packages loaded via zipimport (or any other conformant PEP 302 ++ loader). Original patch by Alexander Belopolsky. ++ ++- Issue #4201: pdb can now access and display source code loaded via ++ zipimport (or any other conformant PEP 302 loader). Original patch by ++ Alexander Belopolsky. ++ ++- Issue #4197: doctests in modules loaded via zipimport (or any other PEP ++ 302 conformant loader) will now work correctly in most cases (they ++ are still subject to the constraints that exist for all code running ++ from inside a module loaded via a PEP 302 loader and attempting to ++ perform IO operations based on __file__). Original patch by ++ Alexander Belopolsky. ++ ++- Issues #4082 and #4512: Add runpy support to zipimport in a manner that ++ allows backporting to maintenance branches. Original patch by ++ Alexander Belopolsky. ++ ++- Issue #4616: TarFile.utime(): Restore directory times on Windows. ++ ++- Issue #4483: _dbm module now builds on systems with gdbm & gdbm_compat ++ libs. ++ ++- FileIO's mode attribute now always includes ``"b"``. ++ ++- Issue #4861: ctypes.util.find_library(): Robustify. Fix library detection on ++ biarch systems. Try to rely on ldconfig only, without using objdump and gcc. ++ ++Extension Modules ++----------------- ++ ++- Issue #1040026: Fix os.times result on systems where HZ is incorrect. ++ ++Build ++----- ++ ++- Link the shared python library with $(MODLIBS). ++ ++ + What's New in Python 2.6.1 + ========================== + +@@ -52,6 +285,72 @@ + Library + ------- + ++- Issue #1885: distutils. When running sdist with --formats=tar,gztar ++ the tar file was overriden by the gztar one. ++ ++- Registered Decimal as a numbers.Number so that isinstance(d, Number) works. ++ ++- Issue #1672332: fix unpickling of subnormal floats, which was ++ producing a ValueError on some platforms. ++ ++- Restore Python 2.3 compatibility for decimal.py. ++ ++- Issue #1702551: distutils sdist was not excluding VCS directories under ++ Windows. Inital solution by Guy Dalberto. ++ ++- Issue #4812: add missing underscore prefix to some internal-use-only ++ constants in the decimal module. (Dec_0 becomes _Dec_0, etc.) ++ ++- Issue #4795: inspect.isgeneratorfunction() returns False instead of None when ++ the function is not a generator. ++ ++- Issue #4702: Throwing a DistutilsPlatformError instead of IOError in case ++ no MSVC compiler is found under Windows. Original patch by Philip Jenvey. ++ ++ - Issue #4739: Add pydoc help topics for symbols, so that e.g. help('@') ++ works as expected in the interactive environment. ++ ++- Issue #4756: zipfile.is_zipfile() now supports file-like objects. Patch by ++ Gabriel Genellina. ++ ++- Issue #4646: distutils was choking on empty options arg in the setup ++ function. Original patch by Thomas Heller. ++ ++- Issue #4400: .pypirc default generated file was broken in distutils. ++ ++- Issue #4736: io.BufferedRWPair's closed property now functions properly. ++ ++- Issue #3954: Fix a potential SystemError in _hotshot.logreader error ++ handling. ++ ++- Issue #4163: Use unicode-friendly word splitting in the textwrap functions ++ when given an unicode string. ++ ++- Issue #4616: TarFile.utime(): Restore directory times on Windows. ++ ++- Issue #4084: Fix max, min, max_mag and min_mag Decimal methods to ++ give correct results in the case where one argument is a quiet NaN ++ and the other is a finite number that requires rounding. ++ ++- Issue #1030250: Distutils created directories even when run with the ++ --dry-run option. ++ ++- Issue #4483: _dbm module now builds on systems with gdbm & gdbm_compat ++ libs. ++ ++- Issue #4529: fix the parser module's validation of try-except-finally ++ statements. ++ ++- Issue #4458: getopt.gnu_getopt() now recognizes a single "-" as an argument, ++ not a malformed option. ++ ++- Added the subprocess.check_output() convenience function to get output ++ from a subprocess on success or raise an exception on error. ++ ++- Issue #1055234: cgi.parse_header(): Fixed parsing of header parameters to ++ support unusual filenames (such as those containing semi-colons) in ++ Content-Disposition headers. ++ + - Issue #3741: DISTUTILS_USE_SDK set causes msvc9compiler.py to raise an + exception. + +@@ -76,9 +375,35 @@ + - Issue #4014: Don't claim that Python has an Alpha release status, in addition + to claiming it is Mature. + ++- Issue #4730: Fixed the cPickle module to handle correctly astral characters ++ when protocol 0 is used. ++ ++- Issue #16278952: plat-mac/videoreader.py now correctly imports MediaDescr ++ ++- Issue #1737832 : plat-mac/EasyDialog.py no longer uses the broken aepack ++ module. ++ ++- Issue #1149804: macostools.mkdirs now even works when another process ++ creates one of the needed subdirectories. ++ ++Tools/Demos ++----------- ++ ++- Issue #4677: add two list comprehension tests to pybench. ++ + Build + ----- + ++- Issue #5134: Silence compiler warnings when compiling sqlite with VC++. ++ ++- Issue #4494: Fix build with Py_NO_ENABLE_SHARED on Windows. ++ ++- Issue #4895: Use _strdup on Windows CE. ++ ++- Issue #4472: "configure --enable-shared" now works on OSX ++ ++- Issues #4728 and #4060: WORDS_BIGEDIAN is now correct in Universal builds. ++ + - Issue #4389: Add icon to the uninstall entry in "add-and-remove-programs". + + - Issue #4289: Remove Cancel button from AdvancedDlg. +@@ -98,12 +423,30 @@ + C-API + ----- + ++- Issue #4720: The format for PyArg_ParseTupleAndKeywords can begin with '|'. ++ ++- Issue #3632: from the gdb debugger, the 'pyo' macro can now be called when ++ the GIL is released, or owned by another thread. ++ + - Issue #4122: On Windows, fix a compilation error when using the + Py_UNICODE_ISSPACE macro in an extension module. + + Extension Modules + ----------------- + ++- Issue #4397: Fix occasional test_socket failure on OS X. ++ ++- Issue #4279: Fix build of parsermodule under Cygwin. ++ ++- Issue #4051: Prevent conflict of UNICODE macros in cPickle. ++ ++- Issue #4228: Pack negative values the same way as 2.4 in struct's L format. ++ ++- Issue #1040026: Fix os.times result on systems where HZ is incorrect. ++ ++- Issues #3167, #3682: Fix test_math failures for log, log10 on Solaris, ++ OpenBSD. ++ + - Issue #4365: Add crtassem.h constants to the msvcrt module. + + - Issue #4396: The parser module now correctly validates the with statement. +@@ -321,6 +664,9 @@ + Extension Modules + ----------------- + ++- Issue #4301: Patch the logging module to add processName support, remove ++ _check_logger_class from multiprocessing. ++ + - Issue #2975: When compiling several extension modules with Visual Studio 2008 + from the same python interpreter, some environment variables would grow + without limit. +Index: Misc/ACKS +=================================================================== +--- Misc/ACKS (.../tags/r261) (Revision 70449) ++++ Misc/ACKS (.../branches/release26-maint) (Revision 70449) +@@ -753,6 +753,7 @@ + Blake Winton + Jean-Claude Wippler + Lars Wirzenius ++Chris Withers + Stefan Witzel + David Wolever + Klaus-Juergen Wolf +Index: Parser/printgrammar.c +=================================================================== +--- Parser/printgrammar.c (.../tags/r261) (Revision 70449) ++++ Parser/printgrammar.c (.../branches/release26-maint) (Revision 70449) +@@ -16,6 +16,7 @@ + fprintf(fp, "/* Generated by Parser/pgen */\n\n"); + fprintf(fp, "#include \"pgenheaders.h\"\n"); + fprintf(fp, "#include \"grammar.h\"\n"); ++ fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n"); + printdfas(g, fp); + printlabels(g, fp); + fprintf(fp, "grammar _PyParser_Grammar = {\n"); +Index: Parser/asdl.py +=================================================================== +--- Parser/asdl.py (.../tags/r261) (Revision 70449) ++++ Parser/asdl.py (.../branches/release26-maint) (Revision 70449) +@@ -167,7 +167,7 @@ + return Product(fields) + + def p_sum_0(self, (constructor,)): +- " sum ::= constructor """ ++ " sum ::= constructor " + return [constructor] + + def p_sum_1(self, (constructor, _, sum)): +Index: README +=================================================================== +--- README (.../tags/r261) (Revision 70449) ++++ README (.../branches/release26-maint) (Revision 70449) +@@ -1,7 +1,7 @@ + This is Python version 2.6.1 + ============================ + +-Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 ++Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 + Python Software Foundation. + All rights reserved. + +Index: Mac/PythonLauncher/Makefile.in +=================================================================== +--- Mac/PythonLauncher/Makefile.in (.../tags/r261) (Revision 70449) ++++ Mac/PythonLauncher/Makefile.in (.../branches/release26-maint) (Revision 70449) +@@ -29,7 +29,7 @@ + install: Python\ Launcher.app + test -d "$(DESTDIR)$(PYTHONAPPSDIR)" || mkdir -p "$(DESTDIR)$(PYTHONAPPSDIR)" + -test -d "$(DESTDIR)$(PYTHONAPPSDIR)/Python Launcher.app" && rm -r "$(DESTDIR)$(PYTHONAPPSDIR)/Python Launcher.app" +- cp -r "Python Launcher.app" "$(DESTDIR)$(PYTHONAPPSDIR)" ++ /bin/cp -r "Python Launcher.app" "$(DESTDIR)$(PYTHONAPPSDIR)" + touch "$(DESTDIR)$(PYTHONAPPSDIR)/Python Launcher.app" + + clean: +Index: Mac/BuildScript/build-installer.py +=================================================================== +--- Mac/BuildScript/build-installer.py (.../tags/r261) (Revision 70449) ++++ Mac/BuildScript/build-installer.py (.../branches/release26-maint) (Revision 70449) +@@ -1031,8 +1031,7 @@ + buildPythonDocs() + fn = os.path.join(WORKDIR, "_root", "Applications", + "Python %s"%(getVersion(),), "Update Shell Profile.command") +- patchFile("scripts/postflight.patch-profile", fn) +- os.chmod(fn, 0755) ++ patchScript("scripts/postflight.patch-profile", fn) + + folder = os.path.join(WORKDIR, "_root", "Applications", "Python %s"%( + getVersion(),)) +Index: Mac/BuildScript/scripts/postflight.patch-profile +=================================================================== +--- Mac/BuildScript/scripts/postflight.patch-profile (.../tags/r261) (Revision 70449) ++++ Mac/BuildScript/scripts/postflight.patch-profile (.../branches/release26-maint) (Revision 70449) +@@ -5,8 +5,8 @@ + echo "These changes will be effective only in shell windows that you open" + echo "after running this script." + +-PYVER=2.6 +-PYTHON_ROOT="/Library/Frameworks/Python.framework/Versions/Current" ++PYVER="@PYVER@" ++PYTHON_ROOT="/Library/Frameworks/Python.framework/Versions/@PYVER@" + + if [ `id -ur` = 0 ]; then + # Run from the installer, do some trickery to fetch the information +Index: Mac/BuildScript/resources/Welcome.rtf +=================================================================== +--- Mac/BuildScript/resources/Welcome.rtf (.../tags/r261) (Revision 70449) ++++ Mac/BuildScript/resources/Welcome.rtf (.../branches/release26-maint) (Revision 70449) +@@ -10,9 +10,9 @@ + \f1\b Mac OS X $MACOSX_DEPLOYMENT_TARGET + \f0\b0 .\ + \ +-MacPython consists of the Python programming language interpreter, plus a set of programs to allow easy access to it for Mac users (an integrated development environment, an applet builder), plus a set of pre-built extension modules that open up specific Macintosh technologies to Python programs (Carbon, AppleScript, Quicktime, more).\ ++MacPython consists of the Python programming language interpreter, plus a set of programs to allow easy access to it for Mac users including an integrated development environment \b IDLE\b0 plus a set of pre-built extension modules that open up specific Macintosh technologies to Python programs.\ + \ + See the ReadMe file for more information.\ + \ + \ +-This package will by default update your shell profile to ensure that this version of Python is on the search path of your shell. Please deselect the "Shell profile updater" package on the package customization screen if you want to avoid this modification. } +\ No newline at end of file ++This package will by default update your shell profile to ensure that this version of Python is on the search path of your shell. Please deselect the "Shell profile updater" package on the package customization screen if you want to avoid this modification. Double-click \b Update Shell Profile\b0 at any time to make $FULL_VERSION the default Python.} +\ No newline at end of file +Index: Mac/BuildScript/resources/ReadMe.txt +=================================================================== +--- Mac/BuildScript/resources/ReadMe.txt (.../tags/r261) (Revision 70449) ++++ Mac/BuildScript/resources/ReadMe.txt (.../branches/release26-maint) (Revision 70449) +@@ -14,10 +14,9 @@ + + MacPython consists of the Python programming language + interpreter, plus a set of programs to allow easy +-access to it for Mac users (an integrated development +-environment, an applet builder), plus a set of pre-built +-extension modules that open up specific Macintosh technologies +-to Python programs (Carbon, AppleScript, Quicktime, more). ++access to it for Mac users including an integrated development ++environment, IDLE, plus a set of pre-built extension modules ++that open up specific Macintosh technologies to Python programs. + + The installer puts the applications in "Python $VERSION" + in your Applications folder, command-line tools in +@@ -25,7 +24,7 @@ + $PYTHONFRAMEWORKINSTALLDIR. + + More information on MacPython can be found at +-http://www.cwi.nl/~jack/macpython and +-http://pythonmac.org/. More information on +-Python in general can be found at ++http://www.python.org/download/mac/. ++ ++More information on Python in general can be found at + http://www.python.org. +Index: Mac/IDLE/Makefile.in +=================================================================== +--- Mac/IDLE/Makefile.in (.../tags/r261) (Revision 70449) ++++ Mac/IDLE/Makefile.in (.../branches/release26-maint) (Revision 70449) +@@ -29,10 +29,10 @@ + install: IDLE.app $(srcdir)/config-main.def $(srcdir)/config-extensions.def + test -d "$(DESTDIR)$(PYTHONAPPSDIR)" || mkdir -p "$(DESTDIR)$(PYTHONAPPSDIR)" + -test -d "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app" && rm -r "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app" +- cp -PR IDLE.app "$(DESTDIR)$(PYTHONAPPSDIR)" ++ /bin/cp -PR IDLE.app "$(DESTDIR)$(PYTHONAPPSDIR)" + touch "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app" +- cp $(srcdir)/config-main.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-main.def" +- cp $(srcdir)/config-extensions.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-extensions.def" ++ /bin/cp $(srcdir)/config-main.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-main.def" ++ /bin/cp $(srcdir)/config-extensions.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-extensions.def" + + clean: + rm -rf IDLE.app +Index: Mac/IDLE/idlemain.py +=================================================================== +--- Mac/IDLE/idlemain.py (.../tags/r261) (Revision 70449) ++++ Mac/IDLE/idlemain.py (.../branches/release26-maint) (Revision 70449) +@@ -3,8 +3,6 @@ + """ + import sys, os + +-from idlelib.PyShell import main +- + # Change the current directory the user's home directory, that way we'll get + # a more useful default location in the open/save dialogs. + os.chdir(os.path.expanduser('~/Documents')) +@@ -13,11 +11,55 @@ + # Make sure sys.executable points to the python interpreter inside the + # framework, instead of at the helper executable inside the application + # bundle (the latter works, but doesn't allow access to the window server) +-if sys.executable.endswith('-32'): +- sys.executable = os.path.join(sys.prefix, 'bin', 'python-32') +-else: +- sys.executable = os.path.join(sys.prefix, 'bin', 'python') ++# ++# .../IDLE.app/ ++# Contents/ ++# MacOS/ ++# IDLE (a python script) ++# Python{-32} (symlink) ++# Resources/ ++# idlemain.py (this module) ++# ... ++# ++# ../IDLE.app/Contents/MacOS/Python{-32} is symlinked to ++# ..Library/Frameworks/Python.framework/Versions/m.n ++# /Resources/Python.app/Contents/MacOS/Python{-32} ++# which is the Python interpreter executable ++# ++# The flow of control is as follows: ++# 1. IDLE.app is launched which starts python running the IDLE script ++# 2. IDLE script exports ++# PYTHONEXECUTABLE = .../IDLE.app/Contents/MacOS/Python{-32} ++# (the symlink to the framework python) ++# 3. IDLE script alters sys.argv and uses os.execve to replace itself with ++# idlemain.py running under the symlinked python. ++# This is the magic step. ++# 4. During interpreter initialization, because PYTHONEXECUTABLE is defined, ++# sys.executable may get set to an unuseful value. ++# ++# (Note that the IDLE script and the setting of PYTHONEXECUTABLE is ++# generated automatically by bundlebuilder in the Python 2.x build. ++# Also, IDLE invoked via command line, i.e. bin/idle, bypasses all of ++# this.) ++# ++# Now fix up the execution environment before importing idlelib. + ++# Reset sys.executable to its normal value, the actual path of ++# the interpreter in the framework, by following the symlink ++# exported in PYTHONEXECUTABLE. ++pyex = os.environ['PYTHONEXECUTABLE'] ++sys.executable = os.path.join(os.path.dirname(pyex), os.readlink(pyex)) ++ ++# Remove any sys.path entries for the Resources dir in the IDLE.app bundle. ++p = pyex.partition('.app') ++if p[2].startswith('/Contents/MacOS/Python'): ++ sys.path = [value for value in sys.path if ++ value.partition('.app') != (p[0], p[1], '/Contents/Resources')] ++ ++# Unexport PYTHONEXECUTABLE so that the other Python processes started ++# by IDLE have a normal sys.executable. ++del os.environ['PYTHONEXECUTABLE'] ++ + # Look for the -psn argument that the launcher adds and remove it, it will + # only confuse the IDLE startup code. + for idx, value in enumerate(sys.argv): +@@ -25,6 +67,7 @@ + del sys.argv[idx] + break + +-#argvemulator.ArgvCollector().mainloop() ++# Now it is safe to import idlelib. ++from idlelib.PyShell import main + if __name__ == '__main__': + main() +Index: Tools/scripts/svneol.py +=================================================================== +--- Tools/scripts/svneol.py (.../tags/r261) (Revision 70449) ++++ Tools/scripts/svneol.py (.../branches/release26-maint) (Revision 70449) +@@ -39,9 +39,9 @@ + format = int(open(os.path.join(root, ".svn", "format")).read().strip()) + except IOError: + return [] +- if format == 8: +- # In version 8, committed props are stored in prop-base, +- # local modifications in props ++ if format in (8, 9): ++ # In version 8 and 9, committed props are stored in prop-base, local ++ # modifications in props + return [os.path.join(root, ".svn", "prop-base", fn+".svn-base"), + os.path.join(root, ".svn", "props", fn+".svn-work")] + raise ValueError, "Unknown repository format" +Index: Tools/scripts/patchcheck.py +=================================================================== +--- Tools/scripts/patchcheck.py (.../tags/r261) (Revision 70449) ++++ Tools/scripts/patchcheck.py (.../branches/release26-maint) (Revision 70449) +@@ -62,12 +62,12 @@ + @status("Misc/ACKS updated", modal=True) + def credit_given(file_paths): + """Check if Misc/ACKS has been changed.""" +- return True if 'Misc/ACKS' in file_paths else False ++ return 'Misc/ACKS' in file_paths + + @status("Misc/NEWS updated", modal=True) + def reported_news(file_paths): + """Check if Misc/NEWS has been changed.""" +- return True if 'Misc/NEWS' in file_paths else False ++ return 'Misc/NEWS' in file_paths + + + def main(): +Index: Tools/msi/msi.py +=================================================================== +--- Tools/msi/msi.py (.../tags/r261) (Revision 70449) ++++ Tools/msi/msi.py (.../branches/release26-maint) (Revision 70449) +@@ -115,6 +115,8 @@ + + # Compute the name that Sphinx gives to the docfile + docfile = "" ++if micro: ++ docfile = str(micro) + if level < 0xf: + docfile = '%x%s' % (level, serial) + docfile = 'python%s%s%s.chm' % (major, minor, docfile) +Index: Tools/msi/uuids.py +=================================================================== +--- Tools/msi/uuids.py (.../tags/r261) (Revision 70449) ++++ Tools/msi/uuids.py (.../branches/release26-maint) (Revision 70449) +@@ -47,4 +47,7 @@ + '2.6.121': '{bbd34464-ddeb-4028-99e5-f16c4a8fbdb3}', # 2.6c1 + '2.6.122': '{8f64787e-a023-4c60-bfee-25d3a3f592c6}', # 2.6c2 + '2.6.150': '{110eb5c4-e995-4cfb-ab80-a5f315bea9e8}', # 2.6.0 ++ '2.6.1150':'{9cc89170-000b-457d-91f1-53691f85b223}', # 2.6.1 ++ '2.6.2121':'{adac412b-b209-4c15-b6ab-dca1b6e47144}', # 2.6.2c1 ++ '2.6.2150':'{24aab420-4e30-4496-9739-3e216f3de6ae}', # 2.6.2 + } +Index: Tools/msi/crtlicense.txt +=================================================================== +--- Tools/msi/crtlicense.txt (.../tags/r261) (Revision 70449) ++++ Tools/msi/crtlicense.txt (.../branches/release26-maint) (Revision 70449) +@@ -26,7 +26,7 @@ + - alter any copyright, trademark or patent notice in Microsoft's + Distributable Code; + +-- use Microsoft’s trademarks in your programs’ names or in a way that ++- use Microsoft's trademarks in your programs' names or in a way that + suggests your programs come from or are endorsed by Microsoft; + + - distribute Microsoft's Distributable Code to run on a platform other +Index: Tools/pybench/Lists.py +=================================================================== +--- Tools/pybench/Lists.py (.../tags/r261) (Revision 70449) ++++ Tools/pybench/Lists.py (.../branches/release26-maint) (Revision 70449) +@@ -293,3 +293,58 @@ + + for i in xrange(self.rounds): + pass ++ ++class SimpleListComprehensions(Test): ++ ++ version = 2.0 ++ operations = 6 ++ rounds = 20000 ++ ++ def test(self): ++ ++ n = range(10) * 10 ++ ++ for i in xrange(self.rounds): ++ l = [x for x in n] ++ l = [x for x in n if x] ++ l = [x for x in n if not x] ++ ++ l = [x for x in n] ++ l = [x for x in n if x] ++ l = [x for x in n if not x] ++ ++ def calibrate(self): ++ ++ n = range(10) * 10 ++ ++ for i in xrange(self.rounds): ++ pass ++ ++class NestedListComprehensions(Test): ++ ++ version = 2.0 ++ operations = 6 ++ rounds = 20000 ++ ++ def test(self): ++ ++ m = range(10) ++ n = range(10) ++ ++ for i in xrange(self.rounds): ++ l = [x for x in n for y in m] ++ l = [y for x in n for y in m] ++ ++ l = [x for x in n for y in m if y] ++ l = [y for x in n for y in m if x] ++ ++ l = [x for x in n for y in m if not y] ++ l = [y for x in n for y in m if not x] ++ ++ def calibrate(self): ++ ++ m = range(10) ++ n = range(10) ++ ++ for i in xrange(self.rounds): ++ pass +Index: PC/_subprocess.c +=================================================================== +--- PC/_subprocess.c (.../tags/r261) (Revision 70449) ++++ PC/_subprocess.c (.../branches/release26-maint) (Revision 70449) +@@ -87,7 +87,7 @@ + + handle = self->handle; + +- self->handle = NULL; ++ self->handle = INVALID_HANDLE_VALUE; + + /* note: return the current handle, as an integer */ + return HANDLE_TO_PYNUM(handle); +Index: PC/VS8.0/build_ssl.bat +=================================================================== +--- PC/VS8.0/build_ssl.bat (.../tags/r261) (Revision 70449) ++++ PC/VS8.0/build_ssl.bat (.../branches/release26-maint) (Revision 70449) +@@ -2,10 +2,10 @@ + if not defined HOST_PYTHON ( + if %1 EQU Debug ( + set HOST_PYTHON=python_d.exe +- if not exist python30_d.dll exit 1 ++ if not exist python26_d.dll exit 1 + ) ELSE ( + set HOST_PYTHON=python.exe +- if not exist python30.dll exit 1 ++ if not exist python26.dll exit 1 + ) + ) + %HOST_PYTHON% build_ssl.py %1 %2 %3 +Index: PC/bdist_wininst/install.c +=================================================================== +--- PC/bdist_wininst/install.c (.../tags/r261) (Revision 70449) ++++ PC/bdist_wininst/install.c (.../branches/release26-maint) (Revision 70449) +@@ -694,8 +694,9 @@ + */ + + static int +-run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv) ++do_run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv) + { ++ int fh, result; + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, int, PySys_SetArgv, (int, char **)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); +@@ -706,9 +707,6 @@ + DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); + DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); + +- int result = 0; +- int fh; +- + if (!Py_Initialize || !PySys_SetArgv + || !PyRun_SimpleString || !Py_Finalize) + return 1; +@@ -730,7 +728,7 @@ + } + + SetDlgItemText(hDialog, IDC_INFO, "Running Script..."); +- ++ + Py_Initialize(); + + prepare_script_environment(hPython); +@@ -751,7 +749,57 @@ + Py_Finalize(); + + close(fh); ++ return result; ++} + ++static int ++run_installscript(char *pathname, int argc, char **argv, char **pOutput) ++{ ++ HINSTANCE hPython; ++ int result = 1; ++ int out_buf_size; ++ HANDLE redirected, old_stderr, old_stdout; ++ char *tempname; ++ ++ *pOutput = NULL; ++ ++ tempname = tempnam(NULL, NULL); ++ // We use a static CRT while the Python version we load uses ++ // the CRT from one of various possibile DLLs. As a result we ++ // need to redirect the standard handles using the API rather ++ // than the CRT. ++ redirected = CreateFile( ++ tempname, ++ GENERIC_WRITE | GENERIC_READ, ++ FILE_SHARE_READ, ++ NULL, ++ CREATE_ALWAYS, ++ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, ++ NULL); ++ old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); ++ old_stderr = GetStdHandle(STD_ERROR_HANDLE); ++ SetStdHandle(STD_OUTPUT_HANDLE, redirected); ++ SetStdHandle(STD_ERROR_HANDLE, redirected); ++ ++ hPython = LoadPythonDll(pythondll); ++ if (hPython) { ++ result = do_run_installscript(hPython, pathname, argc, argv); ++ FreeLibrary(hPython); ++ } else { ++ fprintf(stderr, "*** Could not load Python ***"); ++ } ++ SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); ++ SetStdHandle(STD_ERROR_HANDLE, old_stderr); ++ out_buf_size = min(GetFileSize(redirected, NULL), 4096); ++ *pOutput = malloc(out_buf_size+1); ++ if (*pOutput) { ++ DWORD nread = 0; ++ SetFilePointer(redirected, 0, 0, FILE_BEGIN); ++ ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL); ++ (*pOutput)[nread] = '\0'; ++ } ++ CloseHandle(redirected); ++ DeleteFile(tempname); + return result; + } + +@@ -781,11 +829,21 @@ + static int run_simple_script(char *script) + { + int rc; +- char *tempname; + HINSTANCE hPython; +- tempname = tempnam(NULL, NULL); +- freopen(tempname, "a", stderr); +- freopen(tempname, "a", stdout); ++ char *tempname = tempnam(NULL, NULL); ++ // Redirect output using win32 API - see comments above... ++ HANDLE redirected = CreateFile( ++ tempname, ++ GENERIC_WRITE | GENERIC_READ, ++ FILE_SHARE_READ, ++ NULL, ++ CREATE_ALWAYS, ++ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, ++ NULL); ++ HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); ++ HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE); ++ SetStdHandle(STD_OUTPUT_HANDLE, redirected); ++ SetStdHandle(STD_ERROR_HANDLE, redirected); + + hPython = LoadPythonDll(pythondll); + if (!hPython) { +@@ -796,10 +854,8 @@ + } + rc = do_run_simple_script(hPython, script); + FreeLibrary(hPython); +- fflush(stderr); +- fclose(stderr); +- fflush(stdout); +- fclose(stdout); ++ SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); ++ SetStdHandle(STD_ERROR_HANDLE, old_stderr); + /* We only care about the output when we fail. If the script works + OK, then we discard it + */ +@@ -808,24 +864,24 @@ + char *err_buf; + const char *prefix = "Running the pre-installation script failed\r\n"; + int prefix_len = strlen(prefix); +- FILE *fp = fopen(tempname, "rb"); +- fseek(fp, 0, SEEK_END); +- err_buf_size = ftell(fp); +- fseek(fp, 0, SEEK_SET); ++ err_buf_size = GetFileSize(redirected, NULL); ++ if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway... ++ err_buf_size = 4096; + err_buf = malloc(prefix_len + err_buf_size + 1); + if (err_buf) { +- int n; ++ DWORD n = 0; + strcpy(err_buf, prefix); +- n = fread(err_buf+prefix_len, 1, err_buf_size, fp); ++ SetFilePointer(redirected, 0, 0, FILE_BEGIN); ++ ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL); + err_buf[prefix_len+n] = '\0'; +- fclose(fp); + set_failure_reason(err_buf); + free(err_buf); + } else { + set_failure_reason("Out of memory!"); + } + } +- remove(tempname); ++ CloseHandle(redirected); ++ DeleteFile(tempname); + return rc; + } + +@@ -1946,12 +2002,9 @@ + + if (success && install_script && install_script[0]) { + char fname[MAX_PATH]; +- char *tempname; +- FILE *fp; +- char buffer[4096]; +- int n; ++ char *buffer; + HCURSOR hCursor; +- HINSTANCE hPython; ++ int result; + + char *argv[3] = {NULL, "-install", NULL}; + +@@ -1964,48 +2017,21 @@ + if (logfile) + fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname); + +- tempname = tempnam(NULL, NULL); +- +- if (!freopen(tempname, "a", stderr)) +- MessageBox(GetFocus(), "freopen stderr", NULL, MB_OK); +- if (!freopen(tempname, "a", stdout)) +- MessageBox(GetFocus(), "freopen stdout", NULL, MB_OK); +-/* +- if (0 != setvbuf(stdout, NULL, _IONBF, 0)) +- MessageBox(GetFocus(), "setvbuf stdout", NULL, MB_OK); +-*/ + hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT)); + + argv[0] = fname; + +- hPython = LoadPythonDll(pythondll); +- if (hPython) { +- int result; +- result = run_installscript(hPython, fname, 2, argv); +- if (-1 == result) { +- fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result); +- } +- FreeLibrary(hPython); +- } else { +- fprintf(stderr, "*** Could not load Python ***"); ++ result = run_installscript(fname, 2, argv, &buffer); ++ if (0 != result) { ++ fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result); + } +- fflush(stderr); +- fclose(stderr); +- fflush(stdout); +- fclose(stdout); +- +- fp = fopen(tempname, "rb"); +- n = fread(buffer, 1, sizeof(buffer), fp); +- fclose(fp); +- remove(tempname); +- +- buffer[n] = '\0'; +- +- SetDlgItemText(hwnd, IDC_INFO, buffer); ++ if (buffer) ++ SetDlgItemText(hwnd, IDC_INFO, buffer); + SetDlgItemText(hwnd, IDC_TITLE, + "Postinstall script finished.\n" + "Click the Finish button to exit the Setup wizard."); + ++ free(buffer); + SetCursor(hCursor); + CloseLogfile(); + } +@@ -2418,42 +2444,17 @@ + /* this function may be called more than one time with the same + script, only run it one time */ + if (strcmp(lastscript, scriptname)) { +- HINSTANCE hPython; + char *argv[3] = {NULL, "-remove", NULL}; +- char buffer[4096]; +- FILE *fp; +- char *tempname; +- int n; ++ char *buffer = NULL; + + argv[0] = scriptname; + +- tempname = tempnam(NULL, NULL); ++ if (0 != run_installscript(scriptname, 2, argv, &buffer)) ++ fprintf(stderr, "*** Could not run installation script ***"); + +- if (!freopen(tempname, "a", stderr)) +- MessageBox(GetFocus(), "freopen stderr", NULL, MB_OK); +- if (!freopen(tempname, "a", stdout)) +- MessageBox(GetFocus(), "freopen stdout", NULL, MB_OK); +- +- hPython = LoadLibrary(dllname); +- if (hPython) { +- if (0x80000000 == run_installscript(hPython, scriptname, 2, argv)) +- fprintf(stderr, "*** Could not load Python ***"); +- FreeLibrary(hPython); +- } +- +- fflush(stderr); +- fclose(stderr); +- fflush(stdout); +- fclose(stdout); +- +- fp = fopen(tempname, "rb"); +- n = fread(buffer, 1, sizeof(buffer), fp); +- fclose(fp); +- remove(tempname); +- +- buffer[n] = '\0'; +- if (buffer[0]) ++ if (buffer && buffer[0]) + MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK); ++ free(buffer); + + strcpy(lastscript, scriptname); + } +Index: PC/dl_nt.c +=================================================================== +--- PC/dl_nt.c (.../tags/r261) (Revision 70449) ++++ PC/dl_nt.c (.../branches/release26-maint) (Revision 70449) +@@ -18,7 +18,64 @@ + HMODULE PyWin_DLLhModule = NULL; + const char *PyWin_DLLVersionString = dllVersionBuffer; + ++// Windows "Activation Context" work: ++// Our .pyd extension modules are generally built without a manifest (ie, ++// those included with Python and those built with a default distutils. ++// This requires we perform some "activation context" magic when loading our ++// extensions. In summary: ++// * As our DLL loads we save the context being used. ++// * Before loading our extensions we re-activate our saved context. ++// * After extension load is complete we restore the old context. ++// As an added complication, this magic only works on XP or later - we simply ++// use the existence (or not) of the relevant function pointers from kernel32. ++// See bug 4566 (http://python.org/sf/4566) for more details. + ++typedef BOOL (WINAPI * PFN_GETCURRENTACTCTX)(HANDLE *); ++typedef BOOL (WINAPI * PFN_ACTIVATEACTCTX)(HANDLE, ULONG_PTR *); ++typedef BOOL (WINAPI * PFN_DEACTIVATEACTCTX)(DWORD, ULONG_PTR); ++typedef BOOL (WINAPI * PFN_ADDREFACTCTX)(HANDLE); ++typedef BOOL (WINAPI * PFN_RELEASEACTCTX)(HANDLE); ++ ++// locals and function pointers for this activation context magic. ++static HANDLE PyWin_DLLhActivationContext = NULL; // one day it might be public ++static PFN_GETCURRENTACTCTX pfnGetCurrentActCtx = NULL; ++static PFN_ACTIVATEACTCTX pfnActivateActCtx = NULL; ++static PFN_DEACTIVATEACTCTX pfnDeactivateActCtx = NULL; ++static PFN_ADDREFACTCTX pfnAddRefActCtx = NULL; ++static PFN_RELEASEACTCTX pfnReleaseActCtx = NULL; ++ ++void _LoadActCtxPointers() ++{ ++ HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll"); ++ if (hKernel32) ++ pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx"); ++ // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest. ++ if (pfnGetCurrentActCtx) { ++ pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx"); ++ pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx"); ++ pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx"); ++ pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx"); ++ } ++} ++ ++ULONG_PTR _Py_ActivateActCtx() ++{ ++ ULONG_PTR ret = 0; ++ if (PyWin_DLLhActivationContext && pfnActivateActCtx) ++ if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) { ++ OutputDebugString("Python failed to activate the activation context before loading a DLL\n"); ++ ret = 0; // no promise the failing function didn't change it! ++ } ++ return ret; ++} ++ ++void _Py_DeactivateActCtx(ULONG_PTR cookie) ++{ ++ if (cookie && pfnDeactivateActCtx) ++ if (!(*pfnDeactivateActCtx)(0, cookie)) ++ OutputDebugString("Python failed to de-activate the activation context\n"); ++} ++ + BOOL WINAPI DllMain (HANDLE hInst, + ULONG ul_reason_for_call, + LPVOID lpReserved) +@@ -29,9 +86,18 @@ + PyWin_DLLhModule = hInst; + // 1000 is a magic number I picked out of the air. Could do with a #define, I spose... + LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer)); +- //initall(); ++ ++ // and capture our activation context for use when loading extensions. ++ _LoadActCtxPointers(); ++ if (pfnGetCurrentActCtx && pfnAddRefActCtx) ++ if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext)) ++ if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext)) ++ OutputDebugString("Python failed to load the default activation context\n"); + break; ++ + case DLL_PROCESS_DETACH: ++ if (pfnReleaseActCtx) ++ (*pfnReleaseActCtx)(PyWin_DLLhActivationContext); + break; + } + return TRUE; +Index: PC/getpathp.c +=================================================================== +--- PC/getpathp.c (.../tags/r261) (Revision 70449) ++++ PC/getpathp.c (.../branches/release26-maint) (Revision 70449) +@@ -201,6 +201,7 @@ + } + + #ifdef MS_WINDOWS ++#ifdef Py_ENABLE_SHARED + + /* a string loaded from the DLL at startup.*/ + extern const char *PyWin_DLLVersionString; +@@ -363,6 +364,7 @@ + free(keyBuf); + return retval; + } ++#endif /* Py_ENABLE_SHARED */ + #endif /* MS_WINDOWS */ + + static void +@@ -380,6 +382,7 @@ + but makes no mention of the null terminator. Play it safe. + PLUS Windows itself defines MAX_PATH as the same, but anyway... + */ ++#ifdef Py_ENABLE_SHARED + wprogpath[MAXPATHLEN]=_T('\0'); + if (PyWin_DLLhModule && + GetModuleFileName(PyWin_DLLhModule, wprogpath, MAXPATHLEN)) { +@@ -388,6 +391,9 @@ + dllpath, MAXPATHLEN+1, + NULL, NULL); + } ++#else ++ dllpath[0] = 0; ++#endif + wprogpath[MAXPATHLEN]=_T('\0'); + if (GetModuleFileName(NULL, wprogpath, MAXPATHLEN)) { + WideCharToMultiByte(CP_ACP, 0, +@@ -398,9 +404,13 @@ + } + #else + /* static init of progpath ensures final char remains \0 */ ++#ifdef Py_ENABLE_SHARED + if (PyWin_DLLhModule) + if (!GetModuleFileName(PyWin_DLLhModule, dllpath, MAXPATHLEN)) + dllpath[0] = 0; ++#else ++ dllpath[0] = 0; ++#endif + if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) + return; + #endif +@@ -501,8 +511,10 @@ + } + + skiphome = pythonhome==NULL ? 0 : 1; ++#ifdef Py_ENABLE_SHARED + machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome); + userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome); ++#endif + /* We only use the default relative PYTHONPATH if we havent + anything better to use! */ + skipdefault = envpath!=NULL || pythonhome!=NULL || \ +Index: PC/VC6/tcl852.patch +=================================================================== +--- PC/VC6/tcl852.patch (.../tags/r261) (Revision 0) ++++ PC/VC6/tcl852.patch (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,22 @@ ++--- tcl8.5.2\generic\tcl.h Fri Jun 13 03:35:39 2008 +++++ tcl8.5.2\generic\tcl.h Sun Jan 4 16:52:30 2009 ++@@ -367,7 +367,7 @@ ++ typedef struct stati64 Tcl_StatBuf; ++ # define TCL_LL_MODIFIER "L" ++ # else /* __BORLANDC__ */ ++-# if _MSC_VER < 1400 && !defined(_M_IX86) +++# if _MSC_VER < 1400 /*&& !defined(_M_IX86)*/ ++ typedef struct _stati64 Tcl_StatBuf; ++ # else ++ typedef struct _stat64 Tcl_StatBuf; ++--- tcl8.5.2\generic\tcl.h Fri Jun 13 03:35:39 2008 +++++ tcl8.5.2\generic\tcl.h Sun Jan 4 16:52:30 2009 ++@@ -367,7 +367,7 @@ ++ typedef struct stati64 Tcl_StatBuf; ++ # define TCL_LL_MODIFIER "L" ++ # else /* __BORLANDC__ */ ++-# if _MSC_VER < 1400 && !defined(_M_IX86) +++# if _MSC_VER < 1400 /*&& !defined(_M_IX86)*/ ++ typedef struct _stati64 Tcl_StatBuf; ++ # else ++ typedef struct _stat64 Tcl_StatBuf; + +Eigenschaftsänderungen: PC/VC6/tcl852.patch +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: PC/VC6/bz2.dsp +=================================================================== +--- PC/VC6/bz2.dsp (.../tags/r261) (Revision 70449) ++++ PC/VC6/bz2.dsp (.../branches/release26-maint) (Revision 70449) +@@ -44,7 +44,7 @@ + # PROP Target_Dir "" + F90=df.exe + # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c +-# ADD CPP /nologo /MD /W3 /GX /Zi /O2 /I "..\..\Include" /I ".." /I "..\..\..\bzip2-1.0.3" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c ++# ADD CPP /nologo /MD /W3 /GX /Zi /O2 /I "..\..\Include" /I ".." /I "..\..\..\bzip2-1.0.5" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c + # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 + # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 + # ADD BASE RSC /l 0x409 /d "NDEBUG" +@@ -54,7 +54,7 @@ + # ADD BSC32 /nologo + LINK32=link.exe + # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386 +-# ADD LINK32 ..\..\..\bzip2-1.0.3\libbz2.lib /nologo /base:"0x1D170000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"libc" /out:"./bz2.pyd" ++# ADD LINK32 ..\..\..\bzip2-1.0.5\libbz2.lib /nologo /base:"0x1D170000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"libc" /out:"./bz2.pyd" + # SUBTRACT LINK32 /pdb:none /nodefaultlib + + !ELSEIF "$(CFG)" == "bz2 - Win32 Debug" +@@ -72,7 +72,7 @@ + # PROP Target_Dir "" + F90=df.exe + # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c +-# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\Include" /I ".." /I "..\..\..\bzip2-1.0.3" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c ++# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\Include" /I ".." /I "..\..\..\bzip2-1.0.5" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c + # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 + # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 + # ADD BASE RSC /l 0x409 /d "_DEBUG" +@@ -82,7 +82,7 @@ + # ADD BSC32 /nologo + LINK32=link.exe + # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept +-# ADD LINK32 ..\..\..\bzip2-1.0.3\libbz2.lib /nologo /base:"0x1D170000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"msvcrt" /nodefaultlib:"libc" /out:"./bz2_d.pyd" /pdbtype:sept ++# ADD LINK32 ..\..\..\bzip2-1.0.5\libbz2.lib /nologo /base:"0x1D170000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"msvcrt" /nodefaultlib:"libc" /out:"./bz2_d.pyd" /pdbtype:sept + # SUBTRACT LINK32 /pdb:none + + !ENDIF +Index: PC/VC6/build_tkinter.py +=================================================================== +--- PC/VC6/build_tkinter.py (.../tags/r261) (Revision 0) ++++ PC/VC6/build_tkinter.py (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,81 @@ ++import os ++import sys ++import subprocess ++ ++TCL_MAJOR = 8 ++TCL_MINOR = 5 ++TCL_PATCH = 2 ++ ++TIX_MAJOR = 8 ++TIX_MINOR = 4 ++TIX_PATCH = 3 ++ ++def abspath(name): ++ par = os.path.pardir ++ return os.path.abspath(os.path.join(__file__, par, par, par, par, name)) ++ ++TCL_DIR = abspath("tcl%d.%d.%d" % (TCL_MAJOR, TCL_MINOR, TCL_PATCH)) ++TK_DIR = abspath("tk%d.%d.%d" % (TCL_MAJOR, TCL_MINOR, TCL_PATCH)) ++TIX_DIR = abspath("tix%d.%d.%d" % (TIX_MAJOR, TIX_MINOR, TIX_PATCH)) ++OUT_DIR = abspath("tcltk") ++ ++def have_args(*a): ++ return any(s in sys.argv[1:] for s in a) ++ ++def enter(dir): ++ os.chdir(os.path.join(dir, "win")) ++ ++def main(): ++ debug = have_args("-d", "--debug") ++ clean = have_args("clean") ++ install = have_args("install") ++ tcl = have_args("tcl") ++ tk = have_args("tk") ++ tix = have_args("tix") ++ if not(tcl) and not(tk) and not(tix): ++ tcl = tk = tix = True ++ ++ def nmake(makefile, *a): ++ args = ["nmake", "/nologo", "/f", makefile, "DEBUG=%d" % debug] ++ args.extend(a) ++ subprocess.check_call(args) ++ ++ if tcl: ++ enter(TCL_DIR) ++ def nmake_tcl(*a): ++ nmake("makefile.vc", *a) ++ if clean: ++ nmake_tcl("clean") ++ elif install: ++ nmake_tcl("install", "INSTALLDIR=" + OUT_DIR) ++ else: ++ nmake_tcl() ++ ++ if tk: ++ enter(TK_DIR) ++ def nmake_tk(*a): ++ nmake("makefile.vc", "TCLDIR=" + TCL_DIR, *a) ++ if clean: ++ nmake_tk("clean") ++ elif install: ++ nmake_tk("install", "INSTALLDIR=" + OUT_DIR) ++ else: ++ nmake_tk() ++ ++ if tix: ++ enter(TIX_DIR) ++ def nmake_tix(*a): ++ nmake("python.mak", ++ "TCL_MAJOR=%d" % TCL_MAJOR, ++ "TCL_MINOR=%d" % TCL_MINOR, ++ "TCL_PATCH=%d" % TCL_PATCH, ++ "MACHINE=IX86", *a) ++ if clean: ++ nmake_tix("clean") ++ elif install: ++ nmake_tix("install", "INSTALL_DIR=" + OUT_DIR) ++ else: ++ nmake_tix() ++ ++if __name__ == '__main__': ++ main() + +Eigenschaftsänderungen: PC/VC6/build_tkinter.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: PC/VC6/_bsddb.dsp +=================================================================== +--- PC/VC6/_bsddb.dsp (.../tags/r261) (Revision 70449) ++++ PC/VC6/_bsddb.dsp (.../branches/release26-maint) (Revision 70449) +@@ -44,7 +44,7 @@ + # PROP Target_Dir "" + F90=df.exe + # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c +-# ADD CPP /nologo /MD /W3 /GX /Zi /O2 /I "..\..\Include" /I ".." /I "..\..\..\db-4.4.20\build_win32" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c ++# ADD CPP /nologo /MD /W3 /GX /Zi /O2 /I "..\..\Include" /I ".." /I "..\..\..\db-4.7.25\build_windows" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c + # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 + # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 + # ADD BASE RSC /l 0x409 /d "NDEBUG" +@@ -54,7 +54,7 @@ + # ADD BSC32 /nologo + LINK32=link.exe + # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386 +-# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ..\..\..\db-4.4.20\build_win32\Release\libdb44s.lib /nologo /base:"0x1e180000" /subsystem:windows /dll /debug /machine:I386 /out:"./_bsddb.pyd" ++# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib ..\..\..\db-4.7.25\build_windows\Release\libdb47s.lib /nologo /base:"0x1e180000" /subsystem:windows /dll /debug /machine:I386 /out:"./_bsddb.pyd" + # SUBTRACT LINK32 /pdb:none + + !ELSEIF "$(CFG)" == "_bsddb - Win32 Debug" +@@ -72,7 +72,7 @@ + # PROP Target_Dir "" + F90=df.exe + # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c +-# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\Include" /I ".." /I "..\..\..\db-4.4.20\build_win32" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c ++# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\Include" /I ".." /I "..\..\..\db-4.7.25\build_windows" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c + # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 + # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 + # ADD BASE RSC /l 0x409 /d "_DEBUG" +@@ -82,7 +82,7 @@ + # ADD BSC32 /nologo + LINK32=link.exe + # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept +-# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ..\..\..\db-4.4.20\build_win32\Release\libdb44s.lib /nologo /base:"0x1e180000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"msvcrtd" /out:"./_bsddb_d.pyd" /pdbtype:sept ++# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib ..\..\..\db-4.7.25\build_windows\Release\libdb47s.lib /nologo /base:"0x1e180000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"msvcrtd" /out:"./_bsddb_d.pyd" /pdbtype:sept + # SUBTRACT LINK32 /pdb:none + + !ENDIF +Index: PC/VC6/_tkinter.dsp +=================================================================== +--- PC/VC6/_tkinter.dsp (.../tags/r261) (Revision 70449) ++++ PC/VC6/_tkinter.dsp (.../branches/release26-maint) (Revision 70449) +@@ -54,7 +54,7 @@ + # ADD BSC32 /nologo + LINK32=link.exe + # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept +-# ADD LINK32 ..\..\..\tcltk\lib\tk84.lib ..\..\..\tcltk\lib\tcl84.lib odbc32.lib odbccp32.lib user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /base:"0x1e190000" /subsystem:windows /dll /debug /machine:I386 /out:"./_tkinter_d.pyd" /pdbtype:sept /libpath:"C:\Program Files\Tcl\lib" ++# ADD LINK32 ..\..\..\tcltk\lib\tk85g.lib ..\..\..\tcltk\lib\tcl85g.lib odbc32.lib odbccp32.lib user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /base:"0x1e190000" /subsystem:windows /dll /debug /machine:I386 /out:"./_tkinter_d.pyd" /pdbtype:sept + # SUBTRACT LINK32 /pdb:none + + !ELSEIF "$(CFG)" == "_tkinter - Win32 Release" +@@ -82,7 +82,7 @@ + # ADD BSC32 /nologo + LINK32=link.exe + # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386 +-# ADD LINK32 ..\..\..\tcltk\lib\tk84.lib ..\..\..\tcltk\lib\tcl84.lib odbc32.lib odbccp32.lib user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /base:"0x1e190000" /subsystem:windows /dll /debug /machine:I386 /out:"./_tkinter.pyd" /libpath:"C:\Program Files\Tcl\lib" ++# ADD LINK32 ..\..\..\tcltk\lib\tk85.lib ..\..\..\tcltk\lib\tcl85.lib odbc32.lib odbccp32.lib user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /base:"0x1e190000" /subsystem:windows /dll /debug /machine:I386 /out:"./_tkinter.pyd" + # SUBTRACT LINK32 /pdb:none + + !ENDIF +Index: PC/VC6/build_ssl.py +=================================================================== +--- PC/VC6/build_ssl.py (.../tags/r261) (Revision 70449) ++++ PC/VC6/build_ssl.py (.../branches/release26-maint) (Revision 70449) +@@ -13,7 +13,7 @@ + # it should configure and build SSL, then build the ssl Python extension + # without intervention. + +-import os, sys, re ++import os, sys, re, shutil + + # Find all "foo.exe" files on the PATH. + def find_all_on_path(filename, extras = None): +@@ -51,7 +51,6 @@ + else: + print " NO perl interpreters were found on this machine at all!" + print " Please install ActivePerl and ensure it appears on your path" +- print "The Python SSL module was not built" + return None + + # Locate the best SSL directory given a few roots to look into. +@@ -59,7 +58,8 @@ + candidates = [] + for s in sources: + try: +- s = os.path.abspath(s) ++ # note: do not abspath s; the build will fail if any ++ # higher up directory name has spaces in it. + fnames = os.listdir(s) + except os.error: + fnames = [] +@@ -82,11 +82,54 @@ + print "Found an SSL directory at '%s'" % (best_name,) + else: + print "Could not find an SSL directory in '%s'" % (sources,) ++ sys.stdout.flush() + return best_name + ++def fix_makefile(makefile): ++ """Fix some stuff in all makefiles ++ """ ++ if not os.path.isfile(makefile): ++ return ++ # 2.4 compatibility ++ fin = open(makefile) ++ if 1: # with open(makefile) as fin: ++ lines = fin.readlines() ++ fin.close() ++ fout = open(makefile, 'w') ++ if 1: # with open(makefile, 'w') as fout: ++ for line in lines: ++ if line.startswith("PERL="): ++ continue ++ if line.startswith("CP="): ++ line = "CP=copy\n" ++ if line.startswith("MKDIR="): ++ line = "MKDIR=mkdir\n" ++ if line.startswith("CFLAG="): ++ line = line.strip() ++ for algo in ("RC5", "MDC2", "IDEA"): ++ noalgo = " -DOPENSSL_NO_%s" % algo ++ if noalgo not in line: ++ line = line + noalgo ++ line = line + '\n' ++ fout.write(line) ++ fout.close() ++ ++def run_configure(configure, do_script): ++ print "perl Configure "+configure ++ os.system("perl Configure "+configure) ++ print do_script ++ os.system(do_script) ++ + def main(): + debug = "-d" in sys.argv + build_all = "-a" in sys.argv ++ if 1: # Win32 ++ arch = "x86" ++ configure = "VC-WIN32" ++ do_script = "ms\\do_nasm" ++ makefile="ms\\nt.mak" ++ m32 = makefile ++ configure += " no-idea no-rc5 no-mdc2" + make_flags = "" + if build_all: + make_flags = "-a" +@@ -95,11 +138,12 @@ + perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"]) + perl = find_working_perl(perls) + if perl is None: +- sys.exit(1) +- +- print "Found a working perl at '%s'" % (perl,) ++ print "No Perl installation was found. Existing Makefiles are used." ++ else: ++ print "Found a working perl at '%s'" % (perl,) ++ sys.stdout.flush() + # Look for SSL 3 levels up from pcbuild - ie, same place zlib etc all live. +- ssl_dir = find_best_ssl_dir(("../../..",)) ++ ssl_dir = find_best_ssl_dir(("..\\..\\..",)) + if ssl_dir is None: + sys.exit(1) + +@@ -107,49 +151,44 @@ + try: + os.chdir(ssl_dir) + # If the ssl makefiles do not exist, we invoke Perl to generate them. +- if not os.path.isfile(os.path.join(ssl_dir, "32.mak")) or \ +- not os.path.isfile(os.path.join(ssl_dir, "d32.mak")): ++ # Due to a bug in this script, the makefile sometimes ended up empty ++ # Force a regeneration if it is. ++ if not os.path.isfile(makefile) or os.path.getsize(makefile)==0: ++ if perl is None: ++ print "Perl is required to build the makefiles!" ++ sys.exit(1) ++ + print "Creating the makefiles..." ++ sys.stdout.flush() + # Put our working Perl at the front of our path +- os.environ["PATH"] = os.path.split(perl)[0] + \ ++ os.environ["PATH"] = os.path.dirname(perl) + \ + os.pathsep + \ + os.environ["PATH"] +- # ms\32all.bat will reconfigure OpenSSL and then try to build +- # all outputs (debug/nondebug/dll/lib). So we filter the file +- # to exclude any "nmake" commands and then execute. +- tempname = "ms\\32all_py.bat" ++ run_configure(configure, do_script) ++ if debug: ++ print "OpenSSL debug builds aren't supported." ++ #if arch=="x86" and debug: ++ # # the do_masm script in openssl doesn't generate a debug ++ # # build makefile so we generate it here: ++ # os.system("perl util\mk1mf.pl debug "+configure+" >"+makefile) + +- in_bat = open("ms\\32all.bat") +- temp_bat = open(tempname,"w") +- while 1: +- cmd = in_bat.readline() +- print 'cmd', repr(cmd) +- if not cmd: break +- if cmd.strip()[:5].lower() == "nmake": +- continue +- temp_bat.write(cmd) +- in_bat.close() +- temp_bat.close() +- os.system(tempname) +- try: +- os.remove(tempname) +- except: +- pass ++ fix_makefile(makefile) ++ shutil.copy(r"crypto\buildinf.h", r"crypto\buildinf_%s.h" % arch) ++ shutil.copy(r"crypto\opensslconf.h", r"crypto\opensslconf_%s.h" % arch) + + # Now run make. +- print "Executing nmake over the ssl makefiles..." +- if debug: +- rc = os.system("nmake /nologo -f d32.mak") +- if rc: +- print "Executing d32.mak failed" +- print rc +- sys.exit(rc) +- else: +- rc = os.system("nmake /nologo -f 32.mak") +- if rc: +- print "Executing 32.mak failed" +- print rc +- sys.exit(rc) ++ shutil.copy(r"crypto\buildinf_%s.h" % arch, r"crypto\buildinf.h") ++ shutil.copy(r"crypto\opensslconf_%s.h" % arch, r"crypto\opensslconf.h") ++ ++ #makeCommand = "nmake /nologo PERL=\"%s\" -f \"%s\"" %(perl, makefile) ++ makeCommand = "nmake /nologo -f \"%s\"" % makefile ++ print "Executing ssl makefiles:", makeCommand ++ sys.stdout.flush() ++ rc = os.system(makeCommand) ++ if rc: ++ print "Executing "+makefile+" failed" ++ print rc ++ sys.exit(rc) + finally: + os.chdir(old_cd) + # And finally, we can build the _ssl module itself for Python. +Index: PC/VC6/_ssl.mak +=================================================================== +--- PC/VC6/_ssl.mak (.../tags/r261) (Revision 70449) ++++ PC/VC6/_ssl.mak (.../branches/release26-maint) (Revision 70449) +@@ -3,19 +3,20 @@ + MODULE=_ssl_d.pyd + TEMP_DIR=x86-temp-debug/_ssl + CFLAGS=/Od /Zi /MDd /LDd /DDEBUG /D_DEBUG /DWIN32 +-SSL_LIB_DIR=$(SSL_DIR)/out32.dbg ++LFLAGS=/nodefaultlib:"msvcrt" + !ELSE + MODULE=_ssl.pyd + TEMP_DIR=x86-temp-release/_ssl + CFLAGS=/Ox /MD /LD /DWIN32 +-SSL_LIB_DIR=$(SSL_DIR)/out32 ++LFLAGS= + !ENDIF + + INCLUDES=-I ../../Include -I .. -I $(SSL_DIR)/inc32 ++SSL_LIB_DIR=$(SSL_DIR)/out32 + LIBS=gdi32.lib wsock32.lib user32.lib advapi32.lib /libpath:$(SSL_LIB_DIR) libeay32.lib ssleay32.lib + + SOURCE=../../Modules/_ssl.c $(SSL_LIB_DIR)/libeay32.lib $(SSL_LIB_DIR)/ssleay32.lib + + $(MODULE): $(SOURCE) ../*.h ../../Include/*.h + @if not exist "$(TEMP_DIR)/." mkdir "$(TEMP_DIR)" +- cl /nologo $(SOURCE) $(CFLAGS) /Fo$(TEMP_DIR)\$*.obj $(INCLUDES) /link /out:$(MODULE) $(LIBS) ++ cl /nologo $(SOURCE) $(CFLAGS) /Fo$(TEMP_DIR)\$*.obj $(INCLUDES) /link /out:$(MODULE) $(LIBS) $(LFLAGS) +Index: PC/VC6/_multiprocessing.dsp +=================================================================== +--- PC/VC6/_multiprocessing.dsp (.../tags/r261) (Revision 70449) ++++ PC/VC6/_multiprocessing.dsp (.../branches/release26-maint) (Revision 70449) +@@ -1,115 +1,115 @@ +-# Microsoft Developer Studio Project File - Name="_multiprocessing" - Package Owner=<4> +-# Microsoft Developer Studio Generated Build File, Format Version 6.00 +-# ** DO NOT EDIT ** +- +-# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 +- +-CFG=_multiprocessing - Win32 Debug +-!MESSAGE This is not a valid makefile. To build this project using NMAKE, +-!MESSAGE use the Export Makefile command and run +-!MESSAGE +-!MESSAGE NMAKE /f "_multiprocessing.mak". +-!MESSAGE +-!MESSAGE You can specify a configuration when running NMAKE +-!MESSAGE by defining the macro CFG on the command line. For example: +-!MESSAGE +-!MESSAGE NMAKE /f "_multiprocessing.mak" CFG="_multiprocessing - Win32 Debug" +-!MESSAGE +-!MESSAGE Possible choices for configuration are: +-!MESSAGE +-!MESSAGE "_multiprocessing - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +-!MESSAGE "_multiprocessing - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +-!MESSAGE +- +-# Begin Project +-# PROP AllowPerConfigDependencies 0 +-# PROP Scc_ProjName "_multiprocessing" +-# PROP Scc_LocalPath ".." +-CPP=cl.exe +-MTL=midl.exe +-RSC=rc.exe +- +-!IF "$(CFG)" == "_multiprocessing - Win32 Release" +- +-# PROP BASE Use_MFC 0 +-# PROP BASE Use_Debug_Libraries 0 +-# PROP BASE Output_Dir "Release" +-# PROP BASE Intermediate_Dir "Release" +-# PROP BASE Target_Dir "" +-# PROP Use_MFC 0 +-# PROP Use_Debug_Libraries 0 +-# PROP Output_Dir "." +-# PROP Intermediate_Dir "x86-temp-release\_multiprocessing" +-# PROP Ignore_Export_Lib 0 +-# PROP Target_Dir "" +-F90=df.exe +-# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c +-# ADD CPP /nologo /MD /W3 /GX /Zi /O2 /I "..\..\Include" /I ".." /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c +-# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 +-# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 +-# ADD BASE RSC /l 0x409 /d "NDEBUG" +-# ADD RSC /l 0x409 /d "NDEBUG" +-BSC32=bscmake.exe +-# ADD BASE BSC32 /nologo +-# ADD BSC32 /nologo +-LINK32=link.exe +-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386 +-# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib /nologo /base:"0x1e1D0000" /subsystem:windows /dll /debug /machine:I386 /out:"./_multiprocessing.pyd" +-# SUBTRACT LINK32 /pdb:none +- +-!ELSEIF "$(CFG)" == "_multiprocessing - Win32 Debug" +- +-# PROP BASE Use_MFC 0 +-# PROP BASE Use_Debug_Libraries 1 +-# PROP BASE Output_Dir "Debug" +-# PROP BASE Intermediate_Dir "Debug" +-# PROP BASE Target_Dir "" +-# PROP Use_MFC 0 +-# PROP Use_Debug_Libraries 1 +-# PROP Output_Dir "." +-# PROP Intermediate_Dir "x86-temp-debug\_multiprocessing" +-# PROP Ignore_Export_Lib 0 +-# PROP Target_Dir "" +-F90=df.exe +-# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c +-# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\Include" /I ".." /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c +-# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 +-# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 +-# ADD BASE RSC /l 0x409 /d "_DEBUG" +-# ADD RSC /l 0x409 /d "_DEBUG" +-BSC32=bscmake.exe +-# ADD BASE BSC32 /nologo +-# ADD BSC32 /nologo +-LINK32=link.exe +-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept +-# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib /nologo /base:"0x1e1d0000" /subsystem:windows /dll /debug /machine:I386 /out:"./_multiprocessing_d.pyd" /pdbtype:sept +-# SUBTRACT LINK32 /pdb:none +- +-!ENDIF +- +-# Begin Target +- +-# Name "_multiprocessing - Win32 Release" +-# Name "_multiprocessing - Win32 Debug" +-# Begin Source File +- +-SOURCE=..\..\Modules\_multiprocessing\multiprocessing.c +-# End Source File +-# Begin Source File +- +-SOURCE=..\..\Modules\_multiprocessing\pipe_connection.c +-# End Source File +-# Begin Source File +- +-SOURCE=..\..\Modules\_multiprocessing\semaphore.c +-# End Source File +-# Begin Source File +- +-SOURCE=..\..\Modules\_multiprocessing\socket_connection.c +-# End Source File +-# Begin Source File +- +-SOURCE=..\..\Modules\_multiprocessing\win32_functions.c +-# End Source File +-# End Target +-# End Project ++# Microsoft Developer Studio Project File - Name="_multiprocessing" - Package Owner=<4> ++# Microsoft Developer Studio Generated Build File, Format Version 6.00 ++# ** DO NOT EDIT ** ++ ++# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 ++ ++CFG=_multiprocessing - Win32 Debug ++!MESSAGE This is not a valid makefile. To build this project using NMAKE, ++!MESSAGE use the Export Makefile command and run ++!MESSAGE ++!MESSAGE NMAKE /f "_multiprocessing.mak". ++!MESSAGE ++!MESSAGE You can specify a configuration when running NMAKE ++!MESSAGE by defining the macro CFG on the command line. For example: ++!MESSAGE ++!MESSAGE NMAKE /f "_multiprocessing.mak" CFG="_multiprocessing - Win32 Debug" ++!MESSAGE ++!MESSAGE Possible choices for configuration are: ++!MESSAGE ++!MESSAGE "_multiprocessing - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") ++!MESSAGE "_multiprocessing - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") ++!MESSAGE ++ ++# Begin Project ++# PROP AllowPerConfigDependencies 0 ++# PROP Scc_ProjName "_multiprocessing" ++# PROP Scc_LocalPath ".." ++CPP=cl.exe ++MTL=midl.exe ++RSC=rc.exe ++ ++!IF "$(CFG)" == "_multiprocessing - Win32 Release" ++ ++# PROP BASE Use_MFC 0 ++# PROP BASE Use_Debug_Libraries 0 ++# PROP BASE Output_Dir "Release" ++# PROP BASE Intermediate_Dir "Release" ++# PROP BASE Target_Dir "" ++# PROP Use_MFC 0 ++# PROP Use_Debug_Libraries 0 ++# PROP Output_Dir "." ++# PROP Intermediate_Dir "x86-temp-release\_multiprocessing" ++# PROP Ignore_Export_Lib 0 ++# PROP Target_Dir "" ++F90=df.exe ++# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c ++# ADD CPP /nologo /MD /W3 /GX /Zi /O2 /I "..\..\Include" /I ".." /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c ++# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 ++# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32 ++# ADD BASE RSC /l 0x409 /d "NDEBUG" ++# ADD RSC /l 0x409 /d "NDEBUG" ++BSC32=bscmake.exe ++# ADD BASE BSC32 /nologo ++# ADD BSC32 /nologo ++LINK32=link.exe ++# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386 ++# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib /nologo /base:"0x1e1D0000" /subsystem:windows /dll /debug /machine:I386 /out:"./_multiprocessing.pyd" ++# SUBTRACT LINK32 /pdb:none ++ ++!ELSEIF "$(CFG)" == "_multiprocessing - Win32 Debug" ++ ++# PROP BASE Use_MFC 0 ++# PROP BASE Use_Debug_Libraries 1 ++# PROP BASE Output_Dir "Debug" ++# PROP BASE Intermediate_Dir "Debug" ++# PROP BASE Target_Dir "" ++# PROP Use_MFC 0 ++# PROP Use_Debug_Libraries 1 ++# PROP Output_Dir "." ++# PROP Intermediate_Dir "x86-temp-debug\_multiprocessing" ++# PROP Ignore_Export_Lib 0 ++# PROP Target_Dir "" ++F90=df.exe ++# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c ++# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\Include" /I ".." /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c ++# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 ++# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32 ++# ADD BASE RSC /l 0x409 /d "_DEBUG" ++# ADD RSC /l 0x409 /d "_DEBUG" ++BSC32=bscmake.exe ++# ADD BASE BSC32 /nologo ++# ADD BSC32 /nologo ++LINK32=link.exe ++# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept ++# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib /nologo /base:"0x1e1d0000" /subsystem:windows /dll /debug /machine:I386 /out:"./_multiprocessing_d.pyd" /pdbtype:sept ++# SUBTRACT LINK32 /pdb:none ++ ++!ENDIF ++ ++# Begin Target ++ ++# Name "_multiprocessing - Win32 Release" ++# Name "_multiprocessing - Win32 Debug" ++# Begin Source File ++ ++SOURCE=..\..\Modules\_multiprocessing\multiprocessing.c ++# End Source File ++# Begin Source File ++ ++SOURCE=..\..\Modules\_multiprocessing\pipe_connection.c ++# End Source File ++# Begin Source File ++ ++SOURCE=..\..\Modules\_multiprocessing\semaphore.c ++# End Source File ++# Begin Source File ++ ++SOURCE=..\..\Modules\_multiprocessing\socket_connection.c ++# End Source File ++# Begin Source File ++ ++SOURCE=..\..\Modules\_multiprocessing\win32_functions.c ++# End Source File ++# End Target ++# End Project + +Eigenschaftsänderungen: PC/VC6/_multiprocessing.dsp +___________________________________________________________________ +Geändert: svn:eol-style + - native + + CRLF + +Index: PC/VC6/readme.txt +=================================================================== +--- PC/VC6/readme.txt (.../tags/r261) (Revision 70449) ++++ PC/VC6/readme.txt (.../branches/release26-maint) (Revision 70449) +@@ -63,18 +63,25 @@ + + _tkinter + Python wrapper for the Tk windowing system. Requires building +- Tcl/Tk first. Following are instructions for Tcl/Tk 8.4.12. ++ Tcl/Tk first. Following are instructions for Tcl/Tk 8.5.2. + + Get source + ---------- + In the dist directory, run +- svn export http://svn.python.org/projects/external/tcl8.4.12 +- svn export http://svn.python.org/projects/external/tk8.4.12 +- svn export http://svn.python.org/projects/external/tix-8.4.0 ++ svn export http://svn.python.org/projects/external/tcl-8.5.2.1 tcl8.5.2 ++ svn export http://svn.python.org/projects/external/tk-8.5.2.0 tk8.5.2 ++ svn export http://svn.python.org/projects/external/tix-8.4.3.1 tix8.4.3 + ++ Debug Build ++ ----------- ++ To build debug version, add DEBUG=1 to all nmake call bellow. ++ + Build Tcl first (done here w/ MSVC 6 on Win2K) + --------------- +- cd dist\tcl8.4.12\win ++ If your environment doesn't have struct _stat64, you need to apply ++ tcl852.patch in this directory to dist\tcl8.5.2\generic\tcl.h. ++ ++ cd dist\tcl8.5.2\win + run vcvars32.bat + nmake -f makefile.vc + nmake -f makefile.vc INSTALLDIR=..\..\tcltk install +@@ -84,16 +91,16 @@ + Optional: run tests, via + nmake -f makefile.vc test + +- all.tcl: Total 10835 Passed 10096 Skipped 732 Failed 7 +- Sourced 129 Test Files. +- Files with failing tests: exec.test expr.test io.test main.test string.test stri ++ all.tcl: Total 24242 Passed 23358 Skipped 877 Failed 7 ++ Sourced 137 Test Files. ++ Files with failing tests: exec.test http.test io.test main.test string.test stri + ngObj.test + + Build Tk + -------- +- cd dist\tk8.4.12\win +- nmake -f makefile.vc TCLDIR=..\..\tcl8.4.12 +- nmake -f makefile.vc TCLDIR=..\..\tcl8.4.12 INSTALLDIR=..\..\tcltk install ++ cd dist\tk8.5.2\win ++ nmake -f makefile.vc TCLDIR=..\..\tcl8.5.2 ++ nmake -f makefile.vc TCLDIR=..\..\tcl8.5.2 INSTALLDIR=..\..\tcltk install + + XXX Should we compile with OPTS=threads? + +@@ -101,26 +108,26 @@ + XXX failed. It popped up tons of little windows, and did lots of + XXX stuff, and nothing blew up. + +- Built Tix +- --------- +- cd dist\tix-8.4.0\win +- nmake -f python.mak +- nmake -f python.mak install ++ Build Tix ++ --------- ++ cd dist\tix8.4.3\win ++ nmake -f python.mak TCL_MAJOR=8 TCL_MINOR=5 TCL_PATCH=2 MACHINE=IX86 DEBUG=0 ++ nmake -f python.mak TCL_MAJOR=8 TCL_MINOR=5 TCL_PATCH=2 MACHINE=IX86 DEBUG=0 INSTALL_DIR=..\..\tcltk install + + bz2 + Python wrapper for the libbz2 compression library. Homepage +- http://sources.redhat.com/bzip2/ ++ http://www.bzip.org/ + Download the source from the python.org copy into the dist + directory: + +- svn export http://svn.python.org/projects/external/bzip2-1.0.3 ++ svn export http://svn.python.org/projects/external/bzip2-1.0.5 + + And requires building bz2 first. + +- cd dist\bzip2-1.0.3 ++ cd dist\bzip2-1.0.5 + nmake -f makefile.msc + +- All of this managed to build bzip2-1.0.3\libbz2.lib, which the Python ++ All of this managed to build bzip2-1.0.5\libbz2.lib, which the Python + project links in. + + +@@ -128,23 +135,23 @@ + To use the version of bsddb that Python is built with by default, invoke + (in the dist directory) + +- svn export http://svn.python.org/projects/external/db-4.4.20 ++ svn export http://svn.python.org/projects/external/db-4.7.25.0 db-4.7.25 + +- Then open db-4.4.20\build_win32\Berkeley_DB.dsw and build the "db_static" +- project for "Release" mode. ++ Then open db-4.7.25\build_windows\Berkeley_DB.dsw and build the ++ "db_static" project for "Release" mode. + + Alternatively, if you want to start with the original sources, +- go to Sleepycat's download page: +- http://www.sleepycat.com/downloads/releasehistorybdb.html ++ go to Oracle's download page: ++ http://www.oracle.com/technology/software/products/berkeley-db/db/ + +- and download version 4.4.20. ++ and download version 4.7.25. + + With or without strong cryptography? You can choose either with or + without strong cryptography, as per the instructions below. By + default, Python is built and distributed WITHOUT strong crypto. + + Unpack the sources; if you downloaded the non-crypto version, rename +- the directory from db-4.4.20.NC to db-4.4.20. ++ the directory from db-4.7.25.NC to db-4.7.25. + + Now apply any patches that apply to your version. + +@@ -196,13 +203,13 @@ + http://www.openssl.org + + You (probably) don't want the "engine" code. For example, get +- openssl-0.9.6g.tar.gz ++ openssl-0.9.8g.tar.gz + not +- openssl-engine-0.9.6g.tar.gz ++ openssl-engine-0.9.8g.tar.gz + + Unpack into the "dist" directory, retaining the folder name from + the archive - for example, the latest stable OpenSSL will install as +- dist/openssl-0.9.6g ++ dist/openssl-0.9.8g + + You can (theoretically) use any version of OpenSSL you like - the + build process will automatically select the latest version. + +Eigenschaftsänderungen: PC/VC6/_msi.dsp +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + CRLF + +Index: PC/pyconfig.h +=================================================================== +--- PC/pyconfig.h (.../tags/r261) (Revision 70449) ++++ PC/pyconfig.h (.../branches/release26-maint) (Revision 70449) +@@ -88,6 +88,12 @@ + #define USE_SOCKET + #endif + ++/* CE6 doesn't have strdup() but _strdup(). Assume the same for earlier versions. */ ++#if defined(MS_WINCE) ++# include ++# define strdup _strdup ++#endif ++ + #ifdef MS_WINCE + /* Python uses GetVersion() to distinguish between + * Windows NT and 9x/ME where OS Unicode support is concerned. +Index: Doc/make.bat +=================================================================== +--- Doc/make.bat (.../tags/r261) (Revision 70449) ++++ Doc/make.bat (.../branches/release26-maint) (Revision 70449) +@@ -8,34 +8,41 @@ + if "%1" EQU "" goto help + if "%1" EQU "html" goto build + if "%1" EQU "htmlhelp" goto build +-if "%1" EQU "web" goto build +-if "%1" EQU "webrun" goto webrun ++if "%1" EQU "latex" goto build ++if "%1" EQU "text" goto build ++if "%1" EQU "suspicious" goto build ++if "%1" EQU "linkcheck" goto build ++if "%1" EQU "changes" goto build + if "%1" EQU "checkout" goto checkout + if "%1" EQU "update" goto update + + :help ++set this=%~n0 + echo HELP + echo. +-echo builddoc checkout +-echo builddoc update +-echo builddoc html +-echo builddoc htmlhelp +-echo builddoc web +-echo builddoc webrun ++echo %this% checkout ++echo %this% update ++echo %this% html ++echo %this% htmlhelp ++echo %this% latex ++echo %this% text ++echo %this% suspicious ++echo %this% linkcheck ++echo %this% changes + echo. + goto end + + :checkout + svn co %SVNROOT%/doctools/trunk/sphinx tools/sphinx +-svn co %SVNROOT%/external/docutils-0.4/docutils tools/docutils +-svn co %SVNROOT%/external/Jinja-1.1/jinja tools/jinja +-svn co %SVNROOT%/external/Pygments-0.9/pygments tools/pygments ++svn co %SVNROOT%/external/docutils-0.5/docutils tools/docutils ++svn co %SVNROOT%/external/Jinja-2.1.1/jinja2 tools/jinja2 ++svn co %SVNROOT%/external/Pygments-0.11.1/pygments tools/pygments + goto end + + :update + svn update tools/sphinx + svn update tools/docutils +-svn update tools/jinja ++svn update tools/jinja2 + svn update tools/pygments + goto end + +@@ -43,13 +50,8 @@ + if not exist build mkdir build + if not exist build\%1 mkdir build\%1 + if not exist build\doctrees mkdir build\doctrees +-cmd /C %PYTHON% tools\sphinx-build.py -b%1 -dbuild\doctrees . build\%1 ++cmd /C %PYTHON% tools\sphinx-build.py -b%1 -dbuild\doctrees . build\%* + if "%1" EQU "htmlhelp" "%HTMLHELP%" build\htmlhelp\pydoc.hhp + goto end + +-:webrun +-set PYTHONPATH=tools +-%PYTHON% -m sphinx.web build\web +-goto end +- + :end +Index: Doc/distutils/uploading.rst +=================================================================== +--- Doc/distutils/uploading.rst (.../tags/r261) (Revision 70449) ++++ Doc/distutils/uploading.rst (.../branches/release26-maint) (Revision 70449) +@@ -35,9 +35,9 @@ + be available for execution on the system :envvar:`PATH`. You can also specify + which key to use for signing using the :option:`--identity=*name*` option. + +-Other :command:`upload` options include :option:`--repository=*url*` +-or :option:`--repository=*section*` where `url` is the url of the server +-and `section` the name of the section in :file:`$HOME/.pypirc`, and ++Other :command:`upload` options include :option:`--repository=` or ++:option:`--repository=

` where *url* is the url of the server and ++*section* the name of the section in :file:`$HOME/.pypirc`, and + :option:`--show-response` (which displays the full response text from the PyPI + server for help in debugging upload problems). + +Index: Doc/distutils/builtdist.rst +=================================================================== +--- Doc/distutils/builtdist.rst (.../tags/r261) (Revision 70449) ++++ Doc/distutils/builtdist.rst (.../branches/release26-maint) (Revision 70449) +@@ -268,13 +268,13 @@ + .. % \longprogramopt{spec-file} option; used in conjunction with + .. % \longprogramopt{spec-only}, this gives you an opportunity to customize + .. % the \file{.spec} file manually: +-.. % ++.. % + .. % \ begin{verbatim} + .. % > python setup.py bdist_rpm --spec-only + .. % # ...edit dist/FooBar-1.0.spec + .. % > python setup.py bdist_rpm --spec-file=dist/FooBar-1.0.spec + .. % \ end{verbatim} +-.. % ++.. % + .. % (Although a better way to do this is probably to override the standard + .. % \command{bdist\_rpm} command with one that writes whatever else you want + .. % to the \file{.spec} file.) +@@ -334,31 +334,31 @@ + Cross-compiling on Windows + ========================== + +-Starting with Python 2.6, distutils is capable of cross-compiling between +-Windows platforms. In practice, this means that with the correct tools ++Starting with Python 2.6, distutils is capable of cross-compiling between ++Windows platforms. In practice, this means that with the correct tools + installed, you can use a 32bit version of Windows to create 64bit extensions + and vice-versa. + +-To build for an alternate platform, specify the :option:`--plat-name` option +-to the build command. Valid values are currently 'win32', 'win-amd64' and ++To build for an alternate platform, specify the :option:`--plat-name` option ++to the build command. Valid values are currently 'win32', 'win-amd64' and + 'win-ia64'. For example, on a 32bit version of Windows, you could execute:: + + python setup.py build --plat-name=win-amd64 + +-to build a 64bit version of your extension. The Windows Installers also ++to build a 64bit version of your extension. The Windows Installers also + support this option, so the command:: + + python setup.py build --plat-name=win-amd64 bdist_wininst + + would create a 64bit installation executable on your 32bit version of Windows. + +-To cross-compile, you must download the Python source code and cross-compile ++To cross-compile, you must download the Python source code and cross-compile + Python itself for the platform you are targetting - it is not possible from a + binary installtion of Python (as the .lib etc file for other platforms are +-not included.) In practice, this means the user of a 32 bit operating +-system will need to use Visual Studio 2008 to open the +-:file:`PCBuild/PCbuild.sln` solution in the Python source tree and build the +-"x64" configuration of the 'pythoncore' project before cross-compiling ++not included.) In practice, this means the user of a 32 bit operating ++system will need to use Visual Studio 2008 to open the ++:file:`PCBuild/PCbuild.sln` solution in the Python source tree and build the ++"x64" configuration of the 'pythoncore' project before cross-compiling + extensions is possible. + + Note that by default, Visual Studio 2008 does not install 64bit compilers or +Index: Doc/distutils/packageindex.rst +=================================================================== +--- Doc/distutils/packageindex.rst (.../tags/r261) (Revision 70449) ++++ Doc/distutils/packageindex.rst (.../branches/release26-maint) (Revision 70449) +@@ -72,7 +72,7 @@ + index-servers = + pypi + other +- ++ + [pypi] + repository: + username: +@@ -91,4 +91,4 @@ + + python setup.py register -r other + +- ++ +Index: Doc/distutils/configfile.rst +=================================================================== +--- Doc/distutils/configfile.rst (.../tags/r261) (Revision 70449) ++++ Doc/distutils/configfile.rst (.../branches/release26-maint) (Revision 70449) +@@ -63,7 +63,7 @@ + --include-dirs (-I) list of directories to search for header files + --define (-D) C preprocessor macros to define + --undef (-U) C preprocessor macros to undefine +- --swig-opts list of SWIG command line options ++ --swig-opts list of SWIG command line options + [...] + + Note that an option spelled :option:`--foo-bar` on the command-line is spelled +Index: Doc/distutils/setupscript.rst +=================================================================== +--- Doc/distutils/setupscript.rst (.../tags/r261) (Revision 70449) ++++ Doc/distutils/setupscript.rst (.../branches/release26-maint) (Revision 70449) +@@ -213,7 +213,7 @@ + this:: + + setup(..., +- ext_modules=[Extension('_foo', ['foo.i'], ++ ext_modules=[Extension('_foo', ['foo.i'], + swig_opts=['-modern', '-I../include'])], + py_modules=['foo'], + ) +@@ -563,6 +563,8 @@ + +----------------------+---------------------------+-----------------+--------+ + | ``classifiers`` | a list of classifiers | list of strings | \(4) | + +----------------------+---------------------------+-----------------+--------+ ++| ``platforms`` | a list of platforms | list of strings | | +++----------------------+---------------------------+-----------------+--------+ + + Notes: + +Index: Doc/distutils/apiref.rst +=================================================================== +--- Doc/distutils/apiref.rst (.../tags/r261) (Revision 70449) ++++ Doc/distutils/apiref.rst (.../branches/release26-maint) (Revision 70449) +@@ -88,9 +88,9 @@ + | *options* | default options for the setup | a string | + | | script | | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *license* | The license for the package | | ++ | *license* | The license for the package | a string | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *keywords* | Descriptive meta-data. See | | ++ | *keywords* | Descriptive meta-data, see | | + | | :pep:`314` | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *platforms* | | | +@@ -98,8 +98,15 @@ + | *cmdclass* | A mapping of command names to | a dictionary | + | | :class:`Command` subclasses | | + +--------------------+--------------------------------+-------------------------------------------------------------+ ++ | *data_files* | A list of data files to | a list | ++ | | install | | ++ +--------------------+--------------------------------+-------------------------------------------------------------+ ++ | *package_dir* | A mapping of package to | a dictionary | ++ | | directory names | | ++ +--------------------+--------------------------------+-------------------------------------------------------------+ + + ++ + .. function:: run_setup(script_name[, script_args=None, stop_after='run']) + + Run a setup script in a somewhat controlled environment, and return the +@@ -181,9 +188,10 @@ + | | for C/C++ header files (in | | + | | Unix form for portability) | | + +------------------------+--------------------------------+---------------------------+ +- | *define_macros* | list of macros to define; each | (string,string) tuple or | +- | | macro is defined using a | (name,``None``) | +- | | 2-tuple, where 'value' is | | ++ | *define_macros* | list of macros to define; each | (string, string) tuple or | ++ | | macro is defined using a | (name, ``None``) | ++ | | 2-tuple ``(name, value)``, | | ++ | | where *value* is | | + | | either the string to define it | | + | | to or ``None`` to define it | | + | | without a particular value | | +@@ -747,7 +755,7 @@ + standard output, otherwise do nothing. + + .. % \subsection{Compiler-specific modules} +-.. % ++.. % + .. % The following modules implement concrete subclasses of the abstract + .. % \class{CCompiler} class. They should not be instantiated directly, but should + .. % be created using \function{distutils.ccompiler.new_compiler()} factory +@@ -851,7 +859,7 @@ + Macintosh. Needs work to support CW on Windows or Mac OS X. + + .. % \subsection{Utility modules} +-.. % ++.. % + .. % The following modules all provide general utility functions. They haven't + .. % all been documented yet. + +@@ -1100,6 +1108,24 @@ + + For non-POSIX platforms, currently just returns ``sys.platform``. + ++ For MacOS X systems the OS version reflects the minimal version on which ++ binaries will run (that is, the value of ``MACOSX_DEPLOYMENT_TARGET`` ++ during the build of Python), not the OS version of the current system. ++ ++ For universal binary builds on MacOS X the architecture value reflects ++ 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``. ++ ++ Examples of returned values on MacOS X: ++ ++ * ``macosx-10.3-ppc`` ++ ++ * ``macosx-10.3-fat`` ++ ++ * ``macosx-10.5-universal`` ++ + .. % XXX isn't this also provided by some other non-distutils module? + + +@@ -1667,7 +1693,7 @@ + + .. % todo + .. % \section{Distutils Commands} +-.. % ++.. % + .. % This part of Distutils implements the various Distutils commands, such + .. % as \code{build}, \code{install} \&c. Each command is implemented as a + .. % separate module, with the command name as the name of the module. +Index: Doc/using/windows.rst +=================================================================== +--- Doc/using/windows.rst (.../tags/r261) (Revision 70449) ++++ Doc/using/windows.rst (.../branches/release26-maint) (Revision 70449) +@@ -88,9 +88,9 @@ + --------------------------------------- + + Windows has a built-in dialog for changing environment variables (following +-guide applies to XP classical view): Right-click the icon for your machine +-(usually located on your Desktop and called "My Computer") and choose +-:menuselection:`Properties` there. Then, open the :guilabel:`Advanced` tab ++guide applies to XP classical view): Right-click the icon for your machine ++(usually located on your Desktop and called "My Computer") and choose ++:menuselection:`Properties` there. Then, open the :guilabel:`Advanced` tab + and click the :guilabel:`Environment Variables` button. + + In short, your path is: +@@ -193,11 +193,11 @@ + + #. Launch a command prompt. + #. Associate the correct file group with ``.py`` scripts:: +- ++ + assoc .py=Python.File + + #. Redirect all Python files to the new executable:: +- ++ + ftype Python.File=C:\Path\to\pythonw.exe "%1" %* + + +Index: Doc/using/cmdline.rst +=================================================================== +--- Doc/using/cmdline.rst (.../tags/r261) (Revision 70449) ++++ Doc/using/cmdline.rst (.../branches/release26-maint) (Revision 70449) +@@ -8,8 +8,8 @@ + The CPython interpreter scans the command line and the environment for various + settings. + +-.. note:: +- ++.. note:: ++ + Other implementations' command line schemes may differ. See + :ref:`implementations` for further resources. + +@@ -61,7 +61,7 @@ + Execute the Python code in *command*. *command* can be one ore more + statements separated by newlines, with significant leading whitespace as in + normal module code. +- ++ + If this option is given, the first element of :data:`sys.argv` will be + ``"-c"`` and the current directory will be added to the start of + :data:`sys.path` (allowing modules in that directory to be imported as top +@@ -72,7 +72,7 @@ + + Search :data:`sys.path` for the named module and execute its contents as + the :mod:`__main__` module. +- ++ + Since the argument is a *module* name, you must not give a file extension + (``.py``). The ``module-name`` should be a valid Python module name, but + the implementation may not always enforce this (e.g. it may allow you to +@@ -84,18 +84,18 @@ + written in C, since they do not have Python module files. However, it + can still be used for precompiled modules, even if the original source + file is not available. +- ++ + If this option is given, the first element of :data:`sys.argv` will be the + full path to the module file. As with the :option:`-c` option, the current + directory will be added to the start of :data:`sys.path`. +- ++ + Many standard library modules contain code that is invoked on their execution + as a script. An example is the :mod:`timeit` module:: + + python -mtimeit -s 'setup here' 'benchmarked code here' + python -mtimeit -h # for details + +- .. seealso:: ++ .. seealso:: + :func:`runpy.run_module` + The actual implementation of this feature. + +@@ -163,7 +163,7 @@ + --version + + Print the Python version number and exit. Example output could be:: +- ++ + Python 2.5.1 + + .. versionchanged:: 2.5 +@@ -201,7 +201,7 @@ + enter interactive mode after executing the script or the command, even when + :data:`sys.stdin` does not appear to be a terminal. The + :envvar:`PYTHONSTARTUP` file is not read. +- ++ + This can be useful to inspect global variables or a stack trace when a script + raises an exception. See also :envvar:`PYTHONINSPECT`. + +@@ -221,7 +221,7 @@ + .. cmdoption:: -Q + + Division control. The argument must be one of the following: +- ++ + ``old`` + division of int/int and long/long return an int or long (*default*) + ``new`` +@@ -264,10 +264,10 @@ + + + .. cmdoption:: -u +- ++ + Force stdin, stdout and stderr to be totally unbuffered. On systems where it + matters, also put stdin, stdout and stderr in binary mode. +- ++ + Note that there is internal buffering in :meth:`file.readlines` and + :ref:`bltin-file-objects` (``for line in sys.stdin``) which is not influenced + by this option. To work around this, you will want to use +@@ -279,7 +279,7 @@ + .. XXX should the -U option be documented? + + .. cmdoption:: -v +- ++ + Print a message each time a module is initialized, showing the place + (filename or built-in module) from which it is loaded. When given twice + (:option:`-vv`), print a message for each file that is checked for when +@@ -288,13 +288,13 @@ + + + .. cmdoption:: -W arg +- ++ + Warning control. Python's warning machinery by default prints warning + messages to :data:`sys.stderr`. A typical warning message has the following + form:: + + file:line: category: message +- ++ + By default, each warning is printed once for each source line where it + occurs. This option controls how often warnings are printed. + +@@ -302,13 +302,13 @@ + one option, the action for the last matching option is performed. Invalid + :option:`-W` options are ignored (though, a warning message is printed about + invalid options when the first warning is issued). +- ++ + Warnings can also be controlled from within a Python program using the + :mod:`warnings` module. + + The simplest form of argument is one of the following action strings (or a + unique abbreviation): +- ++ + ``ignore`` + Ignore all warnings. + ``default`` +@@ -324,9 +324,9 @@ + Print each warning only the first time it occurs in the program. + ``error`` + Raise an exception instead of printing a warning message. +- +- The full form of argument is:: +- ++ ++ The full form of argument is:: ++ + action:message:category:module:line + + Here, *action* is as explained above but only applies to messages that match +@@ -347,16 +347,17 @@ + + + .. cmdoption:: -x +- ++ + Skip the first line of the source, allowing use of non-Unix forms of + ``#!cmd``. This is intended for a DOS specific hack only. +- ++ + .. warning:: The line numbers in error messages will be off by one! + + + .. cmdoption:: -3 + +- Warn about Python 3.x incompatibilities. Among these are: ++ Warn about Python 3.x incompatibilities which cannot be fixed trivially by ++ :ref:`2to3 <2to3-reference>`. Among these are: + + * :meth:`dict.has_key` + * :func:`apply` +@@ -380,13 +381,13 @@ + These environment variables influence Python's behavior. + + .. envvar:: PYTHONHOME +- ++ + Change the location of the standard Python libraries. By default, the + libraries are searched in :file:`{prefix}/lib/python{version}` and + :file:`{exec_prefix}/lib/python{version}`, where :file:`{prefix}` and + :file:`{exec_prefix}` are installation-dependent directories, both defaulting + to :file:`/usr/local`. +- ++ + When :envvar:`PYTHONHOME` is set to a single directory, its value replaces + both :file:`{prefix}` and :file:`{exec_prefix}`. To specify different values + for these, set :envvar:`PYTHONHOME` to :file:`{prefix}:{exec_prefix}`. +@@ -402,11 +403,11 @@ + In addition to normal directories, individual :envvar:`PYTHONPATH` entries + may refer to zipfiles containing pure Python modules (in either source or + compiled form). Extension modules cannot be imported from zipfiles. +- ++ + The default search path is installation dependent, but generally begins with +- :file:`{prefix}/lib/python{version}`` (see :envvar:`PYTHONHOME` above). It ++ :file:`{prefix}/lib/python{version}` (see :envvar:`PYTHONHOME` above). It + is *always* appended to :envvar:`PYTHONPATH`. +- ++ + An additional directory will be inserted in the search path in front of + :envvar:`PYTHONPATH` as described above under + :ref:`using-on-interface-options`. The search path can be manipulated from +@@ -414,7 +415,7 @@ + + + .. envvar:: PYTHONSTARTUP +- ++ + If this is the name of a readable file, the Python commands in that file are + executed before the first prompt is displayed in interactive mode. The file + is executed in the same namespace where interactive commands are executed so +@@ -424,7 +425,7 @@ + + + .. envvar:: PYTHONY2K +- ++ + Set this to a non-empty string to cause the :mod:`time` module to require + dates specified as strings to include 4-digit years, otherwise 2-digit years + are converted based on rules described in the :mod:`time` module +@@ -432,21 +433,21 @@ + + + .. envvar:: PYTHONOPTIMIZE +- ++ + If this is set to a non-empty string it is equivalent to specifying the + :option:`-O` option. If set to an integer, it is equivalent to specifying + :option:`-O` multiple times. + + + .. envvar:: PYTHONDEBUG +- ++ + If this is set to a non-empty string it is equivalent to specifying the + :option:`-d` option. If set to an integer, it is equivalent to specifying + :option:`-d` multiple times. + + + .. envvar:: PYTHONINSPECT +- ++ + If this is set to a non-empty string it is equivalent to specifying the + :option:`-i` option. + +@@ -455,20 +456,20 @@ + + + .. envvar:: PYTHONUNBUFFERED +- ++ + If this is set to a non-empty string it is equivalent to specifying the + :option:`-u` option. + + + .. envvar:: PYTHONVERBOSE +- ++ + If this is set to a non-empty string it is equivalent to specifying the + :option:`-v` option. If set to an integer, it is equivalent to specifying + :option:`-v` multiple times. + + + .. envvar:: PYTHONCASEOK +- ++ + If this is set, Python ignores case in :keyword:`import` statements. This + only works on Windows. + +Index: Doc/using/unix.rst +=================================================================== +--- Doc/using/unix.rst (.../tags/r261) (Revision 70449) ++++ Doc/using/unix.rst (.../branches/release26-maint) (Revision 70449) +@@ -19,7 +19,7 @@ + package on all others. However there are certain features you might want to use + that are not available on your distro's package. You can easily compile the + latest version of Python from source. +- ++ + In the event that Python doesn't come preinstalled and isn't in the repositories as + well, you can easily make packages for your own distro. Have a look at the + following links: +@@ -45,8 +45,8 @@ + + * OpenBSD users use:: + +- pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages//python-.tgz +- ++ pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages//python-.tgz ++ + For example i386 users get the 2.5.1 version of Python using:: + + pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz +@@ -87,7 +87,7 @@ + + Python-related paths and files + ============================== +- ++ + These are subject to difference depending on local installation conventions; + :envvar:`prefix` (``${prefix}``) and :envvar:`exec_prefix` (``${exec_prefix}``) + are installation-dependent and should be interpreted as for GNU software; they +@@ -112,8 +112,8 @@ + | | by the user module; not used by default | + | | or by most applications. | + +-----------------------------------------------+------------------------------------------+ +- + ++ + Miscellaneous + ============= + +@@ -140,8 +140,8 @@ + Vim and Emacs are excellent editors which support Python very well. For more + information on how to code in python in these editors, look at: + +-http://www.vim.org/scripts/script.php?script_id=790 +-http://sourceforge.net/projects/python-mode ++* http://www.vim.org/scripts/script.php?script_id=790 ++* http://sourceforge.net/projects/python-mode + + Geany is an excellent IDE with support for a lot of languages. For more + information, read: http://geany.uvena.de/ +Index: Doc/extending/windows.rst +=================================================================== +--- Doc/extending/windows.rst (.../tags/r261) (Revision 70449) ++++ Doc/extending/windows.rst (.../branches/release26-maint) (Revision 70449) +@@ -102,7 +102,7 @@ + and it should call :cfunc:`Py_InitModule` with the string ``"spam"`` as its + first argument (use the minimal :file:`example.c` in this directory as a guide). + By convention, it lives in a file called :file:`spam.c` or :file:`spammodule.c`. +- The output file should be called :file:`spam.pyd` (in Release mode) or ++ The output file should be called :file:`spam.pyd` (in Release mode) or + :file:`spam_d.pyd` (in Debug mode). The extension :file:`.pyd` was chosen + to avoid confusion with a system library :file:`spam.dll` to which your module + could be a Python interface. +Index: Doc/extending/building.rst +=================================================================== +--- Doc/extending/building.rst (.../tags/r261) (Revision 70449) ++++ Doc/extending/building.rst (.../branches/release26-maint) (Revision 70449) +@@ -39,7 +39,7 @@ + + With this :file:`setup.py`, and a file :file:`demo.c`, running :: + +- python setup.py build ++ python setup.py build + + will compile :file:`demo.c`, and produce an extension module named ``demo`` in + the :file:`build` directory. Depending on the system, the module file will end +Index: Doc/extending/newtypes.rst +=================================================================== +--- Doc/extending/newtypes.rst (.../tags/r261) (Revision 70449) ++++ Doc/extending/newtypes.rst (.../branches/release26-maint) (Revision 70449) +@@ -840,8 +840,8 @@ + previous sections. We will break down the main differences between them. :: + + typedef struct { +- PyListObject list; +- int state; ++ PyListObject list; ++ int state; + } Shoddy; + + The primary difference for derived type objects is that the base type's object +@@ -854,10 +854,10 @@ + static int + Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds) + { +- if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0) +- return -1; +- self->state = 0; +- return 0; ++ if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0) ++ return -1; ++ self->state = 0; ++ return 0; + } + + In the :attr:`__init__` method for our type, we can see how to call through to +@@ -876,18 +876,18 @@ + PyMODINIT_FUNC + initshoddy(void) + { +- PyObject *m; ++ PyObject *m; + +- ShoddyType.tp_base = &PyList_Type; +- if (PyType_Ready(&ShoddyType) < 0) +- return; ++ ShoddyType.tp_base = &PyList_Type; ++ if (PyType_Ready(&ShoddyType) < 0) ++ return; + +- m = Py_InitModule3("shoddy", NULL, "Shoddy module"); +- if (m == NULL) +- return; ++ m = Py_InitModule3("shoddy", NULL, "Shoddy module"); ++ if (m == NULL) ++ return; + +- Py_INCREF(&ShoddyType); +- PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType); ++ Py_INCREF(&ShoddyType); ++ PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType); + } + + Before calling :cfunc:`PyType_Ready`, the type structure must have the +@@ -1167,7 +1167,7 @@ + typedef struct PyMethodDef { + char *ml_name; /* method name */ + PyCFunction ml_meth; /* implementation function */ +- int ml_flags; /* flags */ ++ int ml_flags; /* flags */ + char *ml_doc; /* docstring */ + } PyMethodDef; + +@@ -1234,7 +1234,7 @@ + of *NULL* is required. + + .. XXX Descriptors need to be explained in more detail somewhere, but not here. +- ++ + Descriptor objects have two handler functions which correspond to the + \member{tp_getattro} and \member{tp_setattro} handlers. The + \method{__get__()} handler is a function which is passed the descriptor, +Index: Doc/extending/extending.rst +=================================================================== +--- Doc/extending/extending.rst (.../tags/r261) (Revision 70449) ++++ Doc/extending/extending.rst (.../branches/release26-maint) (Revision 70449) +@@ -471,7 +471,7 @@ + :cfunc:`PyEval_CallObject`. This function has two arguments, both pointers to + arbitrary Python objects: the Python function, and the argument list. The + argument list must always be a tuple object, whose length is the number of +-arguments. To call the Python function with no arguments, pass in NULL, or ++arguments. To call the Python function with no arguments, pass in NULL, or + an empty tuple; to call it with one argument, pass a singleton tuple. + :cfunc:`Py_BuildValue` returns a tuple when its format string consists of zero + or more format codes between parentheses. For example:: +@@ -510,7 +510,7 @@ + if (result == NULL) + return NULL; /* Pass error back */ + ...use result... +- Py_DECREF(result); ++ Py_DECREF(result); + + Depending on the desired interface to the Python callback function, you may also + have to provide an argument list to :cfunc:`PyEval_CallObject`. In some cases +@@ -535,7 +535,7 @@ + the error check! Also note that strictly speaking this code is not complete: + :cfunc:`Py_BuildValue` may run out of memory, and this should be checked. + +-You may also call a function with keyword arguments by using ++You may also call a function with keyword arguments by using + :cfunc:`PyEval_CallObjectWithKeywords`. As in the above example, we use + :cfunc:`Py_BuildValue` to construct the dictionary. :: + +@@ -671,7 +671,7 @@ + + static PyObject * + keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds) +- { ++ { + int voltage; + char *state = "a stiff"; + char *action = "voom"; +@@ -679,11 +679,11 @@ + + static char *kwlist[] = {"voltage", "state", "action", "type", NULL}; + +- if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, ++ if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, + &voltage, &state, &action, &type)) +- return NULL; ++ return NULL; + +- printf("-- This parrot wouldn't %s if you put %i Volts through it.\n", ++ printf("-- This parrot wouldn't %s if you put %i Volts through it.\n", + action, voltage); + printf("-- Lovely plumage, the %s -- It's %s!\n", type, state); + +@@ -865,7 +865,7 @@ + The advantage of borrowing over owning a reference is that you don't need to + take care of disposing of the reference on all possible paths through the code + --- in other words, with a borrowed reference you don't run the risk of leaking +-when a premature exit is taken. The disadvantage of borrowing over leaking is ++when a premature exit is taken. The disadvantage of borrowing over owning is + that there are some subtle situations where in seemingly correct code a borrowed + reference can be used after the owner from which it was borrowed has in fact + disposed of it. +Index: Doc/license.rst +=================================================================== +--- Doc/license.rst (.../tags/r261) (Revision 70449) ++++ Doc/license.rst (.../branches/release26-maint) (Revision 70449) +@@ -88,8 +88,14 @@ + +----------------+--------------+-----------+------------+-----------------+ + | 2.5.1 | 2.5 | 2007 | PSF | yes | + +----------------+--------------+-----------+------------+-----------------+ ++| 2.5.2 | 2.5.1 | 2008 | PSF | yes | +++----------------+--------------+-----------+------------+-----------------+ ++| 2.5.3 | 2.5.2 | 2008 | PSF | yes | +++----------------+--------------+-----------+------------+-----------------+ + | 2.6 | 2.5 | 2008 | PSF | yes | + +----------------+--------------+-----------+------------+-----------------+ ++| 2.6.1 | 2.6 | 2008 | PSF | yes | +++----------------+--------------+-----------+------------+-----------------+ + + .. note:: + +@@ -118,7 +124,7 @@ + analyze, test, perform and/or display publicly, prepare derivative works, + distribute, and otherwise use Python |release| alone or in any derivative + version, provided, however, that PSF's License Agreement and PSF's notice of +- copyright, i.e., "Copyright © 2001-2008 Python Software Foundation; All Rights ++ copyright, i.e., "Copyright © 2001-2009 Python Software Foundation; All Rights + Reserved" are retained in Python |release| alone or in any derivative version + prepared by Licensee. + +@@ -380,8 +386,8 @@ + + The source for the :mod:`fpectl` module includes the following notice:: + +- --------------------------------------------------------------------- +- / Copyright (c) 1996. \ ++ --------------------------------------------------------------------- ++ / Copyright (c) 1996. \ + | The Regents of the University of California. | + | All rights reserved. | + | | +@@ -413,7 +419,7 @@ + | 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. / ++ \ endorsement purposes. / + --------------------------------------------------------------------- + + +@@ -447,7 +453,7 @@ + + This code implements the MD5 Algorithm defined in RFC 1321, whose + text is available at +- http://www.ietf.org/rfc/rfc1321.txt ++ http://www.ietf.org/rfc/rfc1321.txt + The code is derived from the text of the RFC, including the test suite + (section A.5) but excluding the rest of Appendix A. It does not include + any code or documentation that is identified in the RFC as being +@@ -458,12 +464,12 @@ + that follows (in reverse chronological order): + + 2002-04-13 lpd Removed support for non-ANSI compilers; removed +- references to Ghostscript; clarified derivation from RFC 1321; +- now handles byte order either statically or dynamically. ++ references to Ghostscript; clarified derivation from RFC 1321; ++ now handles byte order either statically or dynamically. + 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. + 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); +- added conditionalization for C++ compilation from Martin +- Purschke . ++ added conditionalization for C++ compilation from Martin ++ Purschke . + 1999-05-03 lpd Original version. + + +Index: Doc/c-api/sequence.rst +=================================================================== +--- Doc/c-api/sequence.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/sequence.rst (.../branches/release26-maint) (Revision 70449) +@@ -143,9 +143,9 @@ + + Return the underlying array of PyObject pointers. Assumes that *o* was returned + by :cfunc:`PySequence_Fast` and *o* is not *NULL*. +- ++ + Note, if a list gets resized, the reallocation may relocate the items array. +- So, only use the underlying array pointer in contexts where the sequence ++ So, only use the underlying array pointer in contexts where the sequence + cannot change. + + .. versionadded:: 2.4 + +Eigenschaftsänderungen: Doc/c-api/sequence.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/gen.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/buffer.rst +=================================================================== +--- Doc/c-api/buffer.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/buffer.rst (.../branches/release26-maint) (Revision 70449) +@@ -30,7 +30,7 @@ + + .. index:: single: PyBufferProcs + +-More information on the buffer interface is provided in the section ++More information on the buffer interface is provided in the section + :ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`. + + A "buffer object" is defined in the :file:`bufferobject.h` header (included by + +Eigenschaftsänderungen: Doc/c-api/buffer.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/cobject.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/list.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/file.rst +=================================================================== +--- Doc/c-api/file.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/file.rst (.../branches/release26-maint) (Revision 70449) +@@ -63,8 +63,8 @@ + Return the file object associated with *p* as a :ctype:`FILE\*`. + + If the caller will ever use the returned :ctype:`FILE\*` object while +- the GIL is released it must also call the `PyFile_IncUseCount` and +- `PyFile_DecUseCount` functions described below as appropriate. ++ the GIL is released it must also call the :cfunc:`PyFile_IncUseCount` and ++ :cfunc:`PyFile_DecUseCount` functions described below as appropriate. + + + .. cfunction:: void PyFile_IncUseCount(PyFileObject \*p) +@@ -72,13 +72,13 @@ + Increments the PyFileObject's internal use count to indicate + that the underlying :ctype:`FILE\*` is being used. + This prevents Python from calling f_close() on it from another thread. +- Callers of this must call `PyFile_DecUseCount` when they are ++ Callers of this must call :cfunc:`PyFile_DecUseCount` when they are + finished with the :ctype:`FILE\*`. Otherwise the file object will + never be closed by Python. + + The GIL must be held while calling this function. + +- The suggested use is to call this after `PyFile_AsFile` just before ++ The suggested use is to call this after :cfunc:`PyFile_AsFile` just before + you release the GIL. + + .. versionadded:: 2.6 +@@ -88,7 +88,7 @@ + + Decrements the PyFileObject's internal unlocked_count member to + indicate that the caller is done with its own use of the :ctype:`FILE\*`. +- This may only be called to undo a prior call to `PyFile_IncUseCount`. ++ This may only be called to undo a prior call to :cfunc:`PyFile_IncUseCount`. + + The GIL must be held while calling this function. + + +Eigenschaftsänderungen: Doc/c-api/file.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/exceptions.rst +=================================================================== +--- Doc/c-api/exceptions.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/exceptions.rst (.../branches/release26-maint) (Revision 70449) +@@ -41,13 +41,22 @@ + Either alphabetical or some kind of structure. + + +-.. cfunction:: void PyErr_Print() ++.. cfunction:: void PyErr_PrintEx(int set_sys_last_vars) + + Print a standard traceback to ``sys.stderr`` and clear the error indicator. + Call this function only when the error indicator is set. (Otherwise it will + cause a fatal error!) + ++ If *set_sys_last_vars* is nonzero, the variables :data:`sys.last_type`, ++ :data:`sys.last_value` and :data:`sys.last_traceback` will be set to the ++ type, value and traceback of the printed exception, respectively. + ++ ++.. cfunction:: void PyErr_Print() ++ ++ Alias for ``PyErr_PrintEx(1)``. ++ ++ + .. cfunction:: PyObject* PyErr_Occurred() + + Test whether the error indicator is set. If set, return the exception *type* +@@ -73,11 +82,10 @@ + + .. cfunction:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc) + +- Return true if the *given* exception matches the exception in *exc*. If *exc* +- is a class object, this also returns true when *given* is an instance of a +- subclass. If *exc* is a tuple, all exceptions in the tuple (and recursively in +- subtuples) are searched for a match. If *given* is *NULL*, a memory access +- violation will occur. ++ Return true if the *given* exception matches the exception in *exc*. If ++ *exc* is a class object, this also returns true when *given* is an instance ++ of a subclass. If *exc* is a tuple, all exceptions in the tuple (and ++ recursively in subtuples) are searched for a match. + + + .. cfunction:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb) +Index: Doc/c-api/structures.rst +=================================================================== +--- Doc/c-api/structures.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/structures.rst (.../branches/release26-maint) (Revision 70449) +@@ -205,6 +205,68 @@ + .. versionadded:: 2.4 + + ++.. ctype:: PyMemberDef ++ ++ Structure which describes an attribute of a type which corresponds to a C ++ struct member. Its fields are: ++ ++ +------------------+-------------+-------------------------------+ ++ | Field | C Type | Meaning | ++ +==================+=============+===============================+ ++ | :attr:`name` | char \* | name of the member | ++ +------------------+-------------+-------------------------------+ ++ | :attr:`type` | int | the type of the member in the | ++ | | | C struct | ++ +------------------+-------------+-------------------------------+ ++ | :attr:`offset` | Py_ssize_t | the offset in bytes that the | ++ | | | member is located on the | ++ | | | type's object struct | ++ +------------------+-------------+-------------------------------+ ++ | :attr:`flags` | int | flag bits indicating if the | ++ | | | field should be read-only or | ++ | | | writable | ++ +------------------+-------------+-------------------------------+ ++ | :attr:`doc` | char \* | points to the contents of the | ++ | | | docstring | ++ +------------------+-------------+-------------------------------+ ++ ++ :attr:`type` can be one of many ``T_`` macros corresponding to various C ++ types. When the member is accessed in Python, it will be converted to the ++ equivalent Python type. ++ ++ =============== ================== ++ Macro name C type ++ =============== ================== ++ T_SHORT short ++ T_INT int ++ T_LONG long ++ T_FLOAT float ++ T_DOUBLE double ++ T_STRING char \* ++ T_OBJECT PyObject \* ++ T_OBJECT_EX PyObject \* ++ T_CHAR char ++ T_BYTE char ++ T_UNBYTE unsigned char ++ T_UINT unsigned int ++ T_USHORT unsigned short ++ T_ULONG unsigned long ++ T_BOOL char ++ T_LONGLONG long long ++ T_ULONGLONG unsigned long long ++ T_PYSSIZET Py_ssize_t ++ =============== ================== ++ ++ :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX` differ in that ++ :cmacro:`T_OBJECT` returns ``None`` if the member is *NULL* and ++ :cmacro:`T_OBJECT_EX` raises an :exc:`AttributeError`. ++ ++ :attr:`flags` can be 0 for write and read access or :cmacro:`READONLY` for ++ read-only access. Using :cmacro:`T_STRING` for :attr:`type` implies ++ :cmacro:`READONLY`. Only :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX` ++ members can be deleted. (They are set to *NULL*). ++ ++ + .. cfunction:: PyObject* Py_FindMethod(PyMethodDef table[], PyObject *ob, char *name) + + Return a bound method object for an extension type implemented in C. This can + +Eigenschaftsänderungen: Doc/c-api/structures.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/module.rst +=================================================================== +--- Doc/c-api/module.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/module.rst (.../branches/release26-maint) (Revision 70449) +@@ -106,7 +106,7 @@ + + .. cfunction:: int PyModule_AddIntMacro(PyObject *module, macro) + +- Add an int constant to *module*. The name and the value are taken from ++ Add an int constant to *module*. The name and the value are taken from + *macro*. For example ``PyModule_AddConstant(module, AF_INET)`` adds the int + constant *AF_INET* with the value of *AF_INET* to *module*. + Return ``-1`` on error, ``0`` on success. + +Eigenschaftsänderungen: Doc/c-api/module.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/gcsupport.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/iterator.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/reflection.rst +=================================================================== +--- Doc/c-api/reflection.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/reflection.rst (.../branches/release26-maint) (Revision 70449) +@@ -15,8 +15,8 @@ + + Return a dictionary of the local variables in the current execution frame, + or *NULL* if no frame is currently executing. +- + ++ + .. cfunction:: PyObject* PyEval_GetGlobals() + + Return a dictionary of the global variables in the current execution frame, + +Eigenschaftsänderungen: Doc/c-api/reflection.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/intro.rst +=================================================================== +--- Doc/c-api/intro.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/intro.rst (.../branches/release26-maint) (Revision 70449) +@@ -187,7 +187,7 @@ + the caller is said to *borrow* the reference. Nothing needs to be done for a + borrowed reference. + +-Conversely, when a calling function passes it a reference to an object, there ++Conversely, when a calling function passes in a reference to an object, there + are two possibilities: the function *steals* a reference to the object, or it + does not. *Stealing a reference* means that when you pass a reference to a + function, that function assumes that it now owns that reference, and you are not +Index: Doc/c-api/set.rst +=================================================================== +--- Doc/c-api/set.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/set.rst (.../branches/release26-maint) (Revision 70449) +@@ -101,7 +101,7 @@ + + .. versionchanged:: 2.6 + Now guaranteed to return a brand-new :class:`frozenset`. Formerly, +- frozensets of zero-length were a singleton. This got in the way of ++ frozensets of zero-length were a singleton. This got in the way of + building-up new frozensets with :meth:`PySet_Add`. + + The following functions and macros are available for instances of :class:`set` + +Eigenschaftsänderungen: Doc/c-api/set.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/datetime.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/slice.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/none.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/long.rst +=================================================================== +--- Doc/c-api/long.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/long.rst (.../branches/release26-maint) (Revision 70449) +@@ -126,7 +126,7 @@ + + Return a C :ctype:`long` representation of the contents of *pylong*. If + *pylong* is greater than :const:`LONG_MAX`, an :exc:`OverflowError` is raised +- and ``-1`` will be returned. ++ and ``-1`` will be returned. + + + .. cfunction:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong) + +Eigenschaftsänderungen: Doc/c-api/long.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/bytearray.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/init.rst +=================================================================== +--- Doc/c-api/init.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/init.rst (.../branches/release26-maint) (Revision 70449) +@@ -353,18 +353,36 @@ + single: Py_FatalError() + single: argv (in module sys) + +- Set ``sys.argv`` based on *argc* and *argv*. These parameters are similar to +- those passed to the program's :cfunc:`main` function with the difference that +- the first entry should refer to the script file to be executed rather than the +- executable hosting the Python interpreter. If there isn't a script that will be +- run, the first entry in *argv* can be an empty string. If this function fails +- to initialize ``sys.argv``, a fatal condition is signalled using +- :cfunc:`Py_FatalError`. ++ Set :data:`sys.argv` based on *argc* and *argv*. These parameters are ++ similar to those passed to the program's :cfunc:`main` function with the ++ difference that the first entry should refer to the script file to be ++ executed rather than the executable hosting the Python interpreter. If there ++ isn't a script that will be run, the first entry in *argv* can be an empty ++ string. If this function fails to initialize :data:`sys.argv`, a fatal ++ condition is signalled using :cfunc:`Py_FatalError`. + ++ This function also prepends the executed script's path to :data:`sys.path`. ++ If no script is executed (in the case of calling ``python -c`` or just the ++ interactive interpreter), the empty string is used instead. ++ + .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params; + check w/ Guido. + + ++.. cfunction:: void Py_SetPythonHome(char *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}`. ++ ++ ++.. cfunction:: 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` ++ environment variable if it is set. ++ ++ + .. _threads: + + Thread State and the Global Interpreter Lock +@@ -902,7 +920,7 @@ + + Return a tuple of function call counts. There are constants defined for the + positions within the tuple: +- ++ + +-------------------------------+-------+ + | Name | Value | + +===============================+=======+ +@@ -928,7 +946,7 @@ + +-------------------------------+-------+ + | :const:`PCALL_POP` | 10 | + +-------------------------------+-------+ +- ++ + :const:`PCALL_FAST_FUNCTION` means no argument tuple needs to be created. + :const:`PCALL_FASTER_FUNCTION` means that the fast-path frame setup code is used. + + +Eigenschaftsänderungen: Doc/c-api/iter.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/class.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/float.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/string.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/object.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/complex.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/arg.rst +=================================================================== +--- Doc/c-api/arg.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/arg.rst (.../branches/release26-maint) (Revision 70449) +@@ -46,12 +46,12 @@ + :ctype:`Py_ssize_t` rather than an int. + + ``s*`` (string, Unicode, or any buffer compatible object) [Py_buffer \*] +- Similar to ``s#``, this code fills a Py_buffer structure provided by the caller. +- The buffer gets locked, so that the caller can subsequently use the buffer even +- inside a ``Py_BEGIN_ALLOW_THREADS`` block; the caller is responsible for calling +- ``PyBuffer_Release`` with the structure after it has processed the data. ++ Similar to ``s#``, this code fills a Py_buffer structure provided by the caller. ++ The buffer gets locked, so that the caller can subsequently use the buffer even ++ inside a ``Py_BEGIN_ALLOW_THREADS`` block; the caller is responsible for calling ++ ``PyBuffer_Release`` with the structure after it has processed the data. + +- .. versionadded:: 2.6 ++ .. versionadded:: 2.6 + + ``z`` (string or ``None``) [const char \*] + Like ``s``, but the Python object may also be ``None``, in which case the C +@@ -63,7 +63,7 @@ + ``z*`` (string or ``None`` or any buffer compatible object) [Py_buffer*] + This is to ``s*`` as ``z`` is to ``s``. + +- .. versionadded:: 2.6 ++ .. versionadded:: 2.6 + + ``u`` (Unicode object) [Py_UNICODE \*] + Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of +@@ -136,8 +136,9 @@ + them. Instead, the implementation assumes that the string object uses the + encoding passed in as parameter. + +-``b`` (integer) [char] +- Convert a Python integer to a tiny int, stored in a C :ctype:`char`. ++``b`` (integer) [unsigned char] ++ Convert a nonnegative Python integer to an unsigned tiny int, stored in a C ++ :ctype:`unsigned char`. + + ``B`` (integer) [unsigned char] + Convert a Python integer to a tiny int without overflow checking, stored in a C +@@ -260,6 +261,7 @@ + + ``w*`` (read-write byte-oriented buffer) [Py_buffer \*] + This is to ``w`` what ``s*`` is to ``s``. ++ + .. versionadded:: 2.6 + + ``(items)`` (tuple) [*matching-items*] +@@ -297,8 +299,8 @@ + + ``;`` + The list of format units ends here; the string after the semicolon is used as +- the error message *instead* of the default error message. Clearly, ``:`` and +- ``;`` mutually exclude each other. ++ the error message *instead* of the default error message. ``:`` and ``;`` ++ mutually exclude each other. + + Note that any Python object references which are provided to the caller are + *borrowed* references; do not decrement their reference count! +@@ -533,3 +535,8 @@ + + If there is an error in the format string, the :exc:`SystemError` exception is + set and *NULL* returned. ++ ++.. cfunction:: PyObject* Py_VaBuildValue(const char *format, va_list vargs) ++ ++ Identical to :cfunc:`Py_BuildValue`, except that it accepts a va_list ++ rather than a variable number of arguments. + +Eigenschaftsänderungen: Doc/c-api/arg.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/import.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/typeobj.rst +=================================================================== +--- Doc/c-api/typeobj.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/typeobj.rst (.../branches/release26-maint) (Revision 70449) +@@ -743,7 +743,7 @@ + :attr:`__weakref__`, the type inherits its :attr:`tp_weaklistoffset` from its + base type. + +-The next two fields only exist if the :const:`Py_TPFLAGS_HAVE_CLASS` flag bit is ++The next two fields only exist if the :const:`Py_TPFLAGS_HAVE_ITER` flag bit is + set. + + + +Eigenschaftsänderungen: Doc/c-api/typeobj.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/descriptor.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/sys.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/cell.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/method.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/type.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/dict.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/weakref.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/function.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/allocation.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/conversion.rst +=================================================================== +--- Doc/c-api/conversion.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/conversion.rst (.../branches/release26-maint) (Revision 70449) +@@ -77,7 +77,7 @@ + + .. versionadded:: 2.4 + +- ++ + .. cfunction:: double PyOS_ascii_atof(const char *nptr) + + Convert a string to a :ctype:`double` in a locale-independent way. +@@ -86,7 +86,7 @@ + + See the Unix man page :manpage:`atof(2)` for details. + +- ++ + .. cfunction:: char * PyOS_stricmp(char *s1, char *s2) + + Case insensitive comparison of strings. The function works almost + +Eigenschaftsänderungen: Doc/c-api/conversion.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/c-api/veryhigh.rst +=================================================================== +--- Doc/c-api/veryhigh.rst (.../tags/r261) (Revision 70449) ++++ Doc/c-api/veryhigh.rst (.../branches/release26-maint) (Revision 70449) +@@ -16,7 +16,7 @@ + :const:`Py_file_input`, and :const:`Py_single_input`. These are described + following the functions which accept them as parameters. + +-Note also that several of these functions take :ctype:`FILE\*` parameters. On ++Note also that several of these functions take :ctype:`FILE\*` parameters. One + particular issue which needs to be handled carefully is that the :ctype:`FILE` + structure for different C libraries can be different and incompatible. Under + Windows (at least), it is possible for dynamically linked extensions to actually + +Eigenschaftsänderungen: Doc/c-api/unicode.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/marshal.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/number.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/tuple.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/int.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/mapping.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/bool.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Doc/c-api/objbuffer.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/reference/datamodel.rst +=================================================================== +--- Doc/reference/datamodel.rst (.../tags/r261) (Revision 70449) ++++ Doc/reference/datamodel.rst (.../branches/release26-maint) (Revision 70449) +@@ -1162,9 +1162,10 @@ + Basic customization + ------------------- + +- + .. method:: object.__new__(cls[, ...]) + ++ .. index:: pair: subclassing; immutable types ++ + Called to create a new instance of class *cls*. :meth:`__new__` is a static + method (special-cased so you need not declare it as such) that takes the class + of which an instance was requested as its first argument. The remaining +@@ -1248,7 +1249,9 @@ + is printed to ``sys.stderr`` instead. Also, when :meth:`__del__` is invoked in + response to a module being deleted (e.g., when execution of the program is + done), other globals referenced by the :meth:`__del__` method may already have +- been deleted. For this reason, :meth:`__del__` methods should do the absolute ++ been deleted or in the process of being torn down (e.g. the import ++ machinery shutting down). For this reason, :meth:`__del__` methods ++ should do the absolute + minimum needed to maintain external invariants. Starting with version 1.5, + Python guarantees that globals whose name begins with a single underscore are + deleted from their module before other globals are deleted; if no other +@@ -1365,21 +1368,21 @@ + object: dictionary + builtin: hash + +- Called for the key object for dictionary operations, and by the built-in +- function :func:`hash`. Should return an integer usable as a hash value +- for dictionary operations. The only required property is that objects which +- compare equal have the same hash value; it is advised to somehow mix together +- (e.g., using exclusive or) the hash values for the components of the object that +- also play a part in comparison of objects. ++ Called by built-in function :func:`hash` and for operations on members of ++ hashed collections including :class:`set`, :class:`frozenset`, and ++ :class:`dict`. :meth:`__hash__` should return an integer. The only required ++ property is that objects which compare equal have the same hash value; it is ++ advised to somehow mix together (e.g. using exclusive or) the hash values for ++ the components of the object that also play a part in comparison of objects. + + If a class does not define a :meth:`__cmp__` or :meth:`__eq__` method it + should not define a :meth:`__hash__` operation either; if it defines + :meth:`__cmp__` or :meth:`__eq__` but not :meth:`__hash__`, its instances +- will not be usable as dictionary keys. If a class defines mutable objects ++ will not be usable in hashed collections. If a class defines mutable objects + and implements a :meth:`__cmp__` or :meth:`__eq__` method, it should not +- implement :meth:`__hash__`, since the dictionary implementation requires that +- a key's hash value is immutable (if the object's hash value changes, it will +- be in the wrong hash bucket). ++ implement :meth:`__hash__`, since hashable collection implementations require ++ that a object's hash value is immutable (if the object's hash value changes, ++ it will be in the wrong hash bucket). + + User-defined classes have :meth:`__cmp__` and :meth:`__hash__` methods + by default; with them, all objects compare unequal (except with themselves) +@@ -1389,13 +1392,13 @@ + change the meaning of :meth:`__cmp__` or :meth:`__eq__` such that the hash + value returned is no longer appropriate (e.g. by switching to a value-based + concept of equality instead of the default identity based equality) can +- explicitly flag themselves as being unhashable by setting +- ``__hash__ = None`` in the class definition. Doing so means that not only +- will instances of the class raise an appropriate :exc:`TypeError` when +- a program attempts to retrieve their hash value, but they will also be +- correctly identified as unhashable when checking +- ``isinstance(obj, collections.Hashable)`` (unlike classes which define +- their own :meth:`__hash__` to explicitly raise :exc:`TypeError`). ++ explicitly flag themselves as being unhashable by setting ``__hash__ = None`` ++ in the class definition. Doing so means that not only will instances of the ++ class raise an appropriate :exc:`TypeError` when a program attempts to ++ retrieve their hash value, but they will also be correctly identified as ++ unhashable when checking ``isinstance(obj, collections.Hashable)`` (unlike ++ classes which define their own :meth:`__hash__` to explicitly raise ++ :exc:`TypeError`). + + .. versionchanged:: 2.5 + :meth:`__hash__` may now also return a long integer object; the 32-bit +@@ -2075,13 +2078,13 @@ + object.__ixor__(self, other) + object.__ior__(self, other) + +- These methods are called to implement the augmented arithmetic operations ++ These methods are called to implement the augmented arithmetic assignments + (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, ``>>=``, + ``&=``, ``^=``, ``|=``). These methods should attempt to do the operation + in-place (modifying *self*) and return the result (which could be, but does + not have to be, *self*). If a specific method is not defined, the augmented +- operation falls back to the normal methods. For instance, to evaluate the +- expression ``x += y``, where *x* is an instance of a class that has an ++ assignment falls back to the normal methods. For instance, to execute the ++ statement ``x += y``, where *x* is an instance of a class that has an + :meth:`__iadd__` method, ``x.__iadd__(y)`` is called. If *x* is an instance + of a class that does not define a :meth:`__iadd__` method, ``x.__add__(y)`` + and ``y.__radd__(x)`` are considered, as with the evaluation of ``x + y``. +@@ -2241,7 +2244,8 @@ + + In the current implementation, the built-in numeric types :class:`int`, + :class:`long` and :class:`float` do not use coercion; the type :class:`complex` +- however does use it. The difference can become apparent when subclassing these ++ however does use coercion for binary operators and rich comparisons, despite ++ the above rules. The difference can become apparent when subclassing these + types. Over time, the type :class:`complex` may be fixed to avoid coercion. + All these types implement a :meth:`__coerce__` method, for use by the built-in + :func:`coerce` function. +@@ -2369,7 +2373,7 @@ + True + + In addition to bypassing any instance attributes in the interest of +-correctness, implicit special method lookup may also bypass the ++correctness, implicit special method lookup generally also bypasses the + :meth:`__getattribute__` method even of the object's metaclass:: + + >>> class Meta(type): +Index: Doc/reference/introduction.rst +=================================================================== +--- Doc/reference/introduction.rst (.../tags/r261) (Revision 70449) ++++ Doc/reference/introduction.rst (.../branches/release26-maint) (Revision 70449) +@@ -65,8 +65,7 @@ + An alternate Python for .NET. Unlike Python.NET, this is a complete Python + implementation that generates IL, and compiles Python code directly to .NET + assemblies. It was created by Jim Hugunin, the original creator of Jython. For +- more information, see `the IronPython website +- `_. ++ more information, see `the IronPython website `_. + + PyPy + An implementation of Python written in Python; even the bytecode interpreter is +Index: Doc/reference/expressions.rst +=================================================================== +--- Doc/reference/expressions.rst (.../tags/r261) (Revision 70449) ++++ Doc/reference/expressions.rst (.../branches/release26-maint) (Revision 70449) +@@ -560,7 +560,7 @@ + .. productionlist:: + slicing: `simple_slicing` | `extended_slicing` + simple_slicing: `primary` "[" `short_slice` "]" +- extended_slicing: `primary` "[" `slice_list` "]" ++ extended_slicing: `primary` "[" `slice_list` "]" + slice_list: `slice_item` ("," `slice_item`)* [","] + slice_item: `expression` | `proper_slice` | `ellipsis` + proper_slice: `short_slice` | `long_slice` +@@ -664,7 +664,7 @@ + the call. + + .. note:: +- ++ + An implementation may provide builtin 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 +@@ -816,14 +816,14 @@ + + .. _unary: + +-Unary arithmetic operations +-=========================== ++Unary arithmetic and bitwise operations ++======================================= + + .. index:: + triple: unary; arithmetic; operation + triple: unary; bitwise; operation + +-All unary arithmetic (and bitwise) operations have the same priority: ++All unary arithmetic and bitwise operations have the same priority: + + .. productionlist:: + u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr` +@@ -1276,13 +1276,10 @@ + +-----------------------------------------------+-------------------------------------+ + | :keyword:`not` *x* | Boolean NOT | + +-----------------------------------------------+-------------------------------------+ +-| :keyword:`in`, :keyword:`not` :keyword:`in` | Membership tests | ++| :keyword:`in`, :keyword:`not` :keyword:`in`, | Comparisons, including membership | ++| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests, | ++| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` | | + +-----------------------------------------------+-------------------------------------+ +-| :keyword:`is`, :keyword:`is not` | Identity tests | +-+-----------------------------------------------+-------------------------------------+ +-| ``<``, ``<=``, ``>``, ``>=``, ``<>``, ``!=``, | Comparisons | +-| ``==`` | | +-+-----------------------------------------------+-------------------------------------+ + | ``|`` | Bitwise OR | + +-----------------------------------------------+-------------------------------------+ + | ``^`` | Bitwise XOR | +@@ -1293,35 +1290,25 @@ + +-----------------------------------------------+-------------------------------------+ + | ``+``, ``-`` | Addition and subtraction | + +-----------------------------------------------+-------------------------------------+ +-| ``*``, ``/``, ``%`` | Multiplication, division, remainder | ++| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder | + +-----------------------------------------------+-------------------------------------+ +-| ``+x``, ``-x`` | Positive, negative | ++| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT | + +-----------------------------------------------+-------------------------------------+ +-| ``~x`` | Bitwise not | ++| ``**`` | Exponentiation [#]_ | + +-----------------------------------------------+-------------------------------------+ +-| ``**`` | Exponentiation | ++| ``x[index]``, ``x[index:index]``, | Subscription, slicing, | ++| ``x(arguments...)``, ``x.attribute`` | call, attribute reference | + +-----------------------------------------------+-------------------------------------+ +-| ``x[index]`` | Subscription | ++| ``(expressions...)``, | Binding or tuple display, | ++| ``[expressions...]``, | list display, | ++| ``{key:datum...}``, | dictionary display, | ++| ```expressions...``` | string conversion | + +-----------------------------------------------+-------------------------------------+ +-| ``x[index:index]`` | Slicing | +-+-----------------------------------------------+-------------------------------------+ +-| ``x(arguments...)`` | Call | +-+-----------------------------------------------+-------------------------------------+ +-| ``x.attribute`` | Attribute reference | +-+-----------------------------------------------+-------------------------------------+ +-| ``(expressions...)`` | Binding or tuple display | +-+-----------------------------------------------+-------------------------------------+ +-| ``[expressions...]`` | List display | +-+-----------------------------------------------+-------------------------------------+ +-| ``{key:datum...}`` | Dictionary display | +-+-----------------------------------------------+-------------------------------------+ +-| ```expressions...``` | String conversion | +-+-----------------------------------------------+-------------------------------------+ + + .. rubric:: Footnotes + + .. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control +- variables of each ``for`` it contains into the containing scope. However, this ++ variables of each ``for`` it contains into the containing scope. However, this + behavior is deprecated, and relying on it will not work in Python 3.0 + + .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be +@@ -1354,7 +1341,10 @@ + only, but this caused surprises because people expected to be able to test a + dictionary for emptiness by comparing it to ``{}``. + +-.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of ++.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of + descriptors, you may notice seemingly unusual behaviour in certain uses of + the :keyword:`is` operator, like those involving comparisons between instance + methods, or constants. Check their documentation for more info. ++ ++.. [#] The power operator ``**`` binds less tightly than an arithmetic or ++ bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. +Index: Doc/reference/simple_stmts.rst +=================================================================== +--- Doc/reference/simple_stmts.rst (.../tags/r261) (Revision 70449) ++++ Doc/reference/simple_stmts.rst (.../branches/release26-maint) (Revision 70449) +@@ -118,8 +118,8 @@ + + * If the target list is a single target: The object is assigned to that target. + +-* If the target list is a comma-separated list of targets: The object must be a +- sequence with the same number of items as there are targets in the target list, ++* If the target list is a comma-separated list of targets: The object must be an ++ iterable with the same number of items as there are targets in the target list, + and the items are assigned, from left to right, to the corresponding targets. + (This rule is relaxed as of Python 1.5; in earlier versions, the object had to + be a tuple. Since strings are sequences, an assignment like ``a, b = "xy"`` is +@@ -143,9 +143,9 @@ + be deallocated and its destructor (if it has one) to be called. + + * If the target is a target list enclosed in parentheses or in square brackets: +- The object must be a sequence with the same number of items as there are targets +- in the target list, and its items are assigned, from left to right, to the +- corresponding targets. ++ The object must be an iterable with the same number of items as there are ++ targets in the target list, and its items are assigned, from left to right, ++ to the corresponding targets. + + .. index:: pair: attribute; assignment + +@@ -228,7 +228,8 @@ + operation and an assignment statement: + + .. productionlist:: +- augmented_assignment_stmt: `target` `augop` (`expression_list` | `yield_expression`) ++ augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`) ++ augtarget: `identifier` | `attributeref` | `subscription` | `slicing` + augop: "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**=" + : | ">>=" | "<<=" | "&=" | "^=" | "|=" + +@@ -745,7 +746,7 @@ + searched inside the package. A package is generally a subdirectory of a + directory on ``sys.path`` that has a file :file:`__init__.py`. + +-.. ++.. + [XXX Can't be + bothered to spell this out right now; see the URL + http://www.python.org/doc/essays/packages.html for more details, also about how +Index: Doc/reference/lexical_analysis.rst +=================================================================== +--- Doc/reference/lexical_analysis.rst (.../tags/r261) (Revision 70449) ++++ Doc/reference/lexical_analysis.rst (.../branches/release26-maint) (Revision 70449) +@@ -341,13 +341,13 @@ + language, and cannot be used as ordinary identifiers. They must be spelled + exactly as written here:: + +- and del from not while +- as elif global or with +- assert else if pass yield +- break except import print +- class exec in raise +- continue finally is return +- def for lambda try ++ and del from not while ++ as elif global or with ++ assert else if pass yield ++ break except import print ++ class exec in raise ++ continue finally is return ++ def for lambda try + + .. versionchanged:: 2.4 + :const:`None` became a constant and is now recognized by the compiler as a name +@@ -654,7 +654,7 @@ + + 7 2147483647 0177 + 3L 79228162514264337593543950336L 0377L 0x100000000L +- 79228162514264337593543950336 0xdeadbeef ++ 79228162514264337593543950336 0xdeadbeef + + + .. _floating: +@@ -701,7 +701,7 @@ + part, add a floating point number to it, e.g., ``(3+4j)``. Some examples of + imaginary literals:: + +- 3.14j 10.j 10j .001j 1e100j 3.14e-10j ++ 3.14j 10.j 10j .001j 1e100j 3.14e-10j + + + .. _operators: + +Eigenschaftsänderungen: Doc/reference/grammar.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/ACKS.txt +=================================================================== +--- Doc/ACKS.txt (.../tags/r261) (Revision 70449) ++++ Doc/ACKS.txt (.../branches/release26-maint) (Revision 70449) +@@ -60,6 +60,7 @@ + * Peter Funk + * Lele Gaifax + * Matthew Gallagher ++ * Gabriel Genellina + * Ben Gertzfield + * Nadim Ghaznavi + * Jonathan Giddy +Index: Doc/whatsnew/2.0.rst +=================================================================== +--- Doc/whatsnew/2.0.rst (.../tags/r261) (Revision 70449) ++++ Doc/whatsnew/2.0.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,5 +1,5 @@ + **************************** +- What's New in Python 2.0 ++ What's New in Python 2.0 + **************************** + + :Author: A.M. Kuchling and Moshe Zadka +@@ -277,11 +277,11 @@ + finding all the strings in the list containing a given substring. You could + write the following to do it:: + +- # Given the list L, make a list of all strings ++ # Given the list L, make a list of all strings + # containing the substring S. +- sublist = filter( lambda s, substring=S: ++ sublist = filter( lambda s, substring=S: + string.find(s, substring) != -1, +- L) ++ L) + + Because of Python's scoping rules, a default argument is used so that the + anonymous function created by the :keyword:`lambda` statement knows what +@@ -291,9 +291,9 @@ + + List comprehensions have the form:: + +- [ expression for expr in sequence1 ++ [ expression for expr in sequence1 + for expr2 in sequence2 ... +- for exprN in sequenceN ++ for exprN in sequenceN + if condition ] + + The :keyword:`for`...\ :keyword:`in` clauses contain the sequences to be +@@ -312,8 +312,8 @@ + ... + for exprN in sequenceN: + if (condition): +- # Append the value of +- # the expression to the ++ # Append the value of ++ # the expression to the + # resulting list. + + This means that when there are multiple :keyword:`for`...\ :keyword:`in` +@@ -368,7 +368,7 @@ + def __init__(self, value): + self.value = value + def __iadd__(self, increment): +- return Number( self.value + increment) ++ return Number( self.value + increment) + + n = Number(5) + n += 3 +@@ -590,7 +590,7 @@ + + def f(): + print "i=",i +- i = i + 1 ++ i = i + 1 + f() + + Two new exceptions, :exc:`TabError` and :exc:`IndentationError`, have been +@@ -627,7 +627,7 @@ + the following lines of code:: + + if dict.has_key( key ): return dict[key] +- else: ++ else: + dict[key] = [] + return dict[key] + +@@ -836,14 +836,14 @@ + :file:`setup.py` can be just a few lines long:: + + from distutils.core import setup +- setup (name = "foo", version = "1.0", ++ setup (name = "foo", version = "1.0", + py_modules = ["module1", "module2"]) + + The :file:`setup.py` file isn't much more complicated if the software consists + of a few packages:: + + from distutils.core import setup +- setup (name = "foo", version = "1.0", ++ setup (name = "foo", version = "1.0", + packages = ["package", "package.subpackage"]) + + A C extension can be the most complicated case; here's an example taken from +@@ -852,15 +852,14 @@ + from distutils.core import setup, Extension + + expat_extension = Extension('xml.parsers.pyexpat', +- define_macros = [('XML_NS', None)], +- include_dirs = [ 'extensions/expat/xmltok', +- 'extensions/expat/xmlparse' ], +- sources = [ 'extensions/pyexpat.c', +- 'extensions/expat/xmltok/xmltok.c', +- 'extensions/expat/xmltok/xmlrole.c', +- ] ++ define_macros = [('XML_NS', None)], ++ include_dirs = [ 'extensions/expat/xmltok', ++ 'extensions/expat/xmlparse' ], ++ sources = [ 'extensions/pyexpat.c', ++ 'extensions/expat/xmltok/xmltok.c', ++ 'extensions/expat/xmltok/xmlrole.c', ] + ) +- setup (name = "PyXML", version = "0.5.4", ++ setup (name = "PyXML", version = "0.5.4", + ext_modules =[ expat_extension ] ) + + The Distutils can also take care of creating source and binary distributions. +Index: Doc/whatsnew/2.1.rst +=================================================================== +--- Doc/whatsnew/2.1.rst (.../tags/r261) (Revision 70449) ++++ Doc/whatsnew/2.1.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,5 +1,5 @@ + **************************** +- What's New in Python 2.1 ++ What's New in Python 2.1 + **************************** + + :Author: A.M. Kuchling +@@ -98,7 +98,7 @@ + x = 1 + def f(): + # The next line is a syntax error +- exec 'x=2' ++ exec 'x=2' + def g(): + return x + +Index: Doc/whatsnew/2.2.rst +=================================================================== +--- Doc/whatsnew/2.2.rst (.../tags/r261) (Revision 70449) ++++ Doc/whatsnew/2.2.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,5 +1,5 @@ + **************************** +- What's New in Python 2.2 ++ What's New in Python 2.2 + **************************** + + :Author: A.M. Kuchling +@@ -295,7 +295,7 @@ + + class D (B,C): + def save (self): +- # Call superclass .save() ++ # Call superclass .save() + super(D, self).save() + # Save D's private information here + ... +@@ -473,7 +473,7 @@ + Traceback (most recent call last): + File "", line 1, in ? + StopIteration +- >>> ++ >>> + + In 2.2, Python's :keyword:`for` statement no longer expects a sequence; it + expects something for which :func:`iter` will return an iterator. For backward +@@ -909,7 +909,7 @@ + x = 1 + def f(): + # The next line is a syntax error +- exec 'x=2' ++ exec 'x=2' + def g(): + return x + +@@ -952,8 +952,8 @@ + items = s.meerkat.getItems( {'channel': 4} ) + + # 'items' is another list of dictionaries, like this: +- # [{'link': 'http://freshmeat.net/releases/52719/', +- # 'description': 'A utility which converts HTML to XSL FO.', ++ # [{'link': 'http://freshmeat.net/releases/52719/', ++ # 'description': 'A utility which converts HTML to XSL FO.', + # 'title': 'html2fo 0.3 (Default)'}, ... ] + + The :mod:`SimpleXMLRPCServer` module makes it easy to create straightforward +Index: Doc/whatsnew/2.3.rst +=================================================================== +--- Doc/whatsnew/2.3.rst (.../tags/r261) (Revision 70449) ++++ Doc/whatsnew/2.3.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,5 +1,5 @@ + **************************** +- What's New in Python 2.3 ++ What's New in Python 2.3 + **************************** + + :Author: A.M. Kuchling +@@ -301,7 +301,7 @@ + -------- ------- + 8467 1 file + amk@nyman:~/src/python$ ./python +- Python 2.3 (#1, Aug 1 2003, 19:54:32) ++ Python 2.3 (#1, Aug 1 2003, 19:54:32) + >>> import sys + >>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path + >>> import jwzthreading +@@ -671,7 +671,7 @@ + # ... + } + +- if (hasattr(core, 'setup_keywords') and ++ if (hasattr(core, 'setup_keywords') and + 'classifiers' in core.setup_keywords): + kw['classifiers'] = \ + ['Topic :: Internet :: WWW/HTTP :: Dynamic Content', +@@ -1027,7 +1027,7 @@ + creating small dictionaries:: + + >>> dict(red=1, blue=2, green=3, black=4) +- {'blue': 2, 'black': 4, 'green': 3, 'red': 1} ++ {'blue': 2, 'black': 4, 'green': 3, 'red': 1} + + (Contributed by Just van Rossum.) + +@@ -1622,7 +1622,7 @@ + ... self.valuelist.pop(i) + ... def keys(self): + ... return list(self.keylist) +- ... ++ ... + >>> s = SeqDict() + >>> dir(s) # See that other dictionary methods are implemented + ['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__', +@@ -1779,7 +1779,7 @@ + set input filename + -lLENGTH, --length=LENGTH + set maximum length of output +- $ ++ $ + + See the module's documentation for more details. + +Index: Doc/whatsnew/2.4.rst +=================================================================== +--- Doc/whatsnew/2.4.rst (.../tags/r261) (Revision 70449) ++++ Doc/whatsnew/2.4.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,5 +1,5 @@ + **************************** +- What's New in Python 2.4 ++ What's New in Python 2.4 + **************************** + + :Author: A.M. Kuchling +@@ -63,10 +63,10 @@ + >>> a.add('z') # add a new element + >>> a.update('wxy') # add multiple new elements + >>> a +- set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z']) ++ set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z']) + >>> a.remove('x') # take one element out + >>> a +- set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z']) ++ set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z']) + + The :func:`frozenset` type is an immutable version of :func:`set`. Since it is + immutable and hashable, it may be used as a dictionary key or as a member of +@@ -351,7 +351,7 @@ + + >>> for i in reversed(xrange(1,4)): + ... print i +- ... ++ ... + 3 + 2 + 1 +@@ -366,7 +366,7 @@ + >>> input = open('/etc/passwd', 'r') + >>> for line in reversed(list(input)): + ... print line +- ... ++ ... + root:*:0:0:System Administrator:/var/root:/bin/tcsh + ... + +@@ -396,10 +396,10 @@ + different keyword arguments. :: + + class Popen(args, bufsize=0, executable=None, +- stdin=None, stdout=None, stderr=None, +- preexec_fn=None, close_fds=False, shell=False, +- cwd=None, env=None, universal_newlines=False, +- startupinfo=None, creationflags=0): ++ stdin=None, stdout=None, stderr=None, ++ preexec_fn=None, close_fds=False, shell=False, ++ cwd=None, env=None, universal_newlines=False, ++ startupinfo=None, creationflags=0): + + *args* is commonly a sequence of strings that will be the arguments to the + program executed as the subprocess. (If the *shell* argument is true, *args* +@@ -650,7 +650,7 @@ + 28 + >>> decimal.Decimal(1) / decimal.Decimal(7) + Decimal("0.1428571428571428571428571429") +- >>> decimal.getcontext().prec = 9 ++ >>> decimal.getcontext().prec = 9 + >>> decimal.Decimal(1) / decimal.Decimal(7) + Decimal("0.142857143") + +@@ -665,7 +665,7 @@ + >>> decimal.getcontext().traps[decimal.DivisionByZero] = False + >>> decimal.Decimal(1) / decimal.Decimal(0) + Decimal("Infinity") +- >>> ++ >>> + + The :class:`Context` instance also has various methods for formatting numbers + such as :meth:`to_eng_string` and :meth:`to_sci_string`. +@@ -803,7 +803,7 @@ + >>> 'www.python.org'.split('.', 1) + ['www', 'python.org'] + 'www.python.org'.rsplit('.', 1) +- ['www.python', 'org'] ++ ['www.python', 'org'] + + * Three keyword parameters, *cmp*, *key*, and *reverse*, were added to the + :meth:`sort` method of lists. These parameters make some common usages of +@@ -1045,7 +1045,7 @@ + >>> list(d) # list the contents of the deque + ['g', 'h', 'i'] + >>> 'h' in d # search the deque +- True ++ True + + Several modules, such as the :mod:`Queue` and :mod:`threading` modules, now take + advantage of :class:`collections.deque` for improved performance. (Contributed +@@ -1106,13 +1106,13 @@ + >>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14] + >>> for key_val, it in itertools.groupby(L, lambda x: x % 2): + ... print key_val, list(it) +- ... ++ ... + 0 [2, 4, 6] + 1 [7] + 0 [8] + 1 [9, 11] + 0 [12, 14] +- >>> ++ >>> + + :func:`groupby` is typically used with sorted input. The logic for + :func:`groupby` is similar to the Unix ``uniq`` filter which makes it handy for +@@ -1120,21 +1120,21 @@ + + >>> word = 'abracadabra' + >>> letters = sorted(word) # Turn string into a sorted list of letters +- >>> letters ++ >>> letters + ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r'] + >>> for k, g in itertools.groupby(letters): + ... print k, list(g) +- ... ++ ... + a ['a', 'a', 'a', 'a', 'a'] + b ['b', 'b'] + c ['c'] + d ['d'] + r ['r', 'r'] + >>> # List unique letters +- >>> [k for k, g in groupby(letters)] ++ >>> [k for k, g in groupby(letters)] + ['a', 'b', 'c', 'd', 'r'] + >>> # Count letter occurrences +- >>> [(k, len(list(g))) for k, g in groupby(letters)] ++ >>> [(k, len(list(g))) for k, g in groupby(letters)] + [('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)] + + (Contributed by Hye-Shik Chang.) +@@ -1175,7 +1175,7 @@ + import logging + logging.basicConfig(filename='/var/log/application.log', + level=0, # Log all messages +- format='%(levelname):%(process):%(thread):%(message)') ++ format='%(levelname):%(process):%(thread):%(message)') + + Other additions to the :mod:`logging` package include a :meth:`log(level, msg)` + convenience method, as well as a :class:`TimedRotatingFileHandler` class that +@@ -1428,7 +1428,7 @@ + you get the following output:: + + ********************************************************************** +- File ``t.py'', line 15, in g ++ File "t.py", line 15, in g + Failed example: + g(4) + Differences (unified diff with -expected +actual): +Index: Doc/whatsnew/2.5.rst +=================================================================== +--- Doc/whatsnew/2.5.rst (.../tags/r261) (Revision 70449) ++++ Doc/whatsnew/2.5.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,5 +1,5 @@ + **************************** +- What's New in Python 2.5 ++ What's New in Python 2.5 + **************************** + + :Author: A.M. Kuchling +@@ -220,7 +220,7 @@ + required packages. :: + + VERSION = '1.0' +- setup(name='PyPackage', ++ setup(name='PyPackage', + version=VERSION, + requires=['numarray', 'zlib (>=1.1.4)'], + obsoletes=['OldPackage'] +@@ -388,7 +388,7 @@ + else: + else-block + finally: +- final-block ++ final-block + + The code in *block-1* is executed. If the code raises an exception, the various + :keyword:`except` blocks are tested: if the exception is of class +@@ -485,7 +485,7 @@ + 9 + >>> print it.next() + Traceback (most recent call last): +- File ``t.py'', line 15, in ? ++ File "t.py", line 15, in ? + print it.next() + StopIteration + +@@ -835,8 +835,8 @@ + ... + except (KeyboardInterrupt, SystemExit): + raise +- except: +- # Log error... ++ except: ++ # Log error... + # Continue running program... + + In Python 2.5, you can now write ``except Exception`` to achieve the same +@@ -947,7 +947,7 @@ + + class C: + def __index__ (self): +- return self.value ++ return self.value + + The return value must be either a Python integer or long integer. The + interpreter will check that the type returned is correct, and raises a +@@ -1035,9 +1035,9 @@ + + L = ['medium', 'longest', 'short'] + # Prints 'longest' +- print max(L, key=len) ++ print max(L, key=len) + # Prints 'short', because lexicographically 'short' has the largest value +- print max(L) ++ print max(L) + + (Contributed by Steven Bethard and Raymond Hettinger.) + +@@ -1070,8 +1070,8 @@ + using the default ASCII encoding. The result of the comparison is false:: + + >>> chr(128) == unichr(128) # Can't convert chr(128) to Unicode +- __main__:1: UnicodeWarning: Unicode equal comparison failed +- to convert both arguments to Unicode - interpreting them ++ __main__:1: UnicodeWarning: Unicode equal comparison failed ++ to convert both arguments to Unicode - interpreting them + as being unequal + False + >>> chr(127) == unichr(127) # chr(127) can be converted +@@ -1259,10 +1259,10 @@ + + Printing ``index`` results in the following output:: + +- defaultdict(, {'c': ['cammin', 'che'], 'e': ['era'], +- 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'], +- 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'], +- 'p': ['per'], 's': ['selva', 'smarrita'], ++ defaultdict(, {'c': ['cammin', 'che'], 'e': ['era'], ++ 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'], ++ 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'], ++ 'p': ['per'], 's': ['selva', 'smarrita'], + 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']} + + (Contributed by Guido van Rossum.) +@@ -1761,8 +1761,8 @@ + included. + + The rest of this section will provide a brief overview of using ElementTree. +-Full documentation for ElementTree is available at http://effbot.org/zone +-/element-index.htm. ++Full documentation for ElementTree is available at ++http://effbot.org/zone/element-index.htm. + + ElementTree represents an XML document as a tree of element nodes. The text + content of the document is stored as the :attr:`.text` and :attr:`.tail` +@@ -1884,17 +1884,17 @@ + differently. :: + + # Old versions +- h = md5.md5() +- h = md5.new() ++ h = md5.md5() ++ h = md5.new() + +- # New version ++ # New version + h = hashlib.md5() + + # Old versions +- h = sha.sha() +- h = sha.new() ++ h = sha.sha() ++ h = sha.new() + +- # New version ++ # New version + h = hashlib.sha1() + + # Hash that weren't previously available +@@ -2191,7 +2191,7 @@ + case that your extensions were using it, you can replace it by something like + the following:: + +- range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll", ++ range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll", + start, stop, step); + + .. ====================================================================== +Index: Doc/whatsnew/2.6.rst +=================================================================== +--- Doc/whatsnew/2.6.rst (.../tags/r261) (Revision 70449) ++++ Doc/whatsnew/2.6.rst (.../branches/release26-maint) (Revision 70449) +@@ -586,30 +586,30 @@ + + + def factorial(queue, N): +- "Compute a factorial." +- # If N is a multiple of 4, this function will take much longer. +- if (N % 4) == 0: +- time.sleep(.05 * N/4) ++ "Compute a factorial." ++ # If N is a multiple of 4, this function will take much longer. ++ if (N % 4) == 0: ++ time.sleep(.05 * N/4) + +- # Calculate the result +- fact = 1L +- for i in range(1, N+1): +- fact = fact * i ++ # Calculate the result ++ fact = 1L ++ for i in range(1, N+1): ++ fact = fact * i + +- # Put the result on the queue +- queue.put(fact) ++ # Put the result on the queue ++ queue.put(fact) + + if __name__ == '__main__': +- queue = Queue() ++ queue = Queue() + +- N = 5 ++ N = 5 + +- p = Process(target=factorial, args=(queue, N)) +- p.start() +- p.join() ++ p = Process(target=factorial, args=(queue, N)) ++ p.start() ++ p.join() + +- result = queue.get() +- print 'Factorial', N, '=', result ++ result = queue.get() ++ print 'Factorial', N, '=', result + + A :class:`Queue` is used to communicate the input parameter *N* and + the result. The :class:`Queue` object is stored in a global variable. +@@ -630,12 +630,12 @@ + from multiprocessing import Pool + + def factorial(N, dictionary): +- "Compute a factorial." +- ... ++ "Compute a factorial." ++ ... + p = Pool(5) + result = p.map(factorial, range(1, 1000, 10)) + for v in result: +- print v ++ print v + + This produces the following output:: + +@@ -734,7 +734,7 @@ + + Curly brackets can be escaped by doubling them:: + +- >>> format("Empty dict: {{}}") ++ >>> "Empty dict: {{}}".format() + "Empty dict: {}" + + Field names can be integers indicating positional arguments, such as +@@ -744,7 +744,7 @@ + >>> import sys + >>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys) + Platform: darwin +- Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41) ++ Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41) + [GCC 4.0.1 (Apple Computer, Inc. build 5367)]' + + >>> import mimetypes +@@ -958,8 +958,8 @@ + The primary use of :class:`bytes` in 2.6 will be to write tests of + object type such as ``isinstance(x, bytes)``. This will help the 2to3 + converter, which can't tell whether 2.x code intends strings to +-contain either characters or 8-bit bytes; you can now +-use either :class:`bytes` or :class:`str` to represent your intention ++contain either characters or 8-bit bytes; you can now ++use either :class:`bytes` or :class:`str` to represent your intention + exactly, and the resulting code will also be correct in Python 3.0. + + There's also a ``__future__`` import that causes all string literals +@@ -1834,9 +1834,9 @@ + "/cgi-bin/add.py?category=1". (Contributed by Alexandre Fiori and + Nubis; :issue:`1817`.) + +- The :func:`parse_qs` and :func:`parse_qsl` functions have been ++ The :func:`parse_qs` and :func:`parse_qsl` functions have been + relocated from the :mod:`cgi` module to the :mod:`urlparse` module. +- The versions still available in the :mod:`cgi` module will ++ The versions still available in the :mod:`cgi` module will + trigger :exc:`PendingDeprecationWarning` messages in 2.6 + (:issue:`600362`). + +@@ -1885,9 +1885,9 @@ + ('id', 'name', 'type', 'size') + + >>> var = var_type(1, 'frequency', 'int', 4) +- >>> print var[0], var.id # Equivalent ++ >>> print var[0], var.id # Equivalent + 1 1 +- >>> print var[2], var.type # Equivalent ++ >>> print var[2], var.type # Equivalent + int int + >>> var._asdict() + {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'} +@@ -1931,7 +1931,7 @@ + * A new window method in the :mod:`curses` module, + :meth:`chgat`, changes the display attributes for a certain number of + characters on a single line. (Contributed by Fabian Kreutz.) +- ++ + :: + + # Boldface text starting at y=0,x=21 +@@ -2046,8 +2046,8 @@ + + >>> list(itertools.product([1,2,3], [4,5,6])) + [(1, 4), (1, 5), (1, 6), +- (2, 4), (2, 5), (2, 6), +- (3, 4), (3, 5), (3, 6)] ++ (2, 4), (2, 5), (2, 6), ++ (3, 4), (3, 5), (3, 6)] + + The optional *repeat* keyword argument is used for taking the + product of an iterable or a set of iterables with themselves, +@@ -2428,9 +2428,9 @@ + :issue:`742598`, :issue:`1193577`.) + + * The :mod:`sqlite3` module, maintained by Gerhard Haering, +- has been updated from version 2.3.2 in Python 2.5 to ++ has been updated from version 2.3.2 in Python 2.5 to + version 2.4.1. +- ++ + * The :mod:`struct` module now supports the C99 :ctype:`_Bool` type, + using the format character ``'?'``. + (Contributed by David Remahl.) +@@ -2525,9 +2525,9 @@ + ``with tempfile.NamedTemporaryFile() as tmp: ...``. + (Contributed by Alexander Belopolsky; :issue:`2021`.) + +-* The :mod:`test.test_support` module gained a number +- of context managers useful for writing tests. +- :func:`EnvironmentVarGuard` is a ++* The :mod:`test.test_support` module gained a number ++ of context managers useful for writing tests. ++ :func:`EnvironmentVarGuard` is a + context manager that temporarily changes environment variables and + automatically restores them to their old values. + +@@ -2542,7 +2542,7 @@ + f = urllib.urlopen('https://sf.net') + ... + +- Finally, :func:`check_warnings` resets the :mod:`warning` module's ++ Finally, :func:`check_warnings` resets the :mod:`warning` module's + warning filters and returns an object that will record all warning + messages triggered (:issue:`3781`):: + +@@ -2582,7 +2582,7 @@ + :meth:`activeCount` method is renamed to :meth:`active_count`. Both + the 2.6 and 3.0 versions of the module support the same properties + and renamed methods, but don't remove the old methods. No date has been set +- for the deprecation of the old APIs in Python 3.x; the old APIs won't ++ for the deprecation of the old APIs in Python 3.x; the old APIs won't + be removed in any 2.x version. + (Carried out by several people, most notably Benjamin Peterson.) + +@@ -2639,7 +2639,7 @@ + (Added by Facundo Batista.) + + * The Unicode database provided by the :mod:`unicodedata` module +- has been updated to version 5.1.0. (Updated by ++ has been updated to version 5.1.0. (Updated by + Martin von Loewis; :issue:`3811`.) + + * The :mod:`warnings` module's :func:`formatwarning` and :func:`showwarning` +@@ -2650,7 +2650,7 @@ + A new function, :func:`catch_warnings`, is a context manager + intended for testing purposes that lets you temporarily modify the + warning filters and then restore their original values (:issue:`3781`). +- ++ + * The XML-RPC :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer` + classes can now be prevented from immediately opening and binding to + their socket by passing True as the ``bind_and_activate`` +@@ -3213,6 +3213,9 @@ + set ``__hash__ = None`` in their definitions to indicate + the fact. + ++* String exceptions have been removed. Attempting to use them raises a ++ :exc:`TypeError`. ++ + * The :meth:`__init__` method of :class:`collections.deque` + now clears any existing contents of the deque + before adding elements from the iterable. This change makes the +@@ -3220,8 +3223,8 @@ + + * :meth:`object.__init__` previously accepted arbitrary arguments and + keyword arguments, ignoring them. In Python 2.6, this is no longer +- allowed and will result in a :exc:`TypeError`. This will affect +- :meth:`__init__` methods that end up calling the corresponding ++ allowed and will result in a :exc:`TypeError`. This will affect ++ :meth:`__init__` methods that end up calling the corresponding + method on :class:`object` (perhaps through using :func:`super`). + See :issue:`1683368` for discussion. + +@@ -3281,7 +3284,7 @@ + + The author would like to thank the following people for offering + suggestions, corrections and assistance with various drafts of this +-article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy, +-Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr, ++article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy, ++Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr, + Antoine Pitrou, Brian Warner. + +Index: Doc/tools/sphinx-web.py +=================================================================== +--- Doc/tools/sphinx-web.py (.../tags/r261) (Revision 70449) ++++ Doc/tools/sphinx-web.py (.../branches/release26-maint) (Revision 70449) +@@ -1,14 +0,0 @@ +-# -*- coding: utf-8 -*- +-""" +- Sphinx - Python documentation webserver +- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +- +- :copyright: 2007 by Georg Brandl. +- :license: Python license. +-""" +- +-import sys +- +-if __name__ == '__main__': +- from sphinx.web import main +- sys.exit(main(sys.argv)) +Index: Doc/tools/rstlint.py +=================================================================== +--- Doc/tools/rstlint.py (.../tags/r261) (Revision 0) ++++ Doc/tools/rstlint.py (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,233 @@ ++#!/usr/bin/env python ++# -*- coding: utf-8 -*- ++ ++# Check for stylistic and formal issues in .rst and .py ++# files included in the documentation. ++# ++# 01/2009, Georg Brandl ++ ++# TODO: - wrong versions in versionadded/changed ++# - wrong markup after versionchanged directive ++ ++from __future__ import with_statement ++ ++import os ++import re ++import sys ++import getopt ++import subprocess ++from os.path import join, splitext, abspath, exists ++from collections import defaultdict ++ ++directives = [ ++ # standard docutils ones ++ 'admonition', 'attention', 'caution', 'class', 'compound', 'container', ++ 'contents', 'csv-table', 'danger', 'date', 'default-role', 'epigraph', ++ 'error', 'figure', 'footer', 'header', 'highlights', 'hint', 'image', ++ 'important', 'include', 'line-block', 'list-table', 'meta', 'note', ++ 'parsed-literal', 'pull-quote', 'raw', 'replace', ++ 'restructuredtext-test-directive', 'role', 'rubric', 'sectnum', 'sidebar', ++ 'table', 'target-notes', 'tip', 'title', 'topic', 'unicode', 'warning', ++ # Sphinx custom ones ++ 'acks', 'attribute', 'autoattribute', 'autoclass', 'autodata', ++ 'autoexception', 'autofunction', 'automethod', 'automodule', 'centered', ++ 'cfunction', 'class', 'classmethod', 'cmacro', 'cmdoption', 'cmember', ++ 'code-block', 'confval', 'cssclass', 'ctype', 'currentmodule', 'cvar', ++ 'data', 'deprecated', 'describe', 'directive', 'doctest', 'envvar', 'event', ++ 'exception', 'function', 'glossary', 'highlight', 'highlightlang', 'index', ++ 'literalinclude', 'method', 'module', 'moduleauthor', 'productionlist', ++ 'program', 'role', 'sectionauthor', 'seealso', 'sourcecode', 'staticmethod', ++ 'tabularcolumns', 'testcode', 'testoutput', 'testsetup', 'toctree', 'todo', ++ 'todolist', 'versionadded', 'versionchanged' ++] ++ ++all_directives = '(' + '|'.join(directives) + ')' ++seems_directive_re = re.compile(r'\.\. %s([^a-z:]|:(?!:))' % all_directives) ++default_role_re = re.compile(r'(^| )`\w([^`]*?\w)?`($| )') ++leaked_markup_re = re.compile(r'[a-z]::[^=]|:[a-z]+:|`|\.\.\s*\w+:') ++ ++ ++checkers = {} ++ ++checker_props = {'severity': 1, 'falsepositives': False} ++ ++def checker(*suffixes, **kwds): ++ """Decorator to register a function as a checker.""" ++ def deco(func): ++ for suffix in suffixes: ++ checkers.setdefault(suffix, []).append(func) ++ for prop in checker_props: ++ setattr(func, prop, kwds.get(prop, checker_props[prop])) ++ return func ++ return deco ++ ++ ++@checker('.py', severity=4) ++def check_syntax(fn, lines): ++ """Check Python examples for valid syntax.""" ++ code = ''.join(lines) ++ if '\r' in code: ++ if os.name != 'nt': ++ yield 0, '\\r in code file' ++ code = code.replace('\r', '') ++ try: ++ compile(code, fn, 'exec') ++ except SyntaxError, err: ++ yield err.lineno, 'not compilable: %s' % err ++ ++ ++@checker('.rst', severity=2) ++def check_suspicious_constructs(fn, lines): ++ """Check for suspicious reST constructs.""" ++ inprod = False ++ for lno, line in enumerate(lines): ++ if seems_directive_re.match(line): ++ yield lno+1, 'comment seems to be intended as a directive' ++ if '.. productionlist::' in line: ++ inprod = True ++ elif not inprod and default_role_re.search(line): ++ yield lno+1, 'default role used' ++ elif inprod and not line.strip(): ++ inprod = False ++ ++ ++@checker('.py', '.rst') ++def check_whitespace(fn, lines): ++ """Check for whitespace and line length issues.""" ++ for lno, line in enumerate(lines): ++ if '\r' in line: ++ yield lno+1, '\\r in line' ++ if '\t' in line: ++ yield lno+1, 'OMG TABS!!!1' ++ if line[:-1].rstrip(' \t') != line[:-1]: ++ yield lno+1, 'trailing whitespace' ++ ++ ++@checker('.rst', severity=0) ++def check_line_length(fn, lines): ++ """Check for line length; this checker is not run by default.""" ++ for lno, line in enumerate(lines): ++ if len(line) > 81: ++ # don't complain about tables, links and function signatures ++ if line.lstrip()[0] not in '+|' and \ ++ 'http://' not in line and \ ++ not line.lstrip().startswith(('.. function', ++ '.. method', ++ '.. cfunction')): ++ yield lno+1, "line too long" ++ ++ ++@checker('.html', severity=2, falsepositives=True) ++def check_leaked_markup(fn, lines): ++ """Check HTML files for leaked reST markup; this only works if ++ the HTML files have been built. ++ """ ++ for lno, line in enumerate(lines): ++ if leaked_markup_re.search(line): ++ yield lno+1, 'possibly leaked markup: %r' % line ++ ++ ++def main(argv): ++ usage = '''\ ++Usage: %s [-v] [-f] [-s sev] [-i path]* [path] ++ ++Options: -v verbose (print all checked file names) ++ -f enable checkers that yield many false positives ++ -s sev only show problems with severity >= sev ++ -i path ignore subdir or file path ++''' % argv[0] ++ try: ++ gopts, args = getopt.getopt(argv[1:], 'vfs:i:') ++ except getopt.GetoptError: ++ print usage ++ return 2 ++ ++ verbose = False ++ severity = 1 ++ ignore = [] ++ falsepos = False ++ for opt, val in gopts: ++ if opt == '-v': ++ verbose = True ++ elif opt == '-f': ++ falsepos = True ++ elif opt == '-s': ++ severity = int(val) ++ elif opt == '-i': ++ ignore.append(abspath(val)) ++ ++ if len(args) == 0: ++ path = '.' ++ elif len(args) == 1: ++ path = args[0] ++ else: ++ print usage ++ return 2 ++ ++ if not exists(path): ++ print 'Error: path %s does not exist' % path ++ return 2 ++ ++ count = defaultdict(int) ++ out = sys.stdout ++ ++ for root, dirs, files in os.walk(path): ++ # ignore subdirs controlled by svn ++ if '.svn' in dirs: ++ dirs.remove('.svn') ++ ++ # ignore subdirs in ignore list ++ if abspath(root) in ignore: ++ del dirs[:] ++ continue ++ ++ for fn in files: ++ fn = join(root, fn) ++ if fn[:2] == './': ++ fn = fn[2:] ++ ++ # ignore files in ignore list ++ if abspath(fn) in ignore: ++ continue ++ ++ ext = splitext(fn)[1] ++ checkerlist = checkers.get(ext, None) ++ if not checkerlist: ++ continue ++ ++ if verbose: ++ print 'Checking %s...' % fn ++ ++ try: ++ with open(fn, 'r') as f: ++ lines = list(f) ++ except (IOError, OSError), err: ++ print '%s: cannot open: %s' % (fn, err) ++ count[4] += 1 ++ continue ++ ++ for checker in checkerlist: ++ if checker.falsepositives and not falsepos: ++ continue ++ csev = checker.severity ++ if csev >= severity: ++ for lno, msg in checker(fn, lines): ++ print >>out, '[%d] %s:%d: %s' % (csev, fn, lno, msg) ++ count[csev] += 1 ++ if verbose: ++ print ++ if not count: ++ if severity > 1: ++ print 'No problems with severity >= %d found.' % severity ++ else: ++ print 'No problems found.' ++ else: ++ for severity in sorted(count): ++ number = count[severity] ++ print '%d problem%s with severity %d found.' % \ ++ (number, number > 1 and 's' or '', severity) ++ return int(bool(count)) ++ ++ ++if __name__ == '__main__': ++ sys.exit(main(sys.argv)) + +Eigenschaftsänderungen: Doc/tools/rstlint.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native +Hinzugefügt: svn:executable + + * +Hinzugefügt: svn:keywords + + Id + +Index: Doc/tools/sphinxext/layout.html +=================================================================== +--- Doc/tools/sphinxext/layout.html (.../tags/r261) (Revision 70449) ++++ Doc/tools/sphinxext/layout.html (.../branches/release26-maint) (Revision 70449) +@@ -1,4 +1,10 @@ + {% extends "!layout.html" %} + {% block rootrellink %} +-
  • {{ shorttitle }}{{ reldelim1 }}
  • ++
  • ++
  • {{ shorttitle }}{{ reldelim1 }}
  • + {% endblock %} ++{% block extrahead %} ++ ++{{ super() }} ++{% endblock %} +Index: Doc/tools/sphinxext/indexsidebar.html +=================================================================== +--- Doc/tools/sphinxext/indexsidebar.html (.../tags/r261) (Revision 70449) ++++ Doc/tools/sphinxext/indexsidebar.html (.../branches/release26-maint) (Revision 70449) +@@ -1,5 +1,13 @@ +

    Download

    +

    Download these documents

    ++

    Docs for other versions

    ++ ++ +

    Other resources

    + +Index: Doc/tools/sphinxext/pyspecific.py +=================================================================== +--- Doc/tools/sphinxext/pyspecific.py (.../tags/r261) (Revision 70449) ++++ Doc/tools/sphinxext/pyspecific.py (.../branches/release26-maint) (Revision 70449) +@@ -13,6 +13,14 @@ + + from docutils import nodes, utils + ++# monkey-patch reST parser to disable alphabetic and roman enumerated lists ++from docutils.parsers.rst.states import Body ++Body.enum.converters['loweralpha'] = \ ++ Body.enum.converters['upperalpha'] = \ ++ Body.enum.converters['lowerroman'] = \ ++ Body.enum.converters['upperroman'] = lambda x: None ++ ++ + def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): + issue = utils.unescape(text) + text = 'issue ' + issue +@@ -47,13 +55,18 @@ + from pprint import pformat + from docutils.io import StringOutput + from docutils.utils import new_document +-from sphinx.builder import Builder + + 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' + +@@ -88,7 +101,10 @@ + finally: + f.close() + ++# Support for checking for suspicious markup + ++import suspicious ++ + # Support for documenting Opcodes + + import re +@@ -112,5 +128,6 @@ + def setup(app): + app.add_role('issue', issue_role) + app.add_builder(PydocTopicsBuilder) ++ app.add_builder(suspicious.CheckSuspiciousMarkupBuilder) + app.add_description_unit('opcode', 'opcode', '%s (opcode)', + parse_opcode_signature) +Index: Doc/tools/sphinxext/susp-ignored.csv +=================================================================== +--- Doc/tools/sphinxext/susp-ignored.csv (.../tags/r261) (Revision 0) ++++ Doc/tools/sphinxext/susp-ignored.csv (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,164 @@ ++c-api/arg,,:ref,"PyArg_ParseTuple(args, ""O|O:ref"", &object, &callback)" ++c-api/list,,:high,list[low:high] ++c-api/list,,:high,list[low:high] = itemlist ++c-api/sequence,,:i2,o[i1:i2] ++c-api/sequence,,:i2,o[i1:i2] = v ++c-api/sequence,,:i2,del o[i1:i2] ++c-api/unicode,,:end,str[start:end] ++distutils/apiref,,:action,http://pypi.python.org/pypi?:action=list_classifiers ++distutils/setupscript,,::, ++extending/embedding,,:numargs,"if(!PyArg_ParseTuple(args, "":numargs""))" ++extending/extending,,:set,"if (PyArg_ParseTuple(args, ""O:set_callback"", &temp)) {" ++extending/extending,,:myfunction,"PyArg_ParseTuple(args, ""D:myfunction"", &c);" ++extending/newtypes,,:call,"if (!PyArg_ParseTuple(args, ""sss:call"", &arg1, &arg2, &arg3)) {" ++extending/windows,,:initspam,/export:initspam ++howto/cporting,,:add,"if (!PyArg_ParseTuple(args, ""ii:add_ints"", &one, &two))" ++howto/cporting,,:encode,"if (!PyArg_ParseTuple(args, ""O:encode_object"", &myobj))" ++howto/cporting,,:say,"if (!PyArg_ParseTuple(args, ""U:say_hello"", &name))" ++howto/curses,,:black,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and" ++howto/curses,,:blue,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and" ++howto/curses,,:cyan,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and" ++howto/curses,,:green,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and" ++howto/curses,,:magenta,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and" ++howto/curses,,:red,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and" ++howto/curses,,:white,"7:white." ++howto/curses,,:yellow,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and" ++howto/regex,,::, ++howto/regex,,:foo,(?:foo) ++howto/urllib2,,:example,"for example ""joe@password:example.com""" ++howto/webservers,,.. image:,.. image:: http.png ++library/audioop,,:ipos,"# factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)]," ++library/datetime,,:MM, ++library/datetime,,:SS, ++library/decimal,,:optional,"trailneg:optional trailing minus indicator" ++library/difflib,,:ahi,a[alo:ahi] ++library/difflib,,:bhi,b[blo:bhi] ++library/difflib,,:i2, ++library/difflib,,:j2, ++library/difflib,,:i1, ++library/dis,,:TOS, ++library/dis,,`,TOS = `TOS` ++library/doctest,,`,``factorial`` from the ``example`` module: ++library/doctest,,`,The ``example`` module ++library/doctest,,`,Using ``factorial`` ++library/functions,,:step,a[start:stop:step] ++library/functions,,:stop,"a[start:stop, i]" ++library/functions,,:stop,a[start:stop:step] ++library/hotshot,,:lineno,"ncalls tottime percall cumtime percall filename:lineno(function)" ++library/httplib,,:port,host:port ++library/imaplib,,:MM,"""DD-Mmm-YYYY HH:MM:SS +HHMM""" ++library/imaplib,,:SS,"""DD-Mmm-YYYY HH:MM:SS +HHMM""" ++library/linecache,,:sys,"sys:x:3:3:sys:/dev:/bin/sh" ++library/logging,,:And, ++library/logging,,:package1, ++library/logging,,:package2, ++library/logging,,:root, ++library/logging,,:This, ++library/logging,,:port,host:port ++library/mmap,,:i2,obj[i1:i2] ++library/multiprocessing,,:queue,">>> QueueManager.register('get_queue', callable=lambda:queue)" ++library/multiprocessing,,`,">>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`" ++library/multiprocessing,,`,">>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`" ++library/multiprocessing,,`,# `BaseManager`. ++library/multiprocessing,,`,# `Pool.imap()` (which will save on the amount of code needed anyway). ++library/multiprocessing,,`,# A test file for the `multiprocessing` package ++library/multiprocessing,,`,# A test of `multiprocessing.Pool` class ++library/multiprocessing,,`,# Add more tasks using `put()` ++library/multiprocessing,,`,# create server for a `HostManager` object ++library/multiprocessing,,`,# Depends on `multiprocessing` package -- tested with `processing-0.60` ++library/multiprocessing,,`,# in the original order then consider using `Pool.map()` or ++library/multiprocessing,,`,# Not sure if we should synchronize access to `socket.accept()` method by ++library/multiprocessing,,`,# object. (We import `multiprocessing.reduction` to enable this pickling.) ++library/multiprocessing,,`,# register the Foo class; make `f()` and `g()` accessible via proxy ++library/multiprocessing,,`,# register the Foo class; make `g()` and `_h()` accessible via proxy ++library/multiprocessing,,`,# register the generator function baz; use `GeneratorProxy` to make proxies ++library/multiprocessing,,`,`Cluster` is a subclass of `SyncManager` so it allows creation of ++library/multiprocessing,,`,`hostname` gives the name of the host. If hostname is not ++library/multiprocessing,,`,`slots` is used to specify the number of slots for processes on ++library/optparse,,:len,"del parser.rargs[:len(value)]" ++library/os.path,,:foo,c:foo ++library/parser,,`,"""Make a function that raises an argument to the exponent `exp`.""" ++library/posix,,`,"CFLAGS=""`getconf LFS_CFLAGS`"" OPT=""-g -O2 $CFLAGS""" ++library/profile,,:lineno,ncalls tottime percall cumtime percall filename:lineno(function) ++library/profile,,:lineno,filename:lineno(function) ++library/pyexpat,,:elem1, ++library/pyexpat,,:py,"xmlns:py = ""http://www.python.org/ns/"">" ++library/repr,,`,"return `obj`" ++library/smtplib,,:port,"as well as a regular host:port server." ++library/socket,,::,'5aef:2b::8' ++library/sqlite3,,:memory, ++library/sqlite3,,:age,"select name_last, age from people where name_last=:who and age=:age" ++library/sqlite3,,:who,"select name_last, age from people where name_last=:who and age=:age" ++library/ssl,,:My,"Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc." ++library/ssl,,:My,"Organizational Unit Name (eg, section) []:My Group" ++library/ssl,,:myserver,"Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com" ++library/ssl,,:MyState,State or Province Name (full name) [Some-State]:MyState ++library/ssl,,:ops,Email Address []:ops@myserver.mygroup.myorganization.com ++library/ssl,,:Some,"Locality Name (eg, city) []:Some City" ++library/ssl,,:US,Country Name (2 letter code) [AU]:US ++library/stdtypes,,:len,s[len(s):len(s)] ++library/stdtypes,,:len,s[len(s):len(s)] ++library/string,,:end,s[start:end] ++library/string,,:end,s[start:end] ++library/subprocess,,`,"output=`mycmd myarg`" ++library/subprocess,,`,"output=`dmesg | grep hda`" ++library/tarfile,,:compression,filemode[:compression] ++library/tarfile,,:gz, ++library/tarfile,,:bz2, ++library/time,,:mm, ++library/time,,:ss, ++library/turtle,,::,Example:: ++library/urllib,,:port,:port ++library/urllib2,,:password,"""joe:password@python.org""" ++library/uuid,,:uuid,urn:uuid:12345678-1234-5678-1234-567812345678 ++library/xmlrpclib,,:pass,http://user:pass@host:port/path ++library/xmlrpclib,,:pass,user:pass ++library/xmlrpclib,,:port,http://user:pass@host:port/path ++license,,`,THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND ++license,,:zooko,mailto:zooko@zooko.com ++license,,`,THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ++reference/datamodel,,:step,a[i:j:step] ++reference/datamodel,,:max, ++reference/expressions,,:index,x[index:index] ++reference/expressions,,:datum,{key:datum...} ++reference/expressions,,`,`expressions...` ++reference/grammar,,:output,#diagram:output ++reference/grammar,,:rules,#diagram:rules ++reference/grammar,,:token,#diagram:token ++reference/grammar,,`,'`' testlist1 '`' ++reference/lexical_analysis,,:fileencoding,# vim:fileencoding= ++reference/lexical_analysis,,`,", : . ` = ;" ++tutorial/datastructures,,:value,key:value pairs within the braces adds initial key:value pairs ++tutorial/datastructures,,:value,It is also possible to delete a key:value ++tutorial/stdlib2,,:start,"fields = struct.unpack(' don't care ++ self.issue = issue # the markup fragment that triggered this rule ++ self.line = line # text of the container element (single line only) ++ ++ ++class CheckSuspiciousMarkupBuilder(Builder): ++ """ ++ Checks for possibly invalid markup that may leak into the output ++ """ ++ name = 'suspicious' ++ ++ def init(self): ++ # create output file ++ self.log_file_name = os.path.join(self.outdir, 'suspicious.csv') ++ open(self.log_file_name, 'w').close() ++ # load database of previously ignored issues ++ self.load_rules(os.path.join(os.path.dirname(__file__), 'susp-ignored.csv')) ++ ++ def get_outdated_docs(self): ++ return self.env.found_docs ++ ++ def get_target_uri(self, docname, typ=None): ++ return '' ++ ++ def prepare_writing(self, docnames): ++ ### PYTHON PROJECT SPECIFIC ### ++ for name in set(docnames): ++ if name.split('/', 1)[0] == 'documenting': ++ docnames.remove(name) ++ ### PYTHON PROJECT SPECIFIC ### ++ ++ def write_doc(self, docname, doctree): ++ self.any_issue = False # set when any issue is encountered in this document ++ self.docname = docname ++ visitor = SuspiciousVisitor(doctree, self) ++ doctree.walk(visitor) ++ ++ def finish(self): ++ return ++ ++ def check_issue(self, line, lineno, issue): ++ if not self.is_ignored(line, lineno, issue): ++ self.report_issue(line, lineno, issue) ++ ++ def is_ignored(self, line, lineno, issue): ++ """Determine whether this issue should be ignored. ++ """ ++ docname = self.docname ++ for rule in self.rules: ++ if rule.docname != docname: continue ++ if rule.issue != issue: continue ++ # Both lines must match *exactly*. This is rather strict, ++ # and probably should be improved. ++ # Doing fuzzy matches with levenshtein distance could work, ++ # but that means bringing other libraries... ++ # Ok, relax that requirement: just check if the rule fragment ++ # is contained in the document line ++ if rule.line not in line: continue ++ # Check both line numbers. If they're "near" ++ # this rule matches. (lineno=None means "don't care") ++ if (rule.lineno is not None) and \ ++ abs(rule.lineno - lineno) > 5: continue ++ # if it came this far, the rule matched ++ return True ++ return False ++ ++ def report_issue(self, text, lineno, issue): ++ if not self.any_issue: self.info() ++ self.any_issue = True ++ self.write_log_entry(lineno, issue, text) ++ self.warn('[%s:%d] "%s" found in "%-.120s"' % ( ++ self.docname.encode(sys.getdefaultencoding(),'replace'), ++ lineno, ++ issue.encode(sys.getdefaultencoding(),'replace'), ++ text.strip().encode(sys.getdefaultencoding(),'replace'))) ++ self.app.statuscode = 1 ++ ++ def write_log_entry(self, lineno, issue, text): ++ f = open(self.log_file_name, 'ab') ++ writer = csv.writer(f) ++ writer.writerow([self.docname.encode('utf-8'), ++ lineno, ++ issue.encode('utf-8'), ++ text.strip().encode('utf-8')]) ++ del writer ++ f.close() ++ ++ def load_rules(self, filename): ++ """Load database of previously ignored issues. ++ ++ A csv file, with exactly the same format as suspicious.csv ++ Fields: document name (normalized), line number, issue, surrounding text ++ """ ++ self.info("loading ignore rules... ", nonl=1) ++ self.rules = rules = [] ++ try: f = open(filename, 'rb') ++ except IOError: return ++ for i, row in enumerate(csv.reader(f)): ++ if len(row) != 4: ++ raise ValueError, "wrong format in %s, line %d: %s" % (filename, i+1, row) ++ docname, lineno, issue, text = row ++ docname = docname.decode('utf-8') ++ if lineno: lineno = int(lineno) ++ else: lineno = None ++ issue = issue.decode('utf-8') ++ text = text.decode('utf-8') ++ rule = Rule(docname, lineno, issue, text) ++ rules.append(rule) ++ f.close() ++ self.info('done, %d rules loaded' % len(self.rules)) ++ ++ ++def get_lineno(node): ++ "Obtain line number information for a node" ++ lineno = None ++ while lineno is None and node: ++ node = node.parent ++ lineno = node.line ++ return lineno ++ ++ ++def extract_line(text, index): ++ """text may be a multiline string; extract ++ only the line containing the given character index. ++ ++ >>> extract_line("abc\ndefgh\ni", 6) ++ >>> 'defgh' ++ >>> for i in (0, 2, 3, 4, 10): ++ ... print extract_line("abc\ndefgh\ni", i) ++ abc ++ abc ++ abc ++ defgh ++ defgh ++ i ++ """ ++ p = text.rfind('\n', 0, index) + 1 ++ q = text.find('\n', index) ++ if q<0: q = len(text) ++ return text[p:q] ++ ++ ++class SuspiciousVisitor(nodes.GenericNodeVisitor): ++ ++ lastlineno = 0 ++ ++ def __init__(self, document, builder): ++ nodes.GenericNodeVisitor.__init__(self, document) ++ self.builder = builder ++ ++ def default_visit(self, node): ++ if isinstance(node, (nodes.Text, nodes.image)): # direct text containers ++ text = node.astext() ++ # lineno seems to go backwards sometimes (?) ++ self.lastlineno = lineno = max(get_lineno(node) or 0, self.lastlineno) ++ seen = set() # don't report the same issue more than only once per line ++ for match in detect_all(text): ++ #import pdb; pdb.set_trace() ++ issue = match.group() ++ line = extract_line(text, match.start()) ++ if (issue, line) not in seen: ++ self.builder.check_issue(line, lineno, issue) ++ seen.add((issue, line)) ++ ++ unknown_visit = default_visit ++ ++ def visit_document(self, node): ++ self.lastlineno = 0 ++ ++ def visit_comment(self, node): ++ # ignore comments -- too much false positives. ++ # (although doing this could miss some errors; ++ # there were two sections "commented-out" by mistake ++ # in the Python docs that would not be catched) ++ raise nodes.SkipNode + +Eigenschaftsänderungen: Doc/tools/sphinxext/suspicious.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native +Hinzugefügt: svn:keywords + + Id + + +Eigenschaftsänderungen: Doc/tools +___________________________________________________________________ +Geändert: svn:ignore + - sphinx +jinja +pygments +docutils +*.py[co] + + + sphinx +jinja2 +pygments +docutils +*.py[co] + + +Index: Doc/howto/doanddont.rst +=================================================================== +--- Doc/howto/doanddont.rst (.../tags/r261) (Revision 70449) ++++ Doc/howto/doanddont.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,5 +1,5 @@ + ************************************ +- Idioms and Anti-Idioms in Python ++ Idioms and Anti-Idioms in Python + ************************************ + + :Author: Moshe Zadka +@@ -127,7 +127,7 @@ + # bar.py + from foo import a + if something(): +- a = 2 # danger: foo.a != a ++ a = 2 # danger: foo.a != a + + Good example:: + +@@ -303,6 +303,6 @@ + + This version is bulletproof:: + +- value = (foo.bar()['first'][0]*baz.quux(1, 2)[5:9] ++ value = (foo.bar()['first'][0]*baz.quux(1, 2)[5:9] + + calculate_number(10, 20)*forbulate(500, 360)) + +Index: Doc/howto/regex.rst +=================================================================== +--- Doc/howto/regex.rst (.../tags/r261) (Revision 70449) ++++ Doc/howto/regex.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,7 +1,7 @@ + .. _regex-howto: + + **************************** +- Regular Expression HOWTO ++ Regular Expression HOWTO + **************************** + + :Author: A.M. Kuchling +@@ -611,7 +611,7 @@ + is to read? :: + + charref = re.compile(r""" +- &[#] # Start of a numeric entity reference ++ &[#] # Start of a numeric entity reference + ( + 0[0-7]+ # Octal form + | [0-9]+ # Decimal form +@@ -732,7 +732,7 @@ + >>> p = re.compile('\bclass\b') + >>> print p.search('no class at all') + None +- >>> print p.search('\b' + 'class' + '\b') ++ >>> print p.search('\b' + 'class' + '\b') + + + Second, inside a character class, where there's no use for this assertion, +@@ -917,7 +917,7 @@ + + InternalDate = re.compile(r'INTERNALDATE "' + r'(?P[ 123][0-9])-(?P[A-Z][a-z][a-z])-' +- r'(?P[0-9][0-9][0-9][0-9])' ++ r'(?P[0-9][0-9][0-9][0-9])' + r' (?P[0-9][0-9]):(?P[0-9][0-9]):(?P[0-9][0-9])' + r' (?P[-+])(?P[0-9][0-9])(?P[0-9][0-9])' + r'"') +@@ -1236,9 +1236,9 @@ + only report a successful match which will start at 0; if the match wouldn't + start at zero, :func:`match` will *not* report it. :: + +- >>> print re.match('super', 'superstition').span() ++ >>> print re.match('super', 'superstition').span() + (0, 5) +- >>> print re.match('super', 'insuperable') ++ >>> print re.match('super', 'insuperable') + None + + On the other hand, :func:`search` will scan forward through the string, +Index: Doc/howto/sockets.rst +=================================================================== +--- Doc/howto/sockets.rst (.../tags/r261) (Revision 70449) ++++ Doc/howto/sockets.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,5 +1,5 @@ + **************************** +- Socket Programming HOWTO ++ Socket Programming HOWTO + **************************** + + :Author: Gordon McMillan +@@ -63,7 +63,7 @@ + #create an INET, STREAMing socket + s = socket.socket( + socket.AF_INET, socket.SOCK_STREAM) +- #now connect to the web server on port 80 ++ #now connect to the web server on port 80 + # - the normal http port + s.connect(("www.mcmillan-inc.com", 80)) + +@@ -78,7 +78,7 @@ + #create an INET, STREAMing socket + serversocket = socket.socket( + socket.AF_INET, socket.SOCK_STREAM) +- #bind the socket to a public host, ++ #bind the socket to a public host, + # and a well-known port + serversocket.bind((socket.gethostname(), 80)) + #become a server socket +@@ -185,38 +185,38 @@ + length message:: + + class mysocket: +- '''demonstration class only ++ '''demonstration class only + - coded for clarity, not efficiency + ''' + + def __init__(self, sock=None): +- if sock is None: +- self.sock = socket.socket( +- socket.AF_INET, socket.SOCK_STREAM) +- else: +- self.sock = sock ++ if sock is None: ++ self.sock = socket.socket( ++ socket.AF_INET, socket.SOCK_STREAM) ++ else: ++ self.sock = sock + + def connect(self, host, port): +- self.sock.connect((host, port)) ++ self.sock.connect((host, port)) + + def mysend(self, msg): +- totalsent = 0 +- while totalsent < MSGLEN: +- sent = self.sock.send(msg[totalsent:]) +- if sent == 0: +- raise RuntimeError, \ +- "socket connection broken" +- totalsent = totalsent + sent ++ totalsent = 0 ++ while totalsent < MSGLEN: ++ sent = self.sock.send(msg[totalsent:]) ++ if sent == 0: ++ raise RuntimeError, \ ++ "socket connection broken" ++ totalsent = totalsent + sent + + def myreceive(self): +- msg = '' +- while len(msg) < MSGLEN: +- chunk = self.sock.recv(MSGLEN-len(msg)) +- if chunk == '': +- raise RuntimeError, \ +- "socket connection broken" +- msg = msg + chunk +- return msg ++ msg = '' ++ while len(msg) < MSGLEN: ++ chunk = self.sock.recv(MSGLEN-len(msg)) ++ if chunk == '': ++ raise RuntimeError, \ ++ "socket connection broken" ++ msg = msg + chunk ++ return msg + + The sending code here is usable for almost any messaging scheme - in Python you + send strings, and you can use ``len()`` to determine its length (even if it has +@@ -343,9 +343,9 @@ + + ready_to_read, ready_to_write, in_error = \ + select.select( +- potential_readers, +- potential_writers, +- potential_errs, ++ potential_readers, ++ potential_writers, ++ potential_errs, + timeout) + + You pass ``select`` three lists: the first contains all sockets that you might +Index: Doc/howto/urllib2.rst +=================================================================== +--- Doc/howto/urllib2.rst (.../tags/r261) (Revision 70449) ++++ Doc/howto/urllib2.rst (.../branches/release26-maint) (Revision 70449) +@@ -10,8 +10,8 @@ + HOWTO, available at `urllib2 - Le Manuel manquant + `_. + +- + ++ + Introduction + ============ + +@@ -19,9 +19,9 @@ + + You may also find useful the following article on fetching web resources + with Python : +- ++ + * `Basic Authentication `_ +- ++ + A tutorial on *Basic Authentication*, with examples in Python. + + **urllib2** is a `Python `_ module for fetching URLs +@@ -98,7 +98,7 @@ + *not* from ``urllib2``. :: + + import urllib +- import urllib2 ++ import urllib2 + + url = 'http://www.someserver.com/cgi-bin/register.cgi' + values = {'name' : 'Michael Foord', +@@ -161,15 +161,15 @@ + Explorer [#]_. :: + + import urllib +- import urllib2 +- ++ import urllib2 ++ + url = 'http://www.someserver.com/cgi-bin/register.cgi' +- user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' ++ user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' + values = {'name' : 'Michael Foord', + 'location' : 'Northampton', + 'language' : 'Python' } + headers = { 'User-Agent' : user_agent } +- ++ + data = urllib.urlencode(values) + req = urllib2.Request(url, data, headers) + response = urllib2.urlopen(req) +@@ -183,7 +183,7 @@ + =================== + + *urlopen* raises :exc:`URLError` when it cannot handle a response (though as usual +-with Python APIs, builtin exceptions such as ++with Python APIs, builtin exceptions such as + :exc:`ValueError`, :exc:`TypeError` etc. may also + be raised). + +@@ -309,18 +309,18 @@ + geturl, and info, methods. :: + + >>> req = urllib2.Request('http://www.python.org/fish.html') +- >>> try: ++ >>> try: + >>> urllib2.urlopen(req) + >>> except URLError, e: + >>> print e.code + >>> print e.read() +- >>> ++ >>> + 404 +- +- +- Error 404: File Not Found ++ Error 404: File Not Found + ...... etc... + + Wrapping it Up +@@ -372,8 +372,8 @@ + print 'Error code: ', e.code + else: + # everything is fine +- + ++ + info and geturl + =============== + +@@ -443,7 +443,7 @@ + and a 'realm'. The header looks like : ``Www-authenticate: SCHEME + realm="REALM"``. + +-e.g. :: ++e.g. :: + + Www-authenticate: Basic realm="cPanel Users" + +@@ -467,24 +467,24 @@ + than the URL you pass to .add_password() will also match. :: + + # create a password manager +- password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() ++ password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() + + # Add the username and password. +- # If we knew the realm, we could use it instead of ``None``. ++ # If we knew the realm, we could use it instead of None. + top_level_url = "http://example.com/foo/" + password_mgr.add_password(None, top_level_url, username, password) + +- handler = urllib2.HTTPBasicAuthHandler(password_mgr) ++ handler = urllib2.HTTPBasicAuthHandler(password_mgr) + + # create "opener" (OpenerDirector instance) +- opener = urllib2.build_opener(handler) ++ opener = urllib2.build_opener(handler) + + # use the opener to fetch a URL +- opener.open(a_url) ++ opener.open(a_url) + + # Install the opener. + # Now all calls to urllib2.urlopen use our opener. +- urllib2.install_opener(opener) ++ urllib2.install_opener(opener) + + .. note:: + +@@ -540,7 +540,7 @@ + + # timeout in seconds + timeout = 10 +- socket.setdefaulttimeout(timeout) ++ socket.setdefaulttimeout(timeout) + + # this call to urllib2.urlopen now uses the default timeout + # we have set in the socket module +@@ -557,7 +557,7 @@ + This document was reviewed and revised by John Lee. + + .. [#] For an introduction to the CGI protocol see +- `Writing Web Applications in Python `_. ++ `Writing Web Applications in Python `_. + .. [#] Like Google for example. The *proper* way to use google from a program + is to use `PyGoogle `_ of course. See + `Voidspace Google `_ +@@ -574,6 +574,6 @@ + is set to use the proxy, which urllib2 picks up on. In order to test + scripts with a localhost server, I have to prevent urllib2 from using + the proxy. +-.. [#] urllib2 opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe ++.. [#] urllib2 opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe + `_. +- ++ +Index: Doc/howto/functional.rst +=================================================================== +--- Doc/howto/functional.rst (.../tags/r261) (Revision 70449) ++++ Doc/howto/functional.rst (.../branches/release26-maint) (Revision 70449) +@@ -145,7 +145,7 @@ + functions are also easier to read and to check for errors. + + +-Ease of debugging and testing ++Ease of debugging and testing + ----------------------------- + + Testing and debugging a functional-style program is easier. +@@ -213,7 +213,7 @@ + Traceback (most recent call last): + File "", line 1, in ? + StopIteration +- >>> ++ >>> + + Python expects iterable objects in several different contexts, the most + important being the ``for`` statement. In the statement ``for X in Y``, Y must +@@ -362,7 +362,7 @@ + comprehensions are surrounded by square brackets ("[]"). Generator expressions + have the form:: + +- ( expression for expr in sequence1 ++ ( expression for expr in sequence1 + if condition1 + for expr2 in sequence2 + if condition2 +@@ -404,7 +404,7 @@ + if not (conditionN): + continue # Skip this element + +- # Output the value of ++ # Output the value of + # the expression. + + This means that when there are multiple ``for...in`` clauses but no ``if`` +@@ -418,8 +418,8 @@ + >>> seq1 = 'abc' + >>> seq2 = (1,2,3) + >>> [(x,y) for x in seq1 for y in seq2] +- [('a', 1), ('a', 2), ('a', 3), +- ('b', 1), ('b', 2), ('b', 3), ++ [('a', 1), ('a', 2), ('a', 3), ++ ('b', 1), ('b', 2), ('b', 3), + ('c', 1), ('c', 2), ('c', 3)] + + To avoid introducing an ambiguity into Python's grammar, if ``expression`` is +@@ -585,7 +585,7 @@ + 9 + >>> print it.next() + Traceback (most recent call last): +- File ``t.py'', line 15, in ? ++ File "t.py", line 15, in ? + print it.next() + StopIteration + +@@ -728,7 +728,7 @@ + if line.strip() == '': + print 'Blank line at line #%i' % i + +-``sorted(iterable, [cmp=None], [key=None], [reverse=False)`` collects all the ++``sorted(iterable, [cmp=None], [key=None], [reverse=False])`` collects all the + elements of the iterable into a list, sorts the list, and returns the sorted + result. The ``cmp``, ``key``, and ``reverse`` arguments are passed through to + the constructed list's ``.sort()`` method. :: +@@ -759,7 +759,7 @@ + True + >>> all([0,1,0]) + False +- >>> all([0,0,0]) ++ >>> all([0,0,0]) + False + >>> all([1,1,1]) + True +@@ -845,7 +845,7 @@ + 4) Convert the lambda to a def statement, using that name. + 5) Remove the comment. + +-I really like these rules, but you're free to disagree ++I really like these rules, but you're free to disagree + about whether this lambda-free style is better. + + +@@ -970,7 +970,7 @@ + ``itertools.starmap(func, iter)`` assumes that the iterable will return a stream + of tuples, and calls ``f()`` using these tuples as the arguments:: + +- itertools.starmap(os.path.join, ++ itertools.starmap(os.path.join, + [('/usr', 'bin', 'java'), ('/bin', 'python'), + ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')]) + => +@@ -1039,9 +1039,9 @@ + + :: + +- city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), ++ city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), + ('Anchorage', 'AK'), ('Nome', 'AK'), +- ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), ++ ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), + ... + ] + +@@ -1056,7 +1056,7 @@ + where + iterator-1 => + ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL') +- iterator-2 => ++ iterator-2 => + ('Anchorage', 'AK'), ('Nome', 'AK') + iterator-3 => + ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ') +@@ -1150,7 +1150,7 @@ + + >>> double(add(5, 6)) + 22 +- ++ + The ``unpack`` keyword is provided to work around the fact that Python functions + are not always `fully curried `__. By + default, it is expected that the ``inner`` function will return a single object +@@ -1159,15 +1159,15 @@ + will be expanded before being passed to ``outer``. Put simply, :: + + compose(f, g)(5, 6) +- ++ + is equivalent to:: + + f(g(5, 6)) +- ++ + while :: + + compose(f, g, unpack=True)(5, 6) +- ++ + is equivalent to:: + + f(*g(5, 6)) +@@ -1178,20 +1178,20 @@ + ``functional`` and ``functools``). :: + + from functional import compose, partial +- ++ + multi_compose = partial(reduce, compose) +- +- ++ ++ + We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of + ``"".join(...)`` that converts its arguments to string:: + + from functional import compose, partial +- ++ + join = compose("".join, partial(map, str)) + + + ``flip(func)`` +- ++ + ``flip()`` wraps the callable in ``func`` and causes it to receive its + non-keyword arguments in reverse order. :: + +@@ -1206,7 +1206,7 @@ + (7, 6, 5) + + ``foldl(func, start, iterable)`` +- ++ + ``foldl()`` takes a binary function, a starting value (usually some kind of + 'zero'), and an iterable. The function is applied to the starting value and the + first element of the list, then the result of that and the second element of the +@@ -1220,7 +1220,7 @@ + + f(f(f(0, 1), 2), 3) + +- ++ + ``foldl()`` is roughly equivalent to the following recursive function:: + + def foldl(func, start, seq): +@@ -1298,7 +1298,7 @@ + Text Processing". + + Mertz also wrote a 3-part series of articles on functional programming +-for IBM's DeveloperWorks site; see ++for IBM's DeveloperWorks site; see + `part 1 `__, + `part 2 `__, and + `part 3 `__, +Index: Doc/howto/curses.rst +=================================================================== +--- Doc/howto/curses.rst (.../tags/r261) (Revision 70449) ++++ Doc/howto/curses.rst (.../branches/release26-maint) (Revision 70449) +@@ -297,7 +297,7 @@ + could code:: + + stdscr.addstr(0, 0, "Current mode: Typing mode", +- curses.A_REVERSE) ++ curses.A_REVERSE) + stdscr.refresh() + + The curses library also supports color on those terminals that provide it, The +@@ -399,8 +399,8 @@ + + curses.echo() # Enable echoing of characters + +- # Get a 15-character string, with the cursor on the top line +- s = stdscr.getstr(0,0, 15) ++ # Get a 15-character string, with the cursor on the top line ++ s = stdscr.getstr(0,0, 15) + + The Python :mod:`curses.textpad` module supplies something better. With it, you + can turn a window into a text box that supports an Emacs-like set of +Index: Doc/howto/unicode.rst +=================================================================== +--- Doc/howto/unicode.rst (.../tags/r261) (Revision 70449) ++++ Doc/howto/unicode.rst (.../branches/release26-maint) (Revision 70449) +@@ -30,8 +30,8 @@ + looking at Apple ][ BASIC programs, published in French-language publications in + the mid-1980s, that had lines like these:: + +- PRINT "FICHER EST COMPLETE." +- PRINT "CARACTERE NON ACCEPTE." ++ PRINT "FICHIER EST COMPLETE." ++ PRINT "CARACTERE NON ACCEPTE." + + Those messages should contain accents, and they just look wrong to someone who + can read French. +@@ -89,11 +89,11 @@ + character with value 0x12ca (4810 decimal). The Unicode standard contains a lot + of tables listing characters and their corresponding code points:: + +- 0061 'a'; LATIN SMALL LETTER A +- 0062 'b'; LATIN SMALL LETTER B +- 0063 'c'; LATIN SMALL LETTER C +- ... +- 007B '{'; LEFT CURLY BRACKET ++ 0061 'a'; LATIN SMALL LETTER A ++ 0062 'b'; LATIN SMALL LETTER B ++ 0063 'c'; LATIN SMALL LETTER C ++ ... ++ 007B '{'; LEFT CURLY BRACKET + + Strictly, these definitions imply that it's meaningless to say 'this is + character U+12ca'. U+12ca is a code point, which represents some particular +@@ -122,8 +122,8 @@ + representation, the string "Python" would look like this:: + + P y t h o n +- 0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00 +- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ++ 0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00 ++ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 + + This representation is straightforward but using it presents a number of + problems. +@@ -181,7 +181,7 @@ + between 128 and 255. + 3. Code points >0x7ff are turned into three- or four-byte sequences, where each + byte of the sequence is between 128 and 255. +- ++ + UTF-8 has several convenient properties: + + 1. It can handle any Unicode code point. +@@ -252,7 +252,7 @@ + >>> unicode('abcdef' + chr(255)) + Traceback (most recent call last): + File "", line 1, in ? +- UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6: ++ UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6: + ordinal not in range(128) + + The ``errors`` argument specifies the response when the input string can't be +@@ -264,7 +264,7 @@ + >>> unicode('\x80abc', errors='strict') + Traceback (most recent call last): + File "", line 1, in ? +- UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: ++ UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: + ordinal not in range(128) + >>> unicode('\x80abc', errors='replace') + u'\ufffdabc' +@@ -350,7 +350,7 @@ + >>> u2 = utf8_version.decode('utf-8') # Decode using UTF-8 + >>> u == u2 # The two strings match + True +- ++ + The low-level routines for registering and accessing the available encodings are + found in the :mod:`codecs` module. However, the encoding and decoding functions + returned by this module are usually more low-level than is comfortable, so I'm +@@ -362,8 +362,8 @@ + The most commonly used part of the :mod:`codecs` module is the + :func:`codecs.open` function which will be discussed in the section on input and + output. +- +- ++ ++ + Unicode Literals in Python Source Code + -------------------------------------- + +@@ -381,10 +381,10 @@ + + >>> s = u"a\xac\u1234\u20ac\U00008000" + ^^^^ two-digit hex escape +- ^^^^^^ four-digit Unicode escape ++ ^^^^^^ four-digit Unicode escape + ^^^^^^^^^^ eight-digit Unicode escape + >>> for c in s: print ord(c), +- ... ++ ... + 97 172 4660 8364 32768 + + Using escape sequences for code points greater than 127 is fine in small doses, +@@ -404,15 +404,15 @@ + + #!/usr/bin/env python + # -*- coding: latin-1 -*- +- ++ + u = u'abcdé' + print ord(u[-1]) +- ++ + The syntax is inspired by Emacs's notation for specifying variables local to a + file. Emacs supports many different variables, but Python only supports +-'coding'. The ``-*-`` symbols indicate that the comment is special; within +-them, you must supply the name ``coding`` and the name of your chosen encoding, +-separated by ``':'``. ++'coding'. The ``-*-`` symbols indicate to Emacs that the comment is special; ++they have no significance to Python but are a convention. Python looks for ++``coding: name`` or ``coding=name`` in the comment. + + If you don't include such a comment, the default encoding used will be ASCII. + Versions of Python before 2.4 were Euro-centric and assumed Latin-1 as a default +@@ -427,11 +427,11 @@ + When you run it with Python 2.4, it will output the following warning:: + + amk:~$ python p263.py +- sys:1: DeprecationWarning: Non-ASCII character '\xe9' +- in file p263.py on line 2, but no encoding declared; ++ sys:1: DeprecationWarning: Non-ASCII character '\xe9' ++ in file p263.py on line 2, but no encoding declared; + see http://www.python.org/peps/pep-0263.html for details +- + ++ + Unicode Properties + ------------------ + +@@ -446,13 +446,13 @@ + prints the numeric value of one particular character:: + + import unicodedata +- ++ + u = unichr(233) + unichr(0x0bf2) + unichr(3972) + unichr(6000) + unichr(13231) +- ++ + for i, c in enumerate(u): + print i, '%04x' % ord(c), unicodedata.category(c), + print unicodedata.name(c) +- ++ + # Get numeric value of second character + print unicodedata.numeric(u[1]) + +@@ -597,25 +597,25 @@ + path will return the 8-bit versions of the filenames. For example, assuming the + default filesystem encoding is UTF-8, running the following program:: + +- fn = u'filename\u4500abc' +- f = open(fn, 'w') +- f.close() ++ fn = u'filename\u4500abc' ++ f = open(fn, 'w') ++ f.close() + +- import os +- print os.listdir('.') +- print os.listdir(u'.') ++ import os ++ print os.listdir('.') ++ print os.listdir(u'.') + + will produce the following output:: + +- amk:~$ python t.py +- ['.svn', 'filename\xe4\x94\x80abc', ...] +- [u'.svn', u'filename\u4500abc', ...] ++ amk:~$ python t.py ++ ['.svn', 'filename\xe4\x94\x80abc', ...] ++ [u'.svn', u'filename\u4500abc', ...] + + The first list contains UTF-8-encoded filenames, and the second list contains + the Unicode versions. + + +- ++ + Tips for Writing Unicode-aware Programs + --------------------------------------- + +@@ -661,7 +661,7 @@ + unicode_name = filename.decode(encoding) + f = open(unicode_name, 'r') + # ... return contents of file ... +- ++ + However, if an attacker could specify the ``'base64'`` encoding, they could pass + ``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string + ``'/etc/passwd'``, to read a system file. The above code looks for ``'/'`` +@@ -697,32 +697,32 @@ + .. comment Describe obscure -U switch somewhere? + .. comment Describe use of codecs.StreamRecoder and StreamReaderWriter + +-.. comment ++.. comment + Original outline: + + - [ ] Unicode introduction + - [ ] ASCII + - [ ] Terms +- - [ ] Character +- - [ ] Code point +- - [ ] Encodings +- - [ ] Common encodings: ASCII, Latin-1, UTF-8 ++ - [ ] Character ++ - [ ] Code point ++ - [ ] Encodings ++ - [ ] Common encodings: ASCII, Latin-1, UTF-8 + - [ ] Unicode Python type +- - [ ] Writing unicode literals +- - [ ] Obscurity: -U switch +- - [ ] Built-ins +- - [ ] unichr() +- - [ ] ord() +- - [ ] unicode() constructor +- - [ ] Unicode type +- - [ ] encode(), decode() methods ++ - [ ] Writing unicode literals ++ - [ ] Obscurity: -U switch ++ - [ ] Built-ins ++ - [ ] unichr() ++ - [ ] ord() ++ - [ ] unicode() constructor ++ - [ ] Unicode type ++ - [ ] encode(), decode() methods + - [ ] Unicodedata module for character properties + - [ ] I/O +- - [ ] Reading/writing Unicode data into files +- - [ ] Byte-order marks +- - [ ] Unicode filenames ++ - [ ] Reading/writing Unicode data into files ++ - [ ] Byte-order marks ++ - [ ] Unicode filenames + - [ ] Writing Unicode programs +- - [ ] Do everything in Unicode +- - [ ] Declaring source code encodings (PEP 263) ++ - [ ] Do everything in Unicode ++ - [ ] Declaring source code encodings (PEP 263) + - [ ] Other issues +- - [ ] Building Python (UCS2, UCS4) ++ - [ ] Building Python (UCS2, UCS4) +Index: Doc/howto/webservers.rst +=================================================================== +--- Doc/howto/webservers.rst (.../tags/r261) (Revision 70449) ++++ Doc/howto/webservers.rst (.../branches/release26-maint) (Revision 70449) +@@ -88,7 +88,7 @@ + `_ with some additional information + about CGI in Python. + +- ++ + Simple script for testing CGI + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +@@ -99,7 +99,8 @@ + # -*- coding: UTF-8 -*- + + # enable debugging +- import cgitb; cgitb.enable() ++ import cgitb ++ cgitb.enable() + + print "Content-Type: text/plain;charset=utf-8" + print +@@ -386,7 +387,7 @@ + + You might be interested in some WSGI-supporting modules already contained in + the standard library, namely: +- ++ + * :mod:`wsgiref` -- some tiny utilities and servers for WSGI + + +@@ -499,7 +500,7 @@ + time in looking through the most popular ones. Some frameworks have their + own template engine or have a recommentation for one. It's wise to use + these. +- ++ + Popular template engines include: + + * Mako +@@ -687,7 +688,7 @@ + found in the Python wiki. + + .. seealso:: +- ++ + The Python wiki contains an extensive list of `web frameworks + `_. + +Index: Doc/tutorial/controlflow.rst +=================================================================== +--- Doc/tutorial/controlflow.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/controlflow.rst (.../branches/release26-maint) (Revision 70449) +@@ -62,7 +62,7 @@ + ... a = ['cat', 'window', 'defenestrate'] + >>> for x in a: + ... print x, len(x) +- ... ++ ... + cat 3 + window 6 + defenestrate 12 +@@ -75,7 +75,7 @@ + + >>> for x in a[:]: # make a slice copy of the entire list + ... if len(x) > 6: a.insert(0, x) +- ... ++ ... + >>> a + ['defenestrate', 'cat', 'window', 'defenestrate'] + +@@ -104,20 +104,23 @@ + >>> range(-10, -100, -30) + [-10, -40, -70] + +-To iterate over the indices of a sequence, combine :func:`range` and :func:`len` +-as follows:: ++To iterate over the indices of a sequence, you can combine :func:`range` and ++:func:`len` as follows:: + + >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] + >>> for i in range(len(a)): + ... print i, a[i] +- ... ++ ... + 0 Mary + 1 had + 2 a + 3 little + 4 lamb + ++In most such cases, however, it is convenient to use the :func:`enumerate` ++function, see :ref:`tut-loopidioms`. + ++ + .. _tut-break: + + :keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops +@@ -143,7 +146,7 @@ + ... else: + ... # loop fell through without finding a factor + ... print n, 'is a prime number' +- ... ++ ... + 2 is a prime number + 3 is a prime number + 4 equals 2 * 2 +@@ -164,44 +167,22 @@ + + >>> while True: + ... pass # Busy-wait for keyboard interrupt (Ctrl+C) +- ... ++ ... + +-This is commonly used for creating minimal classes such as exceptions, or +-for ignoring unwanted exceptions:: ++This is commonly used for creating minimal classes:: + +- >>> class ParserError(Exception): ++ >>> class MyEmptyClass: + ... pass +- ... +- >>> try: +- ... import audioop +- ... except ImportError: +- ... pass +- ... ++ ... + + Another place :keyword:`pass` can be used is as a place-holder for a function or +-conditional body when you are working on new code, allowing you to keep +-thinking at a more abstract level. However, as :keyword:`pass` is silently +-ignored, a better choice may be to raise a :exc:`NotImplementedError` +-exception:: ++conditional body when you are working on new code, allowing you to keep thinking ++at a more abstract level. The :keyword:`pass` is silently ignored:: + + >>> def initlog(*args): +- ... raise NotImplementedError # Open logfile if not already open +- ... if not logfp: +- ... raise NotImplementedError # Set up dummy log back-end +- ... raise NotImplementedError('Call log initialization handler') +- ... ++ ... pass # Remember to implement this! ++ ... + +-If :keyword:`pass` were used here and you later ran tests, they may fail +-without indicating why. Using :exc:`NotImplementedError` causes this code +-to raise an exception, telling you exactly where the incomplete code +-is. Note the two calling styles of the exceptions above. +-The first style, with no message but with an accompanying comment, +-lets you easily leave the comment when you remove the exception, +-which ideally would be a good description for +-the block of code the exception is a placeholder for. However, the +-third example, providing a message for the exception, will produce +-a more useful traceback. +- + .. _tut-functions: + + Defining Functions +@@ -216,7 +197,7 @@ + ... while b < n: + ... print b, + ... a, b = b, a+b +- ... ++ ... + >>> # Now call the function we just defined: + ... fib(2000) + 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 +@@ -287,7 +268,7 @@ + ... result.append(b) # see below + ... a, b = b, a+b + ... return result +- ... ++ ... + >>> f100 = fib2(100) # call it + >>> f100 # write the result + [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] +@@ -422,7 +403,7 @@ + + >>> def function(a): + ... pass +- ... ++ ... + >>> function(0, a=0) + Traceback (most recent call last): + File "", line 1, in ? +@@ -475,7 +456,7 @@ + ------------------------ + + .. index:: +- statement: * ++ statement: * + + Finally, the least frequently used option is to specify that a function can be + called with an arbitrary number of arguments. These arguments will be wrapped +@@ -584,11 +565,11 @@ + + >>> def my_function(): + ... """Do nothing, but document it. +- ... ++ ... + ... No, really, it doesn't do anything. + ... """ + ... pass +- ... ++ ... + >>> print my_function.__doc__ + Do nothing, but document it. + +Index: Doc/tutorial/modules.rst +=================================================================== +--- Doc/tutorial/modules.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/modules.rst (.../branches/release26-maint) (Revision 70449) +@@ -281,7 +281,7 @@ + ['__name__', 'fib', 'fib2'] + >>> dir(sys) + ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', +- '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', ++ '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', + 'builtin_module_names', 'byteorder', 'callstats', 'copyright', + 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', + 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags', +@@ -314,7 +314,7 @@ + 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError', + 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', + 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', +- 'NotImplementedError', 'OSError', 'OverflowError', ++ 'NotImplementedError', 'OSError', 'OverflowError', + 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', + 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', + 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', +Index: Doc/tutorial/errors.rst +=================================================================== +--- Doc/tutorial/errors.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/errors.rst (.../branches/release26-maint) (Revision 70449) +@@ -91,7 +91,7 @@ + ... break + ... except ValueError: + ... print "Oops! That was no valid number. Try again..." +- ... ++ ... + + The :keyword:`try` statement works as follows. + +@@ -199,12 +199,12 @@ + + >>> def this_fails(): + ... x = 1/0 +- ... ++ ... + >>> try: + ... this_fails() + ... except ZeroDivisionError as detail: + ... print 'Handling run-time error:', detail +- ... ++ ... + Handling run-time error: integer division or modulo by zero + + +@@ -256,12 +256,12 @@ + ... self.value = value + ... def __str__(self): + ... return repr(self.value) +- ... ++ ... + >>> try: + ... raise MyError(2*2) + ... except MyError as e: + ... print 'My exception occurred, value:', e.value +- ... ++ ... + My exception occurred, value: 4 + >>> raise MyError, 'oops!' + Traceback (most recent call last): +@@ -331,7 +331,7 @@ + ... raise KeyboardInterrupt + ... finally: + ... print 'Goodbye, world!' +- ... ++ ... + Goodbye, world! + Traceback (most recent call last): + File "", line 2, in ? +Index: Doc/tutorial/classes.rst +=================================================================== +--- Doc/tutorial/classes.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/classes.rst (.../branches/release26-maint) (Revision 70449) +@@ -250,7 +250,7 @@ + ... def __init__(self, realpart, imagpart): + ... self.r = realpart + ... self.i = imagpart +- ... ++ ... + >>> x = Complex(3.0, -4.5) + >>> x.r, x.i + (3.0, -4.5) +@@ -481,9 +481,9 @@ + ``issubclass(unicode, str)`` is ``False`` since :class:`unicode` is not a + subclass of :class:`str` (they only share a common ancestor, + :class:`basestring`). +- + + ++ + .. _tut-multiple: + + Multiple Inheritance +@@ -743,7 +743,7 @@ + f + l + o +- g ++ g + + Anything that can be done with generators can also be done with class based + iterators as described in the previous section. What makes generators so +Index: Doc/tutorial/datastructures.rst +=================================================================== +--- Doc/tutorial/datastructures.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/datastructures.rst (.../branches/release26-maint) (Revision 70449) +@@ -214,7 +214,7 @@ + >>> def sum(seq): + ... def add(x,y): return x+y + ... return reduce(add, seq, 0) +- ... ++ ... + >>> sum(range(1, 11)) + 55 + >>> sum([]) +@@ -251,7 +251,7 @@ + [] + >>> [[x,x**2] for x in vec] + [[2, 4], [4, 16], [6, 36]] +- >>> [x, x**2 for x in vec] # error - parens required for tuples ++ >>> [x, x**2 for x in vec] # error - parens required for tuples + File "", line 1, in ? + [x, x**2 for x in vec] + ^ +@@ -281,7 +281,7 @@ + powerful tool but -- like all powerful tools -- they need to be used carefully, + if at all. + +-Consider the following example of a 3x3 matrix held as a list containing three ++Consider the following example of a 3x3 matrix held as a list containing three + lists, one list per row:: + + >>> mat = [ +@@ -290,7 +290,7 @@ + ... [7, 8, 9], + ... ] + +-Now, if you wanted to swap rows and columns, you could use a list ++Now, if you wanted to swap rows and columns, you could use a list + comprehension:: + + >>> print [[row[i] for row in mat] for i in [0, 1, 2]] +@@ -308,7 +308,7 @@ + print row[i], + print + +-In real world, you should prefer builtin functions to complex flow statements. ++In real world, you should prefer builtin functions to complex flow statements. + The :func:`zip` function would do a great job for this use case:: + + >>> zip(*mat) +@@ -551,7 +551,7 @@ + >>> answers = ['lancelot', 'the holy grail', 'blue'] + >>> for q, a in zip(questions, answers): + ... print 'What is your {0}? It is {1}.'.format(q, a) +- ... ++ ... + What is your name? It is lancelot. + What is your quest? It is the holy grail. + What is your favorite color? It is blue. +@@ -574,7 +574,7 @@ + >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] + >>> for f in sorted(set(basket)): + ... print f +- ... ++ ... + apple + banana + orange +Index: Doc/tutorial/inputoutput.rst +=================================================================== +--- Doc/tutorial/inputoutput.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/inputoutput.rst (.../branches/release26-maint) (Revision 70449) +@@ -87,7 +87,7 @@ + + >>> for x in range(1,11): + ... print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) +- ... ++ ... + 1 1 1 + 2 4 8 + 3 9 27 +@@ -148,7 +148,7 @@ + ... other='Georg') + The story of Bill, Manfred, and Georg. + +-An optional ``':``` and format specifier can follow the field name. This also ++An optional ``':'`` and format specifier can follow the field name. This also + greater control over how the value is formatted. The following example + truncates the Pi to three places after the decimal. + +@@ -162,7 +162,7 @@ + >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} + >>> for name, phone in table.items(): + ... print '{0:10} ==> {1:10d}'.format(name, phone) +- ... ++ ... + Jack ==> 4098 + Dcab ==> 7678 + Sjoerd ==> 4127 +@@ -330,7 +330,7 @@ + >>> f = open('/tmp/workfile', 'r+') + >>> f.write('0123456789abcdef') + >>> f.seek(5) # Go to the 6th byte in the file +- >>> f.read(1) ++ >>> f.read(1) + '5' + >>> f.seek(-3, 2) # Go to the 3rd byte before the end + >>> f.read(1) +Index: Doc/tutorial/introduction.rst +=================================================================== +--- Doc/tutorial/introduction.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/introduction.rst (.../branches/release26-maint) (Revision 70449) +@@ -84,7 +84,7 @@ + + >>> # try to access an undefined variable + ... n +- Traceback (most recent call last): ++ Traceback (most recent call last): + File "", line 1, in + NameError: name 'n' is not defined + +@@ -219,14 +219,14 @@ + they will be included in the string. :: + + print """ +- Usage: thingy [OPTIONS] ++ Usage: thingy [OPTIONS] + -h Display this usage message + -H hostname Hostname to connect to + """ + + produces the following output:: + +- Usage: thingy [OPTIONS] ++ Usage: thingy [OPTIONS] + -h Display this usage message + -H hostname Hostname to connect to + +@@ -350,10 +350,10 @@ + Then the right edge of the last character of a string of *n* characters has + index *n*, for example:: + +- +---+---+---+---+---+ ++ +---+---+---+---+---+ + | H | e | l | p | A | +- +---+---+---+---+---+ +- 0 1 2 3 4 5 ++ +---+---+---+---+---+ ++ 0 1 2 3 4 5 + -5 -4 -3 -2 -1 + + The first row of numbers gives the position of the indices 0...5 in the string; +@@ -595,7 +595,7 @@ + >>> while b < 10: + ... print b + ... a, b = b, a+b +- ... ++ ... + 1 + 1 + 2 +@@ -645,7 +645,7 @@ + >>> while b < 1000: + ... print b, + ... a, b = b, a+b +- ... ++ ... + 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 + + Note that the interpreter inserts a newline before it prints the next prompt if +Index: Doc/tutorial/stdlib.rst +=================================================================== +--- Doc/tutorial/stdlib.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/stdlib.rst (.../branches/release26-maint) (Revision 70449) +@@ -136,7 +136,7 @@ + >>> random.random() # random float + 0.17970987693706186 + >>> random.randrange(6) # random integer chosen from range(6) +- 4 ++ 4 + + + .. _tut-internet-access: +Index: Doc/tutorial/interpreter.rst +=================================================================== +--- Doc/tutorial/interpreter.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/interpreter.rst (.../branches/release26-maint) (Revision 70449) +@@ -112,7 +112,7 @@ + >>> the_world_is_flat = 1 + >>> if the_world_is_flat: + ... print "Be careful not to fall off!" +- ... ++ ... + Be careful not to fall off! + + +@@ -180,7 +180,7 @@ + best way to do it is to put one more special comment line right after the ``#!`` + line to define the source file encoding:: + +- # -*- coding: encoding -*- ++ # -*- coding: encoding -*- + + + With that declaration, all characters in the source file will be treated as +Index: Doc/tutorial/stdlib2.rst +=================================================================== +--- Doc/tutorial/stdlib2.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/stdlib2.rst (.../branches/release26-maint) (Revision 70449) +@@ -62,7 +62,7 @@ + >>> locale.format("%d", x, grouping=True) + '1,234,567' + >>> locale.format("%s%.*f", (conv['currency_symbol'], +- ... conv['frac_digits'], x), grouping=True) ++ ... conv['frac_digits'], x), grouping=True) + '$1,234,567.80' + + +Index: Doc/tutorial/index.rst +=================================================================== +--- Doc/tutorial/index.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/index.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,7 +1,7 @@ + .. _tutorial-index: + + ###################### +- The Python Tutorial ++ The Python Tutorial + ###################### + + :Release: |version| +Index: Doc/tutorial/whatnow.rst +=================================================================== +--- Doc/tutorial/whatnow.rst (.../tags/r261) (Revision 70449) ++++ Doc/tutorial/whatnow.rst (.../branches/release26-maint) (Revision 70449) +@@ -63,6 +63,6 @@ + + .. Postings figure based on average of last six months activity as + reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182 +- days = 116.9 msgs / day and steadily increasing. (XXX up to date figures?) ++ days = 116.9 msgs / day and steadily increasing. (XXX up to date figures?) + + +Index: Doc/library/email.mime.rst +=================================================================== +--- Doc/library/email.mime.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/email.mime.rst (.../branches/release26-maint) (Revision 70449) +@@ -2,7 +2,7 @@ + ---------------------------------------------------------- + + .. module:: email.mime +- :synopsis: Build MIME messages. ++ :synopsis: Build MIME messages. + + + Ordinarily, you get a message object structure by passing a file or some text to +@@ -19,6 +19,7 @@ + + Here are the classes: + ++.. currentmodule:: email.mime.base + + .. class:: MIMEBase(_maintype, _subtype, **_params) + +@@ -39,6 +40,8 @@ + :mailheader:`MIME-Version` header (always set to ``1.0``). + + ++.. currentmodule:: email.mime.nonmultipart ++ + .. class:: MIMENonMultipart() + + Module: :mod:`email.mime.nonmultipart` +@@ -52,14 +55,16 @@ + .. versionadded:: 2.2.2 + + +-.. class:: MIMEMultipart([subtype[, boundary[, _subparts[, _params]]]]) ++.. currentmodule:: email.mime.multipart + ++.. class:: MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]) ++ + Module: :mod:`email.mime.multipart` + + A subclass of :class:`MIMEBase`, this is an intermediate base class for MIME + messages that are :mimetype:`multipart`. Optional *_subtype* defaults to + :mimetype:`mixed`, but can be used to specify the subtype of the message. A +- :mailheader:`Content-Type` header of :mimetype:`multipart/`*_subtype* will be ++ :mailheader:`Content-Type` header of :mimetype:`multipart/_subtype` will be + added to the message object. A :mailheader:`MIME-Version` header will also be + added. + +@@ -77,6 +82,8 @@ + .. versionadded:: 2.2.2 + + ++.. currentmodule:: email.mime.application ++ + .. class:: MIMEApplication(_data[, _subtype[, _encoder[, **_params]]]) + + Module: :mod:`email.mime.application` +@@ -99,6 +106,8 @@ + .. versionadded:: 2.5 + + ++.. currentmodule:: email.mime.audio ++ + .. class:: MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]) + + Module: :mod:`email.mime.audio` +@@ -122,6 +131,8 @@ + *_params* are passed straight through to the base class constructor. + + ++.. currentmodule:: email.mime.image ++ + .. class:: MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]]) + + Module: :mod:`email.mime.image` +@@ -145,6 +156,8 @@ + *_params* are passed straight through to the :class:`MIMEBase` constructor. + + ++.. currentmodule:: email.mime.message ++ + .. class:: MIMEMessage(_msg[, _subtype]) + + Module: :mod:`email.mime.message` +@@ -158,6 +171,8 @@ + :mimetype:`rfc822`. + + ++.. currentmodule:: email.mime.text ++ + .. class:: MIMEText(_text[, _subtype[, _charset]]) + + Module: :mod:`email.mime.text` +Index: Doc/library/subprocess.rst +=================================================================== +--- Doc/library/subprocess.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/subprocess.rst (.../branches/release26-maint) (Revision 70449) +@@ -73,13 +73,13 @@ + specified by the :envvar:`COMSPEC` environment variable. + + *stdin*, *stdout* and *stderr* specify the executed programs' standard input, +- standard output and standard error file handles, respectively. Valid values are +- ``PIPE``, an existing file descriptor (a positive integer), an existing file +- object, and ``None``. ``PIPE`` indicates that a new pipe to the child should be +- created. With ``None``, no redirection will occur; the child's file handles +- will be inherited from the parent. Additionally, *stderr* can be ``STDOUT``, +- which indicates that the stderr data from the applications should be captured +- into the same file handle as for stdout. ++ standard output and standard error file handles, respectively. Valid values ++ are :data:`PIPE`, an existing file descriptor (a positive integer), an ++ existing file object, and ``None``. :data:`PIPE` indicates that a new pipe ++ to the child should be created. With ``None``, no redirection will occur; ++ the child's file handles will be inherited from the parent. Additionally, ++ *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the ++ applications should be captured into the same file handle as for stdout. + + If *preexec_fn* is set to a callable object, this object will be called in the + child process just before the child is executed. (Unix only) +@@ -119,6 +119,20 @@ + of the main window and priority for the new process. (Windows only) + + ++.. data:: PIPE ++ ++ Special value that can be used as the *stdin*, *stdout* or *stderr* argument ++ to :class:`Popen` and indicates that a pipe to the standard stream should be ++ opened. ++ ++ ++.. data:: STDOUT ++ ++ Special value that can be used as the *stderr* argument to :class:`Popen` and ++ indicates that standard error should go into the same handle as standard ++ output. ++ ++ + Convenience Functions + ^^^^^^^^^^^^^^^^^^^^^ + +@@ -207,7 +221,7 @@ + *input* argument should be a string to be sent to the child process, or + ``None``, if no data should be sent to the child. + +- :meth:`communicate` returns a tuple ``(stdout, stderr)``. ++ :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``. + + Note that if you want to send data to the process's stdin, you need to create + the Popen object with ``stdin=PIPE``. Similarly, to get anything other than +@@ -261,20 +275,21 @@ + + .. attribute:: Popen.stdin + +- If the *stdin* argument is ``PIPE``, this attribute is a file object that +- provides input to the child process. Otherwise, it is ``None``. ++ If the *stdin* argument was :data:`PIPE`, this attribute is a file object ++ that provides input to the child process. Otherwise, it is ``None``. + + + .. attribute:: Popen.stdout + +- If the *stdout* argument is ``PIPE``, this attribute is a file object that +- provides output from the child process. Otherwise, it is ``None``. ++ If the *stdout* argument was :data:`PIPE`, this attribute is a file object ++ that provides output from the child process. Otherwise, it is ``None``. + + + .. attribute:: Popen.stderr + +- If the *stderr* argument is ``PIPE``, this attribute is file object that +- provides error output from the child process. Otherwise, it is ``None``. ++ If the *stderr* argument was :data:`PIPE`, this attribute is a file object ++ that provides error output from the child process. Otherwise, it is ++ ``None``. + + + .. attribute:: Popen.pid +@@ -287,7 +302,7 @@ + The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly + by :meth:`communicate`). A ``None`` value indicates that the process + hasn't terminated yet. +- ++ + A negative value ``-N`` indicates that the child was terminated by signal + ``N`` (Unix only). + +@@ -358,8 +373,8 @@ + print >>sys.stderr, "Execution failed:", e + + +-Replacing os.spawn\* +-^^^^^^^^^^^^^^^^^^^^ ++Replacing the os.spawn family ++^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + P_NOWAIT example:: + +@@ -386,8 +401,8 @@ + Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) + + +-Replacing os.popen\* +-^^^^^^^^^^^^^^^^^^^^ ++Replacing os.popen, os.popen2, os.popen3 ++^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + :: + +@@ -430,8 +445,8 @@ + (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) + + +-Replacing popen2.\* +-^^^^^^^^^^^^^^^^^^^ ++Replacing functions from the popen2 module ++^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + .. note:: + +@@ -454,15 +469,15 @@ + stdin=PIPE, stdout=PIPE, close_fds=True) + (child_stdout, child_stdin) = (p.stdout, p.stdin) + +-The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen, except +-that: ++:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as ++:class:`subprocess.Popen`, except that: + +-* subprocess.Popen raises an exception if the execution fails ++* :class:`Popen` raises an exception if the execution fails. + + * the *capturestderr* argument is replaced with the *stderr* argument. + +-* stdin=PIPE and stdout=PIPE must be specified. ++* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified. + + * popen2 closes all file descriptors by default, but you have to specify +- close_fds=True with subprocess.Popen. ++ ``close_fds=True`` with :class:`Popen`. + +Index: Doc/library/new.rst +=================================================================== +--- Doc/library/new.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/new.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,4 +1,3 @@ +- + :mod:`new` --- Creation of runtime internal objects + =================================================== + +@@ -7,7 +6,8 @@ + :deprecated: + + .. deprecated:: 2.6 +- The :mod:`new` module has been removed in Python 3.0. ++ The :mod:`new` module has been removed in Python 3.0. Use the :mod:`types` ++ module's classes instead. + + .. sectionauthor:: Moshe Zadka + +Index: Doc/library/csv.rst +=================================================================== +--- Doc/library/csv.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/csv.rst (.../branches/release26-maint) (Revision 70449) +@@ -76,7 +76,7 @@ + performed. + + A short usage example:: +- ++ + >>> import csv + >>> spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|') + >>> for row in spamReader: +Index: Doc/library/datetime.rst +=================================================================== +--- Doc/library/datetime.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/datetime.rst (.../branches/release26-maint) (Revision 70449) +@@ -266,10 +266,10 @@ + considered to be true if and only if it isn't equal to ``timedelta(0)``. + + Example usage: +- ++ + >>> from datetime import timedelta + >>> year = timedelta(days=365) +- >>> another_year = timedelta(weeks=40, days=84, hours=23, ++ >>> another_year = timedelta(weeks=40, days=84, hours=23, + ... minutes=50, seconds=600) # adds up to 365 days + >>> year == another_year + True +@@ -517,10 +517,10 @@ + True + >>> my_birthday = date(today.year, 6, 24) + >>> if my_birthday < today: +- ... my_birthday = my_birthday.replace(year=today.year + 1) ++ ... my_birthday = my_birthday.replace(year=today.year + 1) + >>> my_birthday + datetime.date(2008, 6, 24) +- >>> time_to_birthday = abs(my_birthday - today) ++ >>> time_to_birthday = abs(my_birthday - today) + >>> time_to_birthday.days + 202 + +@@ -1015,7 +1015,7 @@ + >>> tt = dt.timetuple() + >>> for it in tt: # doctest: +SKIP + ... print it +- ... ++ ... + 2006 # year + 11 # month + 21 # day +@@ -1044,23 +1044,23 @@ + ... def __init__(self): # DST starts last Sunday in March + ... d = datetime(dt.year, 4, 1) # ends last Sunday in October + ... self.dston = d - timedelta(days=d.weekday() + 1) +- ... d = datetime(dt.year, 11, 1) ++ ... d = datetime(dt.year, 11, 1) + ... self.dstoff = d - timedelta(days=d.weekday() + 1) + ... def utcoffset(self, dt): + ... return timedelta(hours=1) + self.dst(dt) +- ... def dst(self, dt): ++ ... def dst(self, dt): + ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff: + ... return timedelta(hours=1) + ... else: + ... return timedelta(0) + ... def tzname(self,dt): + ... return "GMT +1" +- ... ++ ... + >>> class GMT2(tzinfo): + ... def __init__(self): +- ... d = datetime(dt.year, 4, 1) ++ ... d = datetime(dt.year, 4, 1) + ... self.dston = d - timedelta(days=d.weekday() + 1) +- ... d = datetime(dt.year, 11, 1) ++ ... d = datetime(dt.year, 11, 1) + ... self.dstoff = d - timedelta(days=d.weekday() + 1) + ... def utcoffset(self, dt): + ... return timedelta(hours=1) + self.dst(dt) +@@ -1071,7 +1071,7 @@ + ... return timedelta(0) + ... def tzname(self,dt): + ... return "GMT +2" +- ... ++ ... + >>> gmt1 = GMT1() + >>> # Daylight Saving Time + >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1) +@@ -1092,9 +1092,9 @@ + datetime.datetime(2006, 6, 14, 13, 0, tzinfo=) + >>> dt2.utctimetuple() == dt3.utctimetuple() + True +- + + ++ + .. _datetime-time: + + :class:`time` Objects +@@ -1240,12 +1240,12 @@ + return ``None`` or a string object. + + Example: +- ++ + >>> from datetime import time, tzinfo + >>> class GMT1(tzinfo): + ... def utcoffset(self, dt): +- ... return timedelta(hours=1) +- ... def dst(self, dt): ++ ... return timedelta(hours=1) ++ ... def dst(self, dt): + ... return timedelta(0) + ... def tzname(self,dt): + ... return "Europe/Prague" +@@ -1269,7 +1269,7 @@ + :class:`tzinfo` Objects + ----------------------- + +-:class:`tzinfo` is an abstract base clase, meaning that this class should not be ++:class:`tzinfo` is an abstract base class, meaning that this class should not be + instantiated directly. You need to derive a concrete subclass, and (at least) + supply implementations of the standard :class:`tzinfo` methods needed by the + :class:`datetime` methods you use. The :mod:`datetime` module does not supply +@@ -1476,8 +1476,8 @@ + :class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any + other fixed-offset :class:`tzinfo` subclass (such as a class representing only + EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)). +- + ++ + .. _strftime-behavior: + + :meth:`strftime` Behavior +@@ -1497,11 +1497,10 @@ + microseconds should not be used, as :class:`date` objects have no such + values. If they're used anyway, ``0`` is substituted for them. + +-:class:`time` and :class:`datetime` objects support a ``%f`` format code +-which expands to the number of microseconds in the object, zero-padded on +-the left to six places. +- + .. versionadded:: 2.6 ++ :class:`time` and :class:`datetime` objects support a ``%f`` format code ++ which expands to the number of microseconds in the object, zero-padded on ++ the left to six places. + + For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty + strings. +@@ -1521,7 +1520,7 @@ + + The full set of format codes supported varies across platforms, because Python + calls the platform C library's :func:`strftime` function, and platform +-variations are common. ++variations are common. + + The following is a list of all the format codes that the C standard (1989 + version) requires, and these work on all platforms with a standard C +@@ -1621,7 +1620,9 @@ + (1) + When used with the :func:`strptime` function, the ``%f`` directive + accepts from one to six digits and zero pads on the right. ``%f`` is +- an extension to the set of format characters in the C standard. ++ an extension to the set of format characters in the C standard (but ++ implemented separately in datetime objects, and therefore always ++ available). + + (2) + When used with the :func:`strptime` function, the ``%p`` directive only affects +Index: Doc/library/stringio.rst +=================================================================== +--- Doc/library/stringio.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/stringio.rst (.../branches/release26-maint) (Revision 70449) +@@ -37,7 +37,8 @@ + + .. method:: StringIO.close() + +- Free the memory buffer. ++ Free the memory buffer. Attempting to do further operations with a closed ++ :class:`StringIO` object will raise a :exc:`ValueError`. + + Example usage:: + +@@ -51,7 +52,7 @@ + # 'First line.\nSecond line.\n' + contents = output.getvalue() + +- # Close object and discard memory buffer -- ++ # Close object and discard memory buffer -- + # .getvalue() will now raise an exception. + output.close() + +@@ -80,7 +81,7 @@ + + Calling :func:`StringIO` with a Unicode string parameter populates + the object with the buffer representation of the Unicode string, instead of +-encoding the string. ++encoding the string. + + Another difference from the :mod:`StringIO` module is that calling + :func:`StringIO` with a string parameter creates a read-only object. Unlike an +@@ -117,7 +118,7 @@ + # 'First line.\nSecond line.\n' + contents = output.getvalue() + +- # Close object and discard memory buffer -- ++ # Close object and discard memory buffer -- + # .getvalue() will now raise an exception. + output.close() + +Index: Doc/library/aifc.rst +=================================================================== +--- Doc/library/aifc.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/aifc.rst (.../branches/release26-maint) (Revision 70449) +@@ -17,7 +17,7 @@ + ability to compress the audio data. + + .. warning:: +- ++ + Some operations may only work under IRIX; these will raise :exc:`ImportError` + when attempting to import the :mod:`cl` module, which is only available on IRIX. + +Index: Doc/library/ctypes.rst +=================================================================== +--- Doc/library/ctypes.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/ctypes.rst (.../branches/release26-maint) (Revision 70449) +@@ -1274,6 +1274,7 @@ + + + .. data:: find_library(name) ++ :module: ctypes.util + :noindex: + + Try to find a library and return a pathname. *name* is the library name without +@@ -1370,7 +1371,7 @@ + + All these classes can be instantiated by calling them with at least one + argument, the pathname of the shared library. If you have an existing handle to +-an already loaded shard library, it can be passed as the ``handle`` named ++an already loaded shared library, it can be passed as the ``handle`` named + parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary` + function is used to load the library into the process, and to get a handle to + it. +@@ -1378,24 +1379,22 @@ + The *mode* parameter can be used to specify how the library is loaded. For + details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored. + +-The *use_errno* parameter, when set to True, enables a ctypes +-mechanism that allows to access the system `errno` error number in a +-safe way. `ctypes` maintains a thread-local copy of the systems +-`errno` variable; if you call foreign functions created with +-`use_errno=True` then the `errno` value before the function call is +-swapped with the ctypes private copy, the same happens immediately +-after the function call. ++The *use_errno* parameter, when set to True, enables a ctypes mechanism that ++allows to access the system :data:`errno` error number in a safe way. ++:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno` ++variable; if you call foreign functions created with ``use_errno=True`` then the ++:data:`errno` value before the function call is swapped with the ctypes private ++copy, the same happens immediately after the function call. + +-The function `ctypes.get_errno()` returns the value of the ctypes +-private copy, and the function `ctypes.set_errno(value)` changes the +-ctypes private copy to `value` and returns the former value. ++The function :func:`ctypes.get_errno` returns the value of the ctypes private ++copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy ++to a new value and returns the former value. + +-The *use_last_error* parameter, when set to True, enables the same +-mechanism for the Windows error code which is managed by the +-:func:`GetLastError` and :func:`SetLastError` Windows API functions; +-`ctypes.get_last_error()` and `ctypes.set_last_error(value)` are used +-to request and change the ctypes private copy of the windows error +-code. ++The *use_last_error* parameter, when set to True, enables the same mechanism for ++the Windows error code which is managed by the :func:`GetLastError` and ++:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and ++:func:`ctypes.set_last_error` are used to request and change the ctypes private ++copy of the windows error code. + + .. versionadded:: 2.6 + The ``use_last_error`` and ``use_errno`` optional parameters +@@ -1602,22 +1601,23 @@ + .. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) + + 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 `errno` +- variable is exchanged with the real `errno` value bafore and after the call; +- `use_last_error` does the same for the Windows error code. ++ 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 ++ and after the call; *use_last_error* does the same for the Windows error ++ code. + + .. versionchanged:: 2.6 +- The optional `use_errno` and `use_last_error` parameters were +- added. ++ The optional *use_errno* and *use_last_error* parameters were added. + + + .. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) + + Windows only: The returned function prototype creates functions that use the +- ``stdcall`` calling convention, except on Windows CE where :func:`WINFUNCTYPE` +- is the same as :func:`CFUNCTYPE`. The function will release the GIL during the +- call. `use_errno` and `use_last_error` have the same meaning as above. ++ ``stdcall`` calling convention, except on Windows CE where ++ :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will ++ release the GIL during the call. *use_errno* and *use_last_error* have the ++ same meaning as above. + + + .. function:: PYFUNCTYPE(restype, *argtypes) +@@ -1864,10 +1864,10 @@ + .. function:: find_library(name) + :module: ctypes.util + +- Try to find a library and return a pathname. `name` is the library name without +- any prefix like `lib`, suffix like ``.so``, ``.dylib`` or version number (this +- is the form used for the posix linker option :option:`-l`). If no library can +- be found, returns ``None``. ++ Try to find a library and return a pathname. *name* is the library name ++ without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version ++ number (this is the form used for the posix linker option :option:`-l`). If ++ no library can be found, returns ``None``. + + The exact functionality is system dependent. + +@@ -1905,14 +1905,14 @@ + .. function:: get_errno() + + Returns the current value of the ctypes-private copy of the system +- `errno` variable in the calling thread. ++ :data:`errno` variable in the calling thread. + + .. versionadded:: 2.6 + + .. function:: get_last_error() + + Windows only: returns the current value of the ctypes-private copy of the system +- `LastError` variable in the calling thread. ++ :data:`LastError` variable in the calling thread. + + .. versionadded:: 2.6 + +@@ -1969,17 +1969,16 @@ + + .. function:: set_errno(value) + +- Set the current value of the ctypes-private copy of the system +- `errno` variable in the calling thread to `value` and return the +- previous value. ++ Set the current value of the ctypes-private copy of the system :data:`errno` ++ variable in the calling thread to *value* and return the previous value. + + .. versionadded:: 2.6 + + .. function:: set_last_error(value) + +- Windows only: set the current value of the ctypes-private copy of +- the system `LastError` variable in the calling thread to `value` +- and return the previous value. ++ Windows only: set the current value of the ctypes-private copy of the system ++ :data:`LastError` variable in the calling thread to *value* and return the ++ previous value. + + .. versionadded:: 2.6 + +Index: Doc/library/idle.rst +=================================================================== +--- Doc/library/idle.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/idle.rst (.../branches/release26-maint) (Revision 70449) +@@ -230,7 +230,7 @@ + Keywords + orange + +- Strings ++ Strings + green + + Comments +Index: Doc/library/rlcompleter.rst +=================================================================== +--- Doc/library/rlcompleter.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/rlcompleter.rst (.../branches/release26-maint) (Revision 70449) +@@ -61,6 +61,6 @@ + If called for a dotted name, it will try to evaluate anything without obvious + side-effects (functions will not be evaluated, but it can generate calls to + :meth:`__getattr__`) up to the last part, and find matches for the rest via the +- :func:`dir` function. Any exception raised during the evaluation of the ++ :func:`dir` function. Any exception raised during the evaluation of the + expression is caught, silenced and :const:`None` is returned. + +Index: Doc/library/htmllib.rst +=================================================================== +--- Doc/library/htmllib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/htmllib.rst (.../branches/release26-maint) (Revision 70449) +@@ -4,7 +4,7 @@ + .. module:: htmllib + :synopsis: A parser for HTML documents. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`htmllib` module has been removed in Python 3.0. + +Index: Doc/library/fl.rst +=================================================================== +--- Doc/library/fl.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/fl.rst (.../branches/release26-maint) (Revision 70449) +@@ -6,8 +6,8 @@ + :platform: IRIX + :synopsis: FORMS library for applications with graphical user interfaces. + :deprecated: +- +- ++ ++ + .. deprecated:: 2.6 + The :mod:`fl` module has been deprecated for removal in Python 3.0. + +@@ -484,8 +484,8 @@ + :platform: IRIX + :synopsis: Constants used with the fl module. + :deprecated: +- +- ++ ++ + .. deprecated:: 2.6 + The :mod:`FL` module has been deprecated for removal in Python 3.0. + +@@ -506,8 +506,8 @@ + :platform: IRIX + :synopsis: Functions for loading stored FORMS designs. + :deprecated: +- +- ++ ++ + .. deprecated:: 2.6 + The :mod:`flp` module has been deprecated for removal in Python 3.0. + +Index: Doc/library/re.rst +=================================================================== +--- Doc/library/re.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/re.rst (.../branches/release26-maint) (Revision 70449) +@@ -440,21 +440,25 @@ + + The sequence :: + +- prog = re.compile(pat) +- result = prog.match(str) ++ prog = re.compile(pattern) ++ result = prog.match(string) + + is equivalent to :: + +- result = re.match(pat, str) ++ result = re.match(pattern, string) + +- but the version using :func:`compile` is more efficient when the expression +- will be used several times in a single program. ++ but using :func:`compile` and saving the resulting regular expression object ++ for reuse is more efficient when the expression will be used several times ++ in a single program. + +- .. (The compiled version of the last pattern passed to :func:`re.match` or +- :func:`re.search` is cached, so programs that use only a single regular +- expression at a time needn't worry about compiling regular expressions.) ++ .. note:: + ++ The compiled versions of the most recent patterns passed to ++ :func:`re.match`, :func:`re.search` or :func:`re.compile` are cached, so ++ programs that use only a few regular expressions at a time needn't worry ++ about compiling regular expressions. + ++ + .. data:: I + IGNORECASE + +@@ -750,6 +754,11 @@ + were provided. + + ++.. attribute:: RegexObject.groups ++ ++ The number of capturing groups in the pattern. ++ ++ + .. attribute:: RegexObject.groupindex + + A dictionary mapping any symbolic group names defined by ``(?P)`` to group +@@ -989,14 +998,14 @@ + + >>> pair.match("717ak").group(1) + '7' +- ++ + # Error because re.match() returns None, which doesn't have a group() method: + >>> pair.match("718ak").group(1) + Traceback (most recent call last): + File "", line 1, in + re.match(r".*(.).*\1", "718ak").group(1) + AttributeError: 'NoneType' object has no attribute 'group' +- ++ + >>> pair.match("354aa").group(1) + 'a' + +@@ -1105,7 +1114,7 @@ + Making a Phonebook + ^^^^^^^^^^^^^^^^^^ + +-:func:`split` splits a string into a list delimited by the passed pattern. The ++:func:`split` splits a string into a list delimited by the passed pattern. The + method is invaluable for converting textual data into data structures that can be + easily read and modified by Python as demonstrated in the following example that + creates a phonebook. +@@ -1114,7 +1123,7 @@ + triple-quoted string syntax: + + >>> input = """Ross McFluff: 834.345.1254 155 Elm Street +- ... ++ ... + ... Ronald Heathmore: 892.345.3428 436 Finley Avenue + ... Frank Burger: 925.541.7625 662 South Dogwood Way + ... + +Eigenschaftsänderungen: Doc/library/plistlib.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/abc.rst +=================================================================== +--- Doc/library/abc.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/abc.rst (.../branches/release26-maint) (Revision 70449) +@@ -43,15 +43,15 @@ + Register *subclass* as a "virtual subclass" of this ABC. For + example:: + +- from abc import ABCMeta ++ from abc import ABCMeta + +- class MyABC: +- __metaclass__ = ABCMeta ++ class MyABC: ++ __metaclass__ = ABCMeta + +- MyABC.register(tuple) ++ MyABC.register(tuple) + +- assert issubclass(tuple, MyABC) +- assert isinstance((), MyABC) ++ assert issubclass(tuple, MyABC) ++ assert isinstance((), MyABC) + + You can also override this method in an abstract base class: + +@@ -130,7 +130,7 @@ + A decorator indicating abstract methods. + + Using this decorator requires that the class's metaclass is :class:`ABCMeta` or +- is derived from it. ++ is derived from it. + A class that has a metaclass derived from :class:`ABCMeta` + cannot be instantiated unless all of its abstract methods and + properties are overridden. +@@ -166,7 +166,7 @@ + A subclass of the built-in :func:`property`, indicating an abstract property. + + Using this function requires that the class's metaclass is :class:`ABCMeta` or +- is derived from it. ++ is derived from it. + A class that has a metaclass derived from :class:`ABCMeta` cannot be + instantiated unless all of its abstract methods and properties are overridden. + The abstract properties can be called using any of the normal + +Eigenschaftsänderungen: Doc/library/abc.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/cd.rst +=================================================================== +--- Doc/library/cd.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/cd.rst (.../branches/release26-maint) (Revision 70449) +@@ -6,8 +6,8 @@ + :platform: IRIX + :synopsis: Interface to the CD-ROM on Silicon Graphics systems. + :deprecated: +- +- ++ ++ + .. deprecated:: 2.6 + The :mod:`cd` module has been deprecated for removal in Python 3.0. + +Index: Doc/library/mailbox.rst +=================================================================== +--- Doc/library/mailbox.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/mailbox.rst (.../branches/release26-maint) (Revision 70449) +@@ -1686,7 +1686,7 @@ + # that's better than losing a message completely. + box.lock() + box.add(message) +- box.flush() ++ box.flush() + box.unlock() + + # Remove original message +Index: Doc/library/decimal.rst +=================================================================== +--- Doc/library/decimal.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/decimal.rst (.../branches/release26-maint) (Revision 70449) +@@ -328,7 +328,7 @@ + infinity ::= 'Infinity' | 'Inf' + nan ::= 'NaN' [digits] | 'sNaN' [digits] + numeric-value ::= decimal-part [exponent-part] | infinity +- numeric-string ::= [sign] numeric-value | [sign] nan ++ numeric-string ::= [sign] numeric-value | [sign] nan + + If *value* is a :class:`tuple`, it should have three components, a sign + (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of +@@ -947,7 +947,7 @@ + * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer), + * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or + * :const:`ROUND_UP` (away from zero). +- * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero ++ * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero + would have been 0 or 5; otherwise towards zero) + + The *traps* and *flags* fields list any signals to be set. Generally, new +@@ -1168,7 +1168,7 @@ + + .. method:: logical_and(x, y) + +- Applies the logical operation `and` between each operand's digits. ++ Applies the logical operation *and* between each operand's digits. + + + .. method:: logical_invert(x) +@@ -1178,12 +1178,12 @@ + + .. method:: logical_or(x, y) + +- Applies the logical operation `or` between each operand's digits. ++ Applies the logical operation *or* between each operand's digits. + + + .. method:: logical_xor(x, y) + +- Applies the logical operation `xor` between each operand's digits. ++ Applies the logical operation *xor* between each operand's digits. + + + .. method:: max(x, y) +@@ -1270,7 +1270,7 @@ + that would be obtained by computing ``(x**y) % modulo`` with unbounded + precision, but is computed more efficiently. It is always exact. + +- .. versionchanged:: 2.6 ++ .. versionchanged:: 2.6 + ``y`` may now be nonintegral in ``x**y``. + Stricter requirements for the three-argument version. + +@@ -1294,8 +1294,8 @@ + + .. method:: remainder_near(x, y) + +- Returns `x - y * n`, where *n* is the integer nearest the exact value +- of `x / y` (if the result is `0` then its sign will be the sign of *x*). ++ Returns ``x - y * n``, where *n* is the integer nearest the exact value ++ of ``x / y`` (if the result is 0 then its sign will be the sign of *x*). + + + .. method:: rotate(x, y) +@@ -1412,7 +1412,7 @@ + sqrt(-x) and x > 0 + 0 ** 0 + x ** (non-integer) +- x ** Infinity ++ x ** Infinity + + + .. class:: Overflow +@@ -1515,7 +1515,7 @@ + Decimal('9.51111111') + >>> u + (v + w) + Decimal('9.51111111') +- >>> ++ >>> + >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') + >>> (u*v) + (u*w) + Decimal('0.0060000') +@@ -1654,7 +1654,7 @@ + + """ + q = Decimal(10) ** -places # 2 places --> '0.01' +- sign, digits, exp = value.quantize(q).as_tuple() ++ sign, digits, exp = value.quantize(q).as_tuple() + result = [] + digits = map(str, digits) + build, next = result.append, digits.pop +@@ -1711,12 +1711,12 @@ + getcontext().prec += 2 + i, lasts, s, fact, num = 0, 0, 1, 1, 1 + while s != lasts: +- lasts = s ++ lasts = s + i += 1 + fact *= i +- num *= x +- s += num / fact +- getcontext().prec -= 2 ++ num *= x ++ s += num / fact ++ getcontext().prec -= 2 + return +s + + def cos(x): +@@ -1733,13 +1733,13 @@ + getcontext().prec += 2 + i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 + while s != lasts: +- lasts = s ++ lasts = s + i += 2 + fact *= i * (i-1) + num *= x * x + sign *= -1 +- s += num / fact * sign +- getcontext().prec -= 2 ++ s += num / fact * sign ++ getcontext().prec -= 2 + return +s + + def sin(x): +@@ -1756,13 +1756,13 @@ + getcontext().prec += 2 + i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1 + while s != lasts: +- lasts = s ++ lasts = s + i += 2 + fact *= i * (i-1) + num *= x * x + sign *= -1 +- s += num / fact * sign +- getcontext().prec -= 2 ++ s += num / fact * sign ++ getcontext().prec -= 2 + return +s + + +@@ -1796,7 +1796,7 @@ + >>> Decimal('3.214').quantize(TWOPLACES) + Decimal('3.21') + +- >>> # Validate that a number does not exceed two places ++ >>> # Validate that a number does not exceed two places + >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact])) + Decimal('3.21') + +@@ -1880,13 +1880,14 @@ + def float_to_decimal(f): + "Convert a floating point number to a Decimal with no loss of information" + n, d = f.as_integer_ratio() +- with localcontext() as ctx: +- ctx.traps[Inexact] = True +- while True: +- try: +- return Decimal(n) / Decimal(d) +- except Inexact: +- ctx.prec += 1 ++ numerator, denominator = Decimal(n), Decimal(d) ++ ctx = Context(prec=60) ++ result = ctx.divide(numerator, denominator) ++ while ctx.flags[Inexact]: ++ ctx.flags[Inexact] = False ++ ctx.prec *= 2 ++ result = ctx.divide(numerator, denominator) ++ return result + + .. doctest:: + +Index: Doc/library/pdb.rst +=================================================================== +--- Doc/library/pdb.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/pdb.rst (.../branches/release26-maint) (Revision 70449) +@@ -37,7 +37,7 @@ + (Pdb) continue + NameError: 'spam' + > (1)?() +- (Pdb) ++ (Pdb) + + :file:`pdb.py` can also be invoked as a script to debug other scripts. For + example:: +@@ -68,7 +68,7 @@ + >>> pdb.pm() + > ./mymodule.py(3)test2() + -> print spam +- (Pdb) ++ (Pdb) + + The module defines the following functions; each enters the debugger in a + slightly different way: +@@ -109,7 +109,7 @@ + + .. function:: post_mortem([traceback]) + +- Enter post-mortem debugging of the given *traceback* object. If no ++ Enter post-mortem debugging of the given *traceback* object. If no + *traceback* is given, it uses the one of the exception that is currently + being handled (an exception must be being handled if the default is to be + used). +@@ -351,68 +351,3 @@ + + q(uit) + Quit from the debugger. The program being executed is aborted. +- +- +-.. _debugger-hooks: +- +-How It Works +-============ +- +-Some changes were made to the interpreter: +- +-* ``sys.settrace(func)`` sets the global trace function +- +-* there can also a local trace function (see later) +- +-Trace functions have three arguments: *frame*, *event*, and *arg*. *frame* is +-the current stack frame. *event* is a string: ``'call'``, ``'line'``, +-``'return'``, ``'exception'``, ``'c_call'``, ``'c_return'``, or +-``'c_exception'``. *arg* depends on the event type. +- +-The global trace function is invoked (with *event* set to ``'call'``) whenever a +-new local scope is entered; it should return a reference to the local trace +-function to be used that scope, or ``None`` if the scope shouldn't be traced. +- +-The local trace function should return a reference to itself (or to another +-function for further tracing in that scope), or ``None`` to turn off tracing in +-that scope. +- +-Instance methods are accepted (and very useful!) as trace functions. +- +-The events have the following meaning: +- +-``'call'`` +- A function is called (or some other code block entered). The global trace +- function is called; *arg* is ``None``; the return value specifies the local +- trace function. +- +-``'line'`` +- The interpreter is about to execute a new line of code (sometimes multiple line +- events on one line exist). The local trace function is called; *arg* is +- ``None``; the return value specifies the new local trace function. +- +-``'return'`` +- A function (or other code block) is about to return. The local trace function +- is called; *arg* is the value that will be returned. The trace function's +- return value is ignored. +- +-``'exception'`` +- An exception has occurred. The local trace function is called; *arg* is a +- triple ``(exception, value, traceback)``; the return value specifies the new +- local trace function. +- +-``'c_call'`` +- A C function is about to be called. This may be an extension function or a +- builtin. *arg* is the C function object. +- +-``'c_return'`` +- A C function has returned. *arg* is ``None``. +- +-``'c_exception'`` +- A C function has thrown an exception. *arg* is ``None``. +- +-Note that as an exception is propagated down the chain of callers, an +-``'exception'`` event is generated at each level. +- +-For more information on code and frame objects, refer to :ref:`types`. +- +Index: Doc/library/winsound.rst +=================================================================== +--- Doc/library/winsound.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/winsound.rst (.../branches/release26-maint) (Revision 70449) +@@ -30,8 +30,9 @@ + Call the underlying :cfunc:`PlaySound` function from the Platform API. The + *sound* parameter may be a filename, audio data as a string, or ``None``. Its + interpretation depends on the value of *flags*, which can be a bitwise ORed +- combination of the constants described below. If the system indicates an error, +- :exc:`RuntimeError` is raised. ++ combination of the constants described below. If the *sound* parameter is ++ ``None``, any currently playing waveform sound is stopped. If the system ++ indicates an error, :exc:`RuntimeError` is raised. + + + .. function:: MessageBeep([type=MB_OK]) +@@ -108,7 +109,11 @@ + + Stop playing all instances of the specified sound. + ++ .. note:: + ++ This flag is not supported on modern Windows platforms. ++ ++ + .. data:: SND_ASYNC + + Return immediately, allowing sounds to play asynchronously. +Index: Doc/library/string.rst +=================================================================== +--- Doc/library/string.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/string.rst (.../branches/release26-maint) (Revision 70449) +@@ -126,7 +126,7 @@ + :meth:`format` is just a wrapper that calls :meth:`vformat`. + + .. method:: vformat(format_string, args, kwargs) +- ++ + This function does the actual work of formatting. It is exposed as a + separate function for cases where you want to pass in a predefined + dictionary of arguments, rather than unpacking and repacking the +@@ -139,12 +139,12 @@ + intended to be replaced by subclasses: + + .. method:: parse(format_string) +- ++ + Loop over the format_string and return an iterable of tuples + (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used + by :meth:`vformat` to break the string in to either literal text, or + replacement fields. +- ++ + The values in the tuple conceptually represent a span of literal text + followed by a single replacement field. If there is no literal text + (which can happen if two replacement fields occur consecutively), then +@@ -162,7 +162,7 @@ + *key* parameter to :meth:`get_value`. + + .. method:: get_value(key, args, kwargs) +- ++ + Retrieve a given field value. The *key* argument will be either an + integer or a string. If it is an integer, it represents the index of the + positional argument in *args*; if it is a string, then it represents a +@@ -200,7 +200,7 @@ + method is provided so that subclasses can override it. + + .. method:: convert_field(value, conversion) +- ++ + Converts the value (returned by :meth:`get_field`) given a conversion type + (as in the tuple returned by the :meth:`parse` method.) The default + version understands 'r' (repr) and 's' (str) conversion types. +@@ -229,7 +229,7 @@ + element_index: `integer` + conversion: "r" | "s" + format_spec: +- ++ + In less formal terms, the replacement field starts with a *field_name*, which + can either be a number (for a positional argument), or an identifier (for + keyword arguments). Following this is an optional *conversion* field, which is +@@ -249,7 +249,7 @@ + "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'. +- ++ + The *conversion* field causes a type coercion before formatting. Normally, the + job of formatting a value is done by the :meth:`__format__` method of the value + itself. However, in some cases it is desirable to force a type to be formatted +@@ -292,11 +292,11 @@ + Then the outer replacement field would be evaluated, producing:: + + "noses " +- ++ + Which is substituted into the string, yielding:: +- ++ + "A man with two noses " +- ++ + (The extra space is because we specified a field width of 10, and because left + alignment is the default for strings.) + +@@ -328,7 +328,7 @@ + width: `integer` + precision: `integer` + type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%" +- ++ + The *fill* character can be any character other than '}' (which signifies the + end of the field). The presence of a fill character is signaled by the *next* + character, which must be one of the alignment options. If the second character +@@ -421,9 +421,9 @@ + +---------+----------------------------------------------------------+ + | None | The same as ``'d'``. | + +---------+----------------------------------------------------------+ +- ++ + The available presentation types for floating point and decimal values are: +- ++ + +---------+----------------------------------------------------------+ + | Type | Meaning | + +=========+==========================================================+ +Index: Doc/library/urllib2.rst +=================================================================== +--- Doc/library/urllib2.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/urllib2.rst (.../branches/release26-maint) (Revision 70449) +@@ -109,7 +109,7 @@ + + .. attribute:: code + +- An HTTP status code as defined in `RFC 2616 `_. ++ An HTTP status code as defined in `RFC 2616 `_. + This numeric value corresponds to a value found in the dictionary of + codes as found in :attr:`BaseHTTPServer.BaseHTTPRequestHandler.responses`. + +@@ -391,23 +391,23 @@ + + .. method:: OpenerDirector.add_handler(handler) + +- *handler* should be an instance of :class:`BaseHandler`. The following methods +- are searched, and added to the possible chains (note that HTTP errors are a +- special case). ++ *handler* should be an instance of :class:`BaseHandler`. The following ++ methods are searched, and added to the possible chains (note that HTTP errors ++ are a special case). + +- * :meth:`protocol_open` --- signal that the handler knows how to open *protocol* +- URLs. ++ * :samp:`{protocol}_open` --- signal that the handler knows how to open ++ *protocol* URLs. + +- * :meth:`http_error_type` --- signal that the handler knows how to handle HTTP +- errors with HTTP error code *type*. ++ * :samp:`http_error_{type}` --- signal that the handler knows how to handle ++ HTTP errors with HTTP error code *type*. + +- * :meth:`protocol_error` --- signal that the handler knows how to handle errors +- from (non-\ ``http``) *protocol*. ++ * :samp:`{protocol}_error` --- signal that the handler knows how to handle ++ errors from (non-\ ``http``) *protocol*. + +- * :meth:`protocol_request` --- signal that the handler knows how to pre-process +- *protocol* requests. ++ * :samp:`{protocol}_request` --- signal that the handler knows how to ++ pre-process *protocol* requests. + +- * :meth:`protocol_response` --- signal that the handler knows how to ++ * :samp:`{protocol}_response` --- signal that the handler knows how to + post-process *protocol* responses. + + +@@ -441,24 +441,24 @@ + The order in which these methods are called within each stage is determined by + sorting the handler instances. + +-#. Every handler with a method named like :meth:`protocol_request` has that ++#. Every handler with a method named like :samp:`{protocol}_request` has that + method called to pre-process the request. + +-#. Handlers with a method named like :meth:`protocol_open` are called to handle ++#. Handlers with a method named like :samp:`{protocol}_open` are called to handle + the request. This stage ends when a handler either returns a non-\ :const:`None` + value (ie. a response), or raises an exception (usually :exc:`URLError`). + Exceptions are allowed to propagate. + + In fact, the above algorithm is first tried for methods named +- :meth:`default_open`. If all such methods return :const:`None`, the algorithm +- is repeated for methods named like :meth:`protocol_open`. If all such methods +- return :const:`None`, the algorithm is repeated for methods named +- :meth:`unknown_open`. ++ :meth:`default_open`. If all such methods return :const:`None`, the ++ algorithm is repeated for methods named like :samp:`{protocol}_open`. If all ++ such methods return :const:`None`, the algorithm is repeated for methods ++ named :meth:`unknown_open`. + + Note that the implementation of these methods may involve calls of the parent + :class:`OpenerDirector` instance's :meth:`.open` and :meth:`.error` methods. + +-#. Every handler with a method named like :meth:`protocol_response` has that ++#. Every handler with a method named like :samp:`{protocol}_response` has that + method called to post-process the response. + + +@@ -514,8 +514,10 @@ + .. method:: BaseHandler.protocol_open(req) + :noindex: + ++ ("protocol" is to be replaced by the protocol name.) ++ + This method is *not* defined in :class:`BaseHandler`, but subclasses should +- define it if they want to handle URLs with the given protocol. ++ define it if they want to handle URLs with the given *protocol*. + + This method, if defined, will be called by the parent :class:`OpenerDirector`. + Return values should be the same as for :meth:`default_open`. +@@ -563,8 +565,10 @@ + .. method:: BaseHandler.protocol_request(req) + :noindex: + ++ ("protocol" is to be replaced by the protocol name.) ++ + This method is *not* defined in :class:`BaseHandler`, but subclasses should +- define it if they want to pre-process requests of the given protocol. ++ define it if they want to pre-process requests of the given *protocol*. + + This method, if defined, will be called by the parent :class:`OpenerDirector`. + *req* will be a :class:`Request` object. The return value should be a +@@ -574,8 +578,10 @@ + .. method:: BaseHandler.protocol_response(req, response) + :noindex: + ++ ("protocol" is to be replaced by the protocol name.) ++ + This method is *not* defined in :class:`BaseHandler`, but subclasses should +- define it if they want to post-process responses of the given protocol. ++ define it if they want to post-process responses of the given *protocol*. + + This method, if defined, will be called by the parent :class:`OpenerDirector`. + *req* will be a :class:`Request` object. *response* will be an object +@@ -596,14 +602,15 @@ + precise meanings of the various redirection codes. + + +-.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs) ++.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl) + + Return a :class:`Request` or ``None`` in response to a redirect. This is called + by the default implementations of the :meth:`http_error_30\*` methods when a + redirection is received from the server. If a redirection should take place, + return a new :class:`Request` to allow :meth:`http_error_30\*` to perform the +- redirect. Otherwise, raise :exc:`HTTPError` if no other handler should try to +- handle this URL, or return ``None`` if you can't but another handler might. ++ redirect to *newurl*. Otherwise, raise :exc:`HTTPError` if no other handler ++ should try to handle this URL, or return ``None`` if you can't but another ++ handler might. + + .. note:: + +@@ -616,8 +623,8 @@ + + .. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs) + +- Redirect to the ``Location:`` URL. This method is called by the parent +- :class:`OpenerDirector` when getting an HTTP 'moved permanently' response. ++ Redirect to the ``Location:`` or ``URI:`` URL. This method is called by the ++ parent :class:`OpenerDirector` when getting an HTTP 'moved permanently' response. + + + .. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs) +@@ -660,7 +667,9 @@ + .. method:: ProxyHandler.protocol_open(request) + :noindex: + +- The :class:`ProxyHandler` will have a method :meth:`protocol_open` for every ++ ("protocol" is to be replaced by the protocol name.) ++ ++ The :class:`ProxyHandler` will have a method :samp:`{protocol}_open` for every + *protocol* which has a proxy in the *proxies* dictionary given in the + constructor. The method will modify requests to go through the proxy, by + calling ``request.set_proxy()``, and call the next handler in the chain to +@@ -865,9 +874,10 @@ + For 200 error codes, the response object is returned immediately. + + For non-200 error codes, this simply passes the job on to the +- :meth:`protocol_error_code` handler methods, via :meth:`OpenerDirector.error`. +- Eventually, :class:`urllib2.HTTPDefaultErrorHandler` will raise an +- :exc:`HTTPError` if no other handler handles the error. ++ :samp:`{protocol}_error_code` handler methods, via ++ :meth:`OpenerDirector.error`. Eventually, ++ :class:`urllib2.HTTPDefaultErrorHandler` will raise an :exc:`HTTPError` if no ++ other handler handles the error. + + + .. _urllib2-examples: +Index: Doc/library/sys.rst +=================================================================== +--- Doc/library/sys.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/sys.rst (.../branches/release26-maint) (Revision 70449) +@@ -402,7 +402,7 @@ + + 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`. ++ cause a `TypeError`. + + func:`getsizeof` calls the object's __sizeof__ method and adds an additional + garbage collector overhead if the object is managed by the garbage collector. +@@ -566,7 +566,11 @@ + .. versionchanged:: 2.3 + Unicode strings are no longer ignored. + ++ .. seealso:: ++ Module :mod:`site` This describes how to use .pth files to extend ++ :data:`sys.path`. + ++ + .. data:: platform + + This string contains a platform identifier that can be used to append +@@ -583,7 +587,6 @@ + Windows ``'win32'`` + Windows/Cygwin ``'cygwin'`` + Mac OS X ``'darwin'`` +- Mac OS 9 ``'mac'`` + OS/2 ``'os2'`` + OS/2 EMX ``'os2emx'`` + RiscOS ``'riscos'`` +@@ -712,11 +715,60 @@ + single: debugger + + Set the system's trace function, which allows you to implement a Python +- source code debugger in Python. See section :ref:`debugger-hooks` in the +- chapter on the Python debugger. The function is thread-specific; for a ++ source code debugger in Python. The function is thread-specific; for a + debugger to support multiple threads, it must be registered using + :func:`settrace` for each thread being debugged. + ++ Trace functions should have three arguments: *frame*, *event*, and ++ *arg*. *frame* is the current stack frame. *event* is a string: ``'call'``, ++ ``'line'``, ``'return'``, ``'exception'``, ``'c_call'``, ``'c_return'``, or ++ ``'c_exception'``. *arg* depends on the event type. ++ ++ The trace function is invoked (with *event* set to ``'call'``) whenever a new ++ local scope is entered; it should return a reference to a local trace ++ function to be used that scope, or ``None`` if the scope shouldn't be traced. ++ ++ The local trace function should return a reference to itself (or to another ++ function for further tracing in that scope), or ``None`` to turn off tracing ++ in that scope. ++ ++ The events have the following meaning: ++ ++ ``'call'`` ++ A function is called (or some other code block entered). The ++ global trace function is called; *arg* is ``None``; the return value ++ specifies the local trace function. ++ ++ ``'line'`` ++ The interpreter is about to execute a new line of code (sometimes multiple ++ line events on one line exist). The local trace function is called; *arg* ++ is ``None``; the return value specifies the new local trace function. ++ ++ ``'return'`` ++ A function (or other code block) is about to return. The local trace ++ function is called; *arg* is the value that will be returned. The trace ++ function's return value is ignored. ++ ++ ``'exception'`` ++ An exception has occurred. The local trace function is called; *arg* is a ++ tuple ``(exception, value, traceback)``; the return value specifies the ++ new local trace function. ++ ++ ``'c_call'`` ++ A C function is about to be called. This may be an extension function or ++ a builtin. *arg* is the C function object. ++ ++ ``'c_return'`` ++ A C function has returned. *arg* is ``None``. ++ ++ ``'c_exception'`` ++ A C function has thrown an exception. *arg* is ``None``. ++ ++ Note that as an exception is propagated down the chain of callers, an ++ ``'exception'`` event is generated at each level. ++ ++ For more information on code and frame objects, refer to :ref:`types`. ++ + .. note:: + + The :func:`settrace` function is intended only for implementing debuggers, +@@ -750,7 +802,7 @@ + prompts of :func:`input` and :func:`raw_input`. The interpreter's own prompts + and (almost all of) its error messages go to ``stderr``. ``stdout`` and + ``stderr`` needn't be built-in file objects: any object is acceptable as long +- as it has a :meth:`write` method that takes a string argument. (Changing these ++ as it has a :meth:`write` method that takes a string argument. (Changing these + objects doesn't affect the standard I/O streams of processes executed by + :func:`os.popen`, :func:`os.system` or the :func:`exec\*` family of functions in + the :mod:`os` module.) +@@ -820,10 +872,3 @@ + first three characters of :const:`version`. It is provided in the :mod:`sys` + module for informational purposes; modifying this value has no effect on the + registry keys used by Python. Availability: Windows. +- +- +-.. seealso:: +- +- Module :mod:`site` +- This describes how to use .pth files to extend ``sys.path``. +- +Index: Doc/library/tkinter.rst +=================================================================== +--- Doc/library/tkinter.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/tkinter.rst (.../branches/release26-maint) (Revision 70449) +@@ -284,7 +284,7 @@ + someOptions), in C++, you would express this as fred.someAction(someOptions), + and in Tk, you say:: + +- .fred someAction someOptions ++ .fred someAction someOptions + + Note that the object name, ``.fred``, starts with a dot. + +@@ -490,7 +490,7 @@ + For more extensive information on the packer and the options that it can take, + see the man pages and page 183 of John Ousterhout's book. + +-anchor ++anchor + Anchor type. Denotes where the packer is to place each slave in its parcel. + + expand +@@ -720,7 +720,7 @@ + they are denoted in Tk, which can be useful when referring to the Tk man pages. + :: + +- Tk Tkinter Event Field Tk Tkinter Event Field ++ Tk Tkinter Event Field Tk Tkinter Event Field + -- ------------------- -- ------------------- + %f focus %A char + %h height %E send_event +Index: Doc/library/itertools.rst +=================================================================== +--- Doc/library/itertools.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/itertools.rst (.../branches/release26-maint) (Revision 70449) +@@ -14,42 +14,66 @@ + + .. versionadded:: 2.3 + +-This module implements a number of :term:`iterator` building blocks inspired by +-constructs from the Haskell and SML programming languages. Each has been recast +-in a form suitable for Python. ++This module implements a number of :term:`iterator` building blocks inspired ++by constructs from APL, Haskell, and SML. Each has been recast in a form ++suitable for Python. + + The module standardizes a core set of fast, memory efficient tools that are +-useful by themselves or in combination. Standardization helps avoid the +-readability and reliability problems which arise when many different individuals +-create their own slightly varying implementations, each with their own quirks +-and naming conventions. ++useful by themselves or in combination. Together, they form an "iterator ++algebra" making it possible to construct specialized tools succinctly and ++efficiently in pure Python. + +-The tools are designed to combine readily with one another. This makes it easy +-to construct more specialized tools succinctly and efficiently in pure Python. +- + For instance, SML provides a tabulation tool: ``tabulate(f)`` which produces a + sequence ``f(0), f(1), ...``. This toolbox provides :func:`imap` and +-:func:`count` which can be combined to form ``imap(f, count())`` and produce an ++:func:`count` which can be combined to form ``imap(f, count())`` to produce an + equivalent result. + +-Likewise, the functional tools are designed to work well with the high-speed +-functions provided by the :mod:`operator` module. ++These tools and their built-in counterparts also work well with the high-speed ++functions in the :mod:`operator` module. For example, the multiplication ++operator can be mapped across two vectors to form an efficient dot-product: ++``sum(imap(operator.mul, vector1, vector2))``. + +-Whether cast in pure python form or compiled code, tools that use iterators are +-more memory efficient (and often faster) than their list based counterparts. Adopting +-the principles of just-in-time manufacturing, they create data when and where +-needed instead of consuming memory with the computer equivalent of "inventory". + ++**Infinite Iterators:** + +-.. seealso:: ++ ================== ================= ================================================= ++ Iterator Arguments Results ++ ================== ================= ================================================= ++ :func:`count` start start, start+1, start+2, ... ++ :func:`cycle` p p0, p1, ... plast, p0, p1, ... ++ :func:`repeat` elem [,n] elem, elem, elem, ... endlessly or up to n times ++ ================== ================= ================================================= + +- The Standard ML Basis Library, `The Standard ML Basis Library +- `_. ++**Iterators terminating on the shortest input sequence:** + +- Haskell, A Purely Functional Language, `Definition of Haskell and the Standard +- Libraries `_. ++ ==================== ============================ ================================================= ++ Iterator Arguments Results ++ ==================== ============================ ================================================= ++ :func:`chain` p, q, ... p0, p1, ... plast, q0, q1, ... ++ :func:`dropwhile` pred, seq seq[n], seq[n+1], starting when pred fails ++ :func:`groupby` iterable[, keyfunc] sub-iterators grouped by value of keyfunc(v) ++ :func:`ifilter` pred, seq elements of seq where pred(elem) is True ++ :func:`ifilterfalse` pred, seq elements of seq where pred(elem) is False ++ :func:`islice` seq, [start,] stop [, step] elements from seq[start:stop:step] ++ :func:`imap` func, p, q, ... func(p0, q0), func(p1, q1), ... ++ :func:`starmap` func, seq func(\*seq[0]), func(\*seq[1]), ... ++ :func:`tee` it, n it1, it2 , ... itn splits one iterator into n ++ :func:`takewhile` pred, seq seq[0], seq[1], until pred fails ++ :func:`izip` p, q, ... (p[0], q[0]), (p[1], q[1]), ... ++ :func:`izip_longest` p, q, ... (p[0], q[0]), (p[1], q[1]), ... ++ ==================== ============================ ================================================= + ++**Combinatoric generators:** + ++ ===================================== ==================== ================================================= ++ Iterator Arguments Results ++ ===================================== ==================== ================================================= ++ :func:`product` p, q, ... [repeat=1] cartesian product ++ :func:`permutations` p[, r] r-length permutations (without repeated elements) ++ :func:`combinations` p[, r] r-length combinations (sorted and no repeats) ++ ===================================== ==================== ================================================= ++ ++ + .. _itertools-functions: + + Itertool functions +@@ -76,7 +100,7 @@ + + .. function:: itertools.chain.from_iterable(iterable) + +- Alternate constructor for :func:`chain`. Gets chained inputs from a ++ Alternate constructor for :func:`chain`. Gets chained inputs from a + single iterable argument that is evaluated lazily. Equivalent to:: + + @classmethod +@@ -93,9 +117,9 @@ + + Return *r* length subsequences of elements from the input *iterable*. + +- Combinations are emitted in lexicographic sort order. So, if the ++ Combinations are emitted in lexicographic sort order. So, if the + input *iterable* is sorted, the combination tuples will be produced +- in sorted order. ++ in sorted order. + + Elements are treated as unique based on their position, not on their + value. So if the input elements are unique, there will be no repeat +@@ -108,9 +132,11 @@ + # combinations(range(4), 3) --> 012 013 023 123 + pool = tuple(iterable) + n = len(pool) ++ if r > n: ++ return + indices = range(r) + yield tuple(pool[i] for i in indices) +- while 1: ++ while True: + for i in reversed(range(r)): + if indices[i] != i + n - r: + break +@@ -132,6 +158,9 @@ + if sorted(indices) == list(indices): + yield tuple(pool[i] for i in indices) + ++ The number of items returned is ``n! / r! / (n-r)!`` when ``0 <= r <= n`` ++ or zero when ``r > n``. ++ + .. versionadded:: 2.6 + + .. function:: count([n]) +@@ -216,7 +245,7 @@ + + class groupby(object): + # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B +- # [(list(g)) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D ++ # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D + def __init__(self, iterable, key=None): + if key is None: + key = lambda x: x +@@ -227,14 +256,14 @@ + return self + def next(self): + while self.currkey == self.tgtkey: +- self.currvalue = self.it.next() # Exit on StopIteration ++ self.currvalue = next(self.it) # Exit on StopIteration + self.currkey = self.keyfunc(self.currvalue) + self.tgtkey = self.currkey + return (self.currkey, self._grouper(self.tgtkey)) + def _grouper(self, tgtkey): + while self.currkey == tgtkey: + yield self.currvalue +- self.currvalue = self.it.next() # Exit on StopIteration ++ self.currvalue = next(self.it) # Exit on StopIteration + self.currkey = self.keyfunc(self.currvalue) + + .. versionadded:: 2.4 +@@ -284,7 +313,7 @@ + # imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000 + iterables = map(iter, iterables) + while True: +- args = [it.next() for it in iterables] ++ args = [next(it) for it in iterables] + if function is None: + yield tuple(args) + else: +@@ -310,11 +339,11 @@ + # islice('ABCDEFG', 0, None, 2) --> A C E G + s = slice(*args) + it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1)) +- nexti = it.next() ++ nexti = next(it) + for i, element in enumerate(iterable): + if i == nexti: + yield element +- nexti = it.next() ++ nexti = next(it) + + If *start* is ``None``, then iteration starts at zero. If *step* is ``None``, + then the step defaults to one. +@@ -333,8 +362,7 @@ + # izip('ABCD', 'xy') --> Ax By + iterables = map(iter, iterables) + while iterables: +- result = [it.next() for it in iterables] +- yield tuple(result) ++ yield yield tuple(map(next, iterables)) + + .. versionchanged:: 2.4 + When no iterables are specified, returns a zero length iterator instead of +@@ -380,12 +408,12 @@ + Return successive *r* length permutations of elements in the *iterable*. + + If *r* is not specified or is ``None``, then *r* defaults to the length +- of the *iterable* and all possible full-length permutations ++ of the *iterable* and all possible full-length permutations + are generated. + +- Permutations are emitted in lexicographic sort order. So, if the ++ Permutations are emitted in lexicographic sort order. So, if the + input *iterable* is sorted, the permutation tuples will be produced +- in sorted order. ++ in sorted order. + + Elements are treated as unique based on their position, not on their + value. So if the input elements are unique, there will be no repeat +@@ -399,6 +427,8 @@ + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r ++ if r > n: ++ return + indices = range(n) + cycles = range(n, n-r, -1) + yield tuple(pool[i] for i in indices[:r]) +@@ -416,7 +446,7 @@ + else: + return + +- The code for :func:`permutations` can be also expressed as a subsequence of ++ The code for :func:`permutations` can be also expressed as a subsequence of + :func:`product`, filtered to exclude entries with repeated elements (those + from the same position in the input pool):: + +@@ -428,6 +458,9 @@ + if len(set(indices)) == r: + yield tuple(pool[i] for i in indices) + ++ The number of items returned is ``n! / (n-r)!`` when ``0 <= r <= n`` ++ or zero when ``r > n``. ++ + .. versionadded:: 2.6 + + .. function:: product(*iterables[, repeat]) +@@ -511,28 +544,28 @@ + + .. function:: tee(iterable[, n=2]) + +- Return *n* independent iterators from a single iterable. The case where ``n==2`` +- is equivalent to:: ++ Return *n* independent iterators from a single iterable. Equivalent to:: + +- def tee(iterable): +- def gen(next, data={}): +- for i in count(): +- if i in data: +- yield data.pop(i) +- else: +- data[i] = next() +- yield data[i] +- it = iter(iterable) +- return gen(it.next), gen(it.next) ++ def tee(iterable, n=2): ++ it = iter(iterable) ++ deques = [collections.deque() for i in range(n)] ++ def gen(mydeque): ++ while True: ++ if not mydeque: # when the local deque is empty ++ newval = next(it) # fetch a new value and ++ for d in deques: # load it to all the deques ++ d.append(newval) ++ yield mydeque.popleft() ++ return tuple(gen(d) for d in deques) + +- Note, once :func:`tee` has made a split, the original *iterable* should not be +- used anywhere else; otherwise, the *iterable* could get advanced without the tee +- objects being informed. ++ Once :func:`tee` has made a split, the original *iterable* should not be ++ used anywhere else; otherwise, the *iterable* could get advanced without ++ the tee objects being informed. + +- Note, this member of the toolkit may require significant auxiliary storage +- (depending on how much temporary data needs to be stored). In general, if one +- iterator is going to use most or all of the data before the other iterator, it +- is faster to use :func:`list` instead of :func:`tee`. ++ This itertool may require significant auxiliary storage (depending on how ++ much temporary data needs to be stored). In general, if one iterator uses ++ most or all of the data before another iterator starts, it is faster to use ++ :func:`list` instead of :func:`tee`. + + .. versionadded:: 2.4 + +@@ -547,7 +580,7 @@ + + .. doctest:: + +- # Show a dictionary sorted and grouped by value ++ >>> # Show a dictionary sorted and grouped by value + >>> from operator import itemgetter + >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) + >>> di = sorted(d.iteritems(), key=itemgetter(1)) +@@ -558,13 +591,13 @@ + 2 ['b', 'd', 'f'] + 3 ['g'] + +- # Find runs of consecutive numbers using groupby. The key to the solution +- # is differencing with a range so that consecutive numbers all appear in +- # same group. ++ >>> # Find runs of consecutive numbers using groupby. The key to the solution ++ >>> # is differencing with a range so that consecutive numbers all appear in ++ >>> # same group. + >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] + >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): + ... print map(itemgetter(1), g) +- ... ++ ... + [1] + [4, 5, 6] + [10] +@@ -603,10 +636,14 @@ + "Return function(0), function(1), ..." + return imap(function, count(start)) + +- def nth(iterable, n): +- "Returns the nth item or empty list" +- return list(islice(iterable, n, n+1)) ++ def consume(iterator, n): ++ "Advance the iterator n-steps ahead. If n is none, consume entirely." ++ collections.deque(islice(iterator, n), maxlen=0) + ++ def nth(iterable, n, default=None): ++ "Returns the nth item or a default value" ++ return next(islice(iterable, n, None), default) ++ + def quantify(iterable, pred=bool): + "Count how many times the predicate is true" + return sum(imap(pred, iterable)) +@@ -640,8 +677,7 @@ + def pairwise(iterable): + "s -> (s0,s1), (s1,s2), (s2, s3), ..." + a, b = tee(iterable) +- for elem in b: +- break ++ next(b, None) + return izip(a, b) + + def grouper(n, iterable, fillvalue=None): +@@ -663,23 +699,24 @@ + nexts = cycle(islice(nexts, pending)) + + def powerset(iterable): +- "powerset('ab') --> set([]), set(['a']), set(['b']), set(['a', 'b'])" +- # Recipe credited to Eric Raymond +- pairs = [(2**i, x) for i, x in enumerate(iterable)] +- for n in xrange(2**len(pairs)): +- yield set(x for m, x in pairs if m&n) ++ "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" ++ s = list(iterable) ++ return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) + + def compress(data, selectors): + "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F" + return (d for d, s in izip(data, selectors) if s) + + def combinations_with_replacement(iterable, r): +- "combinations_with_replacement('ABC', 3) --> AA AB AC BB BC CC" ++ "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC" ++ # number items returned: (n+r-1)! / r! / (n-1)! + pool = tuple(iterable) + n = len(pool) ++ if not n and r: ++ return + indices = [0] * r + yield tuple(pool[i] for i in indices) +- while 1: ++ while True: + for i in reversed(range(r)): + if indices[i] != n - 1: + break +@@ -687,3 +724,32 @@ + return + indices[i:] = [indices[i] + 1] * (r - i) + yield tuple(pool[i] for i in indices) ++ ++ def powerset(iterable): ++ "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" ++ s = list(iterable) ++ return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) ++ ++ def unique_everseen(iterable, key=None): ++ "List unique elements, preserving order. Remember all elements ever seen." ++ # unique_everseen('AAAABBBCCDAABBB') --> A B C D ++ # unique_everseen('ABBCcAD', str.lower) --> A B C D ++ seen = set() ++ seen_add = seen.add ++ if key is None: ++ for element in iterable: ++ if element not in seen: ++ seen_add(element) ++ yield element ++ else: ++ for element in iterable: ++ k = key(element) ++ if k not in seen: ++ seen_add(k) ++ yield element ++ ++ def unique_justseen(iterable, key=None): ++ "List unique elements, preserving order. Remember only the element just seen." ++ # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B ++ # unique_justseen('ABBCcAD', str.lower) --> A B C A D ++ return imap(next, imap(itemgetter(1), groupby(iterable, key))) +Index: Doc/library/sched.rst +=================================================================== +--- Doc/library/sched.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/sched.rst (.../branches/release26-maint) (Revision 70449) +@@ -42,7 +42,7 @@ + 930343700.276 + + In multi-threaded environments, the :class:`scheduler` class has limitations +-with respect to thread-safety, inability to insert a new task before ++with respect to thread-safety, inability to insert a new task before + the one currently pending in a running scheduler, and holding up the main + thread until the event queue is empty. Instead, the preferred approach + is to use the :class:`threading.Timer` class instead. +@@ -58,8 +58,8 @@ + ... print time.time() + ... Timer(5, print_time, ()).start() + ... Timer(10, print_time, ()).start() +- ... time.sleep(11) # sleep while time-delay events execute +- ... print time.time() ++ ... time.sleep(11) # sleep while time-delay events execute ++ ... print time.time() + ... + >>> print_some_times() + 930343690.257 +Index: Doc/library/warnings.rst +=================================================================== +--- Doc/library/warnings.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/warnings.rst (.../branches/release26-maint) (Revision 70449) +@@ -274,7 +274,7 @@ + + .. function:: warnpy3k(message[, category[, stacklevel]]) + +- Issue a warning related to Python 3.x deprecation. Warnings are only shown ++ Issue a warning related to Python 3.x deprecation. Warnings are only shown + when Python is started with the -3 option. Like :func:`warn` *message* must + be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k` + is using :exc:`DeprecationWarning` as default warning class. +@@ -288,7 +288,7 @@ + this function with an alternative implementation by assigning to + ``warnings.showwarning``. + *line* is a line of source code to be included in the warning +- message; if *line* is not supplied, :func:`showwarning` will ++ message; if *line* is not supplied, :func:`showwarning` will + try to read the line specified by *filename* and *lineno*. + + .. versionchanged:: 2.6 +@@ -299,8 +299,8 @@ + .. function:: formatwarning(message, category, filename, lineno[, line]) + + 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, ++ 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*. + + .. versionchanged:: 2.6 +Index: Doc/library/difflib.rst +=================================================================== +--- Doc/library/difflib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/difflib.rst (.../branches/release26-maint) (Revision 70449) +@@ -428,7 +428,7 @@ + + .. XXX Explain why a dummy is used! + +- .. versionchanged:: 2.5 ++ .. versionchanged:: 2.5 + The guarantee that adjacent triples always describe non-adjacent blocks + was implemented. + +Index: Doc/library/popen2.rst +=================================================================== +--- Doc/library/popen2.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/popen2.rst (.../branches/release26-maint) (Revision 70449) +@@ -9,7 +9,7 @@ + + + .. deprecated:: 2.6 +- This module is obsolete. Use the :mod:`subprocess` module. Check ++ This module is obsolete. Use the :mod:`subprocess` module. Check + especially the :ref:`subprocess-replacements` section. + + This module allows you to spawn processes and connect to their +Index: Doc/library/tk.rst +=================================================================== +--- Doc/library/tk.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/tk.rst (.../branches/release26-maint) (Revision 70449) +@@ -22,15 +22,15 @@ + mechanism which allows Python and Tcl to interact. + + :mod:`Tkinter`'s chief virtues are that it is fast, and that it usually comes +-bundled with Python. Although its standard documentation is weak, good +-material is available, which includes: references, tutorials, a book and +-others. :mod:`Tkinter` is also famous for having an outdated look and feel, +-which has been vastly improved in Tk 8.5. Nevertheless, there are many other +-GUI libraries that you could be interested in. For more information about ++bundled with Python. Although its standard documentation is weak, good ++material is available, which includes: references, tutorials, a book and ++others. :mod:`Tkinter` is also famous for having an outdated look and feel, ++which has been vastly improved in Tk 8.5. Nevertheless, there are many other ++GUI libraries that you could be interested in. For more information about + alternatives, see the :ref:`other-gui-packages` section. + + .. toctree:: +- ++ + tkinter.rst + tix.rst + scrolledtext.rst +Index: Doc/library/turtle.rst +=================================================================== +--- Doc/library/turtle.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/turtle.rst (.../branches/release26-maint) (Revision 70449) +@@ -325,8 +325,7 @@ + + :param y: a number (integer or float) + +- Set the turtle's first coordinate to *y*, leave second coordinate +- unchanged. ++ Set the turtle's second coordinate to *y*, leave first coordinate unchanged. + + >>> turtle.position() + (0.00, 40.00) +@@ -1587,7 +1586,7 @@ + + Subclass of TurtleScreen, with :ref:`four methods added `. + +- ++ + .. class:: ScrolledCavas(master) + + :param master: some Tkinter widget to contain the ScrolledCanvas, i.e. +@@ -1612,13 +1611,13 @@ + "compound" ``None`` (a compund shape has to be constructed using the + :meth:`addcomponent` method) + =========== =========== +- ++ + .. method:: addcomponent(poly, fill, outline=None) + + :param poly: a polygon, i.e. a tuple of pairs of numbers + :param fill: a color the *poly* will be filled with + :param outline: a color for the poly's outline (if given) +- ++ + Example: + + >>> poly = ((0,0),(10,-5),(0,10),(-10,-5)) +@@ -1662,31 +1661,31 @@ + + >>> help(Screen.bgcolor) + Help on method bgcolor in module turtle: +- ++ + bgcolor(self, *args) unbound turtle.Screen method + Set or return backgroundcolor of the TurtleScreen. +- ++ + Arguments (if given): a color string or three numbers + in the range 0..colormode or a 3-tuple of such numbers. +- +- ++ ++ + >>> screen.bgcolor("orange") + >>> screen.bgcolor() + "orange" + >>> screen.bgcolor(0.5,0,0.5) + >>> screen.bgcolor() + "#800080" +- ++ + >>> help(Turtle.penup) + Help on method penup in module turtle: +- ++ + penup(self) unbound turtle.Turtle method + Pull the pen up -- no drawing when moving. +- ++ + Aliases: penup | pu | up +- ++ + No argument +- ++ + >>> turtle.penup() + + - The docstrings of the functions which are derived from methods have a modified +@@ -1694,32 +1693,32 @@ + + >>> help(bgcolor) + Help on function bgcolor in module turtle: +- ++ + bgcolor(*args) + Set or return backgroundcolor of the TurtleScreen. +- ++ + Arguments (if given): a color string or three numbers + in the range 0..colormode or a 3-tuple of such numbers. +- ++ + Example:: +- ++ + >>> bgcolor("orange") + >>> bgcolor() + "orange" + >>> bgcolor(0.5,0,0.5) + >>> bgcolor() + "#800080" +- ++ + >>> help(penup) + Help on function penup in module turtle: +- ++ + penup() + Pull the pen up -- no drawing when moving. +- ++ + Aliases: penup | pu | up +- ++ + No argument +- ++ + Example: + >>> penup() + + +Eigenschaftsänderungen: Doc/library/turtle.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/random.rst +=================================================================== +--- Doc/library/random.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/random.rst (.../branches/release26-maint) (Revision 70449) +@@ -188,13 +188,13 @@ + + .. function:: uniform(a, b) + +- Return a random floating point number *N* such that ``a <= N < b`` for +- ``a <= b`` and ``b <= N < a`` for ``b < a``. ++ Return a random floating point number *N* such that ``a <= N <= b`` for ++ ``a <= b`` and ``b <= N <= a`` for ``b < a``. + + + .. function:: triangular(low, high, mode) + +- Return a random floating point number *N* such that ``low <= N < high`` and ++ Return a random floating point number *N* such that ``low <= N <= high`` and + with the specified *mode* between those bounds. The *low* and *high* bounds + default to zero and one. The *mode* argument defaults to the midpoint + between the bounds, giving a symmetric distribution. +@@ -204,27 +204,30 @@ + + .. function:: betavariate(alpha, beta) + +- Beta distribution. Conditions on the parameters are ``alpha > 0`` and ``beta > +- 0``. Returned values range between 0 and 1. ++ Beta distribution. Conditions on the parameters are ``alpha > 0`` and ++ ``beta > 0``. Returned values range between 0 and 1. + + + .. function:: expovariate(lambd) + +- Exponential distribution. *lambd* is 1.0 divided by the desired mean. (The +- parameter would be called "lambda", but that is a reserved word in Python.) +- Returned values range from 0 to positive infinity. ++ Exponential distribution. *lambd* is 1.0 divided by the desired ++ mean. It should be nonzero. (The parameter would be called ++ "lambda", but that is a reserved word in Python.) Returned values ++ range from 0 to positive infinity if *lambd* is positive, and from ++ negative infinity to 0 if *lambd* is negative. + + + .. function:: gammavariate(alpha, beta) + +- Gamma distribution. (*Not* the gamma function!) Conditions on the parameters +- are ``alpha > 0`` and ``beta > 0``. ++ Gamma distribution. (*Not* the gamma function!) Conditions on the ++ parameters are ``alpha > 0`` and ``beta > 0``. + + + .. function:: gauss(mu, sigma) + +- Gaussian distribution. *mu* is the mean, and *sigma* is the standard deviation. +- This is slightly faster than the :func:`normalvariate` function defined below. ++ Gaussian distribution. *mu* is the mean, and *sigma* is the standard ++ deviation. This is slightly faster than the :func:`normalvariate` function ++ defined below. + + + .. function:: lognormvariate(mu, sigma) +Index: Doc/library/ftplib.rst +=================================================================== +--- Doc/library/ftplib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/ftplib.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,4 +1,3 @@ +- + :mod:`ftplib` --- FTP protocol client + ===================================== + +Index: Doc/library/configparser.rst +=================================================================== +--- Doc/library/configparser.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/configparser.rst (.../branches/release26-maint) (Revision 70449) +@@ -11,9 +11,9 @@ + + .. note:: + +- The :mod:`ConfigParser` module has been renamed to `configparser` in Python +- 3.0. The :term:`2to3` tool will automatically adapt imports when converting +- your sources to 3.0. ++ The :mod:`ConfigParser` module has been renamed to :mod:`configparser` in ++ Python 3.0. The :term:`2to3` tool will automatically adapt imports when ++ converting your sources to 3.0. + + .. index:: + pair: .ini; file +@@ -76,7 +76,7 @@ + *dict_type* was added. + + +-.. class:: ConfigParser([defaults]) ++.. class:: ConfigParser([defaults[, dict_type]]) + + Derived class of :class:`RawConfigParser` that implements the magical + interpolation feature and adds optional arguments to the :meth:`get` and +@@ -92,7 +92,7 @@ + equivalent. + + +-.. class:: SafeConfigParser([defaults]) ++.. class:: SafeConfigParser([defaults[, dict_type]]) + + Derived class of :class:`ConfigParser` that implements a more-sane variant of + the magical interpolation feature. This implementation is more predictable as +Index: Doc/library/queue.rst +=================================================================== +--- Doc/library/queue.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/queue.rst (.../branches/release26-maint) (Revision 70449) +@@ -66,7 +66,13 @@ + Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called + on a :class:`Queue` object which is full. + ++.. seealso:: + ++ :class:`collections.deque` is an alternative implementation of unbounded ++ queues with fast atomic :func:`append` and :func:`popleft` operations that ++ do not require locking. ++ ++ + .. _queueobjects: + + Queue Objects +@@ -162,7 +168,7 @@ + The count of unfinished tasks goes up whenever an item is added to the queue. + The count goes down whenever a consumer thread calls :meth:`task_done` to + indicate that the item was retrieved and all work on it is complete. When the +- count of unfinished tasks drops to zero, join() unblocks. ++ count of unfinished tasks drops to zero, :meth:`join` unblocks. + + .. versionadded:: 2.5 + +Index: Doc/library/logging.rst +=================================================================== +--- Doc/library/logging.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/logging.rst (.../branches/release26-maint) (Revision 70449) +@@ -121,7 +121,7 @@ + messages at different log levels. This allows you to instrument your code with + debug messages, for example, but turning the log level down so that those debug + messages are not written for your production system. The default levels are +-``CRITICAL``, ``ERROR``, ``WARNING``, ``INFO``, ``DEBUG`` and ``UNSET``. ++``CRITICAL``, ``ERROR``, ``WARNING``, ``INFO``, ``DEBUG`` and ``NOTSET``. + + The logger, handler, and log message call each specify a level. The log message + is only emitted if the handler and logger are configured to emit messages of +@@ -422,6 +422,8 @@ + code approach, mainly separation of configuration and code and the ability of + noncoders to easily modify the logging properties. + ++.. _library-config: ++ + Configuring Logging for a Library + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +@@ -524,40 +526,46 @@ + + #. :class:`FileHandler` instances send error messages to disk files. + +-#. :class:`BaseRotatingHandler` is the base class for handlers that rotate log +- files at a certain point. It is not meant to be instantiated directly. Instead, +- use :class:`RotatingFileHandler` or :class:`TimedRotatingFileHandler`. ++#. :class:`handlers.BaseRotatingHandler` is the base class for handlers that ++ rotate log files at a certain point. It is not meant to be instantiated ++ directly. Instead, use :class:`RotatingFileHandler` or ++ :class:`TimedRotatingFileHandler`. + +-#. :class:`RotatingFileHandler` instances send error messages to disk files, ++#. :class:`handlers.RotatingFileHandler` instances send error messages to disk files, + with support for maximum log file sizes and log file rotation. + +-#. :class:`TimedRotatingFileHandler` instances send error messages to disk files ++#. :class:`handlers.TimedRotatingFileHandler` instances send error messages to disk files + rotating the log file at certain timed intervals. + +-#. :class:`SocketHandler` instances send error messages to TCP/IP sockets. ++#. :class:`handlers.SocketHandler` instances send error messages to TCP/IP sockets. + +-#. :class:`DatagramHandler` instances send error messages to UDP sockets. ++#. :class:`handlers.DatagramHandler` instances send error messages to UDP sockets. + +-#. :class:`SMTPHandler` instances send error messages to a designated email ++#. :class:`handlers.SMTPHandler` instances send error messages to a designated email + address. + +-#. :class:`SysLogHandler` instances send error messages to a Unix syslog daemon, ++#. :class:`handlers.SysLogHandler` instances send error messages to a Unix syslog daemon, + possibly on a remote machine. + +-#. :class:`NTEventLogHandler` instances send error messages to a Windows ++#. :class:`handlers.NTEventLogHandler` instances send error messages to a Windows + NT/2000/XP event log. + +-#. :class:`MemoryHandler` instances send error messages to a buffer in memory, ++#. :class:`handlers.MemoryHandler` instances send error messages to a buffer in memory, + which is flushed whenever specific criteria are met. + +-#. :class:`HTTPHandler` instances send error messages to an HTTP server using ++#. :class:`handlers.HTTPHandler` instances send error messages to an HTTP server using + either ``GET`` or ``POST`` semantics. + +-The :class:`StreamHandler` and :class:`FileHandler` classes are defined in the +-core logging package. The other handlers are defined in a sub- module, +-:mod:`logging.handlers`. (There is also another sub-module, +-:mod:`logging.config`, for configuration functionality.) ++#. :class:`handlers.WatchedFileHandler` instances watch the file they are logging to. If ++the file changes, it is closed and reopened using the file name. This handler ++is only useful on Unix-like systems; Windows does not support the underlying ++mechanism used. + ++The :class:`StreamHandler` and :class:`FileHandler` ++classes are defined in the core logging package. The other handlers are ++defined in a sub- module, :mod:`logging.handlers`. (There is also another ++sub-module, :mod:`logging.config`, for configuration functionality.) ++ + Logged messages are formatted for presentation through instances of the + :class:`Formatter` class. They are initialized with a format string suitable for + use with the % operator and a dictionary. +@@ -1544,6 +1552,8 @@ + StreamHandler + ^^^^^^^^^^^^^ + ++.. module:: logging.handlers ++ + The :class:`StreamHandler` class, located in the core :mod:`logging` package, + sends logging output to streams such as *sys.stdout*, *sys.stderr* or any + file-like object (or, more precisely, any object which supports :meth:`write` +@@ -1599,6 +1609,9 @@ + Outputs the record to the file. + + ++See :ref:`library-config` for more information on how to use ++:class:`NullHandler`. ++ + WatchedFileHandler + ^^^^^^^^^^^^^^^^^^ + +@@ -2050,6 +2063,8 @@ + Formatter Objects + ----------------- + ++.. currentmodule:: logging ++ + :class:`Formatter`\ s have the following attributes and methods. They are + responsible for converting a :class:`LogRecord` to (usually) a string which can + be interpreted by either a human or an external system. The base +Index: Doc/library/2to3.rst +=================================================================== +--- Doc/library/2to3.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/2to3.rst (.../branches/release26-maint) (Revision 70449) +@@ -3,7 +3,7 @@ + 2to3 - Automated Python 2 to 3 code translation + =============================================== + +-.. sectionauthor:: Benjamin Peterson ++.. sectionauthor:: Benjamin Peterson + + 2to3 is a Python program that reads Python 2.x source code and applies a series + of *fixers* to transform it into valid Python 3.x code. The standard library +Index: Doc/library/socket.rst +=================================================================== +--- Doc/library/socket.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/socket.rst (.../branches/release26-maint) (Revision 70449) +@@ -184,10 +184,10 @@ + + .. data:: SIO_* + RCVALL_* +- ++ + Constants for Windows' WSAIoctl(). The constants are used as arguments to the + :meth:`ioctl` method of socket objects. +- ++ + .. versionadded:: 2.6 + + .. data:: TIPC_* +@@ -222,7 +222,7 @@ + all the necessary arguments for creating the corresponding socket. *host* is a domain + name, a string representation of an IPv4/v6 address or ``None``. *port* is a string + service name such as ``'http'``, a numeric port number or ``None``. +- The rest of the arguments are optional and must be numeric if specified. ++ The rest of the arguments are optional and must be numeric if specified. + By passing ``None`` as the value of *host* and *port*, , you can pass ``NULL`` to the C API. + + The :func:`getaddrinfo` function returns a list of 5-tuples with the following +@@ -588,14 +588,14 @@ + contents of the buffer (see the optional built-in module :mod:`struct` for a way + to decode C structures encoded as strings). + +- ++ + .. method:: socket.ioctl(control, option) + +- :platform: Windows +- ++ :platform: Windows ++ + The :meth:`ioctl` method is a limited interface to the WSAIoctl system + interface. Please refer to the MSDN documentation for more information. +- ++ + .. versionadded:: 2.6 + + +@@ -852,20 +852,21 @@ + HOST = None # Symbolic name meaning all available interfaces + PORT = 50007 # Arbitrary non-privileged port + s = None +- for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): ++ for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, ++ socket.SOCK_STREAM, 0, socket.AI_PASSIVE): + af, socktype, proto, canonname, sa = res + try: +- s = socket.socket(af, socktype, proto) ++ s = socket.socket(af, socktype, proto) + except socket.error, msg: +- s = None +- continue ++ s = None ++ continue + try: +- s.bind(sa) +- s.listen(1) ++ s.bind(sa) ++ s.listen(1) + except socket.error, msg: +- s.close() +- s = None +- continue ++ s.close() ++ s = None ++ continue + break + if s is None: + print 'could not open socket' +@@ -890,16 +891,16 @@ + for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): + af, socktype, proto, canonname, sa = res + try: +- s = socket.socket(af, socktype, proto) ++ s = socket.socket(af, socktype, proto) + except socket.error, msg: +- s = None +- continue ++ s = None ++ continue + try: +- s.connect(sa) ++ s.connect(sa) + except socket.error, msg: +- s.close() +- s = None +- continue ++ s.close() ++ s = None ++ continue + break + if s is None: + print 'could not open socket' +@@ -909,7 +910,7 @@ + s.close() + print 'Received', repr(data) + +- ++ + The last example shows how to write a very simple network sniffer with raw + sockets on Windows. The example requires administrator privileges to modify + the interface:: +@@ -918,19 +919,19 @@ + + # the public network interface + HOST = socket.gethostbyname(socket.gethostname()) +- ++ + # create a raw socket and bind it to the public interface + s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) + s.bind((HOST, 0)) +- ++ + # Include IP headers + s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) +- ++ + # receive all packages + s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) +- ++ + # receive a package + print s.recvfrom(65565) +- ++ + # disabled promiscuous mode + s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) +Index: Doc/library/zipimport.rst +=================================================================== +--- Doc/library/zipimport.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/zipimport.rst (.../branches/release26-maint) (Revision 70449) +@@ -148,7 +148,7 @@ + -------- ------- + 8467 1 file + $ ./python +- Python 2.3 (#1, Aug 1 2003, 19:54:32) ++ Python 2.3 (#1, Aug 1 2003, 19:54:32) + >>> import sys + >>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path + >>> import jwzthreading +Index: Doc/library/trace.rst +=================================================================== +--- Doc/library/trace.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/trace.rst (.../branches/release26-maint) (Revision 70449) +@@ -65,13 +65,13 @@ + + :option:`--ignore-module` + Accepts comma separated list of module names. Ignore each of the named +- module and its submodules (if it is a package). May be given ++ module and its submodules (if it is a package). May be given + multiple times. + + :option:`--ignore-dir` + Ignore all modules and packages in the named directory and subdirectories + (multiple directories can be joined by os.pathsep). May be given multiple +- times. ++ times. + + + .. _trace-api: +Index: Doc/library/cookielib.rst +=================================================================== +--- Doc/library/cookielib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/cookielib.rst (.../branches/release26-maint) (Revision 70449) +@@ -733,7 +733,7 @@ + The :class:`Cookie` class also defines the following method: + + +-.. method:: Cookie.is_expired([now=:const:`None`]) ++.. method:: Cookie.is_expired([now=None]) + + True if cookie has passed the time at which the server requested it should + expire. If *now* is given (in seconds since the epoch), return whether the +@@ -769,7 +769,7 @@ + import urllib2 + from cookielib import CookieJar, DefaultCookiePolicy + policy = DefaultCookiePolicy( +- rfc2965=True, strict_ns_domain=Policy.DomainStrict, ++ rfc2965=True, strict_ns_domain=DefaultCookiePolicy.DomainStrict, + blocked_domains=["ads.net", ".ads.net"]) + cj = CookieJar(policy) + opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) +Index: Doc/library/shutil.rst +=================================================================== +--- Doc/library/shutil.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/shutil.rst (.../branches/release26-maint) (Revision 70449) +@@ -20,7 +20,7 @@ + + Even the higher-level file copying functions (:func:`copy`, :func:`copy2`) + can't copy all file metadata. +- ++ + On POSIX platforms, this means that file owner and group are lost as well + as ACLs. On Mac OS, the resource fork and other metadata are not used. + This means that resources will be lost and file type and creator codes will +@@ -43,7 +43,8 @@ + + Copy the contents (no metadata) of the file named *src* to a file named *dst*. + *dst* must be the complete target file name; look at :func:`copy` for a copy that +- accepts a target directory path. ++ accepts a target directory path. If *src* and *dst* are the same files, ++ :exc:`Error` is raised. + The destination location must be writable; otherwise, an :exc:`IOError` exception + will be raised. If *dst* already exists, it will be replaced. Special files + such as character or block devices and pipes cannot be copied with this +@@ -123,7 +124,7 @@ + error. Copy permissions and times of directories using :func:`copystat`. + + .. versionchanged:: 2.6 +- Added the *ignore* argument to be able to influence what is being copied. ++ Added the *ignore* argument to be able to influence what is being copied. + + + .. function:: rmtree(path[, ignore_errors[, onerror]]) +@@ -155,7 +156,7 @@ + Recursively move a file or directory to another location. + + If the destination is on the current filesystem, then simply use rename. +- Otherwise, copy src to the dst and then remove src. ++ Otherwise, copy src (with :func:`copy2`) to the dst and then remove src. + + .. versionadded:: 2.3 + +@@ -188,7 +189,7 @@ + os.makedirs(dst) + errors = [] + for name in names: +- if name in ignored_names: ++ if name in ignored_names: + continue + srcname = os.path.join(src, name) + dstname = os.path.join(dst, name) +@@ -220,7 +221,7 @@ + Another example that uses the :func:`ignore_patterns` helper:: + + from shutil import copytree, ignore_patterns +- ++ + copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*')) + + This will copy everything except ``.pyc`` files and files or directories whose +@@ -230,7 +231,7 @@ + + from shutil import copytree + import logging +- ++ + def _logpath(path, names): + logging.info('Working in %s' % path) + return [] # nothing will be ignored +Index: Doc/library/gzip.rst +=================================================================== +--- Doc/library/gzip.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/gzip.rst (.../branches/release26-maint) (Revision 70449) +@@ -7,7 +7,7 @@ + This module provides a simple interface to compress and decompress files just + like the GNU programs :program:`gzip` and :program:`gunzip` would. + +-The data compression is provided by the :mod:``zlib`` module. ++The data compression is provided by the :mod:`zlib` module. + + The :mod:`gzip` module provides the :class:`GzipFile` class which is modeled + after Python's File Object. The :class:`GzipFile` class reads and writes +Index: Doc/library/smtplib.rst +=================================================================== +--- Doc/library/smtplib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/smtplib.rst (.../branches/release26-maint) (Revision 70449) +@@ -189,9 +189,9 @@ + + Identify yourself to an ESMTP server using ``EHLO``. The hostname argument + defaults to the fully qualified domain name of the local host. Examine the +- response for ESMTP option and store them for use by :meth:`has_extn`. +- Also sets several informational attributes: the message returned by +- the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp` ++ response for ESMTP option and store them for use by :meth:`has_extn`. ++ Also sets several informational attributes: the message returned by ++ the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp` + is set to true or false depending on whether the server supports ESMTP, and + :attr:`esmtp_features` will be a dictionary containing the names of the + SMTP service extensions this server supports, and their +@@ -207,7 +207,7 @@ + previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO`` + first. + +- :exc:SMTPHeloError ++ :exc:`SMTPHeloError` + The server didn't reply properly to the ``HELO`` greeting. + + .. versionadded:: 2.6 +Index: Doc/library/msvcrt.rst +=================================================================== +--- Doc/library/msvcrt.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/msvcrt.rst (.../branches/release26-maint) (Revision 70449) +@@ -18,7 +18,7 @@ + + The module implements both the normal and wide char variants of the console I/O + api. The normal API deals only with ASCII characters and is of limited use +-for internationalized applications. The wide char API should be used where ++for internationalized applications. The wide char API should be used where + ever possible + + .. _msvcrt-files: +@@ -98,14 +98,14 @@ + return the keycode. The :kbd:`Control-C` keypress cannot be read with this + function. + +- ++ + .. function:: getwch() + + Wide char variant of :func:`getch`, returning a Unicode value. +- ++ + .. versionadded:: 2.6 +- + ++ + .. function:: getche() + + Similar to :func:`getch`, but the keypress will be echoed if it represents a +@@ -115,7 +115,7 @@ + .. function:: getwche() + + Wide char variant of :func:`getche`, returning a Unicode value. +- ++ + .. versionadded:: 2.6 + + +@@ -123,24 +123,24 @@ + + Print the character *char* to the console without buffering. + +- ++ + .. function:: putwch(unicode_char) + + Wide char variant of :func:`putch`, accepting a Unicode value. +- ++ + .. versionadded:: 2.6 +- + ++ + .. function:: ungetch(char) + + Cause the character *char* to be "pushed back" into the console buffer; it will + be the next character read by :func:`getch` or :func:`getche`. + +- ++ + .. function:: ungetwch(unicode_char) + + Wide char variant of :func:`ungetch`, accepting a Unicode value. +- ++ + .. versionadded:: 2.6 + + +Index: Doc/library/socketserver.rst +=================================================================== +--- Doc/library/socketserver.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/socketserver.rst (.../branches/release26-maint) (Revision 70449) +@@ -7,9 +7,9 @@ + + .. note:: + +- The :mod:`SocketServer` module has been renamed to `socketserver` in Python +- 3.0. The :term:`2to3` tool will automatically adapt imports when converting +- your sources to 3.0. ++ The :mod:`SocketServer` module has been renamed to :mod:`socketserver` in ++ Python 3.0. The :term:`2to3` tool will automatically adapt imports when ++ converting your sources to 3.0. + + + The :mod:`SocketServer` module simplifies the task of writing network servers. +@@ -448,7 +448,7 @@ + + if __name__ == "__main__": + HOST, PORT = "localhost", 9999 +- server = SocketServer.UDPServer((HOST, PORT), BaseUDPRequestHandler) ++ server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler) + server.serve_forever() + + This is the client side:: +@@ -517,7 +517,7 @@ + # Exit the server thread when the main thread terminates + server_thread.setDaemon(True) + server_thread.start() +- print "Server loop running in thread:", t.getName() ++ print "Server loop running in thread:", server_thread.getName() + + client(ip, port, "Hello World 1") + client(ip, port, "Hello World 2") +Index: Doc/library/imageop.rst +=================================================================== +--- Doc/library/imageop.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/imageop.rst (.../branches/release26-maint) (Revision 70449) +@@ -5,7 +5,7 @@ + .. module:: imageop + :synopsis: Manipulate raw image data. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`imageop` module has been removed in Python 3.0. + +Index: Doc/library/binascii.rst +=================================================================== +--- Doc/library/binascii.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/binascii.rst (.../branches/release26-maint) (Revision 70449) +@@ -113,10 +113,27 @@ + print binascii.crc32("hello world") + # Or, in two pieces: + crc = binascii.crc32("hello") +- crc = binascii.crc32(" world", crc) +- print crc ++ crc = binascii.crc32(" world", crc) & 0xffffffff ++ print 'crc32 = 0x%08x' % crc + ++.. note:: ++ To generate the same numeric value across all Python versions and ++ platforms use crc32(data) & 0xffffffff. If you are only using ++ the checksum in packed binary format this is not necessary as the ++ return value is the correct 32bit binary representation ++ regardless of sign. + ++.. versionchanged:: 2.6 ++ The return value is in the range [-2**31, 2**31-1] ++ regardless of platform. In the past the value would be signed on ++ some platforms and unsigned on others. Use & 0xffffffff on the ++ value if you want it to match 3.0 behavior. ++ ++.. versionchanged:: 3.0 ++ The return value is unsigned and in the range [0, 2**32-1] ++ regardless of platform. ++ ++ + .. function:: b2a_hex(data) + hexlify(data) + +Index: Doc/library/jpeg.rst +=================================================================== +--- Doc/library/jpeg.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/jpeg.rst (.../branches/release26-maint) (Revision 70449) +@@ -6,7 +6,7 @@ + :platform: IRIX + :synopsis: Read and write image files in compressed JPEG format. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`jpeg` module has been deprecated for removal in Python 3.0. + +Index: Doc/library/sunaudio.rst +=================================================================== +--- Doc/library/sunaudio.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/sunaudio.rst (.../branches/release26-maint) (Revision 70449) +@@ -6,7 +6,7 @@ + :platform: SunOS + :synopsis: Access to Sun audio hardware. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`sunaudiodev` module has been deprecated for removal in Python 3.0. + +@@ -151,7 +151,7 @@ + :platform: SunOS + :synopsis: Constants for use with sunaudiodev. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`SUNAUDIODEV` module has been deprecated for removal in Python 3.0. + +Index: Doc/library/urlparse.rst +=================================================================== +--- Doc/library/urlparse.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/urlparse.rst (.../branches/release26-maint) (Revision 70449) +@@ -290,7 +290,7 @@ + + .. versionadded:: 2.5 + +-The following classes provide the implementations of the parse results:: ++The following classes provide the implementations of the parse results: + + + .. class:: BaseResult +Index: Doc/library/macos.rst +=================================================================== +--- Doc/library/macos.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/macos.rst (.../branches/release26-maint) (Revision 70449) +@@ -82,7 +82,7 @@ + parameter can be a pathname or an ``FSSpec`` or ``FSRef`` object. + + .. note:: +- ++ + It is not possible to use an ``FSSpec`` in 64-bit mode. + + +@@ -93,7 +93,7 @@ + strings. + + .. note:: +- ++ + It is not possible to use an ``FSSpec`` in 64-bit mode. + + .. function:: openrf(name [, mode]) +Index: Doc/library/fm.rst +=================================================================== +--- Doc/library/fm.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/fm.rst (.../branches/release26-maint) (Revision 70449) +@@ -6,7 +6,7 @@ + :platform: IRIX + :synopsis: Font Manager interface for SGI workstations. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`fm` module has been deprecated for removal in Python 3.0. + +Index: Doc/library/rexec.rst +=================================================================== +--- Doc/library/rexec.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/rexec.rst (.../branches/release26-maint) (Revision 70449) +@@ -5,7 +5,7 @@ + .. module:: rexec + :synopsis: Basic restricted execution framework. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`rexec` module has been removed in Python 3.0. + +@@ -272,7 +272,7 @@ + pass + elif mode in ('w', 'wb', 'a', 'ab'): + # check filename : must begin with /tmp/ +- if file[:5]!='/tmp/': ++ if file[:5]!='/tmp/': + raise IOError, "can't write outside /tmp" + elif (string.find(file, '/../') >= 0 or + file[:3] == '../' or file[-3:] == '/..'): +Index: Doc/library/httplib.rst +=================================================================== +--- Doc/library/httplib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/httplib.rst (.../branches/release26-maint) (Revision 70449) +@@ -40,7 +40,8 @@ + server. It should be instantiated passing it a host and optional port + number. If no port number is passed, the port is extracted from the host + string if it has the form ``host:port``, else the default HTTP port (80) is +- used. When True, the optional parameter *strict* causes ``BadStatusLine`` to ++ used. When True, the optional parameter *strict* (which defaults to a false ++ value) causes ``BadStatusLine`` to + be raised if the status line can't be parsed as a valid HTTP/1.0 or 1.1 + status line. If the optional *timeout* parameter is given, blocking + operations (like connection attempts) will timeout after that many seconds +Index: Doc/library/json.rst +=================================================================== +--- Doc/library/json.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/json.rst (.../branches/release26-maint) (Revision 70449) +@@ -14,7 +14,7 @@ + :mod:`marshal` and :mod:`pickle` modules. + + Encoding basic Python object hierarchies:: +- ++ + >>> import json + >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) + '["foo", {"bar": ["baz", null, 1.0, 2]}]' +@@ -43,12 +43,12 @@ + >>> import json + >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) + { +- "4": 5, ++ "4": 5, + "6": 7 + } + + Decoding JSON:: +- ++ + >>> import json + >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') + [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] +@@ -66,7 +66,7 @@ + ... if '__complex__' in dct: + ... return complex(dct['real'], dct['imag']) + ... return dct +- ... ++ ... + >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', + ... object_hook=as_complex) + (1+2j) +@@ -75,26 +75,26 @@ + Decimal('1.1') + + Extending :class:`JSONEncoder`:: +- ++ + >>> import json + >>> class ComplexEncoder(json.JSONEncoder): + ... def default(self, obj): + ... if isinstance(obj, complex): + ... return [obj.real, obj.imag] + ... return json.JSONEncoder.default(self, obj) +- ... ++ ... + >>> dumps(2 + 1j, cls=ComplexEncoder) + '[2.0, 1.0]' + >>> ComplexEncoder().encode(2 + 1j) + '[2.0, 1.0]' + >>> list(ComplexEncoder().iterencode(2 + 1j)) + ['[', '2.0', ', ', '1.0', ']'] +- + ++ + .. highlight:: none + + Using json.tool from the shell to validate and pretty-print:: +- ++ + $ echo '{"json":"obj"}' | python -mjson.tool + { + "json": "obj" +@@ -104,7 +104,7 @@ + + .. highlight:: python + +-.. note:: ++.. note:: + + The JSON produced by this module's default settings is a subset of + YAML, so it may be used as a serializer for that as well. +@@ -152,7 +152,7 @@ + *default(obj)* is a function that should return a serializable version of + *obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`. + +- To use a custom :class:`JSONEncoder`` subclass (e.g. one that overrides the ++ To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the + :meth:`default` method to serialize additional types), specify it with the + *cls* kwarg. + +@@ -166,7 +166,7 @@ + :func:`dump`. + + +-.. function load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, **kw]]]]]]]) ++.. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, **kw]]]]]]]) + + Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON + document) to a Python object. +@@ -202,7 +202,7 @@ + class. + + +-.. function loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, **kw]]]]]]]) ++.. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, **kw]]]]]]]) + + Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON + document) to a Python object. +@@ -368,7 +368,7 @@ + + For example, to support arbitrary iterators, you could implement default + like this:: +- ++ + def default(self, o): + try: + iterable = iter(o) +@@ -392,6 +392,6 @@ + + Encode the given object, *o*, and yield each string representation as + available. For example:: +- ++ + for chunk in JSONEncoder().iterencode(bigobject): + mysocket.write(chunk) + +Eigenschaftsänderungen: Doc/library/json.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/xml.etree.elementtree.rst +=================================================================== +--- Doc/library/xml.etree.elementtree.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/xml.etree.elementtree.rst (.../branches/release26-maint) (Revision 70449) +@@ -34,7 +34,7 @@ + A C implementation of this API is available as :mod:`xml.etree.cElementTree`. + + See http://effbot.org/zone/element-index.htm for tutorials and links to other +-docs. Fredrik Lundh's page is also the location of the development version of the ++docs. Fredrik Lundh's page is also the location of the development version of the + xml.etree.ElementTree. + + .. _elementtree-functions: +@@ -94,7 +94,17 @@ + *events* is a list of events to report back. If omitted, only "end" events are + reported. Returns an :term:`iterator` providing ``(event, elem)`` pairs. + ++ .. note:: + ++ :func:`iterparse` only guarantees that it has seen the ">" ++ character of a starting tag when it emits a "start" event, so the ++ attributes are defined, but the contents of the text and tail attributes ++ are undefined at that point. The same applies to the element children; ++ they may or may not be present. ++ ++ If you need a fully populated element, look for "end" events instead. ++ ++ + .. function:: parse(source[, parser]) + + Parses an XML section into an element tree. *source* is a filename or file +@@ -369,7 +379,7 @@ + Example page + + +-

    Moved to example.org ++

    Moved to example.org + or example.com.

    + + +@@ -476,9 +486,9 @@ + + :meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method + for each opening tag, its :meth:`end` method for each closing tag, +-and data is processed by method :meth:`data`. :meth:`XMLTreeBuilder.close` +-calls *target*\'s method :meth:`close`. +-:class:`XMLTreeBuilder` can be used not only for building a tree structure. ++and data is processed by method :meth:`data`. :meth:`XMLTreeBuilder.close` ++calls *target*\'s method :meth:`close`. ++:class:`XMLTreeBuilder` can be used not only for building a tree structure. + This is an example of counting the maximum depth of an XML file:: + + >>> from xml.etree.ElementTree import XMLTreeBuilder +@@ -486,16 +496,16 @@ + ... maxDepth = 0 + ... depth = 0 + ... def start(self, tag, attrib): # Called for each opening tag. +- ... self.depth += 1 ++ ... self.depth += 1 + ... if self.depth > self.maxDepth: + ... self.maxDepth = self.depth + ... def end(self, tag): # Called for each closing tag. + ... self.depth -= 1 +- ... def data(self, data): ++ ... def data(self, data): + ... pass # We do not need to do anything with data. + ... def close(self): # Called when all data has been parsed. + ... return self.maxDepth +- ... ++ ... + >>> target = MaxDepth() + >>> parser = XMLTreeBuilder(target=target) + >>> exampleXml = """ +@@ -519,5 +529,5 @@ + .. [#] The encoding string included in XML output should conform to the + appropriate standards. For example, "UTF-8" is valid, but "UTF8" is + not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl +- and http://www.iana.org/assignments/character-sets . ++ and http://www.iana.org/assignments/character-sets. + + +Eigenschaftsänderungen: Doc/library/scrolledtext.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/bsddb.rst +=================================================================== +--- Doc/library/bsddb.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/bsddb.rst (.../branches/release26-maint) (Revision 70449) +@@ -17,7 +17,7 @@ + objects the user must serialize them somehow, typically using + :func:`marshal.dumps` or :func:`pickle.dumps`. + +-The :mod:`bsddb` module requires a Berkeley DB library version from 3.3 thru ++The :mod:`bsddb` module requires a Berkeley DB library version from 4.0 thru + 4.7. + + +@@ -172,7 +172,7 @@ + >>> import bsddb + >>> db = bsddb.btopen('/tmp/spam.db', 'c') + >>> for i in range(10): db['%d'%i] = '%d'% (i*i) +- ... ++ ... + >>> db['3'] + '9' + >>> db.keys() +@@ -185,7 +185,7 @@ + ('9', '81') + >>> db.set_location('2') + ('2', '4') +- >>> db.previous() ++ >>> db.previous() + ('1', '1') + >>> for k, v in db.iteritems(): + ... print k, v +Index: Doc/library/unittest.rst +=================================================================== +--- Doc/library/unittest.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/unittest.rst (.../branches/release26-maint) (Revision 70449) +@@ -595,7 +595,7 @@ + TestCase.failUnlessAlmostEqual(first, second[, places[, msg]]) + + Test that *first* and *second* are approximately equal by computing the +- difference, rounding to the given number of decimal *places* (default 7), ++ difference, rounding to the given number of decimal *places* (default 7), + and comparing to zero. + Note that comparing a given number of decimal places is not the same as + comparing a given number of significant digits. If the values do not compare +@@ -606,7 +606,7 @@ + TestCase.failIfAlmostEqual(first, second[, places[, msg]]) + + Test that *first* and *second* are not approximately equal by computing the +- difference, rounding to the given number of decimal *places* (default 7), ++ difference, rounding to the given number of decimal *places* (default 7), + and comparing to zero. + Note that comparing a given number of decimal places is not the same as + comparing a given number of significant digits. If the values do not compare +Index: Doc/library/unicodedata.rst +=================================================================== +--- Doc/library/unicodedata.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/unicodedata.rst (.../branches/release26-maint) (Revision 70449) +@@ -164,7 +164,7 @@ + File "", line 1, in ? + ValueError: not a decimal + >>> unicodedata.category(u'A') # 'L'etter, 'u'ppercase +- 'Lu' ++ 'Lu' + >>> unicodedata.bidirectional(u'\u0660') # 'A'rabic, 'N'umber + 'AN' + +Index: Doc/library/sqlite3.rst +=================================================================== +--- Doc/library/sqlite3.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/sqlite3.rst (.../branches/release26-maint) (Revision 70449) +@@ -223,8 +223,8 @@ + + .. attribute:: Connection.isolation_level + +- Get or set the current isolation level. :const:`None` for autocommit mode or one of +- "DEFERRED", "IMMEDIATE" or "EXLUSIVE". See section ++ Get or set the current isolation level. :const:`None` for autocommit mode or ++ one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section + :ref:`sqlite3-controlling-transactions` for a more detailed explanation. + + +@@ -244,7 +244,7 @@ + + .. method:: Connection.rollback() + +- This method rolls back any changes to the database since the last call to ++ This method rolls back any changes to the database since the last call to + :meth:`commit`. + + .. method:: Connection.close() +@@ -487,30 +487,30 @@ + .. literalinclude:: ../includes/sqlite3/executescript.py + + +-.. method:: Cursor.fetchone() +- ++.. method:: Cursor.fetchone() ++ + Fetches the next row of a query result set, returning a single sequence, + or :const:`None` when no more data is available. + + + .. method:: Cursor.fetchmany([size=cursor.arraysize]) +- ++ + Fetches the next set of rows of a query result, returning a list. An empty + list is returned when no more rows are available. +- ++ + The number of rows to fetch per call is specified by the *size* parameter. + If it is not given, the cursor's arraysize determines the number of rows + to be fetched. The method should try to fetch as many rows as indicated by + the size parameter. If this is not possible due to the specified number of + rows not being available, fewer rows may be returned. +- ++ + Note there are performance considerations involved with the *size* parameter. + For optimal performance, it is usually best to use the arraysize attribute. + If the *size* parameter is used, then it is best for it to retain the same + value from one :meth:`fetchmany` call to the next. +- +-.. method:: Cursor.fetchall() + ++.. method:: Cursor.fetchall() ++ + Fetches all (remaining) rows of a query result, returning a list. Note that + the cursor's arraysize attribute can affect the performance of this operation. + An empty list is returned when no rows are available. +@@ -546,8 +546,8 @@ + + This read-only attribute provides the column names of the last query. To + remain compatible with the Python DB API, it returns a 7-tuple for each +- column where the last six items of each tuple are :const:`None`. +- ++ column where the last six items of each tuple are :const:`None`. ++ + It is set for ``SELECT`` statements without any matching rows as well. + + .. _sqlite3-row-objects: +@@ -558,7 +558,7 @@ + .. class:: Row + + A :class:`Row` instance serves as a highly optimized +- :attr:`~Connection.row_factory` for :class:`Connection` objects. ++ :attr:`~Connection.row_factory` for :class:`Connection` objects. + It tries to mimic a tuple in most of its features. + + It supports mapping access by column name and index, iteration, +@@ -566,7 +566,7 @@ + + If two :class:`Row` objects have exactly the same columns and their + members are equal, they compare equal. +- ++ + .. versionchanged:: 2.6 + Added iteration and equality (hashability). + +@@ -793,7 +793,7 @@ + ------------------------ + + By default, the :mod:`sqlite3` module opens transactions implicitly before a +-Data Modification Language (DML) statement (i.e. ++Data Modification Language (DML) statement (i.e. + ``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions + implicitly before a non-DML, non-query statement (i. e. + anything other than ``SELECT`` or the aforementioned). +Index: Doc/library/multiprocessing.rst +=================================================================== +--- Doc/library/multiprocessing.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/multiprocessing.rst (.../branches/release26-maint) (Revision 70449) +@@ -21,9 +21,9 @@ + .. warning:: + + Some of this package's functionality requires a functioning shared semaphore +- implementation on the host operating system. Without one, the +- :mod:`multiprocessing.synchronize` module will be disabled, and attempts to +- import it will result in an :exc:`ImportError`. See ++ implementation on the host operating system. Without one, the ++ :mod:`multiprocessing.synchronize` module will be disabled, and attempts to ++ import it will result in an :exc:`ImportError`. See + :issue:`3770` for additional information. + + .. note:: +@@ -37,8 +37,8 @@ + >>> from multiprocessing import Pool + >>> p = Pool(5) + >>> def f(x): +- ... return x*x +- ... ++ ... return x*x ++ ... + >>> p.map(f, [1,2,3]) + Process PoolWorker-1: + Process PoolWorker-2: +@@ -77,11 +77,11 @@ + print 'module name:', __name__ + print 'parent process:', os.getppid() + print 'process id:', os.getpid() +- ++ + def f(name): + info('function f') + print 'hello', name +- ++ + if __name__ == '__main__': + info('main line') + p = Process(target=f, args=('bob',)) +@@ -109,12 +109,12 @@ + def f(q): + q.put([42, None, 'hello']) + +- if __name__ == '__main__': +- q = Queue() +- p = Process(target=f, args=(q,)) +- p.start() +- print q.get() # prints "[42, None, 'hello']" +- p.join() ++ if __name__ == '__main__': ++ q = Queue() ++ p = Process(target=f, args=(q,)) ++ p.start() ++ print q.get() # prints "[42, None, 'hello']" ++ p.join() + + Queues are thread and process safe. + +@@ -358,7 +358,7 @@ + + .. attribute:: daemon + +- The process's daemon flag, a Boolean value. This must be called before ++ The process's daemon flag, a Boolean value. This must be set before + :meth:`start` is called. + + The initial value is inherited from the creating process. +@@ -543,7 +543,7 @@ + + .. method:: put(item[, block[, timeout]]) + +- Put item into the queue. If the optional argument *block* is ``True`` ++ Put item into the queue. If the optional argument *block* is ``True`` + (the default) and *timeout* is ``None`` (the default), block if necessary until + a free slot is available. If *timeout* is a positive number, it blocks at + most *timeout* seconds and raises the :exc:`Queue.Full` exception if no +@@ -858,7 +858,7 @@ + acceptable. If *block* is ``True`` and *timeout* is not ``None`` then it + specifies a timeout in seconds. If *block* is ``False`` then *timeout* is + ignored. +- ++ + Note that on OS/X ``sem_timedwait`` is unsupported, so timeout arguments + for these will be ignored. + +@@ -880,7 +880,7 @@ + It is possible to create shared objects using shared memory which can be + inherited by child processes. + +-.. function:: Value(typecode_or_type[, *args, lock]]) ++.. function:: Value(typecode_or_type, *args[, lock]) + + Return a :mod:`ctypes` object allocated from shared memory. By default the + return value is actually a synchronized wrapper for the object. +@@ -919,7 +919,7 @@ + + Note that *lock* is a keyword only argument. + +- Note that an array of :data:`ctypes.c_char` has *value* and *rawvalue* ++ Note that an array of :data:`ctypes.c_char` has *value* and *raw* + attributes which allow one to use it to store and retrieve strings. + + +@@ -962,17 +962,17 @@ + + *typecode_or_type* determines the type of the returned object: it is either a + ctypes type or a one character typecode of the kind used by the :mod:`array` +- module. */*args* is passed on to the constructor for the type. ++ module. *\*args* is passed on to the constructor for the type. + + Note that setting and getting the value is potentially non-atomic -- use + :func:`Value` instead to make sure that access is automatically synchronized + using a lock. + +- Note that an array of :data:`ctypes.c_char` has ``value`` and ``rawvalue`` ++ Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw`` + attributes which allow one to use it to store and retrieve strings -- see + documentation for :mod:`ctypes`. + +-.. function:: Array(typecode_or_type, size_or_initializer[, *args[, lock]]) ++.. function:: Array(typecode_or_type, size_or_initializer, *args[, lock]) + + The same as :func:`RawArray` except that depending on the value of *lock* a + process-safe synchronization wrapper may be returned instead of a raw ctypes +@@ -1135,22 +1135,22 @@ + 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 +- the control of the Manager. The :class:`Server` object supports the +- :meth:`serve_forever` method:: +- +- >>> from multiprocessing.managers import BaseManager +- >>> m = BaseManager(address=('', 50000), authkey='abc')) +- >>> server = m.get_server() +- >>> s.serve_forever() +- +- :class:`Server` additionally have an :attr:`address` attribute. ++ the control of the Manager. The :class:`Server` object supports the ++ :meth:`serve_forever` method: + ++ >>> from multiprocessing.managers import BaseManager ++ >>> m = BaseManager(address=('', 50000), authkey='abc')) ++ >>> server = m.get_server() ++ >>> s.serve_forever() ++ ++ :class:`Server` additionally have an :attr:`address` attribute. ++ + .. method:: connect() +- +- Connect a local manager object to a remote manager process:: +- ++ ++ Connect a local manager object to a remote manager process: ++ + >>> from multiprocessing.managers import BaseManager + >>> m = BaseManager(address='127.0.0.1', authkey='abc)) + >>> m.connect() +@@ -1295,7 +1295,7 @@ + >>>>>>>>>>>>>>>>>>> + + To create one's own manager, one creates a subclass of :class:`BaseManager` and +-use the :meth:`~BaseManager.resgister` classmethod to register new types or ++use the :meth:`~BaseManager.register` classmethod to register new types or + callables with the manager class. For example:: + + from multiprocessing.managers import BaseManager +@@ -1360,7 +1360,7 @@ + >>> queue.get() + 'hello' + +-Local processes can also access that queue, using the code from above on the ++Local processes can also access that queue, using the code from above on the + client to access it remotely:: + + >>> from multiprocessing import Process, Queue +@@ -1371,12 +1371,12 @@ + ... super(Worker, self).__init__() + ... def run(self): + ... self.q.put('local hello') +- ... ++ ... + >>> queue = Queue() + >>> w = Worker(queue) + >>> w.start() + >>> class QueueManager(BaseManager): pass +- ... ++ ... + >>> QueueManager.register('get_queue', callable=lambda: queue) + >>> m = QueueManager(address=('', 50000), authkey='abracadabra') + >>> s = m.get_server() +@@ -1438,13 +1438,13 @@ + + Proxy objects are instances of subclasses of :class:`BaseProxy`. + +- .. method:: _call_method(methodname[, args[, kwds]]) ++ .. method:: _callmethod(methodname[, args[, kwds]]) + + Call and return the result of a method of the proxy's referent. + + If ``proxy`` is a proxy whose referent is ``obj`` then the expression :: + +- proxy._call_method(methodname, args, kwds) ++ proxy._callmethod(methodname, args, kwds) + + will evaluate the expression :: + +@@ -1457,26 +1457,26 @@ + argument of :meth:`BaseManager.register`. + + If an exception is raised by the call, then then is re-raised by +- :meth:`_call_method`. If some other exception is raised in the manager's ++ :meth:`_callmethod`. If some other exception is raised in the manager's + process then this is converted into a :exc:`RemoteError` exception and is +- raised by :meth:`_call_method`. ++ raised by :meth:`_callmethod`. + + Note in particular that an exception will be raised if *methodname* has + not been *exposed* + +- An example of the usage of :meth:`_call_method`:: ++ An example of the usage of :meth:`_callmethod`:: + + >>> l = manager.list(range(10)) +- >>> l._call_method('__len__') ++ >>> l._callmethod('__len__') + 10 +- >>> l._call_method('__getslice__', (2, 7)) # equiv to `l[2:7]` ++ >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]` + [2, 3, 4, 5, 6] +- >>> l._call_method('__getitem__', (20,)) # equiv to `l[20]` ++ >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]` + Traceback (most recent call last): + ... + IndexError: list index out of range + +- .. method:: _get_value() ++ .. method:: _getvalue() + + Return a copy of the referent. + +@@ -1810,9 +1810,9 @@ + filesystem. + + * An ``'AF_PIPE'`` address is a string of the form +- ``r'\\\\.\\pipe\\PipeName'``. To use :func:`Client` to connect to a named +- pipe on a remote computer called ServerName* one should use an address of the +- form ``r'\\\\ServerName\\pipe\\PipeName'`` instead. ++ :samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named ++ pipe on a remote computer called *ServerName* one should use an address of the ++ form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead. + + Note that any string beginning with two backslashes is assumed by default to be + an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address. +@@ -1870,7 +1870,7 @@ + Below is an example session with logging turned on:: + + >>> import multiprocessing, logging +- >>> logger = multiprocessing.getLogger() ++ >>> logger = multiprocessing.get_logger() + >>> logger.setLevel(logging.INFO) + >>> logger.warning('doomed') + [WARNING/MainProcess] doomed +@@ -2120,7 +2120,7 @@ + .. literalinclude:: ../includes/mp_benchmarks.py + + An example/demo of how to use the :class:`managers.SyncManager`, :class:`Process` +-and others to build a system which can distribute processes and work via a ++and others to build a system which can distribute processes and work via a + distributed queue to a "cluster" of machines on a network, accessible via SSH. + You will need to have private key authentication for all hosts configured for + this to work. + +Eigenschaftsänderungen: Doc/library/multiprocessing.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/xmlrpclib.rst +=================================================================== +--- Doc/library/xmlrpclib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/xmlrpclib.rst (.../branches/release26-maint) (Revision 70449) +@@ -318,9 +318,8 @@ + import xmlrpclib + + def python_logo(): +- handle = open("python_logo.jpg") +- return xmlrpclib.Binary(handle.read()) +- handle.close() ++ with open("python_logo.jpg") as handle: ++ return xmlrpclib.Binary(handle.read()) + + server = SimpleXMLRPCServer(("localhost", 8000)) + print "Listening on port 8000..." +@@ -333,9 +332,8 @@ + import xmlrpclib + + proxy = xmlrpclib.ServerProxy("http://localhost:8000/") +- handle = open("fetched_python_logo.jpg", "w") +- handle.write(proxy.python_logo().data) +- handle.close() ++ with open("fetched_python_logo.jpg", "w") as handle: ++ handle.write(proxy.python_logo().data) + + .. _fault-objects: + +@@ -560,8 +558,8 @@ + self.proxy = proxy + def make_connection(self, host): + self.realhost = host +- h = httplib.HTTP(self.proxy) +- return h ++ h = httplib.HTTP(self.proxy) ++ return h + def send_request(self, connection, handler, request_body): + connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler)) + def send_host(self, connection, host): +Index: Doc/library/gl.rst +=================================================================== +--- Doc/library/gl.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/gl.rst (.../branches/release26-maint) (Revision 70449) +@@ -6,8 +6,8 @@ + :platform: IRIX + :synopsis: Functions from the Silicon Graphics Graphics Library. + :deprecated: +- +- ++ ++ + .. deprecated:: 2.6 + The :mod:`gl` module has been deprecated for removal in Python 3.0. + +@@ -166,8 +166,8 @@ + :platform: IRIX + :synopsis: Constants used with the gl module. + :deprecated: +- +- ++ ++ + .. deprecated:: 2.6 + The :mod:`DEVICE` module has been deprecated for removal in Python 3.0. + +@@ -184,8 +184,8 @@ + :platform: IRIX + :synopsis: Constants used with the gl module. + :deprecated: +- +- ++ ++ + .. deprecated:: 2.6 + The :mod:`GL` module has been deprecated for removal in Python 3.0. + +Index: Doc/library/simplexmlrpcserver.rst +=================================================================== +--- Doc/library/simplexmlrpcserver.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/simplexmlrpcserver.rst (.../branches/release26-maint) (Revision 70449) +@@ -151,7 +151,7 @@ + requestHandler=RequestHandler) + server.register_introspection_functions() + +- # Register pow() function; this will use the value of ++ # Register pow() function; this will use the value of + # pow.__name__ as the name, which is just 'pow'. + server.register_function(pow) + +@@ -160,10 +160,10 @@ + return x + y + server.register_function(adder_function, 'add') + +- # Register an instance; all the methods of the instance are ++ # Register an instance; all the methods of the instance are + # published as XML-RPC methods (in this case, just 'div'). + class MyFuncs: +- def div(self, x, y): ++ def div(self, x, y): + return x // y + + server.register_instance(MyFuncs()) +Index: Doc/library/undoc.rst +=================================================================== +--- Doc/library/undoc.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/undoc.rst (.../branches/release26-maint) (Revision 70449) +@@ -21,7 +21,7 @@ + + :mod:`ihooks` + --- Import hook support (for :mod:`rexec`; may become obsolete). +- ++ + .. warning:: The :mod:`ihooks` module has been removed in Python 3.0. + + +@@ -54,7 +54,7 @@ + :mod:`linuxaudiodev` + --- Play audio data on the Linux audio device. Replaced in Python 2.3 by the + :mod:`ossaudiodev` module. +- ++ + .. warning:: The :mod:`linuxaudiodev` module has been removed in Python 3.0. + + :mod:`sunaudio` +@@ -240,7 +240,7 @@ + + :mod:`timing` + --- Measure time intervals to high resolution (use :func:`time.clock` instead). +- ++ + .. warning:: The :mod:`timing` module has been removed in Python 3.0. + + +@@ -255,6 +255,6 @@ + + :mod:`sv` + --- Interface to the "simple video" board on SGI Indigo (obsolete hardware). +- ++ + .. warning:: The :mod:`sv` module has been removed in Python 3.0. + +Index: Doc/library/optparse.rst +=================================================================== +--- Doc/library/optparse.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/optparse.rst (.../branches/release26-maint) (Revision 70449) +@@ -548,8 +548,8 @@ + :class:`OptionGroup` to a parser is easy:: + + group = OptionGroup(parser, "Dangerous Options", +- "Caution: use these options at your own risk. " +- "It is believed that some of them bite.") ++ "Caution: use these options at your own risk. " ++ "It is believed that some of them bite.") + group.add_option("-g", action="store_true", help="Group option.") + parser.add_option_group(group) + +@@ -563,12 +563,12 @@ + -q, --quiet be vewwy quiet (I'm hunting wabbits) + -fFILE, --file=FILE write output to FILE + -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate' +- [default], 'expert' ++ [default], 'expert' + + Dangerous Options: +- Caution: use of these options is at your own risk. It is believed that +- some of them bite. +- -g Group option. ++ Caution: use of these options is at your own risk. It is believed that ++ some of them bite. ++ -g Group option. + + .. _optparse-printing-version-string: + +@@ -799,7 +799,7 @@ + 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 ++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 +@@ -1511,7 +1511,7 @@ + records that the option was seen:: + + def record_foo_seen(option, opt_str, value, parser): +- parser.saw_foo = True ++ parser.values.saw_foo = True + + parser.add_option("--foo", action="callback", callback=record_foo_seen) + +@@ -1630,37 +1630,34 @@ + Nevertheless, here's a stab at a callback for an option with variable + arguments:: + +- def vararg_callback(option, opt_str, value, parser): +- assert value is None +- done = 0 +- value = [] +- rargs = parser.rargs +- while rargs: +- arg = rargs[0] ++ def vararg_callback(option, opt_str, value, parser): ++ assert value is None ++ value = [] + +- # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f", +- # etc. Note that this also stops on "-3" or "-3.0", so if +- # your option takes numeric values, you will need to handle +- # this. +- if ((arg[:2] == "--" and len(arg) > 2) or +- (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")): +- break +- else: +- value.append(arg) +- del rargs[0] ++ def floatable(str): ++ try: ++ float(str) ++ return True ++ except ValueError: ++ return False + +- setattr(parser.values, option.dest, value) ++ for arg in parser.rargs: ++ # stop on --foo like options ++ if arg[:2] == "--" and len(arg) > 2: ++ break ++ # stop on -a, but not on -3 or -3.0 ++ if arg[:1] == "-" and len(arg) > 1 and not floatable(arg): ++ break ++ value.append(arg) + ++ del parser.rargs[:len(value)] ++ setattr(parser.values, option.dest, value) ++ + [...] + parser.add_option("-c", "--callback", dest="vararg_attr", + action="callback", callback=vararg_callback) + +-The main weakness with this particular implementation is that negative numbers +-in the arguments following ``"-c"`` will be interpreted as further options +-(probably causing an error), rather than as arguments to ``"-c"``. Fixing this +-is left as an exercise for the reader. + +- + .. _optparse-extending-optparse: + + Extending :mod:`optparse` +Index: Doc/library/dl.rst +=================================================================== +--- Doc/library/dl.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/dl.rst (.../branches/release26-maint) (Revision 70449) +@@ -6,11 +6,11 @@ + :platform: Unix + :synopsis: Call C functions in shared objects. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`dl` module has been removed in Python 3.0. Use the :mod:`ctypes` + module instead. +- ++ + .. sectionauthor:: Moshe Zadka + + The :mod:`dl` module defines an interface to the :cfunc:`dlopen` function, which +@@ -91,9 +91,9 @@ + Return the pointer for the function named *name*, as a number, if it exists in + the referenced shared object, otherwise ``None``. This is useful in code like:: + +- >>> if a.sym('time'): ++ >>> if a.sym('time'): + ... a.call('time') +- ... else: ++ ... else: + ... time.time() + + (Note that this function will return a non-zero number, as zero is the *NULL* +Index: Doc/library/numbers.rst +=================================================================== +--- Doc/library/numbers.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/numbers.rst (.../branches/release26-maint) (Revision 70449) +@@ -51,14 +51,14 @@ + :func:`round`, :func:`math.floor`, :func:`math.ceil`, :func:`divmod`, ``//``, + ``%``, ``<``, ``<=``, ``>``, and ``>=``. + +- Real also provides defaults for :func:`complex`, :attr:`Complex.real`, +- :attr:`Complex.imag`, and :meth:`Complex.conjugate`. ++ Real also provides defaults for :func:`complex`, :attr:`~Complex.real`, ++ :attr:`~Complex.imag`, and :meth:`~Complex.conjugate`. + + + .. class:: Rational + + Subtypes :class:`Real` and adds +- :attr:`Rational.numerator` and :attr:`Rational.denominator` properties, which ++ :attr:`~Rational.numerator` and :attr:`~Rational.denominator` properties, which + should be in lowest terms. With these, it provides a default for + :func:`float`. + +@@ -74,8 +74,8 @@ + .. class:: Integral + + Subtypes :class:`Rational` and adds a conversion to :class:`int`. +- Provides defaults for :func:`float`, :attr:`Rational.numerator`, and +- :attr:`Rational.denominator`, and bit-string operations: ``<<``, ++ Provides defaults for :func:`float`, :attr:`~Rational.numerator`, and ++ :attr:`~Rational.denominator`, and bit-string operations: ``<<``, + ``>>``, ``&``, ``^``, ``|``, ``~``. + + +@@ -171,7 +171,7 @@ + knowledge of ``A``, so it can handle those instances before + delegating to :class:`Complex`. + +-If ``A<:Complex`` and ``B<:Real`` without sharing any other knowledge, ++If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge, + then the appropriate shared operation is the one involving the built + in :class:`complex`, and both :meth:`__radd__` s land there, so ``a+b + == b+a``. +Index: Doc/library/dis.rst +=================================================================== +--- Doc/library/dis.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/dis.rst (.../branches/release26-maint) (Revision 70449) +@@ -755,7 +755,7 @@ + opcode finds the keyword parameters first. For each keyword argument, the value + is on top of the key. Below the keyword parameters, the positional parameters + are on the stack, with the right-most parameter on top. Below the parameters, +- the function object to call is on the stack. Pops all function arguments, and ++ the function object to call is on the stack. Pops all function arguments, and + the function itself off the stack, and pushes the return value. + + +Index: Doc/library/base64.rst +=================================================================== +--- Doc/library/base64.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/base64.rst (.../branches/release26-maint) (Revision 70449) +@@ -63,7 +63,8 @@ + .. function:: urlsafe_b64encode(s) + + Encode string *s* using a URL-safe alphabet, which substitutes ``-`` instead of +- ``+`` and ``_`` instead of ``/`` in the standard Base64 alphabet. ++ ``+`` and ``_`` instead of ``/`` in the standard Base64 alphabet. The result ++ can still contain ``=``. + + + .. function:: urlsafe_b64decode(s) +Index: Doc/library/cgitb.rst +=================================================================== +--- Doc/library/cgitb.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/cgitb.rst (.../branches/release26-maint) (Revision 70449) +@@ -26,9 +26,10 @@ + functions, to help you debug the problem. Optionally, you can save this + information to a file instead of sending it to the browser. + +-To enable this feature, simply add one line to the top of your CGI script:: ++To enable this feature, simply add this to the top of your CGI script:: + +- import cgitb; cgitb.enable() ++ import cgitb ++ cgitb.enable() + + The options to the :func:`enable` function control whether the report is + displayed in the browser and whether the report is logged to a file for later +Index: Doc/library/mmap.rst +=================================================================== +--- Doc/library/mmap.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/mmap.rst (.../branches/release26-maint) (Revision 70449) +@@ -93,7 +93,7 @@ + will be relative to the offset from the beginning of the file. *offset* + defaults to 0. *offset* must be a multiple of the PAGESIZE or + ALLOCATIONGRANULARITY. +- ++ + This example shows a simple way of using :class:`mmap`:: + + import mmap +Index: Doc/library/al.rst +=================================================================== +--- Doc/library/al.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/al.rst (.../branches/release26-maint) (Revision 70449) +@@ -6,7 +6,7 @@ + :platform: IRIX + :synopsis: Audio functions on the SGI. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`al` module has been deprecated for removal in Python 3.0. + +Index: Doc/library/ssl.rst +=================================================================== +--- Doc/library/ssl.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/ssl.rst (.../branches/release26-maint) (Revision 70449) +@@ -48,7 +48,7 @@ + + .. exception:: SSLError + +- Raised to signal an error from the underlying SSL implementation. This ++ 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 +@@ -173,7 +173,7 @@ + >>> import time + >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")) + 'Wed May 9 00:00:00 2007' +- >>> ++ >>> + + .. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None) + +@@ -385,7 +385,7 @@ + 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, ++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 +@@ -422,13 +422,13 @@ + 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 ++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 ++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:: +@@ -570,7 +570,7 @@ + + And go back to listening for new client connections. + +- ++ + .. seealso:: + + Class :class:`socket.socket` +Index: Doc/library/codeop.rst +=================================================================== +--- Doc/library/codeop.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/codeop.rst (.../branches/release26-maint) (Revision 70449) +@@ -43,7 +43,7 @@ + other value will cause :exc:`ValueError` to be raised. + + .. warning:: +- ++ + It is possible (but not likely) that the parser stops parsing with a + successful outcome before reaching the end of the source; in this case, + trailing symbols may be ignored instead of causing an error. For example, +Index: Doc/library/fpformat.rst +=================================================================== +--- Doc/library/fpformat.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/fpformat.rst (.../branches/release26-maint) (Revision 70449) +@@ -5,10 +5,10 @@ + .. module:: fpformat + :synopsis: General floating point formatting functions. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`fpformat` module has been removed in Python 3.0. +- ++ + .. sectionauthor:: Moshe Zadka + + +Index: Doc/library/marshal.rst +=================================================================== +--- Doc/library/marshal.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/marshal.rst (.../branches/release26-maint) (Revision 70449) +@@ -45,7 +45,7 @@ + (they will cause infinite loops). + + .. warning:: +- ++ + On machines where C's ``long int`` type has more than 32 bits (such as the + DEC Alpha), it is possible to create plain Python integers that are longer + than 32 bits. If such an integer is marshaled and read back in on a machine +Index: Doc/library/fractions.rst +=================================================================== +--- Doc/library/fractions.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/fractions.rst (.../branches/release26-maint) (Revision 70449) +@@ -101,11 +101,11 @@ + + .. function:: gcd(a, b) + +- Return the greatest common divisor of the integers `a` and `b`. If +- either `a` or `b` is nonzero, then the absolute value of `gcd(a, +- b)` is the largest integer that divides both `a` and `b`. `gcd(a,b)` +- has the same sign as `b` if `b` is nonzero; otherwise it takes the sign +- of `a`. `gcd(0, 0)` returns `0`. ++ Return the greatest common divisor of the integers *a* and *b*. If either ++ *a* or *b* is nonzero, then the absolute value of ``gcd(a, b)`` is the ++ largest integer that divides both *a* and *b*. ``gcd(a,b)`` has the same ++ sign as *b* if *b* is nonzero; otherwise it takes the sign of *a*. ``gcd(0, ++ 0)`` returns ``0``. + + + .. seealso:: + +Eigenschaftsänderungen: Doc/library/fractions.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/statvfs.rst +=================================================================== +--- Doc/library/statvfs.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/statvfs.rst (.../branches/release26-maint) (Revision 70449) +@@ -4,7 +4,7 @@ + .. module:: statvfs + :synopsis: Constants for interpreting the result of os.statvfs(). + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`statvfs` module has been deprecated for removal in Python 3.0. + +Index: Doc/library/zipfile.rst +=================================================================== +--- Doc/library/zipfile.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/zipfile.rst (.../branches/release26-maint) (Revision 70449) +@@ -200,7 +200,7 @@ + + .. method:: ZipFile.extractall([path[, members[, pwd]]]) + +- Extract all members from the archive to the current working directory. *path* ++ Extract all members from the archive to the current working directory. *path* + specifies a different directory to extract to. *members* is optional and must + be a subset of the list returned by :meth:`namelist`. *pwd* is the password + used for encrypted files. +@@ -280,9 +280,9 @@ + + .. note:: + +- When passing a :class:`ZipInfo` instance as the *zinfo_or_acrname* parameter, +- the compression method used will be that specified in the *compress_type* +- member of the given :class:`ZipInfo` instance. By default, the ++ When passing a :class:`ZipInfo` instance as the *zinfo_or_acrname* parameter, ++ the compression method used will be that specified in the *compress_type* ++ member of the given :class:`ZipInfo` instance. By default, the + :class:`ZipInfo` constructor sets this member to :const:`ZIP_STORED`. + + The following data attributes are also available: +@@ -296,9 +296,9 @@ + + .. attribute:: ZipFile.comment + +- The comment text associated with the ZIP file. If assigning a comment to a +- :class:`ZipFile` instance created with mode 'a' or 'w', this should be a +- string no longer than 65535 bytes. Comments longer than this will be ++ The comment text associated with the ZIP file. If assigning a comment to a ++ :class:`ZipFile` instance created with mode 'a' or 'w', this should be a ++ string no longer than 65535 bytes. Comments longer than this will be + truncated in the written archive when :meth:`ZipFile.close` is called. + + .. _pyzipfile-objects: +@@ -327,10 +327,10 @@ + internal use only. The :meth:`writepy` method makes archives with file names + like this:: + +- string.pyc # Top level name +- test/__init__.pyc # Package directory ++ string.pyc # Top level name ++ test/__init__.pyc # Package directory + test/test_support.pyc # Module test.test_support +- test/bogus/__init__.pyc # Subpackage directory ++ test/bogus/__init__.pyc # Subpackage directory + test/bogus/myfile.pyc # Submodule test.bogus.myfile + + +Index: Doc/library/wsgiref.rst +=================================================================== +--- Doc/library/wsgiref.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/wsgiref.rst (.../branches/release26-maint) (Revision 70449) +@@ -170,7 +170,7 @@ + filelike = StringIO("This is an example file-like object"*10) + wrapper = FileWrapper(filelike, blksize=5) + +- for chunk in wrapper: ++ for chunk in wrapper: + print chunk + + +@@ -415,7 +415,7 @@ + from wsgiref.validate import validator + from wsgiref.simple_server import make_server + +- # Our callable object which is intentionally not compliant to the ++ # Our callable object which is intentionally not compliant to the + # standard, so the validator is going to break + def simple_app(environ, start_response): + status = '200 OK' # HTTP Status +Index: Doc/library/hashlib.rst +=================================================================== +--- Doc/library/hashlib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/hashlib.rst (.../branches/release26-maint) (Revision 70449) +@@ -4,8 +4,8 @@ + + .. module:: hashlib + :synopsis: Secure hash and message digest algorithms. +-.. moduleauthor:: Gregory P. Smith +-.. sectionauthor:: Gregory P. Smith ++.. moduleauthor:: Gregory P. Smith ++.. sectionauthor:: Gregory P. Smith + + + .. versionadded:: 2.5 +Index: Doc/library/stdtypes.rst +=================================================================== +--- Doc/library/stdtypes.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/stdtypes.rst (.../branches/release26-maint) (Revision 70449) +@@ -338,16 +338,14 @@ + module: math + single: floor() (in module math) + single: ceil() (in module math) ++ single: trunc() (in module math) + pair: numeric; conversions +- pair: C; language + +- Conversion from floating point to (long or plain) integer may round or +- truncate as in C; see functions :func:`math.floor` and :func:`math.ceil` for +- well-defined conversions. ++ Conversion from floats using :func:`int` or :func:`long` truncates toward ++ zero like the related function, :func:`math.trunc`. Use the function ++ :func:`math.floor` to round downward and :func:`math.ceil` to round ++ upward. + +- .. deprecated:: 2.6 +- Instead, convert floats to long explicitly with :func:`trunc`. +- + (3) + See :ref:`built-in-funcs` for a full description. + +@@ -362,9 +360,9 @@ + though the result's type is not necessarily int. + + (6) +- float also accepts the strings "nan" and "inf" with an optional prefix "+" ++ float also accepts the strings "nan" and "inf" with an optional prefix "+" + or "-" for Not a Number (NaN) and positive or negative infinity. +- ++ + .. versionadded:: 2.6 + + (7) +@@ -377,7 +375,7 @@ + +--------------------+------------------------------------+--------+ + | Operation | Result | Notes | + +====================+====================================+========+ +-| ``trunc(x)`` | *x* truncated to Integral | | ++| ``math.trunc(x)`` | *x* truncated to Integral | | + +--------------------+------------------------------------+--------+ + | ``round(x[, n])`` | *x* rounded to n digits, | | + | | rounding half to even. If n is | | +@@ -458,7 +456,7 @@ + original float and with a positive denominator. Raises + :exc:`OverflowError` on infinities and a :exc:`ValueError` on + NaNs. +- ++ + .. versionadded:: 2.6 + + Two methods support conversion to +@@ -603,11 +601,11 @@ + + There are six sequence types: strings, Unicode strings, lists, tuples, buffers, + and xrange objects. +-(For other containers see the built in :class:`dict`, :class:`list`, +-:class:`set`, and :class:`tuple` classes, and the :mod:`collections` +-module.) + ++For other containers see the built in :class:`dict` and :class:`set` classes, ++and the :mod:`collections` module. + ++ + .. index:: + object: sequence + object: string +@@ -797,9 +795,9 @@ + + .. method:: str.count(sub[, start[, end]]) + +- Return the number of occurrences of substring *sub* in the range [*start*, +- *end*]. Optional arguments *start* and *end* are interpreted as in slice +- notation. ++ Return the number of non-overlapping occurrences of substring *sub* in the ++ range [*start*, *end*]. Optional arguments *start* and *end* are ++ interpreted as in slice notation. + + + .. method:: str.decode([encoding[, errors]]) +@@ -1178,8 +1176,8 @@ + Return the numeric string left filled with zeros in a string of length + *width*. A sign prefix is handled correctly. The original string is + returned if *width* is less than ``len(s)``. +- + ++ + .. versionadded:: 2.2.2 + + The following methods are present only on unicode objects: +@@ -1190,7 +1188,7 @@ + otherwise. Numeric characters include digit characters, and all characters + that have the Unicode numeric value property, e.g. U+2155, + VULGAR FRACTION ONE FIFTH. +- ++ + .. method:: unicode.isdecimal() + + Return ``True`` if there are only decimal characters in S, ``False`` +@@ -1650,7 +1648,7 @@ + .. method:: union(other, ...) + set | other | ... + +- Return a new set with elements from both sets. ++ Return a new set with elements from the set and all others. + + .. versionchanged:: 2.6 + Accepts multiple input iterables. +@@ -1658,7 +1656,7 @@ + .. method:: intersection(other, ...) + set & other & ... + +- Return a new set with elements common to both sets. ++ Return a new set with elements common to the set and all others. + + .. versionchanged:: 2.6 + Accepts multiple input iterables. +@@ -1867,7 +1865,7 @@ + Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* + is not in the map. + +- .. versionadded:: 2.5 ++ .. versionadded:: 2.5 + If a subclass of dict defines a method :meth:`__missing__`, if the key + *key* is not present, the ``d[key]`` operation calls that method with + the key *key* as argument. The ``d[key]`` operation then returns or +@@ -2186,7 +2184,7 @@ + positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the + current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's + end). There is no return value. +- ++ + For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and + ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last. + + +Eigenschaftsänderungen: Doc/library/future_builtins.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/gettext.rst +=================================================================== +--- Doc/library/gettext.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/gettext.rst (.../branches/release26-maint) (Revision 70449) +@@ -648,10 +648,9 @@ + + animals = ['mollusk', + 'albatross', +- 'rat', +- 'penguin', +- 'python', +- ] ++ 'rat', ++ 'penguin', ++ 'python', ] + # ... + for a in animals: + print a +@@ -666,10 +665,9 @@ + + animals = [_('mollusk'), + _('albatross'), +- _('rat'), +- _('penguin'), +- _('python'), +- ] ++ _('rat'), ++ _('penguin'), ++ _('python'), ] + + del _ + +@@ -692,10 +690,9 @@ + + animals = [N_('mollusk'), + N_('albatross'), +- N_('rat'), +- N_('penguin'), +- N_('python'), +- ] ++ N_('rat'), ++ N_('penguin'), ++ N_('python'), ] + + # ... + for a in animals: +Index: Doc/library/ossaudiodev.rst +=================================================================== +--- Doc/library/ossaudiodev.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/ossaudiodev.rst (.../branches/release26-maint) (Revision 70449) +@@ -18,26 +18,26 @@ + use ALSA, you'll have to make sure its OSS compatibility layer + is active to use ossaudiodev, but you're gonna need it for the vast + majority of Linux audio apps anyways. +- ++ + Sounds like things are also complicated for other BSDs. In response + to my python-dev query, Thomas Wouters said: +- ++ + > Likewise, googling shows OpenBSD also uses OSS/Free -- the commercial + > OSS installation manual tells you to remove references to OSS/Free from the + > kernel :) +- ++ + but Aleksander Piotrowsk actually has an OpenBSD box, and he quotes + from its : + > * WARNING! WARNING! + > * This is an OSS (Linux) audio emulator. + > * Use the Native NetBSD API for developing new code, and this + > * only for compiling Linux programs. +- ++ + There's also an ossaudio manpage on OpenBSD that explains things + further. Presumably NetBSD and OpenBSD have a different standard + audio interface. That's the great thing about standards, there are so + many to choose from ... ;-) +- ++ + This probably all warrants a footnote or two, but I don't understand + things well enough right now to write it! --GPW + +Index: Doc/library/othergui.rst +=================================================================== +--- Doc/library/othergui.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/othergui.rst (.../branches/release26-maint) (Revision 70449) +@@ -70,7 +70,7 @@ + Robin Dunn. + + PyGTK, PyQt, and wxPython, all have a modern look and feel and more +-widgets than Tkinter. In addition, there are many other GUI toolkits for ++widgets than Tkinter. In addition, there are many other GUI toolkits for + Python, both cross-platform, and platform-specific. See the `GUI Programming + `_ page in the Python Wiki for a + much more complete list, and also for links to documents where the +Index: Doc/library/sgmllib.rst +=================================================================== +--- Doc/library/sgmllib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/sgmllib.rst (.../branches/release26-maint) (Revision 70449) +@@ -4,7 +4,7 @@ + .. module:: sgmllib + :synopsis: Only as much of an SGML parser as needed to parse HTML. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`sgmllib` module has been removed in Python 3.0. + +Index: Doc/library/mhlib.rst +=================================================================== +--- Doc/library/mhlib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/mhlib.rst (.../branches/release26-maint) (Revision 70449) +@@ -4,7 +4,7 @@ + .. module:: mhlib + :synopsis: Manipulate MH mailboxes from Python. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`mhlib` module has been removed in Python 3.0. Use the + :mod:`mailbox` instead. +Index: Doc/library/cmath.rst +=================================================================== +--- Doc/library/cmath.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/cmath.rst (.../branches/release26-maint) (Revision 70449) +@@ -70,9 +70,9 @@ + + .. function:: polar(x) + +- Convert a :class:`complex` from rectangular coordinates to polar ++ Convert a :class:`complex` from rectangular coordinates to polar + coordinates. The function returns a tuple with the two elements +- *r* and *phi*. *r* is the distance from 0 and *phi* the phase ++ *r* and *phi*. *r* is the distance from 0 and *phi* the phase + angle. + + .. versionadded:: 2.6 +Index: Doc/library/parser.rst +=================================================================== +--- Doc/library/parser.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/parser.rst (.../branches/release26-maint) (Revision 70449) +@@ -641,7 +641,7 @@ + while the long form uses an indented block and allows nested definitions:: + + def make_power(exp): +- "Make a function that raises an argument to the exponent `exp'." ++ "Make a function that raises an argument to the exponent `exp`." + def raiser(x, y=exp): + return x ** y + return raiser +Index: Doc/library/heapq.rst +=================================================================== +--- Doc/library/heapq.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/heapq.rst (.../branches/release26-maint) (Revision 70449) +@@ -88,6 +88,21 @@ + >>> print data == ordered + True + ++Using a heap to insert items at the correct place in a priority queue: ++ ++ >>> heap = [] ++ >>> data = [(1, 'J'), (4, 'N'), (3, 'H'), (2, 'O')] ++ >>> for item in data: ++ ... heappush(heap, item) ++ ... ++ >>> while heap: ++ ... print heappop(heap)[1] ++ J ++ O ++ H ++ N ++ ++ + The module also offers three general purpose functions based on heaps. + + +Index: Doc/library/crypt.rst +=================================================================== +--- Doc/library/crypt.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/crypt.rst (.../branches/release26-maint) (Revision 70449) +@@ -51,7 +51,7 @@ + username = raw_input('Python login:') + cryptedpasswd = pwd.getpwnam(username)[1] + if cryptedpasswd: +- if cryptedpasswd == 'x' or cryptedpasswd == '*': ++ if cryptedpasswd == 'x' or cryptedpasswd == '*': + raise "Sorry, currently no support for shadow passwords" + cleartext = getpass.getpass() + return crypt.crypt(cleartext, cryptedpasswd) == cryptedpasswd +Index: Doc/library/mutex.rst +=================================================================== +--- Doc/library/mutex.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/mutex.rst (.../branches/release26-maint) (Revision 70449) +@@ -5,7 +5,7 @@ + .. module:: mutex + :synopsis: Lock and queue for mutual exclusion. + :deprecated: +- ++ + .. deprecated:: + The :mod:`mutex` module has been removed in Python 3.0. + +Index: Doc/library/tempfile.rst +=================================================================== +--- Doc/library/tempfile.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/tempfile.rst (.../branches/release26-maint) (Revision 70449) +@@ -164,11 +164,11 @@ + + .. warning:: + +- Use of this function may introduce a security hole in your program. +- By the time you get around to doing anything with the file name it +- returns, someone else may have beaten you to the punch. +- :func:`mktemp` usage can be replaced easily with +- :func:`NamedTemporaryFile`, passing it the `delete=False` parameter:: ++ Use of this function may introduce a security hole in your program. By ++ the time you get around to doing anything with the file name it returns, ++ someone else may have beaten you to the punch. :func:`mktemp` usage can ++ be replaced easily with :func:`NamedTemporaryFile`, passing it the ++ ``delete=False`` parameter:: + + >>> f = NamedTemporaryFile(delete=False) + >>> f +Index: Doc/library/imgfile.rst +=================================================================== +--- Doc/library/imgfile.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/imgfile.rst (.../branches/release26-maint) (Revision 70449) +@@ -6,7 +6,7 @@ + :platform: IRIX + :synopsis: Support for SGI imglib files. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`imgfile` module has been deprecated for removal in Python 3.0. + +Index: Doc/library/collections.rst +=================================================================== +--- Doc/library/collections.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/collections.rst (.../branches/release26-maint) (Revision 70449) +@@ -53,36 +53,34 @@ + :class:`Hashable` ``__hash__`` + :class:`Iterable` ``__iter__`` + :class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__`` +-:class:`Sized` ``__len__`` ++:class:`Sized` ``__len__`` + :class:`Callable` ``__call__`` +- ++ + :class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``. +- :class:`Iterable`, and ``__len__`` ``index``, and ``count`` +- :class:`Container` +- +-:class:`MutableSequnce` :class:`Sequence` ``__getitem__`` Inherited Sequence methods and ++ :class:`Iterable`, ``index``, and ``count`` ++ :class:`Container` ++ ++:class:`MutableSequence` :class:`Sequence` ``__setitem__`` Inherited Sequence methods and + ``__delitem__``, ``append``, ``reverse``, ``extend``, ``pop``, +- ``insert``, ``remove``, and ``__iadd__`` +- and ``__len__`` +- +-:class:`Set` :class:`Sized`, ``__len__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``, +- :class:`Iterable`, ``__iter__``, and ``__gt__``, ``__ge__``, ``__and__``, ``__or__`` +- :class:`Container` ``__contains__`` ``__sub__``, ``__xor__``, and ``isdisjoint`` +- ++ and ``insert`` ``remove``, and ``__iadd__`` ++ ++:class:`Set` :class:`Sized`, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``, ++ :class:`Iterable`, ``__gt__``, ``__ge__``, ``__and__``, ``__or__`` ++ :class:`Container` ``__sub__``, ``__xor__``, and ``isdisjoint`` ++ + :class:`MutableSet` :class:`Set` ``add`` and Inherited Set methods and + ``discard`` ``clear``, ``pop``, ``remove``, ``__ior__``, + ``__iand__``, ``__ixor__``, and ``__isub__`` +- +-:class:`Mapping` :class:`Sized`, ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``, +- :class:`Iterable`, ``__len__``. and ``get``, ``__eq__``, and ``__ne__`` +- :class:`Container` ``__iter__`` +- +-:class:`MutableMapping` :class:`Mapping` ``__getitem__`` Inherited Mapping methods and +- ``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``, +- ``__delitem__``, and ``setdefault`` +- ``__iter__``, and +- ``__len__`` +- ++ ++:class:`Mapping` :class:`Sized`, ``__getitem__`` ``__contains__``, ``keys``, ``items``, ``values``, ++ :class:`Iterable`, ``get``, ``__eq__``, and ``__ne__`` ++ :class:`Container` ++ ++:class:`MutableMapping` :class:`Mapping` ``__setitem__`` and Inherited Mapping methods and ++ ``__delitem__`` ``pop``, ``popitem``, ``clear``, ``update``, ++ and ``setdefault`` ++ ++ + :class:`MappingView` :class:`Sized` ``__len__`` + :class:`KeysView` :class:`MappingView`, ``__contains__``, + :class:`Set` ``__iter__`` +@@ -96,7 +94,7 @@ + + size = None + if isinstance(myvar, collections.Sized): +- size = len(myvar) ++ size = len(myvar) + + Several of the ABCs are also useful as mixins that make it easier to develop + classes supporting container APIs. For example, to write a class supporting +@@ -487,16 +485,16 @@ + self-documenting code. They can be used wherever regular tuples are used, and + they add the ability to access fields by name instead of position index. + +-.. function:: namedtuple(typename, fieldnames, [verbose]) ++.. function:: namedtuple(typename, field_names, [verbose]) + + Returns a new tuple subclass named *typename*. The new subclass is used to + create tuple-like objects that have fields accessible by attribute lookup as + well as being indexable and iterable. Instances of the subclass also have a +- helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__` ++ helpful docstring (with typename and field_names) and a helpful :meth:`__repr__` + method which lists the tuple contents in a ``name=value`` format. + +- The *fieldnames* are a single string with each fieldname separated by whitespace +- and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *fieldnames* ++ The *field_names* are a single string with each fieldname separated by whitespace ++ and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *field_names* + can be a sequence of strings such as ``['x', 'y']``. + + Any valid Python identifier may be used for a fieldname except for names +@@ -549,8 +547,8 @@ + if kwds: + raise ValueError('Got unexpected field names: %r' % kwds.keys()) + return result +- +- def __getnewargs__(self): ++ ++ def __getnewargs__(self): + return tuple(self) + + x = property(itemgetter(0)) +@@ -639,7 +637,8 @@ + >>> getattr(p, 'x') + 11 + +-To convert a dictionary to a named tuple, use the double-star-operator [#]_: ++To convert a dictionary to a named tuple, use the double-star-operator ++(as described in :ref:`tut-unpacking-arguments`): + + >>> d = {'x': 11, 'y': 22} + >>> Point(**d) +@@ -686,7 +685,7 @@ + >>> class Status: + ... open, pending, closed = range(3) + +-.. rubric:: Footnotes ++.. seealso:: + +-.. [#] For information on the double-star-operator see +- :ref:`tut-unpacking-arguments` and :ref:`calls`. ++ `Named tuple recipe `_ ++ adapted for Python 2.4. +Index: Doc/library/os.rst +=================================================================== +--- Doc/library/os.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/os.rst (.../branches/release26-maint) (Revision 70449) +@@ -368,7 +368,7 @@ + is returned. Availability: Unix, Windows. + + .. deprecated:: 2.6 +- This function is obsolete. Use the :mod:`subprocess` module. Check ++ This function is obsolete. Use the :mod:`subprocess` module. Check + especially the :ref:`subprocess-replacements` section. + + .. versionchanged:: 2.0 +@@ -418,7 +418,7 @@ + child_stdout)``. + + .. deprecated:: 2.6 +- This function is obsolete. Use the :mod:`subprocess` module. Check ++ This function is obsolete. Use the :mod:`subprocess` module. Check + especially the :ref:`subprocess-replacements` section. + + Availability: Unix, Windows. +@@ -432,7 +432,7 @@ + child_stdout, child_stderr)``. + + .. deprecated:: 2.6 +- This function is obsolete. Use the :mod:`subprocess` module. Check ++ This function is obsolete. Use the :mod:`subprocess` module. Check + especially the :ref:`subprocess-replacements` section. + + Availability: Unix, Windows. +@@ -446,7 +446,7 @@ + child_stdout_and_stderr)``. + + .. deprecated:: 2.6 +- This function is obsolete. Use the :mod:`subprocess` module. Check ++ This function is obsolete. Use the :mod:`subprocess` module. Check + especially the :ref:`subprocess-replacements` section. + + Availability: Unix, Windows. +@@ -681,10 +681,11 @@ + :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`write` + method. + +-The following data items are available for use in constructing the *flags* +-parameter to the :func:`open` function. Some items will not be available on all +-platforms. For descriptions of their availability and use, consult +-:manpage:`open(2)`. ++The following constants are options for the *flags* parameter to the ++:func:`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. + + + .. data:: O_RDONLY +@@ -695,8 +696,7 @@ + O_EXCL + O_TRUNC + +- Options for the *flag* argument to the :func:`open` function. These can be +- combined using the bitwise OR operator ``|``. Availability: Unix, Windows. ++ These constants are available on Unix and Windows. + + + .. data:: O_DSYNC +@@ -708,8 +708,7 @@ + O_SHLOCK + O_EXLOCK + +- More options for the *flag* argument to the :func:`open` function. Availability: +- Unix. ++ These constants are only available on Unix. + + + .. data:: O_BINARY +@@ -720,8 +719,7 @@ + O_SEQUENTIAL + O_TEXT + +- Options for the *flag* argument to the :func:`open` function. These can be +- combined using the bitwise OR operator ``|``. Availability: Windows. ++ These constants are only available on Windows. + + + .. data:: O_ASYNC +@@ -730,8 +728,8 @@ + O_NOFOLLOW + O_NOATIME + +- Options for the *flag* argument to the :func:`open` function. These are +- GNU extensions and not present if they are not defined by the C library. ++ These constants are GNU extensions and not present if they are not defined by ++ the C library. + + + .. data:: SEEK_SET +@@ -933,10 +931,10 @@ + + .. function:: listdir(path) + +- Return a list containing the names of the entries in the directory. The list is +- in arbitrary order. It does not include the special entries ``'.'`` and +- ``'..'`` even if they are present in the directory. Availability: +- Unix, Windows. ++ Return a list containing the names of the entries in the directory given by ++ *path*. The list is in arbitrary order. It does not include the special ++ entries ``'.'`` and ``'..'`` even if they are present in the ++ directory. Availability: Unix, Windows. + + .. versionchanged:: 2.3 + On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be +@@ -1451,7 +1449,7 @@ + These functions all execute a new program, replacing the current process; they + do not return. On Unix, the new executable is loaded into the current process, + and will have the same process id as the caller. Errors will be reported as +- :exc:`OSError` exceptions. ++ :exc:`OSError` exceptions. + + The current process is replaced immediately. Open file objects and + descriptors are not flushed, so if there may be data buffered +@@ -1483,7 +1481,7 @@ + used to define the environment variables for the new process (these are used + instead of the current process' environment); the functions :func:`execl`, + :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to +- inherit the environment of the current process. ++ inherit the environment of the current process. + + Availability: Unix, Windows. + +@@ -1720,7 +1718,7 @@ + + (Note that the :mod:`subprocess` module provides more powerful facilities for + spawning new processes and retrieving their results; using that module is +- preferable to using these functions. Check specially the *Replacing Older ++ preferable to using these functions. Check specially the *Replacing Older + Functions with the subprocess Module* section in that documentation page.) + + If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new +Index: Doc/library/pyexpat.rst +=================================================================== +--- Doc/library/pyexpat.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/pyexpat.rst (.../branches/release26-maint) (Revision 70449) +@@ -182,9 +182,9 @@ + + .. attribute:: xmlparser.buffer_size + +- The size of the buffer used when :attr:`buffer_text` is true. +- A new buffer size can be set by assigning a new integer value +- to this attribute. ++ The size of the buffer used when :attr:`buffer_text` is true. ++ A new buffer size can be set by assigning a new integer value ++ to this attribute. + When the size is changed, the buffer will be flushed. + + .. versionadded:: 2.3 +Index: Doc/library/bz2.rst +=================================================================== +--- Doc/library/bz2.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/bz2.rst (.../branches/release26-maint) (Revision 70449) +@@ -93,7 +93,7 @@ + performance optimizations previously implemented in the :mod:`xreadlines` + module. + +- .. deprecated:: 2.3 ++ .. deprecated:: 2.3 + This exists only for compatibility with the method by this name on + :class:`file` objects, which is deprecated. Use ``for line in file`` + instead. +Index: Doc/library/dircache.rst +=================================================================== +--- Doc/library/dircache.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/dircache.rst (.../branches/release26-maint) (Revision 70449) +@@ -5,11 +5,11 @@ + .. module:: dircache + :synopsis: Return directory listing, with cache mechanism. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`dircache` module has been removed in Python 3.0. +- +- ++ ++ + .. sectionauthor:: Moshe Zadka + + +Index: Doc/library/nntplib.rst +=================================================================== +--- Doc/library/nntplib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/nntplib.rst (.../branches/release26-maint) (Revision 70449) +@@ -24,16 +24,16 @@ + Group comp.lang.python has 59 articles, range 3742 to 3803 + >>> resp, subs = s.xhdr('subject', first + '-' + last) + >>> for id, sub in subs[-10:]: print id, sub +- ... ++ ... + 3792 Re: Removing elements from a list while iterating... + 3793 Re: Who likes Info files? + 3794 Emacs and doc strings + 3795 a few questions about the Mac implementation + 3796 Re: executable python scripts + 3797 Re: executable python scripts +- 3798 Re: a few questions about the Mac implementation ++ 3798 Re: a few questions about the Mac implementation + 3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules +- 3802 Re: executable python scripts ++ 3802 Re: executable python scripts + 3803 Re: \POSIX{} wait and SIGCHLD + >>> s.quit() + '205 news.cwi.nl closing connection. Goodbye.' +Index: Doc/library/compiler.rst +=================================================================== +--- Doc/library/compiler.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/compiler.rst (.../branches/release26-maint) (Revision 70449) +@@ -559,24 +559,24 @@ + >>> import compiler + >>> mod = compiler.parseFile("/tmp/doublelib.py") + >>> mod +- Module('This is an example module.\n\nThis is the docstring.\n', ++ Module('This is an example module.\n\nThis is the docstring.\n', + Stmt([Function(None, 'double', ['x'], [], 0, +- 'Return twice the argument', ++ 'Return twice the argument', + Stmt([Return(Mul((Name('x'), Const(2))))]))])) + >>> from compiler.ast import * +- >>> Module('This is an example module.\n\nThis is the docstring.\n', ++ >>> Module('This is an example module.\n\nThis is the docstring.\n', + ... Stmt([Function(None, 'double', ['x'], [], 0, +- ... 'Return twice the argument', ++ ... 'Return twice the argument', + ... Stmt([Return(Mul((Name('x'), Const(2))))]))])) +- Module('This is an example module.\n\nThis is the docstring.\n', ++ Module('This is an example module.\n\nThis is the docstring.\n', + Stmt([Function(None, 'double', ['x'], [], 0, +- 'Return twice the argument', ++ 'Return twice the argument', + Stmt([Return(Mul((Name('x'), Const(2))))]))])) + >>> mod.doc + 'This is an example module.\n\nThis is the docstring.\n' + >>> for node in mod.node.nodes: + ... print node +- ... ++ ... + Function(None, 'double', ['x'], [], 0, 'Return twice the argument', + Stmt([Return(Mul((Name('x'), Const(2))))])) + >>> func = mod.node.nodes[0] +Index: Doc/library/pydoc.rst +=================================================================== +--- Doc/library/pydoc.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/pydoc.rst (.../branches/release26-maint) (Revision 70449) +@@ -36,6 +36,13 @@ + Unix), and refers to an existing Python source file, then documentation is + produced for that file. + ++.. note:: ++ ++ In order to find objects and their documentation, :mod:`pydoc` imports the ++ module(s) to be documented. Therefore, any code on module level will be ++ executed on that occasion. Use an ``if __name__ == '__main__':`` guard to ++ only execute code when a file is invoked as a script and not just imported. ++ + Specifying a :option:`-w` flag before the argument will cause HTML documentation + to be written out to a file in the current directory, instead of displaying text + on the console. +Index: Doc/library/traceback.rst +=================================================================== +--- Doc/library/traceback.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/traceback.rst (.../branches/release26-maint) (Revision 70449) +@@ -169,10 +169,10 @@ + + def lumberjack(): + bright_side_of_death() +- ++ + def bright_side_of_death(): + return tuple()[0] +- ++ + try: + lumberjack() + except: +@@ -251,12 +251,12 @@ + >>> import traceback + >>> def another_function(): + ... lumberstack() +- ... ++ ... + >>> def lumberstack(): + ... traceback.print_stack() + ... print repr(traceback.extract_stack()) + ... print repr(traceback.format_stack()) +- ... ++ ... + >>> another_function() + File "", line 10, in + another_function() +Index: Doc/library/ast.rst +=================================================================== +--- Doc/library/ast.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/ast.rst (.../branches/release26-maint) (Revision 70449) +@@ -21,13 +21,12 @@ + Python release; this module helps to find out programmatically what the current + grammar looks like. + +-An abstract syntax tree can be generated by passing :data:`_ast.PyCF_ONLY_AST` +-as a flag to the :func:`compile` builtin function, or using the :func:`parse` ++An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as ++a flag to the :func:`compile` builtin function, or using the :func:`parse` + helper provided in this module. The result will be a tree of objects whose +-classes all inherit from :class:`ast.AST`. ++classes all inherit from :class:`ast.AST`. An abstract syntax tree can be ++compiled into a Python code object using the built-in :func:`compile` function. + +-A modified abstract syntax tree can be compiled into a Python code object using +-the built-in :func:`compile` function. + + Node classes + ------------ +@@ -126,9 +125,9 @@ + .. function:: parse(expr, filename='', mode='exec') + + Parse an expression into an AST node. Equivalent to ``compile(expr, +- filename, mode, PyCF_ONLY_AST)``. ++ filename, mode, ast.PyCF_ONLY_AST)``. + +- ++ + .. function:: literal_eval(node_or_string) + + Safely evaluate an expression node or a string containing a Python +@@ -192,7 +191,7 @@ + + A node visitor base class that walks the abstract syntax tree and calls a + visitor function for every node found. This function may return a value +- which is forwarded by the `visit` method. ++ which is forwarded by the :meth:`visit` method. + + This class is meant to be subclassed, with the subclass adding visitor + methods. +@@ -206,7 +205,7 @@ + .. method:: generic_visit(node) + + This visitor calls :meth:`visit` on all children of the node. +- ++ + Note that child nodes of nodes that have a custom visitor method won't be + visited unless the visitor calls :meth:`generic_visit` or visits them + itself. +@@ -221,11 +220,11 @@ + A :class:`NodeVisitor` subclass that walks the abstract syntax tree and + allows modification of nodes. + +- The `NodeTransformer` will walk the AST and use the return value of the +- visitor methods to replace or remove the old node. If the return value of +- the visitor method is ``None``, the node will be removed from its location, +- otherwise it is replaced with the return value. The return value may be the +- original node in which case no replacement takes place. ++ The :class:`NodeTransformer` will walk the AST and use the return value of ++ the visitor methods to replace or remove the old node. If the return value ++ of the visitor method is ``None``, the node will be removed from its ++ location, otherwise it is replaced with the return value. The return value ++ may be the original node in which case no replacement takes place. + + Here is an example transformer that rewrites all occurrences of name lookups + (``foo``) to ``data['foo']``:: + +Eigenschaftsänderungen: Doc/library/ast.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/operator.rst +=================================================================== +--- Doc/library/operator.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/operator.rst (.../branches/release26-maint) (Revision 70449) +@@ -7,7 +7,7 @@ + + + .. testsetup:: +- ++ + import operator + from operator import itemgetter + +@@ -240,7 +240,11 @@ + + Delete the slice of *a* from index *b* to index *c-1*. + ++ .. deprecated:: 2.6 ++ This function is removed in Python 3.0. Use :func:`delitem` with a slice ++ index. + ++ + .. function:: getitem(a, b) + __getitem__(a, b) + +@@ -252,7 +256,11 @@ + + Return the slice of *a* from index *b* to index *c-1*. + ++ .. deprecated:: 2.6 ++ This function is removed in Python 3.0. Use :func:`getitem` with a slice ++ index. + ++ + .. function:: indexOf(a, b) + + Return the index of the first of occurrence of *b* in *a*. +@@ -261,6 +269,9 @@ + .. function:: repeat(a, b) + __repeat__(a, b) + ++ .. deprecated:: 2.6 ++ This function is removed in Python 3.0. Use :func:`__mul__` instead. ++ + Return ``a * b`` where *a* is a sequence and *b* is an integer. + + +@@ -283,6 +294,20 @@ + + Set the slice of *a* from index *b* to index *c-1* to the sequence *v*. + ++ .. deprecated:: 2.6 ++ This function is removed in Python 3.0. Use :func:`setitem` with a slice ++ index. ++ ++Example use of operator functions:: ++ ++ >>> # Elementwise multiplication ++ >>> map(mul, [0, 1, 2, 3], [10, 20, 30, 40]) ++ [0, 20, 60, 120] ++ ++ >>> # Dot product ++ >>> sum(map(mul, [0, 1, 2, 3], [10, 20, 30, 40])) ++ 200 ++ + Many operations have an "in-place" version. The following functions provide a + more primitive access to in-place operators than the usual syntax does; for + example, the :term:`statement` ``x += y`` is equivalent to +@@ -374,6 +399,9 @@ + .. function:: irepeat(a, b) + __irepeat__(a, b) + ++ .. deprecated:: 2.6 ++ This function is removed in Python 3.0. Use :func:`__imul__` instead. ++ + ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and + *b* is an integer. + +@@ -414,33 +442,14 @@ + + + The :mod:`operator` module also defines a few predicates to test the type of +-objects. ++objects; however, these are not all reliable. It is preferable to test ++abstract base classes instead (see :mod:`collections` and ++:mod:`numbers` for details). + +-.. note:: +- +- Be careful not to misinterpret the results of these functions; only +- :func:`isCallable` has any measure of reliability with instance objects. +- For example: +- +- >>> class C: +- ... pass +- ... +- >>> import operator +- >>> obj = C() +- >>> operator.isMappingType(obj) +- True +- +-.. note:: +- +- Python 3 is expected to introduce abstract base classes for +- collection types, so it should be possible to write, for example, +- ``isinstance(obj, collections.Mapping)`` and ``isinstance(obj, +- collections.Sequence)``. +- + .. function:: isCallable(obj) + + .. deprecated:: 2.0 +- Use the :func:`callable` built-in function instead. ++ Use ``isinstance(x, collections.Callable)`` instead. + + Returns true if the object *obj* can be called like a function, otherwise it + returns false. True is returned for functions, bound and unbound methods, class +@@ -449,50 +458,32 @@ + + .. function:: isMappingType(obj) + ++ .. deprecated:: 2.6 ++ This function is removed in Python 3.0. Use ``isinstance(x, collections.Mapping)`` instead. ++ + Returns true if the object *obj* supports the mapping interface. This is true for + dictionaries and all instance objects defining :meth:`__getitem__`. + +- .. warning:: + +- There is no reliable way to test if an instance supports the complete mapping +- protocol since the interface itself is ill-defined. This makes this test less +- useful than it otherwise might be. +- +- + .. function:: isNumberType(obj) + ++ .. deprecated:: 2.6 ++ This function is removed in Python 3.0. Use ``isinstance(x, numbers.Number)`` instead. ++ + Returns true if the object *obj* represents a number. This is true for all + numeric types implemented in C. + +- .. warning:: + +- There is no reliable way to test if an instance supports the complete numeric +- interface since the interface itself is ill-defined. This makes this test less +- useful than it otherwise might be. +- +- + .. function:: isSequenceType(obj) + ++ .. deprecated:: 2.6 ++ This function is removed in Python 3.0. Use ``isinstance(x, collections.Sequence)`` instead. ++ + Returns true if the object *obj* supports the sequence protocol. This returns true + for all objects which define sequence methods in C, and for all instance objects + defining :meth:`__getitem__`. + +- .. warning:: + +- There is no reliable way to test if an instance supports the complete sequence +- interface since the interface itself is ill-defined. This makes this test less +- useful than it otherwise might be. +- +-Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to +-their character equivalents. +- +- >>> d = {} +- >>> keys = range(256) +- >>> vals = map(chr, keys) +- >>> map(operator.setitem, [d]*len(keys), keys, vals) # doctest: +SKIP +- +-.. XXX: find a better, readable, example +- + The :mod:`operator` module also defines tools for generalized attribute and item + lookups. These are useful for making fast field extractors as arguments for + :func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that +@@ -534,9 +525,9 @@ + def g(obj): + return tuple(obj[item] for item in items) + return g +- +- The items can be any type accepted by the operand's :meth:`__getitem__` +- method. Dictionaries accept any hashable value. Lists, tuples, and ++ ++ The items can be any type accepted by the operand's :meth:`__getitem__` ++ method. Dictionaries accept any hashable value. Lists, tuples, and + strings accept an index or a slice: + + >>> itemgetter(1)('ABCDEFG') + +Eigenschaftsänderungen: Doc/library/tix.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/io.rst +=================================================================== +--- Doc/library/io.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/io.rst (.../branches/release26-maint) (Revision 70449) +@@ -6,7 +6,7 @@ + .. moduleauthor:: Guido van Rossum + .. moduleauthor:: Mike Verdone + .. moduleauthor:: Mark Russell +-.. sectionauthor:: Benjamin Peterson ++.. sectionauthor:: Benjamin Peterson + .. versionadded:: 2.6 + + The :mod:`io` module provides the Python interfaces to stream handling. The +@@ -214,8 +214,10 @@ + + .. method:: close() + +- Flush and close this stream. This method has no effect if the file is +- already closed. ++ Flush and close this stream. This method has no effect if the file is ++ already closed. Once the file is closed, any operation on the file ++ (e.g. reading or writing) will raise an :exc:`IOError`. The internal ++ file descriptor isn't closed if *closefd* was False. + + .. attribute:: closed + +@@ -627,8 +629,8 @@ + .. attribute:: line_buffering + + Whether line buffering is enabled. +- + ++ + .. class:: StringIO([initial_value[, encoding[, errors[, newline]]]]) + + An in-memory stream for text. It in inherits :class:`TextIOWrapper`. + +Eigenschaftsänderungen: Doc/library/io.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/functions.rst +=================================================================== +--- Doc/library/functions.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/functions.rst (.../branches/release26-maint) (Revision 70449) +@@ -8,67 +8,6 @@ + available. They are listed here in alphabetical order. + + +-.. function:: __import__(name[, globals[, locals[, fromlist[, level]]]]) +- +- .. index:: +- statement: import +- module: ihooks +- module: rexec +- module: imp +- +- .. note:: +- +- This is an advanced function that is not needed in everyday Python +- programming. +- +- The function is invoked by the :keyword:`import` statement. It mainly exists +- so that you can replace it with another function that has a compatible +- interface, in order to change the semantics of the :keyword:`import` statement. +- See the built-in module :mod:`imp`, which defines some useful operations out +- of which you can build your own :func:`__import__` function. +- +- For example, the statement ``import spam`` results in the following call: +- ``__import__('spam', globals(), locals(), [], -1)``; the statement +- ``from spam.ham import eggs`` results in ``__import__('spam.ham', globals(), +- locals(), ['eggs'], -1)``. Note that even though ``locals()`` and ``['eggs']`` +- are passed in as arguments, the :func:`__import__` function does not set the +- local variable named ``eggs``; this is done by subsequent code that is generated +- for the import statement. (In fact, the standard implementation does not use +- its *locals* argument at all, and uses its *globals* only to determine the +- package context of the :keyword:`import` statement.) +- +- When the *name* variable is of the form ``package.module``, normally, the +- top-level package (the name up till the first dot) is returned, *not* the +- module named by *name*. However, when a non-empty *fromlist* argument is +- given, the module named by *name* is returned. This is done for +- compatibility with the :term:`bytecode` generated for the different kinds of import +- statement; when using ``import spam.ham.eggs``, the top-level package +- :mod:`spam` must be placed in the importing namespace, but when using ``from +- spam.ham import eggs``, the ``spam.ham`` subpackage must be used to find the +- ``eggs`` variable. As a workaround for this behavior, use :func:`getattr` to +- extract the desired components. For example, you could define the following +- helper:: +- +- def my_import(name): +- mod = __import__(name) +- components = name.split('.') +- for comp in components[1:]: +- mod = getattr(mod, comp) +- return mod +- +- *level* specifies whether to use absolute or relative imports. The default is +- ``-1`` which indicates both absolute and relative imports will be attempted. +- ``0`` means only perform absolute imports. Positive values for *level* indicate +- the number of parent directories to search relative to the directory of the +- module calling :func:`__import__`. +- +- .. versionchanged:: 2.5 +- The level parameter was added. +- +- .. versionchanged:: 2.5 +- Keyword support for parameters was added. +- +- + .. function:: abs(x) + + Return the absolute value of a number. The argument may be a plain or long +@@ -199,16 +138,9 @@ + + Compile the *source* into a code or AST object. Code objects can be executed + by an :keyword:`exec` statement or evaluated by a call to :func:`eval`. +- *source* can either be a string or an AST object. Refer to the :mod:`_ast` +- module documentation for information on how to compile into and from AST +- objects. ++ *source* can either be a string or an AST object. Refer to the :mod:`ast` ++ module documentation for information on how to work with AST objects. + +- When compiling a string with multi-line statements, two caveats apply: line +- endings must be represented by a single newline character (``'\n'``), and the +- input must be terminated by at least one newline character. If line endings +- are represented by ``'\r\n'``, use the string :meth:`replace` method to +- change them into ``'\n'``. +- + The *filename* argument should give the file from which the code was read; + pass some recognizable value if it wasn't read from a file (``''`` is + commonly used). +@@ -219,15 +151,15 @@ + interactive statement (in the latter case, expression statements that + evaluate to something else than ``None`` will be printed). + +- The optional arguments *flags* and *dont_inherit* (which are new in Python 2.2) +- control which future statements (see :pep:`236`) affect the compilation of +- *source*. If neither is present (or both are zero) the code is compiled with +- those future statements that are in effect in the code that is calling compile. +- If the *flags* argument is given and *dont_inherit* is not (or is zero) then the ++ The optional arguments *flags* and *dont_inherit* control which future ++ statements (see :pep:`236`) affect the compilation of *source*. If neither ++ is present (or both are zero) the code is compiled with those future ++ statements that are in effect in the code that is calling compile. If the ++ *flags* argument is given and *dont_inherit* is not (or is zero) then the + future statements specified by the *flags* argument are used in addition to + those that would be used anyway. If *dont_inherit* is a non-zero integer then +- the *flags* argument is it -- the future statements in effect around the call to +- compile are ignored. ++ the *flags* argument is it -- the future statements in effect around the call ++ to compile are ignored. + + Future statements are specified by bits which can be bitwise ORed together to + specify multiple statements. The bitfield required to specify a given feature +@@ -237,7 +169,18 @@ + This function raises :exc:`SyntaxError` if the compiled source is invalid, + and :exc:`TypeError` if the source contains null bytes. + +- .. versionadded:: 2.6 ++ .. note:: ++ ++ When compiling a string with multi-line statements, line endings must be ++ represented by a single newline character (``'\n'``), and the input must ++ be terminated by at least one newline character. If line endings are ++ represented by ``'\r\n'``, use :meth:`str.replace` to change them into ++ ``'\n'``. ++ ++ .. versionchanged:: 2.3 ++ The *flags* and *dont_inherit* arguments were added. ++ ++ .. versionchanged:: 2.6 + Support for compiling AST objects. + + +@@ -454,7 +397,10 @@ + iterable if function(item)]`` if function is not ``None`` and ``[item for item + in iterable if item]`` if function is ``None``. + ++ See :func:`itertools.filterfalse` for the complementary function that returns ++ elements of *iterable* for which *function* returns false. + ++ + .. function:: float([x]) + + Convert a string or a number to floating point. If the argument is a string, it +@@ -479,6 +425,26 @@ + + The float type is described in :ref:`typesnumeric`. + ++ ++.. function:: format(value[, format_spec]) ++ ++ .. index:: ++ pair: str; format ++ single: __format__ ++ ++ Convert a *value* to a "formatted" representation, as controlled by ++ *format_spec*. The interpretation of *format_spec* will depend on the type ++ of the *value* argument, however there is a standard formatting syntax that ++ is used by most built-in types: :ref:`formatspec`. ++ ++ .. note:: ++ ++ ``format(value, format_spec)`` merely calls ++ ``value.__format__(format_spec)``. ++ ++ .. versionadded:: 2.6 ++ ++ + .. function:: frozenset([iterable]) + :noindex: + +@@ -945,7 +911,7 @@ + .. versionchanged:: 2.5 + Use *fget*'s docstring if no *doc* given. + +- .. versionchanged:: 2.6 ++ .. versionchanged:: 2.6 + The ``getter``, ``setter``, and ``deleter`` attributes were added. + + +@@ -1134,7 +1100,8 @@ + default). They have no other explicit functionality; however they are used by + Numerical Python and other third party extensions. Slice objects are also + generated when extended indexing syntax is used. For example: +- ``a[start:stop:step]`` or ``a[start:stop, i]``. ++ ``a[start:stop:step]`` or ``a[start:stop, i]``. See :func:`itertools.islice` ++ for an alternate version that returns an iterator. + + + .. function:: sorted(iterable[, cmp[, key[, reverse]]]) +@@ -1157,10 +1124,12 @@ + *reverse* is a boolean value. If set to ``True``, then the list elements are + sorted as if each comparison were reversed. + +- In general, the *key* and *reverse* conversion processes are much faster than +- specifying an equivalent *cmp* function. This is because *cmp* is called +- multiple times for each list element while *key* and *reverse* touch each +- element only once. ++ In general, the *key* and *reverse* conversion processes are much faster ++ than specifying an equivalent *cmp* function. This is because *cmp* is ++ called multiple times for each list element while *key* and *reverse* touch ++ each element only once. To convert an old-style *cmp* function to a *key* ++ function, see the `CmpToKey recipe in the ASPN cookbook ++ `_\. + + .. versionadded:: 2.4 + +@@ -1217,47 +1186,62 @@ + and are not allowed to be strings. The fast, correct way to concatenate a + sequence of strings is by calling ``''.join(sequence)``. Note that + ``sum(range(n), m)`` is equivalent to ``reduce(operator.add, range(n), m)`` ++ To add floating point values with extended precision, see :func:`math.fsum`\. + + .. versionadded:: 2.3 + + + .. function:: super(type[, object-or-type]) + +- Return a "super" object that acts like the superclass of *type*. ++ Return a proxy object that delegates method calls to a parent or sibling ++ class of *type*. This is useful for accessing inherited methods that have ++ been overridden in a class. The search order is same as that used by ++ :func:`getattr` except that the *type* itself is skipped. + +- If the second argument is omitted the super +- object returned is unbound. If the second argument is an object, +- ``isinstance(obj, type)`` must be true. If the second argument is a type, +- ``issubclass(type2, type)`` must be true. :func:`super` only works for +- :term:`new-style class`\es. ++ The :attr:`__mro__` attribute of the *type* lists the method resolution ++ search order used by both :func:`getattr` and :func:`super`. The attribute ++ is dynamic and can change whenever the inheritance hierarchy is updated. + +- There are two typical use cases for "super". In a class hierarchy with +- single inheritance, "super" can be used to refer to parent classes without ++ If the second argument is omitted, the super object returned is unbound. If ++ the second argument is an object, ``isinstance(obj, type)`` must be true. If ++ the second argument is a type, ``issubclass(type2, type)`` must be true (this ++ is useful for classmethods). ++ ++ .. note:: ++ :func:`super` only works for :term:`new-style class`\es. ++ ++ There are two typical use cases for *super*. In a class hierarchy with ++ single inheritance, *super* can be used to refer to parent classes without + naming them explicitly, thus making the code more maintainable. This use +- closely parallels the use of "super" in other programming languages. +- +- The second use case is to support cooperative multiple inheritence in a +- dynamic execution environment. This use case is unique to Python and is +- not found in statically compiled languages or languages that only support +- single inheritance. This makes in possible to implement "diamond diagrams" ++ closely parallels the use of *super* in other programming languages. ++ ++ The second use case is to support cooperative multiple inheritance in a ++ dynamic execution environment. This use case is unique to Python and is ++ not found in statically compiled languages or languages that only support ++ single inheritance. This makes it possible to implement "diamond diagrams" + where multiple base classes implement the same method. Good design dictates + that this method have the same calling signature in every case (because the +- order of parent calls is determined at runtime and because that order adapts +- to changes in the class hierarchy). ++ order of calls is determined at runtime, because that order adapts ++ to changes in the class hierarchy, and because that order can include ++ sibling classes that are unknown prior to runtime). + + For both use cases, a typical superclass call looks like this:: + + class C(B): +- def meth(self, arg): +- super(C, self).meth(arg) ++ def method(self, arg): ++ super(C, self).method(arg) + + Note that :func:`super` is implemented as part of the binding process for +- explicit dotted attribute lookups such as ``super(C, self).__getitem__(name)``. ++ explicit dotted attribute lookups such as ``super().__getitem__(name)``. + It does so by implementing its own :meth:`__getattribute__` method for searching +- parent classes in a predictable order that supports cooperative multiple inheritance. ++ classes in a predictable order that supports cooperative multiple inheritance. + Accordingly, :func:`super` is undefined for implicit lookups using statements or +- operators such as ``super(C, self)[name]``. ++ operators such as ``super()[name]``. + ++ Also note that :func:`super` is not limited to use inside methods. The two ++ argument form specifies the arguments exactly and makes the appropriate ++ references. ++ + .. versionadded:: 2.2 + + +@@ -1299,7 +1283,7 @@ + + >>> class X(object): + ... a = 1 +- ... ++ ... + >>> X = type('X', (object,), dict(a=1)) + + .. versionadded:: 2.2 +@@ -1380,7 +1364,9 @@ + :func:`xrange` is intended to be simple and fast. Implementations may impose + restrictions to achieve this. The C implementation of Python restricts all + arguments to native C longs ("short" Python integers), and also requires that +- the number of elements fit in a native C long. ++ the number of elements fit in a native C long. If a larger range is needed, ++ an alternate version can be crafted using the :mod:`itertools` module: ++ ``islice(count(start, step), (stop-start+step-1)//step)``. + + + .. function:: zip([iterable, ...]) +@@ -1415,6 +1401,83 @@ + Formerly, :func:`zip` required at least one argument and ``zip()`` raised a + :exc:`TypeError` instead of returning an empty list. + ++ ++.. function:: __import__(name[, globals[, locals[, fromlist[, level]]]]) ++ ++ .. index:: ++ statement: import ++ module: imp ++ ++ .. note:: ++ ++ This is an advanced function that is not needed in everyday Python ++ programming. ++ ++ This function is invoked by the :keyword:`import` statement. It can be ++ replaced (by importing the :mod:`builtins` module and assigning to ++ ``builtins.__import__``) in order to change semantics of the ++ :keyword:`import` statement, but nowadays it is usually simpler to use import ++ hooks (see :pep:`302`). Direct use of :func:`__import__` is rare, except in ++ cases where you want to import a module whose name is only known at runtime. ++ ++ The function imports the module *name*, potentially using the given *globals* ++ and *locals* to determine how to interpret the name in a package context. ++ The *fromlist* gives the names of objects or submodules that should be ++ imported from the module given by *name*. The standard implementation does ++ not use its *locals* argument at all, and uses its *globals* only to ++ determine the package context of the :keyword:`import` statement. ++ ++ *level* specifies whether to use absolute or relative imports. The default ++ is ``-1`` which indicates both absolute and relative imports will be ++ attempted. ``0`` means only perform absolute imports. Positive values for ++ *level* indicate the number of parent directories to search relative to the ++ directory of the module calling :func:`__import__`. ++ ++ When the *name* variable is of the form ``package.module``, normally, the ++ top-level package (the name up till the first dot) is returned, *not* the ++ module named by *name*. However, when a non-empty *fromlist* argument is ++ given, the module named by *name* is returned. ++ ++ For example, the statement ``import spam`` results in bytecode resembling the ++ following code:: ++ ++ spam = __import__('spam', globals(), locals(), [], -1) ++ ++ The statement ``import spam.ham`` results in this call:: ++ ++ spam = __import__('spam.ham', globals(), locals(), [], -1) ++ ++ Note how :func:`__import__` returns the toplevel module here because this is ++ the object that is bound to a name by the :keyword:`import` statement. ++ ++ On the other hand, the statement ``from spam.ham import eggs, sausage as ++ saus`` results in :: ++ ++ _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1) ++ eggs = _temp.eggs ++ saus = _temp.sausage ++ ++ Here, the ``spam.ham`` module is returned from :func:`__import__`. From this ++ object, the names to import are retrieved and assigned to their respective ++ names. ++ ++ If you simply want to import a module (potentially within a package) by name, ++ you can get it from :data:`sys.modules`:: ++ ++ >>> import sys ++ >>> name = 'foo.bar.baz' ++ >>> __import__(name) ++ ++ >>> baz = sys.modules[name] ++ >>> baz ++ ++ ++ .. versionchanged:: 2.5 ++ The level parameter was added. ++ ++ .. versionchanged:: 2.5 ++ Keyword support for parameters was added. ++ + .. --------------------------------------------------------------------------- + + +Index: Doc/library/zlib.rst +=================================================================== +--- Doc/library/zlib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/zlib.rst (.../branches/release26-maint) (Revision 70449) +@@ -31,24 +31,36 @@ + Exception raised on compression and decompression errors. + + +-.. function:: adler32(string[, value]) ++.. function:: adler32(data[, value]) + +- Computes a Adler-32 checksum of *string*. (An Adler-32 checksum is almost as ++ Computes a Adler-32 checksum of *data*. (An Adler-32 checksum is almost as + reliable as a CRC32 but can be computed much more quickly.) If *value* is + present, it is used as the starting value of the checksum; otherwise, a fixed + default value is used. This allows computing a running checksum over the +- concatenation of several input strings. The algorithm is not cryptographically ++ concatenation of several inputs. The algorithm is not cryptographically + strong, and should not be used for authentication or digital signatures. Since + the algorithm is designed for use as a checksum algorithm, it is not suitable + for use as a general hash algorithm. + + This function always returns an integer object. + +- .. versionchanged:: 2.6 +- For consistent cross-platform behavior we always return a signed integer. +- ie: Results in the (2**31)...(2**32-1) range will be negative. ++.. note:: ++ To generate the same numeric value across all Python versions and ++ platforms use adler32(data) & 0xffffffff. If you are only using ++ the checksum in packed binary format this is not necessary as the ++ return value is the correct 32bit binary representation ++ regardless of sign. + ++.. versionchanged:: 2.6 ++ The return value is in the range [-2**31, 2**31-1] ++ regardless of platform. In older versions the value is ++ signed on some platforms and unsigned on others. + ++.. versionchanged:: 3.0 ++ The return value is unsigned and in the range [0, 2**32-1] ++ regardless of platform. ++ ++ + .. function:: compress(string[, level]) + + Compresses the data in *string*, returning a string contained compressed data. +@@ -66,27 +78,39 @@ + ``9`` is slowest and produces the most. The default value is ``6``. + + +-.. function:: crc32(string[, value]) ++.. function:: crc32(data[, value]) + + .. index:: + single: Cyclic Redundancy Check + single: checksum; Cyclic Redundancy Check + +- Computes a CRC (Cyclic Redundancy Check) checksum of *string*. If *value* is ++ Computes a CRC (Cyclic Redundancy Check) checksum of *data*. If *value* is + present, it is used as the starting value of the checksum; otherwise, a fixed + default value is used. This allows computing a running checksum over the +- concatenation of several input strings. The algorithm is not cryptographically ++ concatenation of several inputs. The algorithm is not cryptographically + strong, and should not be used for authentication or digital signatures. Since + the algorithm is designed for use as a checksum algorithm, it is not suitable + for use as a general hash algorithm. + + This function always returns an integer object. + +- .. versionchanged:: 2.6 +- For consistent cross-platform behavior we always return a signed integer. +- ie: Results in the (2**31)...(2**32-1) range will be negative. ++.. note:: ++ To generate the same numeric value across all Python versions and ++ platforms use crc32(data) & 0xffffffff. If you are only using ++ the checksum in packed binary format this is not necessary as the ++ return value is the correct 32bit binary representation ++ regardless of sign. + ++.. versionchanged:: 2.6 ++ The return value is in the range [-2**31, 2**31-1] ++ regardless of platform. In older versions the value would be ++ signed on some platforms and unsigned on others. + ++.. versionchanged:: 3.0 ++ The return value is unsigned and in the range [0, 2**32-1] ++ regardless of platform. ++ ++ + .. function:: decompress(string[, wbits[, bufsize]]) + + Decompresses the data in *string*, returning a string containing the +Index: Doc/library/signal.rst +=================================================================== +--- Doc/library/signal.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/signal.rst (.../branches/release26-maint) (Revision 70449) +@@ -39,12 +39,12 @@ + * Some care must be taken if both signals and threads are used in the same + program. The fundamental thing to remember in using signals and threads + simultaneously is: always perform :func:`signal` operations in the main thread +- of execution. Any thread can perform an :func:`alarm`, :func:`getsignal`, +- :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread +- can set a new signal handler, and the main thread will be the only one to +- receive signals (this is enforced by the Python :mod:`signal` module, even +- if the underlying thread implementation supports sending signals to +- individual threads). This means that signals can't be used as a means of ++ of execution. Any thread can perform an :func:`alarm`, :func:`getsignal`, ++ :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread ++ can set a new signal handler, and the main thread will be the only one to ++ receive signals (this is enforced by the Python :mod:`signal` module, even ++ if the underlying thread implementation supports sending signals to ++ individual threads). This means that signals can't be used as a means of + inter-thread communication. Use locks instead. + + The variables defined in the :mod:`signal` module are: +@@ -52,10 +52,10 @@ + + .. data:: SIG_DFL + +- This is one of two standard signal handling options; it will simply perform the +- default function for the signal. For example, on most systems the default +- action for :const:`SIGQUIT` is to dump core and exit, while the default action +- for :const:`SIGCLD` is to simply ignore it. ++ This is one of two standard signal handling options; it will simply perform ++ the default function for the signal. For example, on most systems the ++ default action for :const:`SIGQUIT` is to dump core and exit, while the ++ default action for :const:`SIGCHLD` is to simply ignore it. + + + .. data:: SIG_IGN +@@ -80,22 +80,22 @@ + One more than the number of the highest signal number. + + +-.. data:: ITIMER_REAL ++.. data:: ITIMER_REAL + + Decrements interval timer in real time, and delivers :const:`SIGALRM` upon expiration. + + +-.. data:: ITIMER_VIRTUAL ++.. data:: ITIMER_VIRTUAL + +- Decrements interval timer only when the process is executing, and delivers ++ Decrements interval timer only when the process is executing, and delivers + SIGVTALRM upon expiration. + + + .. data:: ITIMER_PROF +- +- Decrements interval timer both when the process executes and when the +- system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, +- this timer is usually used to profile the time spent by the application ++ ++ Decrements interval timer both when the process executes and when the ++ system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, ++ this timer is usually used to profile the time spent by the application + in user and kernel space. SIGPROF is delivered upon expiration. + + +@@ -105,7 +105,7 @@ + + Raised to signal an error from the underlying :func:`setitimer` or + :func:`getitimer` implementation. Expect this error if an invalid +- interval timer or a negative time is passed to :func:`setitimer`. ++ interval timer or a negative time is passed to :func:`setitimer`. + This error is a subtype of :exc:`IOError`. + + +@@ -143,21 +143,21 @@ + + .. function:: setitimer(which, seconds[, interval]) + +- Sets given interval timer (one of :const:`signal.ITIMER_REAL`, ++ Sets given interval timer (one of :const:`signal.ITIMER_REAL`, + :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified +- by *which* to fire after *seconds* (float is accepted, different from ++ by *which* to fire after *seconds* (float is accepted, different from + :func:`alarm`) and after that every *interval* seconds. The interval + timer specified by *which* can be cleared by setting seconds to zero. + + When an interval timer fires, a signal is sent to the process. +- The signal sent is dependent on the timer being used; +- :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`, ++ The signal sent is dependent on the timer being used; ++ :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`, + :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`, + and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`. + + The old values are returned as a tuple: (delay, interval). + +- Attempting to pass an invalid interval timer will cause a ++ Attempting to pass an invalid interval timer will cause a + :exc:`ItimerError`. + + .. versionadded:: 2.6 +@@ -190,7 +190,7 @@ + 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. +@@ -239,7 +239,7 @@ + signal.alarm(5) + + # This open() may hang indefinitely +- fd = os.open('/dev/ttyS0', os.O_RDWR) ++ fd = os.open('/dev/ttyS0', os.O_RDWR) + + signal.alarm(0) # Disable the alarm + +Index: Doc/library/exceptions.rst +=================================================================== +--- Doc/library/exceptions.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/exceptions.rst (.../branches/release26-maint) (Revision 70449) +@@ -398,6 +398,11 @@ + more precise exception such as :exc:`IndexError`. + + ++.. exception:: VMSError ++ ++ Only available on VMS. Raised when a VMS-specific error occurs. ++ ++ + .. exception:: WindowsError + + Raised when a Windows-specific error occurs or when the error number does not +Index: Doc/library/webbrowser.rst +=================================================================== +--- Doc/library/webbrowser.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/webbrowser.rst (.../branches/release26-maint) (Revision 70449) +@@ -160,7 +160,7 @@ + + url = 'http://www.python.org' + +- # Open URL in a new tab, if a browser window is already open. ++ # Open URL in a new tab, if a browser window is already open. + webbrowser.open_new_tab(url + '/doc') + + # Open URL in new window, raising the window if possible. +@@ -172,7 +172,7 @@ + Browser Controller Objects + -------------------------- + +-Browser controllers provide two methods which parallel two of the module-level ++Browser controllers provide these methods which parallel two of the module-level + convenience functions: + + +Index: Doc/library/bdb.rst +=================================================================== +--- Doc/library/bdb.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/bdb.rst (.../branches/release26-maint) (Revision 70449) +@@ -107,8 +107,9 @@ + + The *arg* parameter depends on the previous event. + +- For more information on trace functions, see :ref:`debugger-hooks`. For +- more information on code and frame objects, refer to :ref:`types`. ++ See the documentation for :func:`sys.settrace` for more information on the ++ trace function. For more information on code and frame objects, refer to ++ :ref:`types`. + + .. method:: dispatch_line(frame) + +@@ -324,7 +325,7 @@ + + Check whether we should break here, depending on the way the breakpoint *b* + was set. +- ++ + If it was set via line number, it checks if ``b.line`` is the same as the one + in the frame also passed as argument. If the breakpoint was set via function + name, we have to check we are in the right frame (the right function) and if +@@ -334,7 +335,7 @@ + + Determine if there is an effective (active) breakpoint at this line of code. + Return breakpoint number or 0 if none. +- ++ + Called only if we know there is a breakpoint at this location. Returns the + breakpoint that was triggered and a flag that indicates if it is ok to delete + a temporary breakpoint. +Index: Doc/library/bastion.rst +=================================================================== +--- Doc/library/bastion.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/bastion.rst (.../branches/release26-maint) (Revision 70449) +@@ -5,10 +5,10 @@ + .. module:: Bastion + :synopsis: Providing restricted access to objects. + :deprecated: +- ++ + .. deprecated:: 2.6 + The :mod:`Bastion` module has been removed in Python 3.0. +- ++ + .. moduleauthor:: Barry Warsaw + + +Index: Doc/library/fileinput.rst +=================================================================== +--- Doc/library/fileinput.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/fileinput.rst (.../branches/release26-maint) (Revision 70449) +@@ -151,7 +151,7 @@ + when standard input is read. + + .. warning:: +- ++ + The current implementation does not work for MS-DOS 8+3 filesystems. + + +Index: Doc/library/profile.rst +=================================================================== +--- Doc/library/profile.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/profile.rst (.../branches/release26-maint) (Revision 70449) +@@ -51,17 +51,17 @@ + + The Python standard library provides three different profilers: + +-#. :mod:`cProfile` is recommended for most users; it's a C extension ++#. :mod:`cProfile` is recommended for most users; it's a C extension + with reasonable overhead +- that makes it suitable for profiling long-running programs. ++ that makes it suitable for profiling long-running programs. + Based on :mod:`lsprof`, +- contributed by Brett Rosen and Ted Czotter. ++ contributed by Brett Rosen and Ted Czotter. + + .. versionadded:: 2.5 + + #. :mod:`profile`, a pure Python module whose interface is imitated by +- :mod:`cProfile`. Adds significant overhead to profiled programs. +- If you're trying to extend ++ :mod:`cProfile`. Adds significant overhead to profiled programs. ++ If you're trying to extend + the profiler in some way, the task might be easier with this module. + Copyright © 1994, by InfoSeek Corporation. + +@@ -72,8 +72,8 @@ + the overhead of profiling, at the expense of longer data + post-processing times. It is no longer maintained and may be + dropped in a future version of Python. +- + ++ + .. versionchanged:: 2.5 + The results should be more meaningful than in the past: the timing core + contained a critical bug. +@@ -276,24 +276,24 @@ + that the text string in the far right column was used to sort the output. The + column headings include: + +- ncalls ++ ncalls + for the number of calls, + +- tottime ++ tottime + for the total time spent in the given function (and excluding time made in calls + to sub-functions), + +- percall ++ percall + is the quotient of ``tottime`` divided by ``ncalls`` + +- cumtime ++ cumtime + is the total time spent in this and all subfunctions (from invocation till + exit). This figure is accurate *even* for recursive functions. + +- percall ++ percall + is the quotient of ``cumtime`` divided by primitive calls + +- filename:lineno(function) ++ filename:lineno(function) + provides the respective data of each function + + When there are two numbers in the first column (for example, ``43/3``), then the +Index: Doc/library/getopt.rst +=================================================================== +--- Doc/library/getopt.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/getopt.rst (.../branches/release26-maint) (Revision 70449) +@@ -63,8 +63,8 @@ + non-option argument is encountered. + + If the first character of the option string is '+', or if the environment +- variable POSIXLY_CORRECT is set, then option processing stops as soon as a +- non-option argument is encountered. ++ variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as ++ soon as a non-option argument is encountered. + + .. versionadded:: 2.3 + +Index: Doc/library/repr.rst +=================================================================== +--- Doc/library/repr.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/repr.rst (.../branches/release26-maint) (Revision 70449) +@@ -125,15 +125,15 @@ + the handling of types already supported. This example shows how special support + for file objects could be added:: + +- import repr ++ import repr as reprlib + import sys + +- class MyRepr(repr.Repr): ++ class MyRepr(reprlib.Repr): + def repr_file(self, obj, level): + if obj.name in ['', '', '']: + return obj.name + else: +- return `obj` ++ return repr(obj) + + aRepr = MyRepr() + print aRepr.repr(sys.stdin) # prints '' + +Eigenschaftsänderungen: Doc/library/repr.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/library/math.rst +=================================================================== +--- Doc/library/math.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/math.rst (.../branches/release26-maint) (Revision 70449) +@@ -21,8 +21,9 @@ + The following functions are provided by this module. Except when explicitly + noted otherwise, all return values are floats. + +-Number-theoretic and representation functions: + ++Number-theoretic and representation functions ++--------------------------------------------- + + .. function:: ceil(x) + +@@ -86,15 +87,23 @@ + .. function:: fsum(iterable) + + Return an accurate floating point sum of values in the iterable. Avoids +- loss of precision by tracking multiple intermediate partial sums. The +- algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the +- typical case where the rounding mode is half-even. ++ loss of precision by tracking multiple intermediate partial sums:: + +- .. note:: ++ >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) ++ 0.99999999999999989 ++ >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) ++ 1.0 + +- The accuracy of fsum() may be impaired on builds that use +- extended precision addition and then double-round the results. ++ The algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the ++ typical case where the rounding mode is half-even. On some non-Windows ++ builds, the underlying C library uses extended precision addition and may ++ occasionally double-round an intermediate sum causing it to be off in its ++ least significant bit. + ++ For further discussion and two alternative approaches, see the `ASPN cookbook ++ recipes for accurate floating point summation ++ `_\. ++ + .. versionadded:: 2.6 + + +@@ -108,7 +117,7 @@ + .. function:: isnan(x) + + Checks if the float *x* is a NaN (not a number). NaNs are part of the +- IEEE 754 standards. Operation like but not limited to ``inf * 0``, ++ IEEE 754 standards. Operation like but not limited to ``inf * 0``, + ``inf / inf`` or any operation involving a NaN, e.g. ``nan * 1``, return + a NaN. + +@@ -123,8 +132,8 @@ + + .. function:: modf(x) + +- Return the fractional and integer parts of *x*. Both results carry the sign of +- *x*, and both are floats. ++ Return the fractional and integer parts of *x*. Both results carry the sign ++ of *x* and are floats. + + + .. function:: trunc(x) +@@ -146,8 +155,10 @@ + platform C double type), in which case any float *x* with ``abs(x) >= 2**52`` + necessarily has no fractional bits. + +-Power and logarithmic functions: + ++Power and logarithmic functions ++------------------------------- ++ + .. function:: exp(x) + + Return ``e**x``. +@@ -193,7 +204,8 @@ + Return the square root of *x*. + + +-Trigonometric functions: ++Trigonometric functions ++----------------------- + + .. function:: acos(x) + +@@ -241,7 +253,8 @@ + Return the tangent of *x* radians. + + +-Angular conversion: ++Angular conversion ++------------------ + + .. function:: degrees(x) + +@@ -253,7 +266,8 @@ + Converts angle *x* from degrees to radians. + + +-Hyperbolic functions: ++Hyperbolic functions ++-------------------- + + .. function:: acosh(x) + +@@ -291,7 +305,8 @@ + Return the hyperbolic tangent of *x*. + + +-The module also defines two mathematical constants: ++Constants ++--------- + + .. data:: pi + +Index: Doc/library/urllib.rst +=================================================================== +--- Doc/library/urllib.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/urllib.rst (.../branches/release26-maint) (Revision 70449) +@@ -123,7 +123,7 @@ + .. versionchanged:: 2.6 + Added :meth:`getcode` to returned object and support for the + :envvar:`no_proxy` environment variable. +- ++ + .. deprecated:: 2.6 + The :func:`urlopen` function has been removed in Python 3.0 in favor + of :func:`urllib2.urlopen`. +Index: Doc/library/locale.rst +=================================================================== +--- Doc/library/locale.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/locale.rst (.../branches/release26-maint) (Revision 70449) +@@ -492,9 +492,9 @@ + Example:: + + >>> import locale +- >>> loc = locale.getlocale(locale.LC_ALL) # get current locale ++ >>> loc = locale.getlocale() # get current locale + >>> locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform +- >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut ++ >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut + >>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale + >>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale + >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale +Index: Doc/library/audioop.rst +=================================================================== +--- Doc/library/audioop.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/audioop.rst (.../branches/release26-maint) (Revision 70449) +@@ -265,7 +265,7 @@ + in_test = inputdata[pos*2:] + ipos, factor = audioop.findfit(in_test, out_test) + # Optional (for better cancellation): +- # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)], ++ # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)], + # out_test) + prefill = '\0'*(pos+ipos)*2 + postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata)) +Index: Doc/library/robotparser.rst +=================================================================== +--- Doc/library/robotparser.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/robotparser.rst (.../branches/release26-maint) (Revision 70449) +@@ -13,7 +13,7 @@ + single: World Wide Web + single: URL + single: robots.txt +- ++ + .. note:: + The :mod:`robotparser` module has been renamed :mod:`urllib.robotparser` in + Python 3.0. +Index: Doc/library/cgi.rst +=================================================================== +--- Doc/library/cgi.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/cgi.rst (.../branches/release26-maint) (Revision 70449) +@@ -67,16 +67,18 @@ + module defines all sorts of names for its own use or for backward compatibility + that you don't want in your namespace. + +-When you write a new script, consider adding the line:: ++When you write a new script, consider adding these lines:: + +- import cgitb; cgitb.enable() ++ import cgitb ++ cgitb.enable() + + This activates a special exception handler that will display detailed reports in + the Web browser if any errors occur. If you'd rather not show the guts of your + program to users of your script, you can have the reports saved to files +-instead, with a line like this:: ++instead, with code like this:: + +- import cgitb; cgitb.enable(display=0, logdir="/tmp") ++ import cgitb ++ cgitb.enable(display=0, logdir="/tmp") + + It's very helpful to use this feature during script development. The reports + produced by :mod:`cgitb` provide information that can save you a lot of time in +@@ -470,9 +472,10 @@ + + Fortunately, once you have managed to get your script to execute *some* code, + you can easily send tracebacks to the Web browser using the :mod:`cgitb` module. +-If you haven't done so already, just add the line:: ++If you haven't done so already, just add the lines:: + +- import cgitb; cgitb.enable() ++ import cgitb ++ cgitb.enable() + + to the top of your script. Then try running it again; when a problem occurs, + you should see a detailed report that will likely make apparent the cause of the +Index: Doc/library/threading.rst +=================================================================== +--- Doc/library/threading.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/threading.rst (.../branches/release26-maint) (Revision 70449) +@@ -210,7 +210,7 @@ + A thread can be flagged as a "daemon thread". The significance of this flag is + that the entire Python program exits when only daemon threads are left. The + initial value is inherited from the creating thread. The flag can be set +-through the :attr:`daemon` attribute. ++through the :attr:`daemon` property. + + There is a "main thread" object; this corresponds to the initial thread of + control in the Python program. It is not a daemon thread. +@@ -332,11 +332,12 @@ + + .. attribute:: Thread.daemon + +- The thread's daemon flag. This must be set before :meth:`start` is called, +- otherwise :exc:`RuntimeError` is raised. ++ A boolean value indicating whether this thread is a daemon thread (True) or ++ not (False). This must be set before :meth:`start` is called, otherwise ++ :exc:`RuntimeError` is raised. Its initial value is inherited from the ++ creating thread; the main thread is not a daemon thread and therefore all ++ threads created in the main thread default to :attr:`daemon` = ``False``. + +- The initial value is inherited from the creating thread. +- + The entire Python program exits when no alive non-daemon threads are left. + + +Index: Doc/library/pickle.rst +=================================================================== +--- Doc/library/pickle.rst (.../tags/r261) (Revision 70449) ++++ Doc/library/pickle.rst (.../branches/release26-maint) (Revision 70449) +@@ -413,7 +413,7 @@ + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + .. method:: object.__getinitargs__() +- ++ + When a pickled class instance is unpickled, its :meth:`__init__` method is + normally *not* invoked. If it is desirable that the :meth:`__init__` method + be called on unpickling, an old-style class can define a method +@@ -430,31 +430,31 @@ + is affected by the values passed to the :meth:`__new__` method for the type + (as it is for tuples and strings). Instances of a :term:`new-style class` + ``C`` are created using :: +- ++ + obj = C.__new__(C, *args) +- ++ + where *args* is the result of calling :meth:`__getnewargs__` on the original + object; if there is no :meth:`__getnewargs__`, an empty tuple is assumed. + + .. method:: object.__getstate__() +- ++ + Classes can further influence how their instances are pickled; if the class + defines the method :meth:`__getstate__`, it is called and the return state is + pickled as the contents for the instance, instead of the contents of the + instance's dictionary. If there is no :meth:`__getstate__` method, the + instance's :attr:`__dict__` is pickled. + +-.. method:: object.__setstate__() +- ++.. method:: object.__setstate__() ++ + Upon unpickling, if the class also defines the method :meth:`__setstate__`, + it is called with the unpickled state. [#]_ If there is no + :meth:`__setstate__` method, the pickled state must be a dictionary and its + items are assigned to the new instance's dictionary. If a class defines both + :meth:`__getstate__` and :meth:`__setstate__`, the state object needn't be a + dictionary and these methods can do what they want. [#]_ +- ++ + .. warning:: +- ++ + For :term:`new-style class`\es, if :meth:`__getstate__` returns a false + value, the :meth:`__setstate__` method will not be called. + +@@ -463,7 +463,7 @@ + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + .. method:: object.__reduce__() +- ++ + When the :class:`Pickler` encounters an object of a type it knows nothing + about --- such as an extension type --- it looks in two places for a hint of + how to pickle it. One alternative is for the object to implement a +@@ -518,7 +518,7 @@ + is primarily used for dictionary subclasses, but may be used by other + classes as long as they implement :meth:`__setitem__`. + +-.. method:: object.__reduce_ex__(protocol) ++.. method:: object.__reduce_ex__(protocol) + + It is sometimes useful to know the protocol version when implementing + :meth:`__reduce__`. This can be done by implementing a method named +Index: Doc/includes/mp_workers.py +=================================================================== +--- Doc/includes/mp_workers.py (.../tags/r261) (Revision 70449) ++++ Doc/includes/mp_workers.py (.../branches/release26-maint) (Revision 70449) +@@ -7,6 +7,9 @@ + # in the original order then consider using `Pool.map()` or + # `Pool.imap()` (which will save on the amount of code needed anyway). + # ++# Copyright (c) 2006-2008, R Oudkerk ++# All rights reserved. ++# + + import time + import random +Index: Doc/includes/mp_webserver.py +=================================================================== +--- Doc/includes/mp_webserver.py (.../tags/r261) (Revision 70449) ++++ Doc/includes/mp_webserver.py (.../branches/release26-maint) (Revision 70449) +@@ -8,6 +8,9 @@ + # Not sure if we should synchronize access to `socket.accept()` method by + # using a process-shared lock -- does not seem to be necessary. + # ++# Copyright (c) 2006-2008, R Oudkerk ++# All rights reserved. ++# + + import os + import sys +Index: Doc/includes/mp_distributing.py +=================================================================== +--- Doc/includes/mp_distributing.py (.../tags/r261) (Revision 70449) ++++ Doc/includes/mp_distributing.py (.../branches/release26-maint) (Revision 70449) +@@ -1,361 +1,364 @@ +-# +-# Module to allow spawning of processes on foreign host +-# +-# Depends on `multiprocessing` package -- tested with `processing-0.60` +-# +- +-__all__ = ['Cluster', 'Host', 'get_logger', 'current_process'] +- +-# +-# Imports +-# +- +-import sys +-import os +-import tarfile +-import shutil +-import subprocess +-import logging +-import itertools +-import Queue +- +-try: +- import cPickle as pickle +-except ImportError: +- import pickle +- +-from multiprocessing import Process, current_process, cpu_count +-from multiprocessing import util, managers, connection, forking, pool +- +-# +-# Logging +-# +- +-def get_logger(): +- return _logger +- +-_logger = logging.getLogger('distributing') +-_logger.propogate = 0 +- +-_formatter = logging.Formatter(util.DEFAULT_LOGGING_FORMAT) +-_handler = logging.StreamHandler() +-_handler.setFormatter(_formatter) +-_logger.addHandler(_handler) +- +-info = _logger.info +-debug = _logger.debug +- +-# +-# Get number of cpus +-# +- +-try: +- slot_count = cpu_count() +-except NotImplemented: +- slot_count = 1 +- +-# +-# Manager type which spawns subprocesses +-# +- +-class HostManager(managers.SyncManager): +- ''' +- Manager type used for spawning processes on a (presumably) foreign host +- ''' +- def __init__(self, address, authkey): +- managers.SyncManager.__init__(self, address, authkey) +- self._name = 'Host-unknown' +- +- def Process(self, group=None, target=None, name=None, args=(), kwargs={}): +- if hasattr(sys.modules['__main__'], '__file__'): +- main_path = os.path.basename(sys.modules['__main__'].__file__) +- else: +- main_path = None +- data = pickle.dumps((target, args, kwargs)) +- p = self._RemoteProcess(data, main_path) +- if name is None: +- temp = self._name.split('Host-')[-1] + '/Process-%s' +- name = temp % ':'.join(map(str, p.get_identity())) +- p.set_name(name) +- return p +- +- @classmethod +- def from_address(cls, address, authkey): +- manager = cls(address, authkey) +- managers.transact(address, authkey, 'dummy') +- manager._state.value = managers.State.STARTED +- manager._name = 'Host-%s:%s' % manager.address +- manager.shutdown = util.Finalize( +- manager, HostManager._finalize_host, +- args=(manager._address, manager._authkey, manager._name), +- exitpriority=-10 +- ) +- return manager +- +- @staticmethod +- def _finalize_host(address, authkey, name): +- managers.transact(address, authkey, 'shutdown') +- +- def __repr__(self): +- return '' % self._name +- +-# +-# Process subclass representing a process on (possibly) a remote machine +-# +- +-class RemoteProcess(Process): +- ''' +- Represents a process started on a remote host +- ''' +- def __init__(self, data, main_path): +- assert not main_path or os.path.basename(main_path) == main_path +- Process.__init__(self) +- self._data = data +- self._main_path = main_path +- +- def _bootstrap(self): +- forking.prepare({'main_path': self._main_path}) +- self._target, self._args, self._kwargs = pickle.loads(self._data) +- return Process._bootstrap(self) +- +- def get_identity(self): +- return self._identity +- +-HostManager.register('_RemoteProcess', RemoteProcess) +- +-# +-# A Pool class that uses a cluster +-# +- +-class DistributedPool(pool.Pool): +- +- def __init__(self, cluster, processes=None, initializer=None, initargs=()): +- self._cluster = cluster +- self.Process = cluster.Process +- pool.Pool.__init__(self, processes or len(cluster), +- initializer, initargs) +- +- def _setup_queues(self): +- self._inqueue = self._cluster._SettableQueue() +- self._outqueue = self._cluster._SettableQueue() +- self._quick_put = self._inqueue.put +- self._quick_get = self._outqueue.get +- +- @staticmethod +- def _help_stuff_finish(inqueue, task_handler, size): +- inqueue.set_contents([None] * size) +- +-# +-# Manager type which starts host managers on other machines +-# +- +-def LocalProcess(**kwds): +- p = Process(**kwds) +- p.set_name('localhost/' + p.name) +- return p +- +-class Cluster(managers.SyncManager): +- ''' +- Represents collection of slots running on various hosts. +- +- `Cluster` is a subclass of `SyncManager` so it allows creation of +- various types of shared objects. +- ''' +- def __init__(self, hostlist, modules): +- managers.SyncManager.__init__(self, address=('localhost', 0)) +- self._hostlist = hostlist +- self._modules = modules +- if __name__ not in modules: +- modules.append(__name__) +- files = [sys.modules[name].__file__ for name in modules] +- for i, file in enumerate(files): +- if file.endswith('.pyc') or file.endswith('.pyo'): +- files[i] = file[:-4] + '.py' +- self._files = [os.path.abspath(file) for file in files] +- +- def start(self): +- managers.SyncManager.start(self) +- +- l = connection.Listener(family='AF_INET', authkey=self._authkey) +- +- for i, host in enumerate(self._hostlist): +- host._start_manager(i, self._authkey, l.address, self._files) +- +- for host in self._hostlist: +- if host.hostname != 'localhost': +- conn = l.accept() +- i, address, cpus = conn.recv() +- conn.close() +- other_host = self._hostlist[i] +- other_host.manager = HostManager.from_address(address, +- self._authkey) +- other_host.slots = other_host.slots or cpus +- other_host.Process = other_host.manager.Process +- else: +- host.slots = host.slots or slot_count +- host.Process = LocalProcess +- +- self._slotlist = [ +- Slot(host) for host in self._hostlist for i in range(host.slots) +- ] +- self._slot_iterator = itertools.cycle(self._slotlist) +- self._base_shutdown = self.shutdown +- del self.shutdown +- +- def shutdown(self): +- for host in self._hostlist: +- if host.hostname != 'localhost': +- host.manager.shutdown() +- self._base_shutdown() +- +- def Process(self, group=None, target=None, name=None, args=(), kwargs={}): +- slot = self._slot_iterator.next() +- return slot.Process( +- group=group, target=target, name=name, args=args, kwargs=kwargs +- ) +- +- def Pool(self, processes=None, initializer=None, initargs=()): +- return DistributedPool(self, processes, initializer, initargs) +- +- def __getitem__(self, i): +- return self._slotlist[i] +- +- def __len__(self): +- return len(self._slotlist) +- +- def __iter__(self): +- return iter(self._slotlist) +- +-# +-# Queue subclass used by distributed pool +-# +- +-class SettableQueue(Queue.Queue): +- def empty(self): +- return not self.queue +- def full(self): +- return self.maxsize > 0 and len(self.queue) == self.maxsize +- def set_contents(self, contents): +- # length of contents must be at least as large as the number of +- # threads which have potentially called get() +- self.not_empty.acquire() +- try: +- self.queue.clear() +- self.queue.extend(contents) +- self.not_empty.notifyAll() +- finally: +- self.not_empty.release() +- +-Cluster.register('_SettableQueue', SettableQueue) +- +-# +-# Class representing a notional cpu in the cluster +-# +- +-class Slot(object): +- def __init__(self, host): +- self.host = host +- self.Process = host.Process +- +-# +-# Host +-# +- +-class Host(object): +- ''' +- Represents a host to use as a node in a cluster. +- +- `hostname` gives the name of the host. If hostname is not +- "localhost" then ssh is used to log in to the host. To log in as +- a different user use a host name of the form +- "username@somewhere.org" +- +- `slots` is used to specify the number of slots for processes on +- the host. This affects how often processes will be allocated to +- this host. Normally this should be equal to the number of cpus on +- that host. +- ''' +- def __init__(self, hostname, slots=None): +- self.hostname = hostname +- self.slots = slots +- +- def _start_manager(self, index, authkey, address, files): +- if self.hostname != 'localhost': +- tempdir = copy_to_remote_temporary_directory(self.hostname, files) +- debug('startup files copied to %s:%s', self.hostname, tempdir) +- p = subprocess.Popen( +- ['ssh', self.hostname, 'python', '-c', +- '"import os; os.chdir(%r); ' +- 'from distributing import main; main()"' % tempdir], +- stdin=subprocess.PIPE +- ) +- data = dict( +- name='BoostrappingHost', index=index, +- dist_log_level=_logger.getEffectiveLevel(), +- dir=tempdir, authkey=str(authkey), parent_address=address +- ) +- pickle.dump(data, p.stdin, pickle.HIGHEST_PROTOCOL) +- p.stdin.close() +- +-# +-# Copy files to remote directory, returning name of directory +-# +- +-unzip_code = '''" +-import tempfile, os, sys, tarfile +-tempdir = tempfile.mkdtemp(prefix='distrib-') +-os.chdir(tempdir) +-tf = tarfile.open(fileobj=sys.stdin, mode='r|gz') +-for ti in tf: +- tf.extract(ti) +-print tempdir +-"''' +- +-def copy_to_remote_temporary_directory(host, files): +- p = subprocess.Popen( +- ['ssh', host, 'python', '-c', unzip_code], +- stdout=subprocess.PIPE, stdin=subprocess.PIPE +- ) +- tf = tarfile.open(fileobj=p.stdin, mode='w|gz') +- for name in files: +- tf.add(name, os.path.basename(name)) +- tf.close() +- p.stdin.close() +- return p.stdout.read().rstrip() +- +-# +-# Code which runs a host manager +-# +- +-def main(): +- # get data from parent over stdin +- data = pickle.load(sys.stdin) +- sys.stdin.close() +- +- # set some stuff +- _logger.setLevel(data['dist_log_level']) +- forking.prepare(data) +- +- # create server for a `HostManager` object +- server = managers.Server(HostManager._registry, ('', 0), data['authkey']) +- current_process()._server = server +- +- # report server address and number of cpus back to parent +- conn = connection.Client(data['parent_address'], authkey=data['authkey']) +- conn.send((data['index'], server.address, slot_count)) +- conn.close() +- +- # set name etc +- current_process().set_name('Host-%s:%s' % server.address) +- util._run_after_forkers() +- +- # register a cleanup function +- def cleanup(directory): +- debug('removing directory %s', directory) +- shutil.rmtree(directory) +- debug('shutting down host manager') +- util.Finalize(None, cleanup, args=[data['dir']], exitpriority=0) +- +- # start host manager +- debug('remote host manager starting in %s', data['dir']) +- server.serve_forever() ++# ++# Module to allow spawning of processes on foreign host ++# ++# Depends on `multiprocessing` package -- tested with `processing-0.60` ++# ++# Copyright (c) 2006-2008, R Oudkerk ++# All rights reserved. ++# ++ ++__all__ = ['Cluster', 'Host', 'get_logger', 'current_process'] ++ ++# ++# Imports ++# ++ ++import sys ++import os ++import tarfile ++import shutil ++import subprocess ++import logging ++import itertools ++import Queue ++ ++try: ++ import cPickle as pickle ++except ImportError: ++ import pickle ++ ++from multiprocessing import Process, current_process, cpu_count ++from multiprocessing import util, managers, connection, forking, pool ++ ++# ++# Logging ++# ++ ++def get_logger(): ++ return _logger ++ ++_logger = logging.getLogger('distributing') ++_logger.propogate = 0 ++ ++_formatter = logging.Formatter(util.DEFAULT_LOGGING_FORMAT) ++_handler = logging.StreamHandler() ++_handler.setFormatter(_formatter) ++_logger.addHandler(_handler) ++ ++info = _logger.info ++debug = _logger.debug ++ ++# ++# Get number of cpus ++# ++ ++try: ++ slot_count = cpu_count() ++except NotImplemented: ++ slot_count = 1 ++ ++# ++# Manager type which spawns subprocesses ++# ++ ++class HostManager(managers.SyncManager): ++ ''' ++ Manager type used for spawning processes on a (presumably) foreign host ++ ''' ++ def __init__(self, address, authkey): ++ managers.SyncManager.__init__(self, address, authkey) ++ self._name = 'Host-unknown' ++ ++ def Process(self, group=None, target=None, name=None, args=(), kwargs={}): ++ if hasattr(sys.modules['__main__'], '__file__'): ++ main_path = os.path.basename(sys.modules['__main__'].__file__) ++ else: ++ main_path = None ++ data = pickle.dumps((target, args, kwargs)) ++ p = self._RemoteProcess(data, main_path) ++ if name is None: ++ temp = self._name.split('Host-')[-1] + '/Process-%s' ++ name = temp % ':'.join(map(str, p.get_identity())) ++ p.set_name(name) ++ return p ++ ++ @classmethod ++ def from_address(cls, address, authkey): ++ manager = cls(address, authkey) ++ managers.transact(address, authkey, 'dummy') ++ manager._state.value = managers.State.STARTED ++ manager._name = 'Host-%s:%s' % manager.address ++ manager.shutdown = util.Finalize( ++ manager, HostManager._finalize_host, ++ args=(manager._address, manager._authkey, manager._name), ++ exitpriority=-10 ++ ) ++ return manager ++ ++ @staticmethod ++ def _finalize_host(address, authkey, name): ++ managers.transact(address, authkey, 'shutdown') ++ ++ def __repr__(self): ++ return '' % self._name ++ ++# ++# Process subclass representing a process on (possibly) a remote machine ++# ++ ++class RemoteProcess(Process): ++ ''' ++ Represents a process started on a remote host ++ ''' ++ def __init__(self, data, main_path): ++ assert not main_path or os.path.basename(main_path) == main_path ++ Process.__init__(self) ++ self._data = data ++ self._main_path = main_path ++ ++ def _bootstrap(self): ++ forking.prepare({'main_path': self._main_path}) ++ self._target, self._args, self._kwargs = pickle.loads(self._data) ++ return Process._bootstrap(self) ++ ++ def get_identity(self): ++ return self._identity ++ ++HostManager.register('_RemoteProcess', RemoteProcess) ++ ++# ++# A Pool class that uses a cluster ++# ++ ++class DistributedPool(pool.Pool): ++ ++ def __init__(self, cluster, processes=None, initializer=None, initargs=()): ++ self._cluster = cluster ++ self.Process = cluster.Process ++ pool.Pool.__init__(self, processes or len(cluster), ++ initializer, initargs) ++ ++ def _setup_queues(self): ++ self._inqueue = self._cluster._SettableQueue() ++ self._outqueue = self._cluster._SettableQueue() ++ self._quick_put = self._inqueue.put ++ self._quick_get = self._outqueue.get ++ ++ @staticmethod ++ def _help_stuff_finish(inqueue, task_handler, size): ++ inqueue.set_contents([None] * size) ++ ++# ++# Manager type which starts host managers on other machines ++# ++ ++def LocalProcess(**kwds): ++ p = Process(**kwds) ++ p.set_name('localhost/' + p.name) ++ return p ++ ++class Cluster(managers.SyncManager): ++ ''' ++ Represents collection of slots running on various hosts. ++ ++ `Cluster` is a subclass of `SyncManager` so it allows creation of ++ various types of shared objects. ++ ''' ++ def __init__(self, hostlist, modules): ++ managers.SyncManager.__init__(self, address=('localhost', 0)) ++ self._hostlist = hostlist ++ self._modules = modules ++ if __name__ not in modules: ++ modules.append(__name__) ++ files = [sys.modules[name].__file__ for name in modules] ++ for i, file in enumerate(files): ++ if file.endswith('.pyc') or file.endswith('.pyo'): ++ files[i] = file[:-4] + '.py' ++ self._files = [os.path.abspath(file) for file in files] ++ ++ def start(self): ++ managers.SyncManager.start(self) ++ ++ l = connection.Listener(family='AF_INET', authkey=self._authkey) ++ ++ for i, host in enumerate(self._hostlist): ++ host._start_manager(i, self._authkey, l.address, self._files) ++ ++ for host in self._hostlist: ++ if host.hostname != 'localhost': ++ conn = l.accept() ++ i, address, cpus = conn.recv() ++ conn.close() ++ other_host = self._hostlist[i] ++ other_host.manager = HostManager.from_address(address, ++ self._authkey) ++ other_host.slots = other_host.slots or cpus ++ other_host.Process = other_host.manager.Process ++ else: ++ host.slots = host.slots or slot_count ++ host.Process = LocalProcess ++ ++ self._slotlist = [ ++ Slot(host) for host in self._hostlist for i in range(host.slots) ++ ] ++ self._slot_iterator = itertools.cycle(self._slotlist) ++ self._base_shutdown = self.shutdown ++ del self.shutdown ++ ++ def shutdown(self): ++ for host in self._hostlist: ++ if host.hostname != 'localhost': ++ host.manager.shutdown() ++ self._base_shutdown() ++ ++ def Process(self, group=None, target=None, name=None, args=(), kwargs={}): ++ slot = self._slot_iterator.next() ++ return slot.Process( ++ group=group, target=target, name=name, args=args, kwargs=kwargs ++ ) ++ ++ def Pool(self, processes=None, initializer=None, initargs=()): ++ return DistributedPool(self, processes, initializer, initargs) ++ ++ def __getitem__(self, i): ++ return self._slotlist[i] ++ ++ def __len__(self): ++ return len(self._slotlist) ++ ++ def __iter__(self): ++ return iter(self._slotlist) ++ ++# ++# Queue subclass used by distributed pool ++# ++ ++class SettableQueue(Queue.Queue): ++ def empty(self): ++ return not self.queue ++ def full(self): ++ return self.maxsize > 0 and len(self.queue) == self.maxsize ++ def set_contents(self, contents): ++ # length of contents must be at least as large as the number of ++ # threads which have potentially called get() ++ self.not_empty.acquire() ++ try: ++ self.queue.clear() ++ self.queue.extend(contents) ++ self.not_empty.notifyAll() ++ finally: ++ self.not_empty.release() ++ ++Cluster.register('_SettableQueue', SettableQueue) ++ ++# ++# Class representing a notional cpu in the cluster ++# ++ ++class Slot(object): ++ def __init__(self, host): ++ self.host = host ++ self.Process = host.Process ++ ++# ++# Host ++# ++ ++class Host(object): ++ ''' ++ Represents a host to use as a node in a cluster. ++ ++ `hostname` gives the name of the host. If hostname is not ++ "localhost" then ssh is used to log in to the host. To log in as ++ a different user use a host name of the form ++ "username@somewhere.org" ++ ++ `slots` is used to specify the number of slots for processes on ++ the host. This affects how often processes will be allocated to ++ this host. Normally this should be equal to the number of cpus on ++ that host. ++ ''' ++ def __init__(self, hostname, slots=None): ++ self.hostname = hostname ++ self.slots = slots ++ ++ def _start_manager(self, index, authkey, address, files): ++ if self.hostname != 'localhost': ++ tempdir = copy_to_remote_temporary_directory(self.hostname, files) ++ debug('startup files copied to %s:%s', self.hostname, tempdir) ++ p = subprocess.Popen( ++ ['ssh', self.hostname, 'python', '-c', ++ '"import os; os.chdir(%r); ' ++ 'from distributing import main; main()"' % tempdir], ++ stdin=subprocess.PIPE ++ ) ++ data = dict( ++ name='BoostrappingHost', index=index, ++ dist_log_level=_logger.getEffectiveLevel(), ++ dir=tempdir, authkey=str(authkey), parent_address=address ++ ) ++ pickle.dump(data, p.stdin, pickle.HIGHEST_PROTOCOL) ++ p.stdin.close() ++ ++# ++# Copy files to remote directory, returning name of directory ++# ++ ++unzip_code = '''" ++import tempfile, os, sys, tarfile ++tempdir = tempfile.mkdtemp(prefix='distrib-') ++os.chdir(tempdir) ++tf = tarfile.open(fileobj=sys.stdin, mode='r|gz') ++for ti in tf: ++ tf.extract(ti) ++print tempdir ++"''' ++ ++def copy_to_remote_temporary_directory(host, files): ++ p = subprocess.Popen( ++ ['ssh', host, 'python', '-c', unzip_code], ++ stdout=subprocess.PIPE, stdin=subprocess.PIPE ++ ) ++ tf = tarfile.open(fileobj=p.stdin, mode='w|gz') ++ for name in files: ++ tf.add(name, os.path.basename(name)) ++ tf.close() ++ p.stdin.close() ++ return p.stdout.read().rstrip() ++ ++# ++# Code which runs a host manager ++# ++ ++def main(): ++ # get data from parent over stdin ++ data = pickle.load(sys.stdin) ++ sys.stdin.close() ++ ++ # set some stuff ++ _logger.setLevel(data['dist_log_level']) ++ forking.prepare(data) ++ ++ # create server for a `HostManager` object ++ server = managers.Server(HostManager._registry, ('', 0), data['authkey']) ++ current_process()._server = server ++ ++ # report server address and number of cpus back to parent ++ conn = connection.Client(data['parent_address'], authkey=data['authkey']) ++ conn.send((data['index'], server.address, slot_count)) ++ conn.close() ++ ++ # set name etc ++ current_process().set_name('Host-%s:%s' % server.address) ++ util._run_after_forkers() ++ ++ # register a cleanup function ++ def cleanup(directory): ++ debug('removing directory %s', directory) ++ shutil.rmtree(directory) ++ debug('shutting down host manager') ++ util.Finalize(None, cleanup, args=[data['dir']], exitpriority=0) ++ ++ # start host manager ++ debug('remote host manager starting in %s', data['dir']) ++ server.serve_forever() + +Eigenschaftsänderungen: Doc/includes/mp_distributing.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/includes/mp_pool.py +=================================================================== +--- Doc/includes/mp_pool.py (.../tags/r261) (Revision 70449) ++++ Doc/includes/mp_pool.py (.../branches/release26-maint) (Revision 70449) +@@ -1,6 +1,9 @@ + # + # A test of `multiprocessing.Pool` class + # ++# Copyright (c) 2006-2008, R Oudkerk ++# All rights reserved. ++# + + import multiprocessing + import time +Index: Doc/includes/mp_synchronize.py +=================================================================== +--- Doc/includes/mp_synchronize.py (.../tags/r261) (Revision 70449) ++++ Doc/includes/mp_synchronize.py (.../branches/release26-maint) (Revision 70449) +@@ -1,6 +1,9 @@ + # + # A test file for the `multiprocessing` package + # ++# Copyright (c) 2006-2008, R Oudkerk ++# All rights reserved. ++# + + import time, sys, random + from Queue import Empty +Index: Doc/includes/mp_benchmarks.py +=================================================================== +--- Doc/includes/mp_benchmarks.py (.../tags/r261) (Revision 70449) ++++ Doc/includes/mp_benchmarks.py (.../branches/release26-maint) (Revision 70449) +@@ -1,6 +1,9 @@ + # + # Simple benchmarks for the multiprocessing package + # ++# Copyright (c) 2006-2008, R Oudkerk ++# All rights reserved. ++# + + import time, sys, multiprocessing, threading, Queue, gc + +Index: Doc/includes/mp_newtype.py +=================================================================== +--- Doc/includes/mp_newtype.py (.../tags/r261) (Revision 70449) ++++ Doc/includes/mp_newtype.py (.../branches/release26-maint) (Revision 70449) +@@ -2,6 +2,9 @@ + # This module shows how to use arbitrary callables with a subclass of + # `BaseManager`. + # ++# Copyright (c) 2006-2008, R Oudkerk ++# All rights reserved. ++# + + from multiprocessing import freeze_support + from multiprocessing.managers import BaseManager, BaseProxy +Index: Doc/install/index.rst +=================================================================== +--- Doc/install/index.rst (.../tags/r261) (Revision 70449) ++++ Doc/install/index.rst (.../branches/release26-maint) (Revision 70449) +@@ -3,7 +3,7 @@ + .. _install-index: + + ***************************** +- Installing Python Modules ++ Installing Python Modules + ***************************** + + :Author: Greg Ward +@@ -18,7 +18,7 @@ + Thus, I have to be sure to explain the basics at some point: + sys.path and PYTHONPATH at least. Should probably give pointers to + other docs on "import site", PYTHONSTARTUP, PYTHONHOME, etc. +- ++ + Finally, it might be useful to include all the material from my "Care + and Feeding of a Python Installation" talk in here somewhere. Yow! + +@@ -268,7 +268,7 @@ + statements shown below, and get the output as shown, to find out my + :file:`{prefix}` and :file:`{exec-prefix}`:: + +- Python 2.4 (#26, Aug 7 2004, 17:19:02) ++ Python 2.4 (#26, Aug 7 2004, 17:19:02) + Type "help", "copyright", "credits" or "license" for more information. + >>> import sys + >>> sys.prefix +@@ -587,11 +587,11 @@ + $ python + Python 2.2 (#11, Oct 3 2002, 13:31:27) + [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2 +- Type ``help'', ``copyright'', ``credits'' or ``license'' for more information. ++ Type "help", "copyright", "credits" or "license" for more information. + >>> import sys + >>> sys.path +- ['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', +- '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload', ++ ['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', ++ '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload', + '/usr/local/lib/python2.3/site-packages'] + >>> + +Index: Doc/glossary.rst +=================================================================== +--- Doc/glossary.rst (.../tags/r261) (Revision 70449) ++++ Doc/glossary.rst (.../branches/release26-maint) (Revision 70449) +@@ -11,7 +11,7 @@ + ``>>>`` + The default Python prompt of the interactive shell. Often seen for code + examples which can be executed interactively in the interpreter. +- ++ + ``...`` + The default Python prompt of the interactive shell when entering code for + an indented code block or within a pair of matching left and right +@@ -50,11 +50,11 @@ + A value associated with an object which is referenced by name using + dotted expressions. For example, if an object *o* has an attribute + *a* it would be referenced as *o.a*. +- ++ + BDFL + Benevolent Dictator For Life, a.k.a. `Guido van Rossum + `_, Python's creator. +- ++ + bytecode + Python source code is compiled into bytecode, the internal representation + of a Python program in the interpreter. The bytecode is also cached in +@@ -67,11 +67,11 @@ + A template for creating user-defined objects. Class definitions + normally contain method definitions which operate on instances of the + class. +- ++ + classic class + Any class which does not inherit from :class:`object`. See + :term:`new-style class`. Classic classes will be removed in Python 3.0. +- ++ + coercion + The implicit conversion of an instance of one type to another during an + operation which involves two arguments of the same type. For example, +@@ -84,7 +84,7 @@ + ``operator.add(3.0, 4.5)``. Without coercion, all arguments of even + compatible types would have to be normalized to the same value by the + programmer, e.g., ``float(3)+4.5`` rather than just ``3+4.5``. +- ++ + complex number + An extension of the familiar real number system in which all numbers are + expressed as a sum of a real part and an imaginary part. Imaginary +@@ -96,7 +96,7 @@ + :mod:`math` module, use :mod:`cmath`. Use of complex numbers is a fairly + advanced mathematical feature. If you're not aware of a need for them, + it's almost certain you can safely ignore them. +- ++ + context manager + An object which controls the environment seen in a :keyword:`with` + statement by defining :meth:`__enter__` and :meth:`__exit__` methods. +@@ -123,6 +123,9 @@ + def f(...): + ... + ++ See :ref:`the documentation for function definition ` for more ++ about decorators. ++ + descriptor + Any *new-style* object which defines the methods :meth:`__get__`, + :meth:`__set__`, or :meth:`__delete__`. When a class attribute is a +@@ -135,7 +138,7 @@ + class methods, static methods, and reference to super classes. + + For more information about descriptors' methods, see :ref:`descriptors`. +- ++ + dictionary + An associative array, where arbitrary keys are mapped to values. The use + of :class:`dict` closely resembles that for :class:`list`, but the keys can +@@ -149,8 +152,8 @@ + of the enclosing class, function or module. Since it is available via + introspection, it is the canonical place for documentation of the + object. +- +- duck-typing ++ ++ duck-typing + A pythonic programming style which determines an object's type by inspection + of its method or attribute signature rather than by explicit relationship + to some type object ("If it looks like a duck and quacks like a duck, it +@@ -160,13 +163,13 @@ + :func:`isinstance`. (Note, however, that duck-typing can be complemented + with abstract base classes.) Instead, it typically employs :func:`hasattr` + tests or :term:`EAFP` programming. +- ++ + EAFP + Easier to ask for forgiveness than permission. This common Python coding + style assumes the existence of valid keys or attributes and catches + exceptions if the assumption proves false. This clean and fast style is + characterized by the presence of many :keyword:`try` and :keyword:`except` +- statements. The technique contrasts with the :term:`LBYL` style ++ statements. The technique contrasts with the :term:`LBYL` style + common to many other languages such as C. + + expression +@@ -192,14 +195,14 @@ + which are not compatible with the current interpreter. For example, the + expression ``11/4`` currently evaluates to ``2``. If the module in which + it is executed had enabled *true division* by executing:: +- ++ + from __future__ import division +- ++ + the expression ``11/4`` would evaluate to ``2.75``. By importing the + :mod:`__future__` module and evaluating its variables, you can see when a + new feature was first added to the language and when it will become the + default:: +- ++ + >>> import __future__ + >>> __future__.division + _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192) +@@ -208,7 +211,7 @@ + The process of freeing memory when it is not used anymore. Python + performs garbage collection via reference counting and a cyclic garbage + collector that is able to detect and break reference cycles. +- ++ + generator + A function which returns an iterator. It looks like a normal function + except that values are returned to the caller using a :keyword:`yield` +@@ -218,21 +221,21 @@ + stopped at the :keyword:`yield` keyword (returning the result) and is + resumed there when the next element is requested by calling the + :meth:`next` method of the returned iterator. +- ++ + .. index:: single: generator expression +- ++ + generator expression + An expression that returns a generator. It looks like a normal expression + followed by a :keyword:`for` expression defining a loop variable, range, + and an optional :keyword:`if` expression. The combined expression + generates values for an enclosing function:: +- ++ + >>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81 + 285 +- ++ + GIL + See :term:`global interpreter lock`. +- ++ + global interpreter lock + The lock used by Python threads to assure that only one thread + executes in the :term:`CPython` :term:`virtual machine` at a time. +@@ -258,21 +261,21 @@ + containers (such as lists or dictionaries) are. Objects which are + instances of user-defined classes are hashable by default; they all + compare unequal, and their hash value is their :func:`id`. +- ++ + IDLE + An Integrated Development Environment for Python. IDLE is a basic editor + and interpreter environment which ships with the standard distribution of + Python. Good for beginners, it also serves as clear example code for + those wanting to implement a moderately sophisticated, multi-platform GUI + application. +- ++ + immutable + An object with a fixed value. Immutable objects include numbers, strings and + tuples. Such an object cannot be altered. A new object has to + be created if a different value has to be stored. They play an important + role in places where a constant hash value is needed, for example as a key + in a dictionary. +- ++ + integer division + Mathematical division discarding any remainder. For example, the + expression ``11/4`` currently evaluates to ``2`` in contrast to the +@@ -284,7 +287,7 @@ + divided by a float will result in a float value, possibly with a decimal + fraction. Integer division can be forced by using the ``//`` operator + instead of the ``/`` operator. See also :term:`__future__`. +- ++ + interactive + Python has an interactive interpreter which means you can enter + statements and expressions at the interpreter prompt, immediately +@@ -292,7 +295,7 @@ + arguments (possibly by selecting it from your computer's main + menu). It is a very powerful way to test out new ideas or inspect + modules and packages (remember ``help(x)``). +- ++ + interpreted + Python is an interpreted language, as opposed to a compiled one, + though the distinction can be blurry because of the presence of the +@@ -301,7 +304,7 @@ + Interpreted languages typically have a shorter development/debug cycle + than compiled ones, though their programs generally also run more + slowly. See also :term:`interactive`. +- ++ + iterable + A container object capable of returning its members one at a + time. Examples of iterables include all sequence types (such as +@@ -317,7 +320,7 @@ + statement does that automatically for you, creating a temporary unnamed + variable to hold the iterator for the duration of the loop. See also + :term:`iterator`, :term:`sequence`, and :term:`generator`. +- ++ + iterator + An object representing a stream of data. Repeated calls to the iterator's + :meth:`next` method return successive items in the stream. When no more +@@ -332,7 +335,7 @@ + :func:`iter` function or use it in a :keyword:`for` loop. Attempting this + with an iterator will just return the same exhausted iterator object used + in the previous iteration pass, making it appear like an empty container. +- ++ + More information can be found in :ref:`typeiter`. + + keyword argument +@@ -356,7 +359,7 @@ + A built-in Python :term:`sequence`. Despite its name it is more akin + to an array in other languages than to a linked list since access to + elements are O(1). +- ++ + list comprehension + A compact way to process all or part of the elements in a sequence and + return a list with the results. ``result = ["0x%02x" % x for x in +@@ -364,11 +367,11 @@ + even hex numbers (0x..) in the range from 0 to 255. The :keyword:`if` + clause is optional. If omitted, all elements in ``range(256)`` are + processed. +- ++ + mapping + A container object (such as :class:`dict`) which supports arbitrary key + lookups using the special method :meth:`__getitem__`. +- ++ + metaclass + The class of a class. Class definitions create a class name, a class + dictionary, and a list of base classes. The metaclass is responsible for +@@ -387,13 +390,13 @@ + of an instance of that class, the method will get the instance object as + its first :term:`argument` (which is usually called ``self``). + See :term:`function` and :term:`nested scope`. +- ++ + mutable + Mutable objects can change their value but keep their :func:`id`. See + also :term:`immutable`. + + named tuple +- Any tuple subclass whose indexable elements are also accessible using ++ Any tuple-like class whose indexable elements are also accessible using + named attributes (for example, :func:`time.localtime` returns a + tuple-like object where the *year* is accessible either with an + index such as ``t[0]`` or with a named attribute like ``t.tm_year``). +@@ -404,7 +407,7 @@ + :func:`collections.namedtuple`. The latter approach automatically + provides extra features such as a self-documenting representation like + ``Employee(name='jones', title='programmer')``. +- ++ + namespace + The place where a variable is stored. Namespaces are implemented as + dictionaries. There are the local, global and builtin namespaces as well +@@ -416,7 +419,7 @@ + :func:`random.seed` or :func:`itertools.izip` makes it clear that those + functions are implemented by the :mod:`random` and :mod:`itertools` + modules, respectively. +- ++ + nested scope + The ability to refer to a variable in an enclosing definition. For + instance, a function defined inside another function can refer to +@@ -424,7 +427,7 @@ + reference and not for assignment which will always write to the innermost + scope. In contrast, local variables both read and write in the innermost + scope. Likewise, global variables read and write to the global namespace. +- ++ + new-style class + Any class which inherits from :class:`object`. This includes all built-in + types like :class:`list` and :class:`dict`. Only new-style classes can +@@ -437,7 +440,7 @@ + Any data with state (attributes or value) and defined behavior + (methods). Also the ultimate base class of any :term:`new-style + class`. +- ++ + positional argument + The arguments assigned to local names inside a function or method, + determined by the order in which they were given in the call. ``*`` is +@@ -445,7 +448,7 @@ + definition), or pass several arguments as a list to a function. See + :term:`argument`. + +- Python 3000 ++ Python 3000 + Nickname for the next major Python version, 3.0 (coined long ago + when the release of version 3 was something in the distant future.) This + is also abbreviated "Py3k". +@@ -457,7 +460,7 @@ + to loop over all elements of an iterable using a :keyword:`for` + statement. Many other languages don't have this type of construct, so + people unfamiliar with Python sometimes use a numerical counter instead:: +- ++ + for i in range(len(food)): + print food[i] + +@@ -480,7 +483,7 @@ + dictionaries. Though popular, the technique is somewhat tricky to get + right and is best reserved for rare cases where there are large numbers of + instances in a memory-critical application. +- ++ + sequence + An :term:`iterable` which supports efficient element access using integer + indices via the :meth:`__getitem__` special method and defines a +@@ -498,6 +501,12 @@ + (subscript) notation uses :class:`slice` objects internally (or in older + versions, :meth:`__getslice__` and :meth:`__setslice__`). + ++ special method ++ A method that is called implicitly by Python to execute a certain ++ operation on a type, such as addition. Such methods have names starting ++ and ending with double underscores. Special methods are documented in ++ :ref:`specialnames`. ++ + statement + A statement is part of a suite (a "block" of code). A statement is either + an :term:`expression` or a one of several constructs with a keyword, such +@@ -520,7 +529,7 @@ + virtual machine + A computer defined entirely in software. Python's virtual machine + executes the :term:`bytecode` emitted by the bytecode compiler. +- ++ + Zen of Python + Listing of Python design principles and philosophies that are helpful in + understanding and using the language. The listing can be found by typing +Index: Doc/README.txt +=================================================================== +--- Doc/README.txt (.../tags/r261) (Revision 70449) ++++ Doc/README.txt (.../branches/release26-maint) (Revision 70449) +@@ -76,8 +76,7 @@ + + svn co http://svn.python.org/projects/doctools/trunk/sphinx tools/sphinx + +-Then, you need to install Docutils 0.4 (the SVN snapshot won't work), either +-by checking it out via :: ++Then, you need to install Docutils, either by checking it out via :: + + svn co http://svn.python.org/projects/external/docutils-0.4/docutils tools/docutils + +@@ -94,19 +93,18 @@ + + python tools/sphinx-build.py -b . build/ + +-where `` is one of html, web or htmlhelp (for explanations see the make +-targets above). ++where `` is one of html, text, latex, or htmlhelp (for explanations see ++the make targets above). + + + Contributing + ============ + +-For bugs in the content, the online version at http://docs.python.org/ has a +-"suggest change" facility that can be used to correct errors in the source text +-and submit them as a patch to the maintainers. ++Bugs in the content should be reported to the Python bug tracker at ++http://bugs.python.org. + +-Bugs in the toolset should be reported in the Python bug tracker at +-http://bugs.python.org/. ++Bugs in the toolset should be reported in the Sphinx bug tracker at ++http://www.bitbucket.org/birkenfeld/sphinx/issues/. + + You can also send a mail to the Python Documentation Team at docs@python.org, + and we will process your request as soon as possible. +Index: Doc/documenting/sphinx.rst +=================================================================== +--- Doc/documenting/sphinx.rst (.../tags/r261) (Revision 70449) ++++ Doc/documenting/sphinx.rst (.../branches/release26-maint) (Revision 70449) +@@ -1,76 +0,0 @@ +-.. highlightlang:: rest +- +-The Sphinx build system +-======================= +- +-.. XXX: intro... +- +-.. _doc-build-config: +- +-The build configuration file +----------------------------- +- +-The documentation root, that is the ``Doc`` subdirectory of the source +-distribution, contains a file named ``conf.py``. This file is called the "build +-configuration file", and it contains several variables that are read and used +-during a build run. +- +-These variables are: +- +-version : string +- A string that is used as a replacement for the ``|version|`` reST +- substitution. It should be the Python version the documentation refers to. +- This consists only of the major and minor version parts, e.g. ``2.5``, even +- for version 2.5.1. +- +-release : string +- A string that is used as a replacement for the ``|release|`` reST +- substitution. It should be the full version string including +- alpha/beta/release candidate tags, e.g. ``2.5.2b3``. +- +-Both ``release`` and ``version`` can be ``'auto'``, which means that they are +-determined at runtime from the ``Include/patchlevel.h`` file, if a complete +-Python source distribution can be found, or else from the interpreter running +-Sphinx. +- +-today_fmt : string +- A ``strftime`` format that is used to format a replacement for the +- ``|today|`` reST substitution. +- +-today : string +- A string that can contain a date that should be written to the documentation +- output literally. If this is nonzero, it is used instead of +- ``strftime(today_fmt)``. +- +-unused_files : list of strings +- A list of reST filenames that are to be disregarded during building. This +- could be docs for temporarily disabled modules or documentation that's not +- yet ready for public consumption. +- +-add_function_parentheses : bool +- If true, ``()`` will be appended to the content of ``:func:``, ``:meth:`` and +- ``:cfunc:`` cross-references. +- +-add_module_names : bool +- If true, the current module name will be prepended to all description unit +- titles (such as ``.. function::``). +- +-Builder-specific variables +-^^^^^^^^^^^^^^^^^^^^^^^^^^ +- +-html_download_base_url : string +- The base URL for download links on the download page. +- +-html_last_updated_fmt : string +- If this is not an empty string, it will be given to ``time.strftime()`` and +- written to each generated output file after "last updated on:". +- +-html_use_smartypants : bool +- If true, use SmartyPants to convert quotes and dashes to the typographically +- correct entities. +- +-latex_paper_size : "letter" or "a4" +- The paper size option for the LaTeX document class. +- +-latex_font_size : "10pt", "11pt" or "12pt" +- The font size option for the LaTeX document class. +\ No newline at end of file +Index: Doc/documenting/rest.rst +=================================================================== +--- Doc/documenting/rest.rst (.../tags/r261) (Revision 70449) ++++ Doc/documenting/rest.rst (.../branches/release26-maint) (Revision 70449) +@@ -67,13 +67,7 @@ + #. This is a numbered list. + #. It has two items too. + +-Note that Sphinx disables the use of enumerated lists introduced by alphabetic +-or roman numerals, such as :: + +- A. First item +- B. Second item +- +- + Nested lists are possible, but be aware that they must be separated from the + parent list items by blank lines:: + +@@ -104,7 +98,7 @@ + ----------- + + Literal code blocks are introduced by ending a paragraph with the special marker +-``::``. The literal block must be indented, to be able to include blank lines:: ++``::``. The literal block must be indented:: + + This is a normal text paragraph. The next paragraph is a code sample:: + +@@ -247,5 +241,3 @@ + * **Separation of inline markup:** As said above, inline markup spans must be + separated from the surrounding text by non-word characters, you have to use + an escaped space to get around that. +- +-.. XXX more? +Index: Doc/documenting/markup.rst +=================================================================== +--- Doc/documenting/markup.rst (.../tags/r261) (Revision 70449) ++++ Doc/documenting/markup.rst (.../branches/release26-maint) (Revision 70449) +@@ -8,26 +8,13 @@ + Documentation for "standard" reST constructs is not included here, though + they are used in the Python documentation. + +-File-wide metadata +------------------- ++.. note:: + +-reST has the concept of "field lists"; these are a sequence of fields marked up +-like this:: ++ This is just an overview of Sphinx' extended markup capabilities; full ++ coverage can be found in `its own documentation ++ `_. + +- :Field name: Field content + +-A field list at the very top of a file is parsed as the "docinfo", which in +-normal documents can be used to record the author, date of publication and +-other metadata. In Sphinx, the docinfo is used as metadata, too, but not +-displayed in the output. +- +-At the moment, only one metadata field is recognized: +- +-``nocomments`` +- If set, the web application won't display a comment form for a page generated +- from this source file. +- +- + Meta-information markup + ----------------------- + +@@ -88,7 +75,6 @@ + authors of the module code, just like ``sectionauthor`` names the author(s) + of a piece of documentation. It too does not result in any output currently. + +- + .. note:: + + It is important to make the section title of a module-describing file +@@ -272,7 +258,7 @@ + This language is used until the next ``highlightlang`` directive is + encountered. + +-* The valid values for the highlighting language are: ++* The values normally used for the highlighting language are: + + * ``python`` (the default) + * ``c`` +@@ -299,15 +285,28 @@ + As said before, Sphinx uses interpreted text roles to insert semantic markup in + documents. + +-Variable names are an exception, they should be marked simply with ``*var*``. ++Names of local variables, such as function/method arguments, are an exception, ++they should be marked simply with ``*var*``. + + For all other roles, you have to write ``:rolename:`content```. + +-.. note:: ++There are some additional facilities that make cross-referencing roles more ++versatile: + +- For all cross-referencing roles, if you prefix the content with ``!``, no +- reference/hyperlink will be created. ++* You may supply an explicit title and reference target, like in reST direct ++ hyperlinks: ``:role:`title ``` will refer to *target*, but the link ++ text will be *title*. + ++* If you prefix the content with ``!``, no reference/hyperlink will be created. ++ ++* For the Python object roles, if you prefix the content with ``~``, the link ++ text will only be the last component of the target. For example, ++ ``:meth:`~Queue.Queue.get``` will refer to ``Queue.Queue.get`` but only ++ display ``get`` as the link text. ++ ++ In HTML output, the link's ``title`` attribute (that is e.g. shown as a ++ tool-tip on mouse-hover) will always be the full target name. ++ + The following roles refer to objects in modules and are possibly hyperlinked if + a matching identifier is found: + +@@ -324,7 +323,7 @@ + + .. describe:: data + +- The name of a module-level variable. ++ The name of a module-level variable or constant. + + .. describe:: const + +@@ -522,7 +521,7 @@ + curly braces to indicate a "variable" part, as in ``:file:``. + + If you don't need the "variable part" indication, use the standard +- ````code```` instead. ++ ````code```` instead. + + .. describe:: var + +@@ -613,7 +612,7 @@ + Example:: + + .. versionadded:: 2.5 +- The `spam` parameter. ++ The *spam* parameter. + + Note that there must be no blank line between the directive head and the + explanation; this is to make these blocks visually continuous in the markup. +@@ -774,14 +773,14 @@ + Blank lines are not allowed within ``productionlist`` directive arguments. + + The definition can contain token names which are marked as interpreted text +- (e.g. ``sum ::= `integer` "+" `integer```) -- this generates cross-references ++ (e.g. ``unaryneg ::= "-" `integer```) -- this generates cross-references + to the productions of these tokens. + + Note that no further reST parsing is done in the production, so that you + don't have to escape ``*`` or ``|`` characters. + + +-.. XXX describe optional first parameter ++.. XXX describe optional first parameter + + The following is an example taken from the Python Reference Manual:: + +@@ -799,7 +798,7 @@ + ------------- + + The documentation system provides three substitutions that are defined by default. +-They are set in the build configuration file, see :ref:`doc-build-config`. ++They are set in the build configuration file :file:`conf.py`. + + .. describe:: |release| + +Index: Doc/documenting/style.rst +=================================================================== +--- Doc/documenting/style.rst (.../tags/r261) (Revision 70449) ++++ Doc/documenting/style.rst (.../branches/release26-maint) (Revision 70449) +@@ -66,5 +66,5 @@ + 1970s. + + +-.. _Apple Publications Style Guide: http://developer.apple.com/documentation/UserExperience/Conceptual/APStyleGuide/AppleStyleGuide2006.pdf ++.. _Apple Publications Style Guide: http://developer.apple.com/documentation/UserExperience/Conceptual/APStyleGuide/APSG_2008.pdf + +Index: Doc/documenting/index.rst +=================================================================== +--- Doc/documenting/index.rst (.../tags/r261) (Revision 70449) ++++ Doc/documenting/index.rst (.../branches/release26-maint) (Revision 70449) +@@ -8,7 +8,7 @@ + The Python language has a substantial body of documentation, much of it + contributed by various authors. The markup used for the Python documentation is + `reStructuredText`_, developed by the `docutils`_ project, amended by custom +-directives and using a toolset named *Sphinx* to postprocess the HTML output. ++directives and using a toolset named `Sphinx`_ to postprocess the HTML output. + + This document describes the style guide for our documentation, the custom + reStructuredText markup introduced to support Python documentation and how it +@@ -16,6 +16,7 @@ + + .. _reStructuredText: http://docutils.sf.net/rst.html + .. _docutils: http://docutils.sf.net/ ++.. _Sphinx: http://sphinx.pocoo.org/ + + If you're interested in contributing to Python's documentation, there's no need + to write reStructuredText if you're not so inclined; plain text contributions +@@ -28,7 +29,3 @@ + rest.rst + markup.rst + fromlatex.rst +- sphinx.rst +- +-.. XXX add credits, thanks etc. +- +Index: Doc/conf.py +=================================================================== +--- Doc/conf.py (.../tags/r261) (Revision 70449) ++++ Doc/conf.py (.../branches/release26-maint) (Revision 70449) +@@ -128,7 +128,7 @@ + ] + # Collect all HOWTOs individually + latex_documents.extend(('howto/' + fn[:-4], 'howto-' + fn[:-4] + '.tex', +- 'HOWTO', _stdauthor, 'howto') ++ '', _stdauthor, 'howto') + for fn in os.listdir('howto') + if fn.endswith('.rst') and fn != 'index.rst') + +Index: Doc/Makefile +=================================================================== +--- Doc/Makefile (.../tags/r261) (Revision 70449) ++++ Doc/Makefile (.../branches/release26-maint) (Revision 70449) +@@ -9,12 +9,12 @@ + SPHINXOPTS = + PAPER = + SOURCES = +-DISTVERSION = ++DISTVERSION = $(shell $(PYTHON) tools/sphinxext/patchlevel.py) + + ALLSPHINXOPTS = -b $(BUILDER) -d build/doctrees -D latex_paper_size=$(PAPER) \ + $(SPHINXOPTS) . build/$(BUILDER) $(SOURCES) + +-.PHONY: help checkout update build html htmlhelp clean coverage dist ++.PHONY: help checkout update build html htmlhelp clean coverage dist check + + help: + @echo "Please use \`make ' where is one of" +@@ -24,6 +24,7 @@ + @echo " text to make plain text files" + @echo " changes to make an overview over all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" ++ @echo " suspicious to check for suspicious markup in output text" + @echo " coverage to check documentation coverage for library and C API" + @echo " dist to create a \"dist\" directory with archived docs for download" + +@@ -36,9 +37,9 @@ + echo "Checking out Docutils..."; \ + svn checkout $(SVNROOT)/external/docutils-0.5/docutils tools/docutils; \ + fi +- @if [ ! -d tools/jinja ]; then \ ++ @if [ ! -d tools/jinja2 ]; then \ + echo "Checking out Jinja..."; \ +- svn checkout $(SVNROOT)/external/Jinja-1.2/jinja tools/jinja; \ ++ svn checkout $(SVNROOT)/external/Jinja-2.1.1/jinja2 tools/jinja2; \ + fi + @if [ ! -d tools/pygments ]; then \ + echo "Checking out Pygments..."; \ +@@ -48,7 +49,7 @@ + update: checkout + svn update tools/sphinx + svn update tools/docutils +- svn update tools/jinja ++ svn update tools/jinja2 + svn update tools/pygments + + build: checkout +@@ -84,6 +85,11 @@ + @echo "Link check complete; look for any errors in the above output " \ + "or in build/$(BUILDER)/output.txt" + ++suspicious: BUILDER = suspicious ++suspicious: build ++ @echo "Suspicious check complete; look for any errors in the above output " \ ++ "or in build/$(BUILDER)/suspicious.txt" ++ + coverage: BUILDER = coverage + coverage: build + @echo "Coverage finished; see c.txt and python.txt in build/coverage" +@@ -111,33 +117,35 @@ + + # archive the HTML + make html +- cp -pPR build/html dist/python$(DISTVERSION)-docs-html +- tar -C dist -cf dist/python$(DISTVERSION)-docs-html.tar python$(DISTVERSION)-docs-html +- bzip2 -9 -k dist/python$(DISTVERSION)-docs-html.tar +- (cd dist; zip -q -r -9 python$(DISTVERSION)-docs-html.zip python$(DISTVERSION)-docs-html) +- rm -r dist/python$(DISTVERSION)-docs-html +- rm dist/python$(DISTVERSION)-docs-html.tar ++ cp -pPR build/html dist/python-$(DISTVERSION)-docs-html ++ tar -C dist -cf dist/python-$(DISTVERSION)-docs-html.tar python-$(DISTVERSION)-docs-html ++ bzip2 -9 -k dist/python-$(DISTVERSION)-docs-html.tar ++ (cd dist; zip -q -r -9 python-$(DISTVERSION)-docs-html.zip python-$(DISTVERSION)-docs-html) ++ rm -r dist/python-$(DISTVERSION)-docs-html ++ rm dist/python-$(DISTVERSION)-docs-html.tar + + # archive the text build + make text +- cp -pPR build/text dist/python$(DISTVERSION)-docs-text +- tar -C dist -cf dist/python$(DISTVERSION)-docs-text.tar python$(DISTVERSION)-docs-text +- bzip2 -9 -k dist/python$(DISTVERSION)-docs-text.tar +- (cd dist; zip -q -r -9 python$(DISTVERSION)-docs-text.zip python$(DISTVERSION)-docs-text) +- rm -r dist/python$(DISTVERSION)-docs-text +- rm dist/python$(DISTVERSION)-docs-text.tar ++ cp -pPR build/text dist/python-$(DISTVERSION)-docs-text ++ tar -C dist -cf dist/python-$(DISTVERSION)-docs-text.tar python-$(DISTVERSION)-docs-text ++ bzip2 -9 -k dist/python-$(DISTVERSION)-docs-text.tar ++ (cd dist; zip -q -r -9 python-$(DISTVERSION)-docs-text.zip python-$(DISTVERSION)-docs-text) ++ rm -r dist/python-$(DISTVERSION)-docs-text ++ rm dist/python-$(DISTVERSION)-docs-text.tar + + # archive the A4 latex + -rm -r build/latex + make latex PAPER=a4 + (cd build/latex; make clean && make all-pdf && make FMT=pdf zip bz2) +- cp build/latex/docs-pdf.zip dist/python$(DISTVERSION)-docs-pdf-a4.zip +- cp build/latex/docs-pdf.tar.bz2 dist/python$(DISTVERSION)-docs-pdf-a4.tar.bz2 ++ cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-a4.zip ++ cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-a4.tar.bz2 + + # archive the letter latex + rm -r build/latex + make latex PAPER=letter + (cd build/latex; make clean && make all-pdf && make FMT=pdf zip bz2) +- cp build/latex/docs-pdf.zip dist/python$(DISTVERSION)-docs-pdf-letter.zip +- cp build/latex/docs-pdf.tar.bz2 dist/python$(DISTVERSION)-docs-pdf-letter.tar.bz2 ++ cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-letter.zip ++ cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-letter.tar.bz2 + ++check: ++ $(PYTHON) tools/rstlint.py -i tools +Index: Lib/fractions.py +=================================================================== +--- Lib/fractions.py (.../tags/r261) (Revision 70449) ++++ Lib/fractions.py (.../branches/release26-maint) (Revision 70449) +@@ -111,7 +111,7 @@ + + """ + if isinstance(f, numbers.Integral): +- f = float(f) ++ return cls(f) + elif not isinstance(f, float): + raise TypeError("%s.from_float() only takes floats, not %r (%s)" % + (cls.__name__, f, type(f).__name__)) +Index: Lib/mimetypes.py +=================================================================== +--- Lib/mimetypes.py (.../tags/r261) (Revision 70449) ++++ Lib/mimetypes.py (.../branches/release26-maint) (Revision 70449) +@@ -237,7 +237,8 @@ + Optional `strict' argument when false adds a bunch of commonly found, but + non-standard types. + """ +- init() ++ if not inited: ++ init() + return guess_type(url, strict) + + +@@ -254,7 +255,8 @@ + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + """ +- init() ++ if not inited: ++ init() + return guess_all_extensions(type, strict) + + def guess_extension(type, strict=True): +@@ -269,7 +271,8 @@ + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + """ +- init() ++ if not inited: ++ init() + return guess_extension(type, strict) + + def add_type(type, ext, strict=True): +@@ -284,7 +287,8 @@ + list of standard types, else to the list of non-standard + types. + """ +- init() ++ if not inited: ++ init() + return add_type(type, ext, strict) + + +Index: Lib/idlelib/Bindings.py +=================================================================== +--- Lib/idlelib/Bindings.py (.../tags/r261) (Revision 70449) ++++ Lib/idlelib/Bindings.py (.../branches/release26-maint) (Revision 70449) +@@ -10,6 +10,7 @@ + """ + import sys + from configHandler import idleConf ++import macosxSupport + + menudefs = [ + # underscore prefixes character to underscore +@@ -80,8 +81,7 @@ + ]), + ] + +-import sys +-if sys.platform == 'darwin' and '.app' in sys.executable: ++if macosxSupport.runningAsOSXApp(): + # Running as a proper MacOS application bundle. This block restructures + # the menus a little to make them conform better to the HIG. + +Index: Lib/idlelib/configDialog.py +=================================================================== +--- Lib/idlelib/configDialog.py (.../tags/r261) (Revision 70449) ++++ Lib/idlelib/configDialog.py (.../branches/release26-maint) (Revision 70449) +@@ -19,6 +19,7 @@ + from keybindingDialog import GetKeysDialog + from configSectionNameDialog import GetCfgSectionNameDialog + from configHelpSourceEdit import GetHelpSourceDialog ++import macosxSupport + + class ConfigDialog(Toplevel): + +@@ -69,18 +70,25 @@ + page_names=['Fonts/Tabs','Highlighting','Keys','General']) + frameActionButtons = Frame(self,pady=2) + #action buttons ++ if macosxSupport.runningAsOSXApp(): ++ # Changing the default padding on OSX results in unreadable ++ # text in the buttons ++ paddingArgs={} ++ else: ++ paddingArgs={'padx':6, 'pady':3} ++ + self.buttonHelp = Button(frameActionButtons,text='Help', + command=self.Help,takefocus=FALSE, +- padx=6,pady=3) ++ **paddingArgs) + self.buttonOk = Button(frameActionButtons,text='Ok', + command=self.Ok,takefocus=FALSE, +- padx=6,pady=3) ++ **paddingArgs) + self.buttonApply = Button(frameActionButtons,text='Apply', + command=self.Apply,takefocus=FALSE, +- padx=6,pady=3) ++ **paddingArgs) + self.buttonCancel = Button(frameActionButtons,text='Cancel', + command=self.Cancel,takefocus=FALSE, +- padx=6,pady=3) ++ **paddingArgs) + self.CreatePageFontTab() + self.CreatePageHighlight() + self.CreatePageKeys() +Index: Lib/idlelib/keybindingDialog.py +=================================================================== +--- Lib/idlelib/keybindingDialog.py (.../tags/r261) (Revision 70449) ++++ Lib/idlelib/keybindingDialog.py (.../branches/release26-maint) (Revision 70449) +@@ -132,8 +132,8 @@ + order is also important: key binding equality depends on it, so + config-keys.def must use the same ordering. + """ +- import sys +- if sys.platform == 'darwin' and sys.argv[0].count('.app'): ++ import macosxSupport ++ if macosxSupport.runningAsOSXApp(): + self.modifiers = ['Shift', 'Control', 'Option', 'Command'] + else: + self.modifiers = ['Control', 'Alt', 'Shift'] +Index: Lib/idlelib/EditorWindow.py +=================================================================== +--- Lib/idlelib/EditorWindow.py (.../tags/r261) (Revision 70449) ++++ Lib/idlelib/EditorWindow.py (.../branches/release26-maint) (Revision 70449) +@@ -368,7 +368,7 @@ + menudict[name] = menu = Menu(mbar, name=name) + mbar.add_cascade(label=label, menu=menu, underline=underline) + +- if sys.platform == 'darwin' and '.framework' in sys.executable: ++ if macosxSupport.runningAsOSXApp(): + # Insert the application menu + menudict['application'] = menu = Menu(mbar, name='apple') + mbar.add_cascade(label='IDLE', menu=menu) +Index: Lib/idlelib/help.txt +=================================================================== +--- Lib/idlelib/help.txt (.../tags/r261) (Revision 70449) ++++ Lib/idlelib/help.txt (.../branches/release26-maint) (Revision 70449) +@@ -90,7 +90,10 @@ + Configure IDLE -- Open a configuration dialog. Fonts, indentation, + keybindings, and color themes may be altered. + Startup Preferences may be set, and Additional Help +- Souces can be specified. ++ Sources can be specified. ++ ++ On MacOS X this menu is not present, use ++ menu 'IDLE -> Preferences...' instead. + --- + Code Context -- Open a pane at the top of the edit window which + shows the block context of the section of code +Index: Lib/idlelib/MultiCall.py +=================================================================== +--- Lib/idlelib/MultiCall.py (.../tags/r261) (Revision 70449) ++++ Lib/idlelib/MultiCall.py (.../branches/release26-maint) (Revision 70449) +@@ -33,6 +33,7 @@ + import string + import re + import Tkinter ++import macosxSupport + + # the event type constants, which define the meaning of mc_type + MC_KEYPRESS=0; MC_KEYRELEASE=1; MC_BUTTONPRESS=2; MC_BUTTONRELEASE=3; +@@ -45,7 +46,7 @@ + MC_OPTION = 1<<6; MC_COMMAND = 1<<7 + + # define the list of modifiers, to be used in complex event types. +-if sys.platform == "darwin" and sys.executable.count(".app"): ++if macosxSupport.runningAsOSXApp(): + _modifiers = (("Shift",), ("Control",), ("Option",), ("Command",)) + _modifier_masks = (MC_SHIFT, MC_CONTROL, MC_OPTION, MC_COMMAND) + else: +Index: Lib/idlelib/macosxSupport.py +=================================================================== +--- Lib/idlelib/macosxSupport.py (.../tags/r261) (Revision 70449) ++++ Lib/idlelib/macosxSupport.py (.../branches/release26-maint) (Revision 70449) +@@ -6,8 +6,12 @@ + import Tkinter + + def runningAsOSXApp(): +- """ Returns True iff running from the IDLE.app bundle on OSX """ +- return (sys.platform == 'darwin' and 'IDLE.app' in sys.argv[0]) ++ """ ++ 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. ++ """ ++ return (sys.platform == 'darwin' and '.app' in sys.executable) + + def addOpenEventSupport(root, flist): + """ +@@ -89,7 +93,9 @@ + + ###check if Tk version >= 8.4.14; if so, use hard-coded showprefs binding + tkversion = root.tk.eval('info patchlevel') +- if tkversion >= '8.4.14': ++ # Note: we cannot check if the string tkversion >= '8.4.14', because ++ # the string '8.4.7' is greater than the string '8.4.14'. ++ if map(int, tkversion.split('.')) >= (8, 4, 14): + Bindings.menudefs[0] = ('application', [ + ('About IDLE', '<>'), + None, +Index: Lib/_abcoll.py +=================================================================== +--- Lib/_abcoll.py (.../tags/r261) (Revision 70449) ++++ Lib/_abcoll.py (.../branches/release26-maint) (Revision 70449) +@@ -60,7 +60,7 @@ + class Iterator(Iterable): + + @abstractmethod +- def __next__(self): ++ def next(self): + raise StopIteration + + def __iter__(self): +@@ -249,12 +249,12 @@ + + @abstractmethod + def add(self, value): +- """Return True if it was added, False if already there.""" ++ """Add an element.""" + raise NotImplementedError + + @abstractmethod + def discard(self, value): +- """Return True if it was deleted, False if not there.""" ++ """Remove an element. Do not raise an exception if absent.""" + raise NotImplementedError + + def remove(self, value): +@@ -267,7 +267,7 @@ + """Return the popped value. Raise KeyError if empty.""" + it = iter(self) + try: +- value = it.__next__() ++ value = next(it) + except StopIteration: + raise KeyError + self.discard(value) +@@ -519,6 +519,7 @@ + Sequence.register(tuple) + Sequence.register(basestring) + Sequence.register(buffer) ++Sequence.register(xrange) + + + class MutableSequence(Sequence): +Index: Lib/multiprocessing/pool.py +=================================================================== +--- Lib/multiprocessing/pool.py (.../tags/r261) (Revision 70449) ++++ Lib/multiprocessing/pool.py (.../branches/release26-maint) (Revision 70449) +@@ -149,7 +149,7 @@ + + def imap(self, func, iterable, chunksize=1): + ''' +- Equivalent of `itertool.imap()` -- can be MUCH slower than `Pool.map()` ++ Equivalent of `itertools.imap()` -- can be MUCH slower than `Pool.map()` + ''' + assert self._state == RUN + if chunksize == 1: +Index: Lib/multiprocessing/util.py +=================================================================== +--- Lib/multiprocessing/util.py (.../tags/r261) (Revision 70449) ++++ Lib/multiprocessing/util.py (.../branches/release26-maint) (Revision 70449) +@@ -69,34 +69,10 @@ + atexit._exithandlers.remove((_exit_function, (), {})) + atexit._exithandlers.append((_exit_function, (), {})) + +- _check_logger_class() + _logger = logging.getLogger(LOGGER_NAME) + + return _logger + +-def _check_logger_class(): +- ''' +- Make sure process name is recorded when loggers are used +- ''' +- # XXX This function is unnecessary once logging is patched +- import logging +- if hasattr(logging, 'multiprocessing'): +- return +- +- logging._acquireLock() +- try: +- OldLoggerClass = logging.getLoggerClass() +- if not getattr(OldLoggerClass, '_process_aware', False): +- class ProcessAwareLogger(OldLoggerClass): +- _process_aware = True +- def makeRecord(self, *args, **kwds): +- record = OldLoggerClass.makeRecord(self, *args, **kwds) +- record.processName = current_process()._name +- return record +- logging.setLoggerClass(ProcessAwareLogger) +- finally: +- logging._releaseLock() +- + def log_to_stderr(level=None): + ''' + Turn on logging and add a handler which prints to stderr +Index: Lib/multiprocessing/sharedctypes.py +=================================================================== +--- Lib/multiprocessing/sharedctypes.py (.../tags/r261) (Revision 70449) ++++ Lib/multiprocessing/sharedctypes.py (.../branches/release26-maint) (Revision 70449) +@@ -69,9 +69,12 @@ + if kwds: + raise ValueError('unrecognized keyword argument(s): %s' % kwds.keys()) + obj = RawValue(typecode_or_type, *args) +- if lock is None: ++ if lock is False: ++ return obj ++ if lock in (True, None): + lock = RLock() +- assert hasattr(lock, 'acquire') ++ if not hasattr(lock, 'acquire'): ++ raise AttributeError("'%r' has no method 'acquire'" % lock) + return synchronized(obj, lock) + + def Array(typecode_or_type, size_or_initializer, **kwds): +@@ -82,9 +85,12 @@ + if kwds: + raise ValueError('unrecognized keyword argument(s): %s' % kwds.keys()) + obj = RawArray(typecode_or_type, size_or_initializer) +- if lock is None: ++ if lock is False: ++ return obj ++ if lock in (True, None): + lock = RLock() +- assert hasattr(lock, 'acquire') ++ if not hasattr(lock, 'acquire'): ++ raise AttributeError("'%r' has no method 'acquire'" % lock) + return synchronized(obj, lock) + + def copy(obj): +Index: Lib/multiprocessing/__init__.py +=================================================================== +--- Lib/multiprocessing/__init__.py (.../tags/r261) (Revision 70449) ++++ Lib/multiprocessing/__init__.py (.../branches/release26-maint) (Revision 70449) +@@ -113,7 +113,7 @@ + num = int(os.environ['NUMBER_OF_PROCESSORS']) + except (ValueError, KeyError): + num = 0 +- elif sys.platform == 'darwin': ++ elif 'bsd' in sys.platform or sys.platform == 'darwin': + try: + num = int(os.popen('sysctl -n hw.ncpu').read()) + except ValueError: +Index: Lib/textwrap.py +=================================================================== +--- Lib/textwrap.py (.../tags/r261) (Revision 70449) ++++ Lib/textwrap.py (.../branches/release26-maint) (Revision 70449) +@@ -17,7 +17,7 @@ + #except NameError: + # (True, False) = (1, 0) + +-__all__ = ['TextWrapper', 'wrap', 'fill'] ++__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent'] + + # Hardcode the recognized whitespace characters to the US-ASCII + # whitespace characters. The main reason for doing this is that in +@@ -86,7 +86,7 @@ + # (after stripping out empty strings). + wordsep_re = re.compile( + r'(\s+|' # any whitespace +- r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words ++ r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|' # hyphenated words + r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash + + # This less funky little regex just split on recognized spaces. E.g. +@@ -124,7 +124,14 @@ + self.drop_whitespace = drop_whitespace + self.break_on_hyphens = break_on_hyphens + ++ # recompile the regexes for Unicode mode -- done in this clumsy way for ++ # backwards compatibility because it's rather common to monkey-patch ++ # the TextWrapper class' wordsep_re attribute. ++ self.wordsep_re_uni = re.compile(self.wordsep_re.pattern, re.U) ++ self.wordsep_simple_re_uni = re.compile( ++ self.wordsep_simple_re.pattern, re.U) + ++ + # -- Private methods ----------------------------------------------- + # (possibly useful for subclasses to override) + +@@ -160,10 +167,17 @@ + 'use', ' ', 'the', ' ', '-b', ' ', option!' + otherwise. + """ +- if self.break_on_hyphens is True: +- chunks = self.wordsep_re.split(text) ++ if isinstance(text, unicode): ++ if self.break_on_hyphens: ++ pat = self.wordsep_re_uni ++ else: ++ pat = self.wordsep_simple_re_uni + else: +- chunks = self.wordsep_simple_re.split(text) ++ if self.break_on_hyphens: ++ pat = self.wordsep_re ++ else: ++ pat = self.wordsep_simple_re ++ chunks = pat.split(text) + chunks = filter(None, chunks) # remove empty chunks + return chunks + +Index: Lib/distutils/msvc9compiler.py +=================================================================== +--- Lib/distutils/msvc9compiler.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/msvc9compiler.py (.../branches/release26-maint) (Revision 70449) +@@ -247,7 +247,7 @@ + result = {} + + if vcvarsall is None: +- raise IOError("Unable to find vcvarsall.bat") ++ raise DistutilsPlatformError("Unable to find vcvarsall.bat") + log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version) + popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch), + stdout=subprocess.PIPE, +@@ -255,7 +255,7 @@ + + stdout, stderr = popen.communicate() + if popen.wait() != 0: +- raise IOError(stderr.decode("mbcs")) ++ raise DistutilsPlatformError(stderr.decode("mbcs")) + + stdout = stdout.decode("mbcs") + for line in stdout.split("\n"): +Index: Lib/distutils/config.py +=================================================================== +--- Lib/distutils/config.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/config.py (.../branches/release26-maint) (Revision 70449) +@@ -10,8 +10,8 @@ + from distutils.cmd import Command + + DEFAULT_PYPIRC = """\ +-[pypirc] +-servers = ++[distutils] ++index-servers = + pypi + + [pypi] +Index: Lib/distutils/tests/test_msvc9compiler.py +=================================================================== +--- Lib/distutils/tests/test_msvc9compiler.py (.../tags/r261) (Revision 0) ++++ Lib/distutils/tests/test_msvc9compiler.py (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,37 @@ ++"""Tests for distutils.msvc9compiler.""" ++import sys ++import unittest ++ ++from distutils.errors import DistutilsPlatformError ++ ++class msvc9compilerTestCase(unittest.TestCase): ++ ++ def test_no_compiler(self): ++ # makes sure query_vcvarsall throws ++ # a DistutilsPlatformError if the compiler ++ # is not found ++ if sys.platform != 'win32': ++ # this test is only for win32 ++ return ++ from distutils.msvccompiler import get_build_version ++ if get_build_version() < 8.0: ++ # this test is only for MSVC8.0 or above ++ return ++ from distutils.msvc9compiler import query_vcvarsall ++ def _find_vcvarsall(version): ++ return None ++ ++ from distutils import msvc9compiler ++ old_find_vcvarsall = msvc9compiler.find_vcvarsall ++ msvc9compiler.find_vcvarsall = _find_vcvarsall ++ try: ++ self.assertRaises(DistutilsPlatformError, query_vcvarsall, ++ 'wont find this version') ++ finally: ++ msvc9compiler.find_vcvarsall = old_find_vcvarsall ++ ++def test_suite(): ++ return unittest.makeSuite(msvc9compilerTestCase) ++ ++if __name__ == "__main__": ++ unittest.main(defaultTest="test_suite") + +Eigenschaftsänderungen: Lib/distutils/tests/test_msvc9compiler.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native +Hinzugefügt: svn:keywords + + Id + +Index: Lib/distutils/tests/test_dist.py +=================================================================== +--- Lib/distutils/tests/test_dist.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/tests/test_dist.py (.../branches/release26-maint) (Revision 70449) +@@ -8,6 +8,7 @@ + import StringIO + import sys + import unittest ++import warnings + + from test.test_support import TESTFN + +@@ -131,6 +132,29 @@ + if os.path.exists(my_file): + os.remove(my_file) + ++ def test_empty_options(self): ++ # an empty options dictionary should not stay in the ++ # list of attributes ++ klass = distutils.dist.Distribution ++ ++ # catching warnings ++ warns = [] ++ def _warn(msg): ++ warns.append(msg) ++ ++ old_warn = warnings.warn ++ warnings.warn = _warn ++ try: ++ dist = klass(attrs={'author': 'xxx', ++ 'name': 'xxx', ++ 'version': 'xxx', ++ 'url': 'xxxx', ++ 'options': {}}) ++ finally: ++ warnings.warn = old_warn ++ ++ self.assertEquals(len(warns), 0) ++ + class MetadataTestCase(unittest.TestCase): + + def test_simple_metadata(self): +Index: Lib/distutils/tests/test_sysconfig.py +=================================================================== +--- Lib/distutils/tests/test_sysconfig.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/tests/test_sysconfig.py (.../branches/release26-maint) (Revision 70449) +@@ -17,6 +17,8 @@ + # XXX doesn't work on Linux when Python was never installed before + #self.assert_(os.path.isdir(lib_dir), lib_dir) + # test for pythonxx.lib? ++ self.assertNotEqual(sysconfig.get_python_lib(), ++ sysconfig.get_python_lib(prefix=TESTFN)) + + def test_get_python_inc(self): + # The check for srcdir is copied from Python's setup.py, +Index: Lib/distutils/tests/test_config.py +=================================================================== +--- Lib/distutils/tests/test_config.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/tests/test_config.py (.../branches/release26-maint) (Revision 70449) +@@ -5,6 +5,8 @@ + + from distutils.core import PyPIRCCommand + from distutils.core import Distribution ++from distutils.log import set_threshold ++from distutils.log import WARN + + from distutils.tests import support + +@@ -32,6 +34,17 @@ + password:secret + """ + ++WANTED = """\ ++[distutils] ++index-servers = ++ pypi ++ ++[pypi] ++username:tarek ++password:xxx ++""" ++ ++ + class PyPIRCCommandTestCase(support.TempdirManager, unittest.TestCase): + + def setUp(self): +@@ -53,6 +66,7 @@ + finalize_options = initialize_options + + self._cmd = command ++ self.old_threshold = set_threshold(WARN) + + def tearDown(self): + """Removes the patch.""" +@@ -62,6 +76,7 @@ + os.environ['HOME'] = self._old_home + if os.path.exists(self.rc): + os.remove(self.rc) ++ set_threshold(self.old_threshold) + + def test_server_registration(self): + # This test makes sure PyPIRCCommand knows how to: +@@ -98,6 +113,20 @@ + ('server', 'server-login'), ('username', 'tarek')] + self.assertEquals(config, waited) + ++ def test_server_empty_registration(self): ++ ++ cmd = self._cmd(self.dist) ++ rc = cmd._get_rc_file() ++ self.assert_(not os.path.exists(rc)) ++ ++ cmd._store_pypirc('tarek', 'xxx') ++ ++ self.assert_(os.path.exists(rc)) ++ content = open(rc).read() ++ ++ self.assertEquals(content, WANTED) ++ ++ + def test_suite(): + return unittest.makeSuite(PyPIRCCommandTestCase) + +Index: Lib/distutils/tests/test_build_scripts.py +=================================================================== +--- Lib/distutils/tests/test_build_scripts.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/tests/test_build_scripts.py (.../branches/release26-maint) (Revision 70449) +@@ -5,6 +5,7 @@ + + from distutils.command.build_scripts import build_scripts + from distutils.core import Distribution ++from distutils import sysconfig + + from distutils.tests import support + +@@ -73,7 +74,34 @@ + f.write(text) + f.close() + ++ def test_version_int(self): ++ source = self.mkdtemp() ++ target = self.mkdtemp() ++ expected = self.write_sample_scripts(source) + ++ ++ cmd = self.get_build_scripts_cmd(target, ++ [os.path.join(source, fn) ++ for fn in expected]) ++ cmd.finalize_options() ++ ++ # http://bugs.python.org/issue4524 ++ # ++ # On linux-g++-32 with command line `./configure --enable-ipv6 ++ # --with-suffix=3`, python is compiled okay but the build scripts ++ # failed when writing the name of the executable ++ old = sysconfig._config_vars.get('VERSION') ++ sysconfig._config_vars['VERSION'] = 4 ++ try: ++ cmd.run() ++ finally: ++ if old is not None: ++ sysconfig._config_vars['VERSION'] = old ++ ++ built = os.listdir(target) ++ for name in expected: ++ self.assert_(name in built) ++ + def test_suite(): + return unittest.makeSuite(BuildScriptsTestCase) + +Index: Lib/distutils/tests/test_build_ext.py +=================================================================== +--- Lib/distutils/tests/test_build_ext.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/tests/test_build_ext.py (.../branches/release26-maint) (Revision 70449) +@@ -11,6 +11,10 @@ + import unittest + from test import test_support + ++# http://bugs.python.org/issue4373 ++# Don't load the xx module more than once. ++ALREADY_TESTED = False ++ + class BuildExtTestCase(unittest.TestCase): + def setUp(self): + # Create a simple test environment +@@ -23,6 +27,7 @@ + shutil.copy(xx_c, self.tmp_dir) + + def test_build_ext(self): ++ global ALREADY_TESTED + xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') + xx_ext = Extension('xx', [xx_c]) + dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) +@@ -45,6 +50,11 @@ + finally: + sys.stdout = old_stdout + ++ if ALREADY_TESTED: ++ return ++ else: ++ ALREADY_TESTED = True ++ + import xx + + for attr in ('error', 'foo', 'new', 'roj'): +@@ -65,6 +75,27 @@ + # XXX on Windows the test leaves a directory with xx module in TEMP + shutil.rmtree(self.tmp_dir, os.name == 'nt' or sys.platform == 'cygwin') + ++ def test_solaris_enable_shared(self): ++ dist = Distribution({'name': 'xx'}) ++ cmd = build_ext(dist) ++ old = sys.platform ++ ++ sys.platform = 'sunos' # fooling finalize_options ++ from distutils.sysconfig import _config_vars ++ old_var = _config_vars.get('Py_ENABLE_SHARED') ++ _config_vars['Py_ENABLE_SHARED'] = 1 ++ try: ++ cmd.ensure_finalized() ++ finally: ++ sys.platform = old ++ if old_var is None: ++ del _config_vars['Py_ENABLE_SHARED'] ++ else: ++ _config_vars['Py_ENABLE_SHARED'] = old_var ++ ++ # make sur we get some lobrary dirs under solaris ++ self.assert_(len(cmd.library_dirs) > 0) ++ + def test_suite(): + if not sysconfig.python_build: + if test_support.verbose: +Index: Lib/distutils/tests/test_register.py +=================================================================== +--- Lib/distutils/tests/test_register.py (.../tags/r261) (Revision 0) ++++ Lib/distutils/tests/test_register.py (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,109 @@ ++"""Tests for distutils.command.register.""" ++import sys ++import os ++import unittest ++ ++from distutils.command.register import register ++from distutils.core import Distribution ++ ++from distutils.tests import support ++from distutils.tests.test_config import PYPIRC, PyPIRCCommandTestCase ++ ++class RawInputs(object): ++ """Fakes user inputs.""" ++ def __init__(self, *answers): ++ self.answers = answers ++ self.index = 0 ++ ++ def __call__(self, prompt=''): ++ try: ++ return self.answers[self.index] ++ finally: ++ self.index += 1 ++ ++WANTED_PYPIRC = """\ ++[distutils] ++index-servers = ++ pypi ++ ++[pypi] ++username:tarek ++password:xxx ++""" ++ ++class registerTestCase(PyPIRCCommandTestCase): ++ ++ def test_create_pypirc(self): ++ # this test makes sure a .pypirc file ++ # is created when requested. ++ ++ # let's create a fake distribution ++ # and a register instance ++ dist = Distribution() ++ dist.metadata.url = 'xxx' ++ dist.metadata.author = 'xxx' ++ dist.metadata.author_email = 'xxx' ++ dist.metadata.name = 'xxx' ++ dist.metadata.version = 'xxx' ++ cmd = register(dist) ++ ++ # we shouldn't have a .pypirc file yet ++ self.assert_(not os.path.exists(self.rc)) ++ ++ # patching raw_input and getpass.getpass ++ # so register gets happy ++ # ++ # Here's what we are faking : ++ # use your existing login (choice 1.) ++ # Username : 'tarek' ++ # Password : 'xxx' ++ # Save your login (y/N)? : 'y' ++ inputs = RawInputs('1', 'tarek', 'y') ++ from distutils.command import register as register_module ++ register_module.raw_input = inputs.__call__ ++ def _getpass(prompt): ++ return 'xxx' ++ register_module.getpass.getpass = _getpass ++ class FakeServer(object): ++ def __init__(self): ++ self.calls = [] ++ ++ def __call__(self, *args): ++ # we want to compare them, so let's store ++ # something comparable ++ els = args[0].items() ++ els.sort() ++ self.calls.append(tuple(els)) ++ return 200, 'OK' ++ ++ cmd.post_to_server = pypi_server = FakeServer() ++ ++ # let's run the command ++ cmd.run() ++ ++ # we should have a brand new .pypirc file ++ self.assert_(os.path.exists(self.rc)) ++ ++ # with the content similar to WANTED_PYPIRC ++ content = open(self.rc).read() ++ self.assertEquals(content, WANTED_PYPIRC) ++ ++ # now let's make sure the .pypirc file generated ++ # really works : we shouldn't be asked anything ++ # if we run the command again ++ def _no_way(prompt=''): ++ raise AssertionError(prompt) ++ register_module.raw_input = _no_way ++ ++ cmd.run() ++ ++ # let's see what the server received : we should ++ # have 2 similar requests ++ self.assert_(len(pypi_server.calls), 2) ++ self.assert_(pypi_server.calls[0], pypi_server.calls[1]) ++ ++def test_suite(): ++ return unittest.makeSuite(registerTestCase) ++ ++if __name__ == "__main__": ++ unittest.main(defaultTest="test_suite") + +Eigenschaftsänderungen: Lib/distutils/tests/test_register.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native +Hinzugefügt: svn:keywords + + Id + +Index: Lib/distutils/tests/test_sdist.py +=================================================================== +--- Lib/distutils/tests/test_sdist.py (.../tags/r261) (Revision 0) ++++ Lib/distutils/tests/test_sdist.py (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,162 @@ ++"""Tests for distutils.command.sdist.""" ++import os ++import unittest ++import shutil ++import zipfile ++from os.path import join ++import sys ++ ++from distutils.command.sdist import sdist ++from distutils.core import Distribution ++from distutils.tests.test_config import PyPIRCCommandTestCase ++from distutils.errors import DistutilsExecError ++from distutils.spawn import find_executable ++ ++CURDIR = os.path.dirname(__file__) ++TEMP_PKG = join(CURDIR, 'temppkg') ++ ++SETUP_PY = """ ++from distutils.core import setup ++import somecode ++ ++setup(name='fake') ++""" ++ ++MANIFEST_IN = """ ++recursive-include somecode * ++""" ++ ++class sdistTestCase(PyPIRCCommandTestCase): ++ ++ def setUp(self): ++ PyPIRCCommandTestCase.setUp(self) ++ self.old_path = os.getcwd() ++ ++ def tearDown(self): ++ os.chdir(self.old_path) ++ if os.path.exists(TEMP_PKG): ++ shutil.rmtree(TEMP_PKG) ++ PyPIRCCommandTestCase.tearDown(self) ++ ++ def _init_tmp_pkg(self): ++ if os.path.exists(TEMP_PKG): ++ shutil.rmtree(TEMP_PKG) ++ os.mkdir(TEMP_PKG) ++ os.mkdir(join(TEMP_PKG, 'somecode')) ++ os.mkdir(join(TEMP_PKG, 'dist')) ++ # creating a MANIFEST, a package, and a README ++ self._write(join(TEMP_PKG, 'MANIFEST.in'), MANIFEST_IN) ++ self._write(join(TEMP_PKG, 'README'), 'xxx') ++ self._write(join(TEMP_PKG, 'somecode', '__init__.py'), '#') ++ self._write(join(TEMP_PKG, 'setup.py'), SETUP_PY) ++ os.chdir(TEMP_PKG) ++ ++ def _write(self, path, content): ++ f = open(path, 'w') ++ try: ++ f.write(content) ++ finally: ++ f.close() ++ ++ def test_prune_file_list(self): ++ # this test creates a package with some vcs dirs in it ++ # and launch sdist to make sure they get pruned ++ # on all systems ++ self._init_tmp_pkg() ++ ++ # creating VCS directories with some files in them ++ os.mkdir(join(TEMP_PKG, 'somecode', '.svn')) ++ self._write(join(TEMP_PKG, 'somecode', '.svn', 'ok.py'), 'xxx') ++ ++ os.mkdir(join(TEMP_PKG, 'somecode', '.hg')) ++ self._write(join(TEMP_PKG, 'somecode', '.hg', ++ 'ok'), 'xxx') ++ ++ os.mkdir(join(TEMP_PKG, 'somecode', '.git')) ++ self._write(join(TEMP_PKG, 'somecode', '.git', ++ 'ok'), 'xxx') ++ ++ # now building a sdist ++ dist = Distribution() ++ dist.script_name = 'setup.py' ++ dist.metadata.name = 'fake' ++ dist.metadata.version = '1.0' ++ dist.metadata.url = 'http://xxx' ++ dist.metadata.author = dist.metadata.author_email = 'xxx' ++ dist.packages = ['somecode'] ++ dist.include_package_data = True ++ cmd = sdist(dist) ++ cmd.manifest = 'MANIFEST' ++ cmd.template = 'MANIFEST.in' ++ cmd.dist_dir = 'dist' ++ ++ # zip is available universally ++ # (tar might not be installed under win32) ++ cmd.formats = ['zip'] ++ cmd.run() ++ ++ # now let's check what we have ++ dist_folder = join(TEMP_PKG, 'dist') ++ files = os.listdir(dist_folder) ++ self.assertEquals(files, ['fake-1.0.zip']) ++ ++ zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) ++ try: ++ content = zip_file.namelist() ++ finally: ++ zip_file.close() ++ ++ # making sure everything has been pruned correctly ++ self.assertEquals(len(content), 4) ++ ++ def test_make_distribution(self): ++ ++ # check if tar and gzip are installed ++ if (find_executable('tar') is None or ++ find_executable('gzip') is None): ++ return ++ ++ self._init_tmp_pkg() ++ ++ # now building a sdist ++ dist = Distribution() ++ dist.script_name = 'setup.py' ++ dist.metadata.name = 'fake' ++ dist.metadata.version = '1.0' ++ dist.metadata.url = 'http://xxx' ++ dist.metadata.author = dist.metadata.author_email = 'xxx' ++ dist.packages = ['somecode'] ++ dist.include_package_data = True ++ cmd = sdist(dist) ++ cmd.manifest = 'MANIFEST' ++ cmd.template = 'MANIFEST.in' ++ cmd.dist_dir = 'dist' ++ ++ # creating a gztar then a tar ++ cmd.formats = ['gztar', 'tar'] ++ cmd.run() ++ ++ # making sure we have two files ++ dist_folder = join(TEMP_PKG, 'dist') ++ result = os.listdir(dist_folder) ++ result.sort() ++ self.assertEquals(result, ++ ['fake-1.0.tar', 'fake-1.0.tar.gz'] ) ++ ++ os.remove(join(dist_folder, 'fake-1.0.tar')) ++ os.remove(join(dist_folder, 'fake-1.0.tar.gz')) ++ ++ # now trying a tar then a gztar ++ cmd.formats = ['tar', 'gztar'] ++ cmd.run() ++ ++ result = os.listdir(dist_folder) ++ result.sort() ++ self.assertEquals(result, ++ ['fake-1.0.tar', 'fake-1.0.tar.gz']) ++ ++def test_suite(): ++ return unittest.makeSuite(sdistTestCase) ++ ++if __name__ == "__main__": ++ unittest.main(defaultTest="test_suite") + +Eigenschaftsänderungen: Lib/distutils/tests/test_sdist.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native +Hinzugefügt: svn:keywords + + Id + +Index: Lib/distutils/util.py +=================================================================== +--- Lib/distutils/util.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/util.py (.../branches/release26-maint) (Revision 70449) +@@ -100,7 +100,11 @@ + if not macver: + macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET') + +- if not macver: ++ if 1: ++ # Always calculate the release of the running machine, ++ # needed to determine if we can build fat binaries or not. ++ ++ macrelease = macver + # Get the system version. Reading this plist is a documented + # way to get the system version (see the documentation for + # the Gestalt Manager) +@@ -116,16 +120,18 @@ + r'(.*?)', f.read()) + f.close() + if m is not None: +- macver = '.'.join(m.group(1).split('.')[:2]) ++ macrelease = '.'.join(m.group(1).split('.')[:2]) + # else: fall back to the default behaviour + ++ if not macver: ++ macver = macrelease ++ + if macver: + from distutils.sysconfig import get_config_vars + release = macver + osname = "macosx" + +- +- if (release + '.') >= '10.4.' and \ ++ if (macrelease + '.') >= '10.4.' and \ + '-arch' in get_config_vars().get('CFLAGS', '').strip(): + # The universal build will build fat binaries, but not on + # systems before 10.4 +@@ -134,9 +140,13 @@ + # 'universal' instead of 'fat'. + + machine = 'fat' ++ cflags = get_config_vars().get('CFLAGS') + +- if '-arch x86_64' in get_config_vars().get('CFLAGS'): +- machine = 'universal' ++ if '-arch x86_64' in cflags: ++ if '-arch i386' in cflags: ++ machine = 'universal' ++ else: ++ machine = 'fat64' + + elif machine in ('PowerPC', 'Power_Macintosh'): + # Pick a sane name for the PPC architecture. +Index: Lib/distutils/ccompiler.py +=================================================================== +--- Lib/distutils/ccompiler.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/ccompiler.py (.../branches/release26-maint) (Revision 70449) +@@ -1041,7 +1041,7 @@ + return move_file (src, dst, dry_run=self.dry_run) + + def mkpath (self, name, mode=0777): +- mkpath (name, mode, self.dry_run) ++ mkpath (name, mode, dry_run=self.dry_run) + + + # class CCompiler +Index: Lib/distutils/command/wininst-9.0.exe +=================================================================== +Kann nicht anzeigen: Dateityp ist als binär angegeben. +svn:mime-type = application/octet-stream +Index: Lib/distutils/command/wininst-9.0-amd64.exe +=================================================================== +Kann nicht anzeigen: Dateityp ist als binär angegeben. +svn:mime-type = application/octet-stream +Index: Lib/distutils/command/build_scripts.py +=================================================================== +--- Lib/distutils/command/build_scripts.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/command/build_scripts.py (.../branches/release26-maint) (Revision 70449) +@@ -104,8 +104,8 @@ + outf.write("#!%s%s\n" % + (os.path.join( + sysconfig.get_config_var("BINDIR"), +- "python" + sysconfig.get_config_var("VERSION") +- + sysconfig.get_config_var("EXE")), ++ "python%s%s" % (sysconfig.get_config_var("VERSION"), ++ sysconfig.get_config_var("EXE"))), + post_interp)) + outf.writelines(f.readlines()) + outf.close() +Index: Lib/distutils/command/build_ext.py +=================================================================== +--- Lib/distutils/command/build_ext.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/command/build_ext.py (.../branches/release26-maint) (Revision 70449) +@@ -233,10 +233,12 @@ + # building python standard extensions + self.library_dirs.append('.') + +- # for extensions under Linux with a shared Python library, ++ # for extensions under Linux or Solaris with a shared Python library, + # Python's library directory must be appended to library_dirs +- if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \ +- and sysconfig.get_config_var('Py_ENABLE_SHARED'): ++ sysconfig.get_config_var('Py_ENABLE_SHARED') ++ if ((sys.platform.startswith('linux') or sys.platform.startswith('gnu') ++ or sys.platform.startswith('sunos')) ++ and sysconfig.get_config_var('Py_ENABLE_SHARED')): + if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")): + # building third party extensions + self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) +Index: Lib/distutils/command/register.py +=================================================================== +--- Lib/distutils/command/register.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/command/register.py (.../branches/release26-maint) (Revision 70449) +@@ -141,12 +141,14 @@ + # get the user's login info + choices = '1 2 3 4'.split() + while choice not in choices: +- print '''We need to know who you are, so please choose either: ++ self.announce('''\ ++We need to know who you are, so please choose either: + 1. use your existing login, + 2. register as a new user, + 3. have the server generate a new password for you (and email it to you), or + 4. quit +-Your selection [default 1]: ''', ++Your selection [default 1]: ''', log.INFO) ++ + choice = raw_input() + if not choice: + choice = '1' +@@ -167,12 +169,16 @@ + # send the info to the server and report the result + code, result = self.post_to_server(self.build_post_data('submit'), + auth) +- print 'Server response (%s): %s' % (code, result) ++ self.announce('Server response (%s): %s' % (code, result), ++ log.INFO) + + # possibly save the login + if not self.has_config and code == 200: +- print 'I can store your PyPI login so future submissions will be faster.' +- print '(the login will be stored in %s)' % self._get_rc_file() ++ self.announce(('I can store your PyPI login so future ' ++ 'submissions will be faster.'), log.INFO) ++ self.announce('(the login will be stored in %s)' % \ ++ self._get_rc_file(), log.INFO) ++ + choice = 'X' + while choice.lower() not in 'yn': + choice = raw_input('Save your login (y/N)?') +Index: Lib/distutils/command/sdist.py +=================================================================== +--- Lib/distutils/command/sdist.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/command/sdist.py (.../branches/release26-maint) (Revision 70449) +@@ -7,6 +7,7 @@ + __revision__ = "$Id$" + + import os, string ++import sys + from types import * + from glob import glob + from distutils.core import Command +@@ -354,9 +355,19 @@ + + self.filelist.exclude_pattern(None, prefix=build.build_base) + self.filelist.exclude_pattern(None, prefix=base_dir) +- self.filelist.exclude_pattern(r'(^|/)(RCS|CVS|\.svn|\.hg|\.git|\.bzr|_darcs)/.*', is_regex=1) + ++ # pruning out vcs directories ++ # both separators are used under win32 ++ if sys.platform == 'win32': ++ seps = r'/|\\' ++ else: ++ seps = '/' + ++ vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', ++ '_darcs'] ++ vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps) ++ self.filelist.exclude_pattern(vcs_ptrn, is_regex=1) ++ + def write_manifest (self): + """Write the file list in 'self.filelist' (presumably as filled in + by 'add_defaults()' and 'read_template()') to the manifest file +@@ -447,6 +458,10 @@ + + self.make_release_tree(base_dir, self.filelist.files) + archive_files = [] # remember names of files we create ++ # tar archive must be created last to avoid overwrite and remove ++ if 'tar' in self.formats: ++ self.formats.append(self.formats.pop(self.formats.index('tar'))) ++ + for fmt in self.formats: + file = self.make_archive(base_name, fmt, base_dir=base_dir) + archive_files.append(file) +Index: Lib/distutils/dist.py +=================================================================== +--- Lib/distutils/dist.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/dist.py (.../branches/release26-maint) (Revision 70449) +@@ -235,7 +235,7 @@ + # command options will override any supplied redundantly + # through the general options dictionary. + options = attrs.get('options') +- if options: ++ if options is not None: + del attrs['options'] + for (command, cmd_options) in options.items(): + opt_dict = self.get_option_dict(command) +Index: Lib/distutils/sysconfig.py +=================================================================== +--- Lib/distutils/sysconfig.py (.../tags/r261) (Revision 70449) ++++ Lib/distutils/sysconfig.py (.../branches/release26-maint) (Revision 70449) +@@ -129,7 +129,7 @@ + if get_python_version() < "2.2": + return prefix + else: +- return os.path.join(PREFIX, "Lib", "site-packages") ++ return os.path.join(prefix, "Lib", "site-packages") + + elif os.name == "mac": + if plat_specific: +@@ -145,9 +145,9 @@ + + elif os.name == "os2": + if standard_lib: +- return os.path.join(PREFIX, "Lib") ++ return os.path.join(prefix, "Lib") + else: +- return os.path.join(PREFIX, "Lib", "site-packages") ++ return os.path.join(prefix, "Lib", "site-packages") + + else: + raise DistutilsPlatformError( +Index: Lib/re.py +=================================================================== +--- Lib/re.py (.../tags/r261) (Revision 70449) ++++ Lib/re.py (.../branches/release26-maint) (Revision 70449) +@@ -145,7 +145,8 @@ + """Return the string obtained by replacing the leftmost + non-overlapping occurrences of the pattern in string by the + replacement repl. repl can be either a string or a callable; +- if a callable, it's passed the match object and must return ++ if a string, backslash escapes in it are processed. If it is ++ a callable, it's passed the match object and must return + a replacement string to be used.""" + return _compile(pattern, 0).sub(repl, string, count) + +@@ -155,7 +156,8 @@ + non-overlapping occurrences of the pattern in the source + string by the replacement repl. number is the number of + substitutions that were made. repl can be either a string or a +- callable; if a callable, it's passed the match object and must ++ callable; if a string, backslash escapes in it are processed. ++ If it is a callable, it's passed the match object and must + return a replacement string to be used.""" + return _compile(pattern, 0).subn(repl, string, count) + +Index: Lib/random.py +=================================================================== +--- Lib/random.py (.../tags/r261) (Revision 70449) ++++ Lib/random.py (.../branches/release26-maint) (Revision 70449) +@@ -413,9 +413,11 @@ + def expovariate(self, lambd): + """Exponential distribution. + +- lambd is 1.0 divided by the desired mean. (The parameter would be +- called "lambda", but that is a reserved word in Python.) Returned +- values range from 0 to positive infinity. ++ lambd is 1.0 divided by the desired mean. It should be ++ nonzero. (The parameter would be called "lambda", but that is ++ a reserved word in Python.) Returned values range from 0 to ++ positive infinity if lambd is positive, and from negative ++ infinity to 0 if lambd is negative. + + """ + # lambd: rate lambd = 1/mean +Index: Lib/compiler/symbols.py +=================================================================== +--- Lib/compiler/symbols.py (.../tags/r261) (Revision 70449) ++++ Lib/compiler/symbols.py (.../branches/release26-maint) (Revision 70449) +@@ -49,9 +49,9 @@ + + def add_global(self, name): + name = self.mangle(name) +- if self.uses.has_key(name) or self.defs.has_key(name): ++ if name in self.uses or name in self.defs: + pass # XXX warn about global following def/use +- if self.params.has_key(name): ++ if name in self.params: + raise SyntaxError, "%s in %s is global and parameter" % \ + (name, self.name) + self.globals[name] = 1 +@@ -88,14 +88,13 @@ + + The scope of a name could be LOCAL, GLOBAL, FREE, or CELL. + """ +- if self.globals.has_key(name): ++ if name in self.globals: + return SC_GLOBAL +- if self.cells.has_key(name): ++ if name in self.cells: + return SC_CELL +- if self.defs.has_key(name): ++ if name in self.defs: + return SC_LOCAL +- if self.nested and (self.frees.has_key(name) or +- self.uses.has_key(name)): ++ if self.nested and (name in self.frees or name in self.uses): + return SC_FREE + if self.nested: + return SC_UNKNOWN +@@ -108,8 +107,7 @@ + free = {} + free.update(self.frees) + for name in self.uses.keys(): +- if not (self.defs.has_key(name) or +- self.globals.has_key(name)): ++ if name not in self.defs and name not in self.globals: + free[name] = 1 + return free.keys() + +@@ -134,7 +132,7 @@ + free. + """ + self.globals[name] = 1 +- if self.frees.has_key(name): ++ if name in self.frees: + del self.frees[name] + for child in self.children: + if child.check_name(name) == SC_FREE: +Index: Lib/compiler/misc.py +=================================================================== +--- Lib/compiler/misc.py (.../tags/r261) (Revision 70449) ++++ Lib/compiler/misc.py (.../branches/release26-maint) (Revision 70449) +@@ -14,13 +14,13 @@ + def __len__(self): + return len(self.elts) + def __contains__(self, elt): +- return self.elts.has_key(elt) ++ return elt in self.elts + def add(self, elt): + self.elts[elt] = elt + def elements(self): + return self.elts.keys() + def has_elt(self, elt): +- return self.elts.has_key(elt) ++ return elt in self.elts + def remove(self, elt): + del self.elts[elt] + def copy(self): +Index: Lib/compiler/visitor.py +=================================================================== +--- Lib/compiler/visitor.py (.../tags/r261) (Revision 70449) ++++ Lib/compiler/visitor.py (.../branches/release26-maint) (Revision 70449) +@@ -84,7 +84,7 @@ + meth(node, *args) + elif self.VERBOSE > 0: + klass = node.__class__ +- if not self.examples.has_key(klass): ++ if klass not in self.examples: + self.examples[klass] = klass + print + print self.visitor +Index: Lib/compiler/pyassem.py +=================================================================== +--- Lib/compiler/pyassem.py (.../tags/r261) (Revision 70449) ++++ Lib/compiler/pyassem.py (.../branches/release26-maint) (Revision 70449) +@@ -210,7 +210,7 @@ + order = [] + seen[b] = b + for c in b.get_children(): +- if seen.has_key(c): ++ if c in seen: + continue + order = order + dfs_postorder(c, seen) + order.append(b) +@@ -406,7 +406,7 @@ + seen = {} + + def max_depth(b, d): +- if seen.has_key(b): ++ if b in seen: + return d + seen[b] = 1 + d = d + depth[b] +@@ -482,7 +482,7 @@ + for name in self.cellvars: + cells[name] = 1 + self.cellvars = [name for name in self.varnames +- if cells.has_key(name)] ++ if name in cells] + for name in self.cellvars: + del cells[name] + self.cellvars = self.cellvars + cells.keys() +Index: Lib/compiler/transformer.py +=================================================================== +--- Lib/compiler/transformer.py (.../tags/r261) (Revision 70449) ++++ Lib/compiler/transformer.py (.../branches/release26-maint) (Revision 70449) +@@ -81,7 +81,7 @@ + + def Node(*args): + kind = args[0] +- if nodes.has_key(kind): ++ if kind in nodes: + try: + return nodes[kind](*args[1:]) + except TypeError: +@@ -120,7 +120,7 @@ + def transform(self, tree): + """Transform an AST into a modified parse tree.""" + if not (isinstance(tree, tuple) or isinstance(tree, list)): +- tree = parser.ast2tuple(tree, line_info=1) ++ tree = parser.st2tuple(tree, line_info=1) + return self.compile_node(tree) + + def parsesuite(self, text): +Index: Lib/pickletools.py +=================================================================== +--- Lib/pickletools.py (.../tags/r261) (Revision 70449) ++++ Lib/pickletools.py (.../branches/release26-maint) (Revision 70449) +@@ -2083,11 +2083,11 @@ + + Exercise the INST/OBJ/BUILD family. + +->>> import random +->>> dis(pickle.dumps(random.random, 0)) +- 0: c GLOBAL 'random random' +- 15: p PUT 0 +- 18: . STOP ++>>> import pickletools ++>>> dis(pickle.dumps(pickletools.dis, 0)) ++ 0: c GLOBAL 'pickletools dis' ++ 17: p PUT 0 ++ 20: . STOP + highest protocol among opcodes = 0 + + >>> from pickletools import _Example +Index: Lib/decimal.py +=================================================================== +--- Lib/decimal.py (.../tags/r261) (Revision 70449) ++++ Lib/decimal.py (.../branches/release26-maint) (Revision 70449) +@@ -135,6 +135,7 @@ + ] + + import copy as _copy ++import numbers as _numbers + + try: + from collections import namedtuple as _namedtuple +@@ -216,7 +217,7 @@ + if args: + ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True) + return ans._fix_nan(context) +- return NaN ++ return _NaN + + class ConversionSyntax(InvalidOperation): + """Trying to convert badly formed string. +@@ -226,7 +227,7 @@ + syntax. The result is [0,qNaN]. + """ + def handle(self, context, *args): +- return NaN ++ return _NaN + + class DivisionByZero(DecimalException, ZeroDivisionError): + """Division by 0. +@@ -242,7 +243,7 @@ + """ + + def handle(self, context, sign, *args): +- return Infsign[sign] ++ return _SignedInfinity[sign] + + class DivisionImpossible(InvalidOperation): + """Cannot perform the division adequately. +@@ -253,7 +254,7 @@ + """ + + def handle(self, context, *args): +- return NaN ++ return _NaN + + class DivisionUndefined(InvalidOperation, ZeroDivisionError): + """Undefined result of division. +@@ -264,7 +265,7 @@ + """ + + def handle(self, context, *args): +- return NaN ++ return _NaN + + class Inexact(DecimalException): + """Had to round, losing information. +@@ -290,7 +291,7 @@ + """ + + def handle(self, context, *args): +- return NaN ++ return _NaN + + class Rounded(DecimalException): + """Number got rounded (not necessarily changed during rounding). +@@ -340,15 +341,15 @@ + def handle(self, context, sign, *args): + if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, + ROUND_HALF_DOWN, ROUND_UP): +- return Infsign[sign] ++ return _SignedInfinity[sign] + if sign == 0: + if context.rounding == ROUND_CEILING: +- return Infsign[sign] ++ return _SignedInfinity[sign] + return _dec_from_triple(sign, '9'*context.prec, + context.Emax-context.prec+1) + if sign == 1: + if context.rounding == ROUND_FLOOR: +- return Infsign[sign] ++ return _SignedInfinity[sign] + return _dec_from_triple(sign, '9'*context.prec, + context.Emax-context.prec+1) + +@@ -760,9 +761,16 @@ + if self > other. This routine is for internal use only.""" + + if self._is_special or other._is_special: +- return cmp(self._isinfinity(), other._isinfinity()) ++ self_inf = self._isinfinity() ++ other_inf = other._isinfinity() ++ if self_inf == other_inf: ++ return 0 ++ elif self_inf < other_inf: ++ return -1 ++ else: ++ return 1 + +- # check for zeros; note that cmp(0, -0) should return 0 ++ # check for zeros; Decimal('0') == Decimal('-0') + if not self: + if not other: + return 0 +@@ -782,7 +790,12 @@ + if self_adjusted == other_adjusted: + self_padded = self._int + '0'*(self._exp - other._exp) + other_padded = other._int + '0'*(other._exp - self._exp) +- return cmp(self_padded, other_padded) * (-1)**self._sign ++ if self_padded == other_padded: ++ return 0 ++ elif self_padded < other_padded: ++ return -(-1)**self._sign ++ else: ++ return (-1)**self._sign + elif self_adjusted > other_adjusted: + return (-1)**self._sign + else: # self_adjusted < other_adjusted +@@ -1171,12 +1184,12 @@ + if self._isinfinity(): + if not other: + return context._raise_error(InvalidOperation, '(+-)INF * 0') +- return Infsign[resultsign] ++ return _SignedInfinity[resultsign] + + if other._isinfinity(): + if not self: + return context._raise_error(InvalidOperation, '0 * (+-)INF') +- return Infsign[resultsign] ++ return _SignedInfinity[resultsign] + + resultexp = self._exp + other._exp + +@@ -1226,7 +1239,7 @@ + return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') + + if self._isinfinity(): +- return Infsign[sign] ++ return _SignedInfinity[sign] + + if other._isinfinity(): + context._raise_error(Clamped, 'Division by infinity') +@@ -1329,7 +1342,7 @@ + ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') + return ans, ans + else: +- return (Infsign[sign], ++ return (_SignedInfinity[sign], + context._raise_error(InvalidOperation, 'INF % x')) + + if not other: +@@ -1477,7 +1490,7 @@ + if other._isinfinity(): + return context._raise_error(InvalidOperation, 'INF // INF') + else: +- return Infsign[self._sign ^ other._sign] ++ return _SignedInfinity[self._sign ^ other._sign] + + if not other: + if self: +@@ -1515,13 +1528,13 @@ + + __trunc__ = __int__ + +- @property + def real(self): + return self ++ real = property(real) + +- @property + def imag(self): + return Decimal(0) ++ imag = property(imag) + + def conjugate(self): + return self +@@ -1732,12 +1745,12 @@ + if not other: + return context._raise_error(InvalidOperation, + 'INF * 0 in fma') +- product = Infsign[self._sign ^ other._sign] ++ product = _SignedInfinity[self._sign ^ other._sign] + elif other._exp == 'F': + if not self: + return context._raise_error(InvalidOperation, + '0 * INF in fma') +- product = Infsign[self._sign ^ other._sign] ++ product = _SignedInfinity[self._sign ^ other._sign] + else: + product = _dec_from_triple(self._sign ^ other._sign, + str(int(self._int) * int(other._int)), +@@ -2087,7 +2100,7 @@ + if not self: + return context._raise_error(InvalidOperation, '0 ** 0') + else: +- return Dec_p1 ++ return _One + + # result has sign 1 iff self._sign is 1 and other is an odd integer + result_sign = 0 +@@ -2109,19 +2122,19 @@ + if other._sign == 0: + return _dec_from_triple(result_sign, '0', 0) + else: +- return Infsign[result_sign] ++ return _SignedInfinity[result_sign] + + # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 + if self._isinfinity(): + if other._sign == 0: +- return Infsign[result_sign] ++ return _SignedInfinity[result_sign] + else: + return _dec_from_triple(result_sign, '0', 0) + + # 1**other = 1, but the choice of exponent and the flags + # depend on the exponent of self, and on whether other is a + # positive integer, a negative integer, or neither +- if self == Dec_p1: ++ if self == _One: + if other._isinteger(): + # exp = max(self._exp*max(int(other), 0), + # 1-context.prec) but evaluating int(other) directly +@@ -2154,7 +2167,7 @@ + if (other._sign == 0) == (self_adj < 0): + return _dec_from_triple(result_sign, '0', 0) + else: +- return Infsign[result_sign] ++ return _SignedInfinity[result_sign] + + # from here on, the result always goes through the call + # to _fix at the end of this function. +@@ -2563,10 +2576,10 @@ + sn = self._isnan() + on = other._isnan() + if sn or on: +- if on == 1 and sn != 2: +- return self._fix_nan(context) +- if sn == 1 and on != 2: +- return other._fix_nan(context) ++ if on == 1 and sn == 0: ++ return self._fix(context) ++ if sn == 1 and on == 0: ++ return other._fix(context) + return self._check_nans(other, context) + + c = self._cmp(other) +@@ -2605,10 +2618,10 @@ + sn = self._isnan() + on = other._isnan() + if sn or on: +- if on == 1 and sn != 2: +- return self._fix_nan(context) +- if sn == 1 and on != 2: +- return other._fix_nan(context) ++ if on == 1 and sn == 0: ++ return self._fix(context) ++ if sn == 1 and on == 0: ++ return other._fix(context) + return self._check_nans(other, context) + + c = self._cmp(other) +@@ -2674,9 +2687,9 @@ + """ + # if one is negative and the other is positive, it's easy + if self._sign and not other._sign: +- return Dec_n1 ++ return _NegativeOne + if not self._sign and other._sign: +- return Dec_p1 ++ return _One + sign = self._sign + + # let's handle both NaN types +@@ -2686,51 +2699,51 @@ + if self_nan == other_nan: + if self._int < other._int: + if sign: +- return Dec_p1 ++ return _One + else: +- return Dec_n1 ++ return _NegativeOne + if self._int > other._int: + if sign: +- return Dec_n1 ++ return _NegativeOne + else: +- return Dec_p1 +- return Dec_0 ++ return _One ++ return _Zero + + if sign: + if self_nan == 1: +- return Dec_n1 ++ return _NegativeOne + if other_nan == 1: +- return Dec_p1 ++ return _One + if self_nan == 2: +- return Dec_n1 ++ return _NegativeOne + if other_nan == 2: +- return Dec_p1 ++ return _One + else: + if self_nan == 1: +- return Dec_p1 ++ return _One + if other_nan == 1: +- return Dec_n1 ++ return _NegativeOne + if self_nan == 2: +- return Dec_p1 ++ return _One + if other_nan == 2: +- return Dec_n1 ++ return _NegativeOne + + if self < other: +- return Dec_n1 ++ return _NegativeOne + if self > other: +- return Dec_p1 ++ return _One + + if self._exp < other._exp: + if sign: +- return Dec_p1 ++ return _One + else: +- return Dec_n1 ++ return _NegativeOne + if self._exp > other._exp: + if sign: +- return Dec_n1 ++ return _NegativeOne + else: +- return Dec_p1 +- return Dec_0 ++ return _One ++ return _Zero + + + def compare_total_mag(self, other): +@@ -2771,11 +2784,11 @@ + + # exp(-Infinity) = 0 + if self._isinfinity() == -1: +- return Dec_0 ++ return _Zero + + # exp(0) = 1 + if not self: +- return Dec_p1 ++ return _One + + # exp(Infinity) = Infinity + if self._isinfinity() == 1: +@@ -2927,15 +2940,15 @@ + + # ln(0.0) == -Infinity + if not self: +- return negInf ++ return _NegativeInfinity + + # ln(Infinity) = Infinity + if self._isinfinity() == 1: +- return Inf ++ return _Infinity + + # ln(1.0) == 0.0 +- if self == Dec_p1: +- return Dec_0 ++ if self == _One: ++ return _Zero + + # ln(negative) raises InvalidOperation + if self._sign == 1: +@@ -3007,11 +3020,11 @@ + + # log10(0.0) == -Infinity + if not self: +- return negInf ++ return _NegativeInfinity + + # log10(Infinity) = Infinity + if self._isinfinity() == 1: +- return Inf ++ return _Infinity + + # log10(negative or -Infinity) raises InvalidOperation + if self._sign == 1: +@@ -3063,7 +3076,7 @@ + + # logb(+/-Inf) = +Inf + if self._isinfinity(): +- return Inf ++ return _Infinity + + # logb(0) = -Inf, DivisionByZero + if not self: +@@ -3133,7 +3146,7 @@ + (opa, opb) = self._fill_logical(context, self._int, other._int) + + # make the operation, and clean starting zeroes +- result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb)) ++ result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)]) + return _dec_from_triple(0, result.lstrip('0') or '0', 0) + + def logical_xor(self, other, context=None): +@@ -3147,7 +3160,7 @@ + (opa, opb) = self._fill_logical(context, self._int, other._int) + + # make the operation, and clean starting zeroes +- result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb)) ++ result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)]) + return _dec_from_triple(0, result.lstrip('0') or '0', 0) + + def max_mag(self, other, context=None): +@@ -3163,10 +3176,10 @@ + sn = self._isnan() + on = other._isnan() + if sn or on: +- if on == 1 and sn != 2: +- return self._fix_nan(context) +- if sn == 1 and on != 2: +- return other._fix_nan(context) ++ if on == 1 and sn == 0: ++ return self._fix(context) ++ if sn == 1 and on == 0: ++ return other._fix(context) + return self._check_nans(other, context) + + c = self.copy_abs()._cmp(other.copy_abs()) +@@ -3193,10 +3206,10 @@ + sn = self._isnan() + on = other._isnan() + if sn or on: +- if on == 1 and sn != 2: +- return self._fix_nan(context) +- if sn == 1 and on != 2: +- return other._fix_nan(context) ++ if on == 1 and sn == 0: ++ return self._fix(context) ++ if sn == 1 and on == 0: ++ return other._fix(context) + return self._check_nans(other, context) + + c = self.copy_abs()._cmp(other.copy_abs()) +@@ -3220,7 +3233,7 @@ + return ans + + if self._isinfinity() == -1: +- return negInf ++ return _NegativeInfinity + if self._isinfinity() == 1: + return _dec_from_triple(0, '9'*context.prec, context.Etop()) + +@@ -3243,7 +3256,7 @@ + return ans + + if self._isinfinity() == 1: +- return Inf ++ return _Infinity + if self._isinfinity() == -1: + return _dec_from_triple(1, '9'*context.prec, context.Etop()) + +@@ -3555,6 +3568,12 @@ + + return self + ++# Register Decimal as a kind of Number (an abstract base class). ++# However, do not register it as Real (because Decimals are not ++# interoperable with floats). ++_numbers.Number.register(Decimal) ++ ++ + ##### Context class ####################################################### + + +@@ -5472,9 +5491,9 @@ + + align = spec_dict['align'] + if align == '<': ++ result = sign + body + padding ++ elif align == '>': + result = padding + sign + body +- elif align == '>': +- result = sign + body + padding + elif align == '=': + result = sign + padding + body + else: #align == '^' +@@ -5490,15 +5509,15 @@ + ##### Useful Constants (internal use only) ################################ + + # Reusable defaults +-Inf = Decimal('Inf') +-negInf = Decimal('-Inf') +-NaN = Decimal('NaN') +-Dec_0 = Decimal(0) +-Dec_p1 = Decimal(1) +-Dec_n1 = Decimal(-1) ++_Infinity = Decimal('Inf') ++_NegativeInfinity = Decimal('-Inf') ++_NaN = Decimal('NaN') ++_Zero = Decimal(0) ++_One = Decimal(1) ++_NegativeOne = Decimal(-1) + +-# Infsign[sign] is infinity w/ that sign +-Infsign = (Inf, negInf) ++# _SignedInfinity[sign] is infinity w/ that sign ++_SignedInfinity = (_Infinity, _NegativeInfinity) + + + +Index: Lib/heapq.py +=================================================================== +--- Lib/heapq.py (.../tags/r261) (Revision 70449) ++++ Lib/heapq.py (.../branches/release26-maint) (Revision 70449) +@@ -354,6 +354,10 @@ + + Equivalent to: sorted(iterable, key=key)[:n] + """ ++ if key is None: ++ it = izip(iterable, count()) # decorate ++ result = _nsmallest(n, it) ++ return map(itemgetter(0), result) # undecorate + in1, in2 = tee(iterable) + it = izip(imap(key, in1), count(), in2) # decorate + result = _nsmallest(n, it) +@@ -365,6 +369,10 @@ + + Equivalent to: sorted(iterable, key=key, reverse=True)[:n] + """ ++ if key is None: ++ it = izip(iterable, imap(neg, count())) # decorate ++ result = _nlargest(n, it) ++ return map(itemgetter(0), result) # undecorate + in1, in2 = tee(iterable) + it = izip(imap(key, in1), imap(neg, count()), in2) # decorate + result = _nlargest(n, it) +Index: Lib/logging/__init__.py +=================================================================== +--- Lib/logging/__init__.py (.../tags/r261) (Revision 70449) ++++ Lib/logging/__init__.py (.../branches/release26-maint) (Revision 70449) +@@ -1,4 +1,4 @@ +-# Copyright 2001-2008 by Vinay Sajip. All Rights Reserved. ++# Copyright 2001-2009 by Vinay Sajip. All Rights Reserved. + # + # Permission to use, copy, modify, and distribute this software and its + # documentation for any purpose and without fee is hereby granted, +@@ -18,11 +18,8 @@ + Logging package for Python. Based on PEP 282 and comments thereto in + comp.lang.python, and influenced by Apache's log4j system. + +-Should work under Python versions >= 1.5.2, except that source line +-information is not available unless 'sys._getframe()' is. ++Copyright (C) 2001-2009 Vinay Sajip. All Rights Reserved. + +-Copyright (C) 2001-2008 Vinay Sajip. All Rights Reserved. +- + To use, simply 'import logging' and log away! + """ + +@@ -47,7 +44,7 @@ + __author__ = "Vinay Sajip " + __status__ = "production" + __version__ = "0.5.0.5" +-__date__ = "24 January 2008" ++__date__ = "17 February 2009" + + #--------------------------------------------------------------------------- + # Miscellaneous module data +@@ -100,6 +97,11 @@ + logThreads = 1 + + # ++# If you don't want multiprocessing information in the log, set this to zero ++# ++logMultiprocessing = 1 ++ ++# + # If you don't want process information in the log, set this to zero + # + logProcesses = 1 +@@ -266,6 +268,11 @@ + else: + self.thread = None + self.threadName = None ++ if logMultiprocessing: ++ from multiprocessing import current_process ++ self.processName = current_process().name ++ else: ++ self.processName = None + if logProcesses and hasattr(os, 'getpid'): + self.process = os.getpid() + else: +@@ -730,7 +737,6 @@ + if strm is None: + strm = sys.stderr + self.stream = strm +- self.formatter = None + + def flush(self): + """ +@@ -752,17 +758,19 @@ + """ + try: + msg = self.format(record) ++ stream = self.stream + fs = "%s\n" + if not hasattr(types, "UnicodeType"): #if no unicode support... +- self.stream.write(fs % msg) ++ stream.write(fs % msg) + else: + try: +- if getattr(self.stream, 'encoding', None) is not None: +- self.stream.write(fs % msg.encode(self.stream.encoding)) ++ if (isinstance(msg, unicode) or ++ getattr(stream, 'encoding', None) is None): ++ stream.write(fs % msg) + else: +- self.stream.write(fs % msg) ++ stream.write(fs % msg.encode(stream.encoding)) + except UnicodeError: +- self.stream.write(fs % msg.encode("UTF-8")) ++ stream.write(fs % msg.encode("UTF-8")) + self.flush() + except (KeyboardInterrupt, SystemExit): + raise +@@ -785,10 +793,12 @@ + self.mode = mode + self.encoding = encoding + if delay: ++ #We don't open the stream, but we still need to call the ++ #Handler constructor to set level, formatter, lock etc. ++ Handler.__init__(self) + self.stream = None + else: +- stream = self._open() +- StreamHandler.__init__(self, stream) ++ StreamHandler.__init__(self, self._open()) + + def close(self): + """ +@@ -820,8 +830,7 @@ + constructor, open it before calling the superclass's emit. + """ + if self.stream is None: +- stream = self._open() +- StreamHandler.__init__(self, stream) ++ self.stream = self._open() + StreamHandler.emit(self, record) + + #--------------------------------------------------------------------------- +@@ -846,7 +855,7 @@ + Add the specified logger as a child of this placeholder. + """ + #if alogger not in self.loggers: +- if not self.loggerMap.has_key(alogger): ++ if alogger not in self.loggerMap: + #self.loggers.append(alogger) + self.loggerMap[alogger] = None + +@@ -1119,7 +1128,12 @@ + all the handlers of this logger to handle the record. + """ + if _srcfile: +- fn, lno, func = self.findCaller() ++ #IronPython doesn't track Python frames, so findCaller throws an ++ #exception. We trap it here so that IronPython can use logging. ++ try: ++ fn, lno, func = self.findCaller() ++ except ValueError: ++ fn, lno, func = "(unknown file)", 0, "(unknown function)" + else: + fn, lno, func = "(unknown file)", 0, "(unknown function)" + if exc_info: +Index: Lib/logging/handlers.py +=================================================================== +--- Lib/logging/handlers.py (.../tags/r261) (Revision 70449) ++++ Lib/logging/handlers.py (.../branches/release26-maint) (Revision 70449) +@@ -19,12 +19,9 @@ + based on PEP 282 and comments thereto in comp.lang.python, and influenced by + Apache's log4j system. + +-Should work under Python versions >= 1.5.2, except that source line +-information is not available unless 'sys._getframe()' is. ++Copyright (C) 2001-2009 Vinay Sajip. All Rights Reserved. + +-Copyright (C) 2001-2008 Vinay Sajip. All Rights Reserved. +- +-To use, simply 'import logging' and log away! ++To use, simply 'import logging.handlers' and log away! + """ + + import logging, socket, types, os, string, cPickle, struct, time, re +@@ -141,6 +138,8 @@ + Basically, see if the supplied record would cause the file to exceed + the size limit we have. + """ ++ if self.stream is None: # delay was set... ++ self.stream = self._open() + if self.maxBytes > 0: # are we rolling over? + msg = "%s\n" % self.format(record) + self.stream.seek(0, 2) #due to non-posix-compliant Windows feature +@@ -305,7 +304,8 @@ + then we have to get a list of matching filenames, sort them and remove + the one with the oldest suffix. + """ +- self.stream.close() ++ if self.stream: ++ self.stream.close() + # get the time that this sequence started at and make it a TimeTuple + t = self.rolloverAt - self.interval + if self.utc: +Index: Lib/inspect.py +=================================================================== +--- Lib/inspect.py (.../tags/r261) (Revision 70449) ++++ Lib/inspect.py (.../branches/release26-maint) (Revision 70449) +@@ -158,9 +158,8 @@ + Generator function objects provides same attributes as functions. + + See isfunction.__doc__ for attributes listing.""" +- if (isfunction(object) or ismethod(object)) and \ +- object.func_code.co_flags & CO_GENERATOR: +- return True ++ return bool((isfunction(object) or ismethod(object)) and ++ object.func_code.co_flags & CO_GENERATOR) + + def isgenerator(object): + """Return true if the object is a generator. +Index: Lib/string.py +=================================================================== +--- Lib/string.py (.../tags/r261) (Revision 70449) ++++ Lib/string.py (.../branches/release26-maint) (Revision 70449) +@@ -532,9 +532,8 @@ + # the Formatter class + # see PEP 3101 for details and purpose of this class + +-# The hard parts are reused from the C implementation. They're +-# exposed here via the sys module. sys was chosen because it's always +-# available and doesn't have to be dynamically loaded. ++# The hard parts are reused from the C implementation. They're exposed as "_" ++# prefixed methods of str and unicode. + + # The overall parser is implemented in str._formatter_parser. + # The field name parser is implemented in str._formatter_field_name_split +Index: Lib/shutil.py +=================================================================== +--- Lib/shutil.py (.../tags/r261) (Revision 70449) ++++ Lib/shutil.py (.../branches/release26-maint) (Revision 70449) +@@ -265,4 +265,10 @@ + os.unlink(src) + + def destinsrc(src, dst): +- return abspath(dst).startswith(abspath(src)) ++ src = abspath(src) ++ dst = abspath(dst) ++ if not src.endswith(os.path.sep): ++ src += os.path.sep ++ if not dst.endswith(os.path.sep): ++ dst += os.path.sep ++ return dst.startswith(src) +Index: Lib/numbers.py +=================================================================== +--- Lib/numbers.py (.../tags/r261) (Revision 70449) ++++ Lib/numbers.py (.../branches/release26-maint) (Revision 70449) +@@ -17,6 +17,7 @@ + caring what kind, use isinstance(x, Number). + """ + __metaclass__ = ABCMeta ++ __slots__ = () + + # Concrete numeric types must provide their own hash implementation + __hash__ = None +@@ -41,6 +42,8 @@ + type as described below. + """ + ++ __slots__ = () ++ + @abstractmethod + def __complex__(self): + """Return a builtin complex instance. Called for complex(self).""" +@@ -172,6 +175,8 @@ + Real also provides defaults for the derived operations. + """ + ++ __slots__ = () ++ + @abstractmethod + def __float__(self): + """Any Real can be converted to a native float object. +@@ -265,6 +270,8 @@ + class Rational(Real): + """.numerator and .denominator should be in lowest terms.""" + ++ __slots__ = () ++ + @abstractproperty + def numerator(self): + raise NotImplementedError +@@ -288,6 +295,8 @@ + class Integral(Rational): + """Integral adds a conversion to long and the bit-string operations.""" + ++ __slots__ = () ++ + @abstractmethod + def __long__(self): + """long(self)""" +Index: Lib/runpy.py +=================================================================== +--- Lib/runpy.py (.../tags/r261) (Revision 70449) ++++ Lib/runpy.py (.../branches/release26-maint) (Revision 70449) +@@ -65,13 +65,14 @@ + + # This helper is needed due to a missing component in the PEP 302 + # loader protocol (specifically, "get_filename" is non-standard) ++# Since we can't introduce new features in maintenance releases, ++# support was added to zipimporter under the name '_get_filename' + def _get_filename(loader, mod_name): +- try: +- get_filename = loader.get_filename +- except AttributeError: +- return None +- else: +- return get_filename(mod_name) ++ for attr in ("get_filename", "_get_filename"): ++ meth = getattr(loader, attr, None) ++ if meth is not None: ++ return meth(mod_name) ++ return None + + # Helper to get the loader, code and filename for a module + def _get_module_details(mod_name): +Index: Lib/collections.py +=================================================================== +--- Lib/collections.py (.../tags/r261) (Revision 70449) ++++ Lib/collections.py (.../branches/release26-maint) (Revision 70449) +@@ -103,7 +103,7 @@ + # where the named tuple is created. Bypass this step in enviroments where + # sys._getframe is not defined (Jython for example). + if hasattr(_sys, '_getframe'): +- result.__module__ = _sys._getframe(1).f_globals['__name__'] ++ result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__') + + return result + +Index: Lib/ctypes/test/__init__.py +=================================================================== +--- Lib/ctypes/test/__init__.py (.../tags/r261) (Revision 70449) ++++ Lib/ctypes/test/__init__.py (.../branches/release26-maint) (Revision 70449) +@@ -67,9 +67,6 @@ + if verbosity > 1: + print >> sys.stderr, "Skipped %s: %s" % (modname, detail) + continue +- except Exception, detail: +- print >> sys.stderr, "Warning: could not import %s: %s" % (modname, detail) +- continue + for name in dir(mod): + if name.startswith("_"): + continue +Index: Lib/ctypes/util.py +=================================================================== +--- Lib/ctypes/util.py (.../tags/r261) (Revision 70449) ++++ Lib/ctypes/util.py (.../branches/release26-maint) (Revision 70449) +@@ -92,18 +92,20 @@ + expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) + fdout, ccout = tempfile.mkstemp() + os.close(fdout) +- cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; else CC=cc; fi;' \ ++ cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; elif type cc >/dev/null 2>&1; then CC=cc;else exit 10; fi;' \ + '$CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name + try: + f = os.popen(cmd) + trace = f.read() +- f.close() ++ rv = f.close() + finally: + try: + os.unlink(ccout) + except OSError, e: + if e.errno != errno.ENOENT: + raise ++ if rv == 10: ++ raise OSError, 'gcc or cc command not found' + res = re.search(expr, trace) + if not res: + return None +@@ -125,7 +127,13 @@ + # assuming GNU binutils / ELF + if not f: + return None +- cmd = "objdump -p -j .dynamic 2>/dev/null " + f ++ cmd = 'if ! type objdump >/dev/null 2>&1; then exit 10; fi;' \ ++ "objdump -p -j .dynamic 2>/dev/null " + f ++ f = os.popen(cmd) ++ dump = f.read() ++ rv = f.close() ++ if rv == 10: ++ raise OSError, 'objdump command not found' + res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read()) + if not res: + return None +@@ -171,8 +179,32 @@ + return None + return res.group(0) + ++ def _findSoname_ldconfig(name): ++ import struct ++ if struct.calcsize('l') == 4: ++ machine = os.uname()[4] + '-32' ++ else: ++ machine = os.uname()[4] + '-64' ++ mach_map = { ++ 'x86_64-64': 'libc6,x86-64', ++ 'ppc64-64': 'libc6,64bit', ++ 'sparc64-64': 'libc6,64bit', ++ 's390x-64': 'libc6,64bit', ++ 'ia64-64': 'libc6,IA-64', ++ } ++ abi_type = mach_map.get(machine, 'libc6') ++ ++ # XXX assuming GLIBC's ldconfig (with option -p) ++ expr = r'(\S+)\s+\((%s(?:, OS ABI:[^\)]*)?)\)[^/]*(/[^\(\)\s]*lib%s\.[^\(\)\s]*)' \ ++ % (abi_type, re.escape(name)) ++ res = re.search(expr, ++ os.popen('/sbin/ldconfig -p 2>/dev/null').read()) ++ if not res: ++ return None ++ return res.group(1) ++ + def find_library(name): +- return _get_soname(_findLib_ldconfig(name) or _findLib_gcc(name)) ++ return _findSoname_ldconfig(name) or _get_soname(_findLib_gcc(name)) + + ################################################################ + # test code +Index: Lib/abc.py +=================================================================== +--- Lib/abc.py (.../tags/r261) (Revision 70449) ++++ Lib/abc.py (.../branches/release26-maint) (Revision 70449) +@@ -15,7 +15,8 @@ + + Usage: + +- class C(metaclass=ABCMeta): ++ class C: ++ __metaclass__ = ABCMeta + @abstractmethod + def my_abstract_method(self, ...): + ... +@@ -35,7 +36,8 @@ + + Usage: + +- class C(metaclass=ABCMeta): ++ class C: ++ __metaclass__ = ABCMeta + @abstractproperty + def my_abstract_property(self): + ... +@@ -43,7 +45,8 @@ + This defines a read-only property; you can also define a read-write + abstract property using the 'long' form of property declaration: + +- class C(metaclass=ABCMeta): ++ class C: ++ __metaclass__ = ABCMeta + def getx(self): ... + def setx(self, value): ... + x = abstractproperty(getx, setx) +Index: Lib/cgi.py +=================================================================== +--- Lib/cgi.py (.../tags/r261) (Revision 70449) ++++ Lib/cgi.py (.../branches/release26-maint) (Revision 70449) +@@ -289,16 +289,28 @@ + return partdict + + ++def _parseparam(s): ++ while s[:1] == ';': ++ s = s[1:] ++ end = s.find(';') ++ while end > 0 and s.count('"', 0, end) % 2: ++ end = s.find(';', end + 1) ++ if end < 0: ++ end = len(s) ++ f = s[:end] ++ yield f.strip() ++ s = s[end:] ++ + def parse_header(line): + """Parse a Content-type like header. + + Return the main content-type and a dictionary of options. + + """ +- plist = [x.strip() for x in line.split(';')] +- key = plist.pop(0).lower() ++ parts = _parseparam(';' + line) ++ key = parts.next() + pdict = {} +- for p in plist: ++ for p in parts: + i = p.find('=') + if i >= 0: + name = p[:i].strip().lower() +Index: Lib/pdb.py +=================================================================== +--- Lib/pdb.py (.../tags/r261) (Revision 70449) ++++ Lib/pdb.py (.../branches/release26-maint) (Revision 70449) +@@ -440,7 +440,7 @@ + Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank + line or EOF). Warning: testing is not comprehensive. + """ +- line = linecache.getline(filename, lineno) ++ line = linecache.getline(filename, lineno, self.curframe.f_globals) + if not line: + print >>self.stdout, 'End of file' + return 0 +@@ -768,7 +768,7 @@ + breaklist = self.get_file_breaks(filename) + try: + for lineno in range(first, last+1): +- line = linecache.getline(filename, lineno) ++ line = linecache.getline(filename, lineno, self.curframe.f_globals) + if not line: + print >>self.stdout, '[EOF]' + break +Index: Lib/io.py +=================================================================== +--- Lib/io.py (.../tags/r261) (Revision 70449) ++++ Lib/io.py (.../branches/release26-maint) (Revision 70449) +@@ -238,8 +238,6 @@ + raise ValueError("invalid buffering size") + if buffering == 0: + if binary: +- raw._name = file +- raw._mode = mode + return raw + raise ValueError("can't have unbuffered text I/O") + if updating: +@@ -251,11 +249,8 @@ + else: + raise ValueError("unknown mode: %r" % mode) + if binary: +- buffer.name = file +- buffer.mode = mode + return buffer + text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering) +- text.name = file + text.mode = mode + return text + +@@ -622,6 +617,10 @@ + # that _fileio._FileIO inherits from io.RawIOBase (which would be hard + # to do since _fileio.c is written in C). + ++ def __init__(self, name, mode="r", closefd=True): ++ _fileio._FileIO.__init__(self, name, mode, closefd) ++ self._name = name ++ + def close(self): + _fileio._FileIO.close(self) + RawIOBase.close(self) +@@ -630,11 +629,7 @@ + def name(self): + return self._name + +- @property +- def mode(self): +- return self._mode + +- + class BufferedIOBase(IOBase): + + """Base class for buffered IO objects. +@@ -767,6 +762,14 @@ + def closed(self): + return self.raw.closed + ++ @property ++ def name(self): ++ return self.raw.name ++ ++ @property ++ def mode(self): ++ return self.raw.mode ++ + ### Lower-level APIs ### + + def fileno(self): +@@ -1164,7 +1167,7 @@ + + @property + def closed(self): +- return self.writer.closed() ++ return self.writer.closed + + + class BufferedRandom(BufferedWriter, BufferedReader): +@@ -1289,25 +1292,23 @@ + """ + def __init__(self, decoder, translate, errors='strict'): + codecs.IncrementalDecoder.__init__(self, errors=errors) +- self.buffer = b'' + self.translate = translate + self.decoder = decoder + self.seennl = 0 ++ self.pendingcr = False + + def decode(self, input, final=False): + # decode input (with the eventual \r from a previous pass) +- if self.buffer: +- input = self.buffer + input +- + output = self.decoder.decode(input, final=final) ++ if self.pendingcr and (output or final): ++ output = "\r" + output ++ self.pendingcr = False + + # retain last \r even when not translating data: + # then readline() is sure to get \r\n in one pass + if output.endswith("\r") and not final: + output = output[:-1] +- self.buffer = b'\r' +- else: +- self.buffer = b'' ++ self.pendingcr = True + + # Record which newlines are read + crlf = output.count('\r\n') +@@ -1326,20 +1327,19 @@ + + def getstate(self): + buf, flag = self.decoder.getstate() +- return buf + self.buffer, flag ++ flag <<= 1 ++ if self.pendingcr: ++ flag |= 1 ++ return buf, flag + + def setstate(self, state): + buf, flag = state +- if buf.endswith(b'\r'): +- self.buffer = b'\r' +- buf = buf[:-1] +- else: +- self.buffer = b'' +- self.decoder.setstate((buf, flag)) ++ self.pendingcr = bool(flag & 1) ++ self.decoder.setstate((buf, flag >> 1)) + + def reset(self): + self.seennl = 0 +- self.buffer = b'' ++ self.pendingcr = False + self.decoder.reset() + + _LF = 1 +@@ -1473,6 +1473,10 @@ + def closed(self): + return self.buffer.closed + ++ @property ++ def name(self): ++ return self.buffer.name ++ + def fileno(self): + return self.buffer.fileno() + +Index: Lib/pydoc.py +=================================================================== +--- Lib/pydoc.py (.../tags/r261) (Revision 70449) ++++ Lib/pydoc.py (.../branches/release26-maint) (Revision 70449) +@@ -1574,6 +1574,42 @@ + 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'), + 'yield': ('yield', ''), + } ++ # Either add symbols to this dictionary or to the symbols dictionary ++ # directly: Whichever is easier. They are merged later. ++ _symbols_inverse = { ++ 'STRINGS' : ("'", "'''", "r'", "u'", '"""', '"', 'r"', 'u"'), ++ 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&', ++ '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'), ++ 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'), ++ 'UNARY' : ('-', '~'), ++ 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=', ++ '^=', '<<=', '>>=', '**=', '//='), ++ 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'), ++ 'COMPLEX' : ('j', 'J') ++ } ++ symbols = { ++ '%': 'OPERATORS FORMATTING', ++ '**': 'POWER', ++ ',': 'TUPLES LISTS FUNCTIONS', ++ '.': 'ATTRIBUTES FLOAT MODULES OBJECTS', ++ '...': 'ELLIPSIS', ++ ':': 'SLICINGS DICTIONARYLITERALS', ++ '@': 'def class', ++ '\\': 'STRINGS', ++ '_': 'PRIVATENAMES', ++ '__': 'PRIVATENAMES SPECIALMETHODS', ++ '`': 'BACKQUOTES', ++ '(': 'TUPLES FUNCTIONS CALLS', ++ ')': 'TUPLES FUNCTIONS CALLS', ++ '[': 'LISTS SUBSCRIPTS SLICINGS', ++ ']': 'LISTS SUBSCRIPTS SLICINGS' ++ } ++ for topic, symbols_ in _symbols_inverse.iteritems(): ++ for symbol in symbols_: ++ topics = symbols.get(symbol, topic) ++ if topic not in topics: ++ topics = topics + ' ' + topic ++ symbols[symbol] = topics + + topics = { + 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS ' +@@ -1717,10 +1753,12 @@ + if type(request) is type(''): + if request == 'help': self.intro() + elif request == 'keywords': self.listkeywords() ++ elif request == 'symbols': self.listsymbols() + elif request == 'topics': self.listtopics() + elif request == 'modules': self.listmodules() + elif request[:8] == 'modules ': + self.listmodules(split(request)[1]) ++ elif request in self.symbols: self.showsymbol(request) + elif request in self.keywords: self.showtopic(request) + elif request in self.topics: self.showtopic(request) + elif request: doc(request, 'Help on %s:') +@@ -1766,6 +1804,14 @@ + ''') + self.list(self.keywords.keys()) + ++ def listsymbols(self): ++ self.output.write(''' ++Here is a list of the punctuation symbols which Python assigns special meaning ++to. Enter any symbol to get more help. ++ ++''') ++ self.list(self.symbols.keys()) ++ + def listtopics(self): + self.output.write(''' + Here is a list of available topics. Enter any topic name to get more help. +@@ -1773,7 +1819,7 @@ + ''') + self.list(self.topics.keys()) + +- def showtopic(self, topic): ++ def showtopic(self, topic, more_xrefs=''): + try: + import pydoc_topics + except ImportError: +@@ -1787,7 +1833,7 @@ + self.output.write('no documentation found for %s\n' % repr(topic)) + return + if type(target) is type(''): +- return self.showtopic(target) ++ return self.showtopic(target, more_xrefs) + + label, xrefs = target + try: +@@ -1796,6 +1842,8 @@ + self.output.write('no documentation found for %s\n' % repr(topic)) + return + pager(strip(doc) + '\n') ++ if more_xrefs: ++ xrefs = (xrefs or '') + ' ' + more_xrefs + if xrefs: + import StringIO, formatter + buffer = StringIO.StringIO() +@@ -1803,6 +1851,11 @@ + 'Related help topics: ' + join(split(xrefs), ', ') + '\n') + self.output.write('\n%s\n' % buffer.getvalue()) + ++ def showsymbol(self, symbol): ++ target = self.symbols[symbol] ++ topic, _, xrefs = target.partition(' ') ++ self.showtopic(topic, xrefs) ++ + def listmodules(self, key=''): + if key: + self.output.write(''' +Index: Lib/bsddb/test/test_lock.py +=================================================================== +--- Lib/bsddb/test/test_lock.py (.../tags/r261) (Revision 70449) ++++ Lib/bsddb/test/test_lock.py (.../branches/release26-maint) (Revision 70449) +@@ -124,7 +124,7 @@ + self.env.lock_get,anID2, "shared lock", db.DB_LOCK_READ) + end_time=time.time() + deadlock_detection.end=True +- self.assertTrue((end_time-start_time) >= 0.1) ++ self.assertTrue((end_time-start_time) >= 0.0999) + self.env.lock_put(lock) + t.join() + +Index: Lib/tarfile.py +=================================================================== +--- Lib/tarfile.py (.../tags/r261) (Revision 70449) ++++ Lib/tarfile.py (.../branches/release26-maint) (Revision 70449) +@@ -2284,10 +2284,6 @@ + """ + if not hasattr(os, 'utime'): + return +- if sys.platform == "win32" and tarinfo.isdir(): +- # According to msdn.microsoft.com, it is an error (EACCES) +- # to use utime() on directories. +- return + try: + os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) + except EnvironmentError, e: +Index: Lib/lib2to3/pytree.py +=================================================================== +--- Lib/lib2to3/pytree.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/pytree.py (.../branches/release26-maint) (Revision 70449) +@@ -279,18 +279,21 @@ + child.parent = self + self.children[i].parent = None + self.children[i] = child ++ self.changed() + + def insert_child(self, i, child): + """Equivalent to 'node.children.insert(i, child)'. This method also + sets the child's parent attribute appropriately.""" + child.parent = self + self.children.insert(i, child) ++ self.changed() + + def append_child(self, child): + """Equivalent to 'node.children.append(child)'. This method also + sets the child's parent attribute appropriately.""" + child.parent = self + self.children.append(child) ++ self.changed() + + + class Leaf(Base): +Index: Lib/lib2to3/fixer_util.py +=================================================================== +--- Lib/lib2to3/fixer_util.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixer_util.py (.../branches/release26-maint) (Revision 70449) +@@ -158,7 +158,10 @@ + ### Misc + ########################################################### + ++def parenthesize(node): ++ return Node(syms.atom, [LParen(), node, RParen()]) + ++ + consuming_calls = set(["sorted", "list", "set", "any", "all", "tuple", "sum", + "min", "max"]) + +@@ -219,6 +222,29 @@ + return True + return False + ++def is_probably_builtin(node): ++ """ ++ Check that something isn't an attribute or function name etc. ++ """ ++ prev = node.get_prev_sibling() ++ if prev is not None and prev.type == token.DOT: ++ # Attribute lookup. ++ return False ++ parent = node.parent ++ if parent.type in (syms.funcdef, syms.classdef): ++ return False ++ if parent.type == syms.expr_stmt and parent.children[0] is node: ++ # Assignment. ++ return False ++ if parent.type == syms.parameters or \ ++ (parent.type == syms.typedargslist and ( ++ (prev is not None and prev.type == token.COMMA) or ++ parent.children[0] is node ++ )): ++ # The name of an argument. ++ return False ++ return True ++ + ########################################################### + ### The following functions are to find bindings in a suite + ########################################################### +@@ -232,20 +258,77 @@ + suite.parent = parent + return suite + +-def does_tree_import(package, name, node): +- """ Returns true if name is imported from package at the +- top level of the tree which node belongs to. +- To cover the case of an import like 'import foo', use +- Null for the package and 'foo' for the name. """ ++def find_root(node): ++ """Find the top level namespace.""" + # Scamper up to the top level namespace + while node.type != syms.file_input: + assert node.parent, "Tree is insane! root found before "\ + "file_input node was found." + node = node.parent ++ return node + +- binding = find_binding(name, node, package) ++def does_tree_import(package, name, node): ++ """ Returns true if name is imported from package at the ++ top level of the tree which node belongs to. ++ To cover the case of an import like 'import foo', use ++ None for the package and 'foo' for the name. """ ++ binding = find_binding(name, find_root(node), package) + return bool(binding) + ++def is_import(node): ++ """Returns true if the node is an import statement.""" ++ return node.type in (syms.import_name, syms.import_from) ++ ++def touch_import(package, name, node): ++ """ Works like `does_tree_import` but adds an import statement ++ if it was not imported. """ ++ def is_import_stmt(node): ++ return node.type == syms.simple_stmt and node.children and \ ++ is_import(node.children[0]) ++ ++ root = find_root(node) ++ ++ if does_tree_import(package, name, root): ++ return ++ ++ add_newline_before = False ++ ++ # figure out where to insert the new import. First try to find ++ # the first import and then skip to the last one. ++ insert_pos = offset = 0 ++ for idx, node in enumerate(root.children): ++ if not is_import_stmt(node): ++ continue ++ for offset, node2 in enumerate(root.children[idx:]): ++ if not is_import_stmt(node2): ++ break ++ insert_pos = idx + offset ++ break ++ ++ # if there are no imports where we can insert, find the docstring. ++ # if that also fails, we stick to the beginning of the file ++ if insert_pos == 0: ++ for idx, node in enumerate(root.children): ++ if node.type == syms.simple_stmt and node.children and \ ++ node.children[0].type == token.STRING: ++ insert_pos = idx + 1 ++ add_newline_before ++ break ++ ++ if package is None: ++ import_ = Node(syms.import_name, [ ++ Leaf(token.NAME, 'import'), ++ Leaf(token.NAME, name, prefix=' ') ++ ]) ++ else: ++ import_ = FromImport(package, [Leaf(token.NAME, name, prefix=' ')]) ++ ++ children = [import_, Newline()] ++ if add_newline_before: ++ children.insert(0, Newline()) ++ root.insert_child(insert_pos, Node(syms.simple_stmt, children)) ++ ++ + _def_syms = set([syms.classdef, syms.funcdef]) + def find_binding(name, node, package=None): + """ Returns the node which binds variable name, otherwise None. +@@ -285,7 +368,7 @@ + if ret: + if not package: + return ret +- if ret.type in (syms.import_name, syms.import_from): ++ if is_import(ret): + return ret + return None + +Index: Lib/lib2to3/tests/benchmark.py +=================================================================== +--- Lib/lib2to3/tests/benchmark.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/tests/benchmark.py (.../branches/release26-maint) (Revision 70449) +@@ -1,58 +0,0 @@ +-#!/usr/bin/env python2.5 +-""" +-This is a benchmarking script to test the speed of 2to3's pattern matching +-system. It's equivalent to "refactor.py -f all" for every Python module +-in sys.modules, but without engaging the actual transformations. +-""" +- +-__author__ = "Collin Winter " +- +-# Python imports +-import os.path +-import sys +-from time import time +- +-# Test imports +-from .support import adjust_path +-adjust_path() +- +-# Local imports +-from .. import refactor +- +-### Mock code for refactor.py and the fixers +-############################################################################### +-class Options: +- def __init__(self, **kwargs): +- for k, v in kwargs.items(): +- setattr(self, k, v) +- +- self.verbose = False +- +-def dummy_transform(*args, **kwargs): +- pass +- +-### Collect list of modules to match against +-############################################################################### +-files = [] +-for mod in sys.modules.values(): +- if mod is None or not hasattr(mod, '__file__'): +- continue +- f = mod.__file__ +- if f.endswith('.pyc'): +- f = f[:-1] +- if f.endswith('.py'): +- files.append(f) +- +-### Set up refactor and run the benchmark +-############################################################################### +-options = Options(fix=["all"], print_function=False, doctests_only=False) +-refactor = refactor.RefactoringTool(options) +-for fixer in refactor.fixers: +- # We don't want them to actually fix the tree, just match against it. +- fixer.transform = dummy_transform +- +-t = time() +-for f in files: +- print "Matching", f +- refactor.refactor_file(f) +-print "%d seconds to match %d files" % (time() - t, len(sys.modules)) +Index: Lib/lib2to3/tests/test_util.py +=================================================================== +--- Lib/lib2to3/tests/test_util.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/tests/test_util.py (.../branches/release26-maint) (Revision 70449) +@@ -526,7 +526,34 @@ + b = 7""" + self.failIf(self.find_binding("a", s)) + ++class Test_touch_import(support.TestCase): + ++ def test_after_docstring(self): ++ node = parse('"""foo"""\nbar()') ++ fixer_util.touch_import(None, "foo", node) ++ self.assertEqual(str(node), '"""foo"""\nimport foo\nbar()\n\n') ++ ++ def test_after_imports(self): ++ node = parse('"""foo"""\nimport bar\nbar()') ++ fixer_util.touch_import(None, "foo", node) ++ self.assertEqual(str(node), '"""foo"""\nimport bar\nimport foo\nbar()\n\n') ++ ++ def test_beginning(self): ++ node = parse('bar()') ++ fixer_util.touch_import(None, "foo", node) ++ self.assertEqual(str(node), 'import foo\nbar()\n\n') ++ ++ def test_from_import(self): ++ node = parse('bar()') ++ fixer_util.touch_import("cgi", "escape", node) ++ self.assertEqual(str(node), 'from cgi import escape\nbar()\n\n') ++ ++ def test_name_import(self): ++ node = parse('bar()') ++ fixer_util.touch_import(None, "cgi", node) ++ self.assertEqual(str(node), 'import cgi\nbar()\n\n') ++ ++ + if __name__ == "__main__": + import __main__ + support.run_all_tests(__main__) +Index: Lib/lib2to3/tests/test_fixers.py +=================================================================== +--- Lib/lib2to3/tests/test_fixers.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/tests/test_fixers.py (.../branches/release26-maint) (Revision 70449) +@@ -293,30 +293,30 @@ + + def test_prefix_preservation(self): + b = """x = intern( a )""" +- a = """x = sys.intern( a )""" ++ a = """import sys\nx = sys.intern( a )""" + self.check(b, a) + + b = """y = intern("b" # test + )""" +- a = """y = sys.intern("b" # test ++ a = """import sys\ny = sys.intern("b" # test + )""" + self.check(b, a) + + b = """z = intern(a+b+c.d, )""" +- a = """z = sys.intern(a+b+c.d, )""" ++ a = """import sys\nz = sys.intern(a+b+c.d, )""" + self.check(b, a) + + def test(self): + b = """x = intern(a)""" +- a = """x = sys.intern(a)""" ++ a = """import sys\nx = sys.intern(a)""" + self.check(b, a) + + b = """z = intern(a+b+c.d,)""" +- a = """z = sys.intern(a+b+c.d,)""" ++ a = """import sys\nz = sys.intern(a+b+c.d,)""" + self.check(b, a) + + b = """intern("y%s" % 5).replace("y", "")""" +- a = """sys.intern("y%s" % 5).replace("y", "")""" ++ a = """import sys\nsys.intern("y%s" % 5).replace("y", "")""" + self.check(b, a) + + # These should not be refactored +@@ -337,6 +337,35 @@ + s = """intern()""" + self.unchanged(s) + ++class Test_reduce(FixerTestCase): ++ fixer = "reduce" ++ ++ def test_simple_call(self): ++ b = "reduce(a, b, c)" ++ a = "from functools import reduce\nreduce(a, b, c)" ++ self.check(b, a) ++ ++ def test_call_with_lambda(self): ++ b = "reduce(lambda x, y: x + y, seq)" ++ a = "from functools import reduce\nreduce(lambda x, y: x + y, seq)" ++ self.check(b, a) ++ ++ def test_unchanged(self): ++ s = "reduce(a)" ++ self.unchanged(s) ++ ++ s = "reduce(a, b=42)" ++ self.unchanged(s) ++ ++ s = "reduce(a, b, c, d)" ++ self.unchanged(s) ++ ++ s = "reduce(**c)" ++ self.unchanged(s) ++ ++ s = "reduce()" ++ self.unchanged(s) ++ + class Test_print(FixerTestCase): + fixer = "print" + +@@ -1044,33 +1073,100 @@ + a = """z = type(x) in (int, int)""" + self.check(b, a) + +- def test_4(self): +- b = """a = 12L""" +- a = """a = 12""" +- self.check(b, a) ++ def test_unchanged(self): ++ s = """long = True""" ++ self.unchanged(s) + +- def test_5(self): +- b = """b = 0x12l""" +- a = """b = 0x12""" +- self.check(b, a) ++ s = """s.long = True""" ++ self.unchanged(s) + +- def test_unchanged_1(self): +- s = """a = 12""" ++ s = """def long(): pass""" + self.unchanged(s) + +- def test_unchanged_2(self): +- s = """b = 0x12""" ++ s = """class long(): pass""" + self.unchanged(s) + +- def test_unchanged_3(self): +- s = """c = 3.14""" ++ s = """def f(long): pass""" + self.unchanged(s) + ++ s = """def f(g, long): pass""" ++ self.unchanged(s) ++ ++ s = """def f(x, long=True): pass""" ++ self.unchanged(s) ++ + def test_prefix_preservation(self): + b = """x = long( x )""" + a = """x = int( x )""" + self.check(b, a) + ++ ++class Test_execfile(FixerTestCase): ++ fixer = "execfile" ++ ++ def test_conversion(self): ++ b = """execfile("fn")""" ++ a = """exec(compile(open("fn").read(), "fn", 'exec'))""" ++ self.check(b, a) ++ ++ b = """execfile("fn", glob)""" ++ a = """exec(compile(open("fn").read(), "fn", 'exec'), glob)""" ++ self.check(b, a) ++ ++ b = """execfile("fn", glob, loc)""" ++ a = """exec(compile(open("fn").read(), "fn", 'exec'), glob, loc)""" ++ self.check(b, a) ++ ++ b = """execfile("fn", globals=glob)""" ++ a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob)""" ++ self.check(b, a) ++ ++ b = """execfile("fn", locals=loc)""" ++ a = """exec(compile(open("fn").read(), "fn", 'exec'), locals=loc)""" ++ self.check(b, a) ++ ++ b = """execfile("fn", globals=glob, locals=loc)""" ++ a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob, locals=loc)""" ++ self.check(b, a) ++ ++ def test_spacing(self): ++ b = """execfile( "fn" )""" ++ a = """exec(compile(open( "fn" ).read(), "fn", 'exec'))""" ++ self.check(b, a) ++ ++ b = """execfile("fn", globals = glob)""" ++ a = """exec(compile(open("fn").read(), "fn", 'exec'), globals = glob)""" ++ self.check(b, a) ++ ++ ++class Test_isinstance(FixerTestCase): ++ fixer = "isinstance" ++ ++ def test_remove_multiple_items(self): ++ b = """isinstance(x, (int, int, int))""" ++ a = """isinstance(x, int)""" ++ self.check(b, a) ++ ++ b = """isinstance(x, (int, float, int, int, float))""" ++ a = """isinstance(x, (int, float))""" ++ self.check(b, a) ++ ++ b = """isinstance(x, (int, float, int, int, float, str))""" ++ a = """isinstance(x, (int, float, str))""" ++ self.check(b, a) ++ ++ b = """isinstance(foo() + bar(), (x(), y(), x(), int, int))""" ++ a = """isinstance(foo() + bar(), (x(), y(), x(), int))""" ++ self.check(b, a) ++ ++ def test_prefix_preservation(self): ++ b = """if isinstance( foo(), ( bar, bar, baz )) : pass""" ++ a = """if isinstance( foo(), ( bar, baz )) : pass""" ++ self.check(b, a) ++ ++ def test_unchanged(self): ++ self.unchanged("isinstance(x, (str, int))") ++ + class Test_dict(FixerTestCase): + fixer = "dict" + +@@ -1287,6 +1383,14 @@ + a = """x = list(range(10, 3, 9)) + [4]""" + self.check(b, a) + ++ b = """x = range(10)[::-1]""" ++ a = """x = list(range(10))[::-1]""" ++ self.check(b, a) ++ ++ b = """x = range(10) [3]""" ++ a = """x = list(range(10)) [3]""" ++ self.check(b, a) ++ + def test_xrange_in_for(self): + b = """for i in xrange(10):\n j=i""" + a = """for i in range(10):\n j=i""" +@@ -1422,10 +1526,9 @@ + s = "foo(xreadlines)" + self.unchanged(s) + +-class Test_imports(FixerTestCase): +- fixer = "imports" +- from ..fixes.fix_imports import MAPPING as modules + ++class ImportsFixerTests: ++ + def test_import_module(self): + for old, new in self.modules.items(): + b = "import %s" % old +@@ -1522,18 +1625,36 @@ + self.check(b, a) + + ++class Test_imports(FixerTestCase, ImportsFixerTests): ++ fixer = "imports" ++ from ..fixes.fix_imports import MAPPING as modules + +-class Test_imports2(Test_imports): ++ def test_multiple_imports(self): ++ b = """import urlparse, cStringIO""" ++ a = """import urllib.parse, io""" ++ self.check(b, a) ++ ++ def test_multiple_imports_as(self): ++ b = """ ++ import copy_reg as bar, HTMLParser as foo, urlparse ++ s = urlparse.spam(bar.foo()) ++ """ ++ a = """ ++ import copyreg as bar, html.parser as foo, urllib.parse ++ s = urllib.parse.spam(bar.foo()) ++ """ ++ self.check(b, a) ++ ++ ++class Test_imports2(FixerTestCase, ImportsFixerTests): + fixer = "imports2" + from ..fixes.fix_imports2 import MAPPING as modules + + +-class Test_imports_fixer_order(Test_imports): ++class Test_imports_fixer_order(FixerTestCase, ImportsFixerTests): + +- fixer = None +- + def setUp(self): +- Test_imports.setUp(self, ['imports', 'imports2']) ++ super(Test_imports_fixer_order, self).setUp(['imports', 'imports2']) + from ..fixes.fix_imports2 import MAPPING as mapping2 + self.modules = mapping2.copy() + from ..fixes.fix_imports import MAPPING as mapping1 +@@ -2656,7 +2777,7 @@ + + def check(self, b, a): + self.unchanged("from future_builtins import map; " + b, a) +- FixerTestCase.check(self, b, a) ++ super(Test_map, self).check(b, a) + + def test_prefix_preservation(self): + b = """x = map( f, 'abc' )""" +@@ -2763,7 +2884,7 @@ + + def check(self, b, a): + self.unchanged("from future_builtins import zip; " + b, a) +- FixerTestCase.check(self, b, a) ++ super(Test_zip, self).check(b, a) + + def test_zip_basic(self): + b = """x = zip(a, b, c)""" +@@ -3308,7 +3429,7 @@ + fixer = "import" + + def setUp(self): +- FixerTestCase.setUp(self) ++ super(Test_import, self).setUp() + # Need to replace fix_import's exists method + # so we can check that it's doing the right thing + self.files_checked = [] +@@ -3327,9 +3448,9 @@ + + def check_both(self, b, a): + self.always_exists = True +- FixerTestCase.check(self, b, a) ++ super(Test_import, self).check(b, a) + self.always_exists = False +- FixerTestCase.unchanged(self, b) ++ super(Test_import, self).unchanged(b) + + def test_files_checked(self): + def p(path): +@@ -3406,6 +3527,30 @@ + a = "from . import foo, bar" + self.check_both(b, a) + ++ b = "import foo, bar, x" ++ a = "from . import foo, bar, x" ++ self.check_both(b, a) ++ ++ b = "import x, y, z" ++ a = "from . import x, y, z" ++ self.check_both(b, a) ++ ++ def test_import_as(self): ++ b = "import foo as x" ++ a = "from . import foo as x" ++ self.check_both(b, a) ++ ++ b = "import a as b, b as c, c as d" ++ a = "from . import a as b, b as c, c as d" ++ self.check_both(b, a) ++ ++ def test_local_and_absolute(self): ++ self.always_exists = False ++ self.present_files = set(["foo.py", "__init__.py"]) ++ ++ s = "import foo, bar" ++ self.warns_unchanged(s, "absolute and local imports together") ++ + def test_dotted_import(self): + b = "import foo.bar" + a = "from . import foo.bar" +@@ -3800,7 +3945,18 @@ + """ + self.check(b, a) + ++ b = """ ++ class X: ++ __metaclass__ = Meta ++ save.py = 23 ++ """ ++ a = """ ++ class X(metaclass=Meta): ++ save.py = 23 ++ """ ++ self.check(b, a) + ++ + class Test_getcwdu(FixerTestCase): + + fixer = 'getcwdu' + +Eigenschaftsänderungen: Lib/lib2to3/tests/data/fixers/myfixes +___________________________________________________________________ +Hinzugefügt: svn:ignore + + *.pyc +*.pyo + + + +Eigenschaftsänderungen: Lib/lib2to3/tests/data/fixers +___________________________________________________________________ +Hinzugefügt: svn:ignore + + *.pyc +*.pyo + + + +Eigenschaftsänderungen: Lib/lib2to3/tests/data/infinite_recursion.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Lib/lib2to3/tests/data/py3_test_grammar.py +=================================================================== +--- Lib/lib2to3/tests/data/py3_test_grammar.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/tests/data/py3_test_grammar.py (.../branches/release26-maint) (Revision 70449) +@@ -485,6 +485,14 @@ + global a, b + global one, two, three, four, five, six, seven, eight, nine, ten + ++ def testNonlocal(self): ++ # 'nonlocal' NAME (',' NAME)* ++ x = 0 ++ y = 0 ++ def f(): ++ nonlocal x ++ nonlocal x, y ++ + def testAssert(self): + # assert_stmt: 'assert' test [',' test] + assert 1 +Index: Lib/lib2to3/pygram.py +=================================================================== +--- Lib/lib2to3/pygram.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/pygram.py (.../branches/release26-maint) (Revision 70449) +@@ -29,10 +29,3 @@ + + python_grammar = driver.load_grammar(_GRAMMAR_FILE) + python_symbols = Symbols(python_grammar) +- +- +-def parenthesize(node): +- return pytree.Node(python_symbols.atom, +- (pytree.Leaf(token.LPAR, "("), +- node, +- pytree.Leaf(token.RPAR, ")"))) +Index: Lib/lib2to3/main.py +=================================================================== +--- Lib/lib2to3/main.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/main.py (.../branches/release26-maint) (Revision 70449) +@@ -5,6 +5,7 @@ + import sys + import os + import logging ++import shutil + import optparse + + from . import refactor +@@ -39,6 +40,8 @@ + # Actually write the new file + super(StdoutRefactoringTool, self).write_file(new_text, + filename, old_text) ++ if not self.nobackups: ++ shutil.copymode(backup, filename) + + def print_output(self, lines): + for line in lines: +@@ -56,7 +59,7 @@ + Returns a suggested exit status (0, 1, 2). + """ + # Set up option parser +- parser = optparse.OptionParser(usage="refactor.py [options] file|dir ...") ++ parser = optparse.OptionParser(usage="2to3 [options] file|dir ...") + parser.add_option("-d", "--doctests_only", action="store_true", + help="Fix up doctests only") + parser.add_option("-f", "--fix", action="append", default=[], +Index: Lib/lib2to3/pgen2/driver.py +=================================================================== +--- Lib/lib2to3/pgen2/driver.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/pgen2/driver.py (.../branches/release26-maint) (Revision 70449) +@@ -77,7 +77,8 @@ + column = 0 + else: + # We never broke out -- EOF is too soon (how can this happen???) +- raise parse.ParseError("incomplete input", t, v, x) ++ raise parse.ParseError("incomplete input", ++ type, value, (prefix, start)) + return p.rootnode + + def parse_stream_raw(self, stream, debug=False): +Index: Lib/lib2to3/refactor.py +=================================================================== +--- Lib/lib2to3/refactor.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/refactor.py (.../branches/release26-maint) (Revision 70449) +@@ -123,8 +123,8 @@ + logger=self.logger) + self.pre_order, self.post_order = self.get_fixers() + +- self.pre_order_mapping = get_headnode_dict(self.pre_order) +- self.post_order_mapping = get_headnode_dict(self.post_order) ++ self.pre_order_heads = get_headnode_dict(self.pre_order) ++ self.post_order_heads = get_headnode_dict(self.post_order) + + self.files = [] # List of files that were or should be modified + +@@ -287,17 +287,13 @@ + Returns: + True if the tree was modified, False otherwise. + """ +- # Two calls to chain are required because pre_order.values() +- # will be a list of lists of fixers: +- # [[, ], []] +- all_fixers = chain(self.pre_order, self.post_order) +- for fixer in all_fixers: ++ for fixer in chain(self.pre_order, self.post_order): + fixer.start_tree(tree, name) + +- self.traverse_by(self.pre_order_mapping, tree.pre_order()) +- self.traverse_by(self.post_order_mapping, tree.post_order()) ++ self.traverse_by(self.pre_order_heads, tree.pre_order()) ++ self.traverse_by(self.post_order_heads, tree.post_order()) + +- for fixer in all_fixers: ++ for fixer in chain(self.pre_order, self.post_order): + fixer.finish_tree(tree, name) + return tree.was_changed + +Index: Lib/lib2to3/fixer_base.py +=================================================================== +--- Lib/lib2to3/fixer_base.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixer_base.py (.../branches/release26-maint) (Revision 70449) +@@ -94,10 +94,6 @@ + """ + raise NotImplementedError() + +- def parenthesize(self, node): +- """Wrapper around pygram.parenthesize().""" +- return pygram.parenthesize(node) +- + def new_name(self, template="xxx_todo_changeme"): + """Return a string suitable for use as an identifier + +Index: Lib/lib2to3/fixes/fix_has_key.py +=================================================================== +--- Lib/lib2to3/fixes/fix_has_key.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_has_key.py (.../branches/release26-maint) (Revision 70449) +@@ -33,7 +33,7 @@ + from .. import pytree + from ..pgen2 import token + from .. import fixer_base +-from ..fixer_util import Name ++from ..fixer_util import Name, parenthesize + + + class FixHasKey(fixer_base.BaseFix): +@@ -86,7 +86,7 @@ + after = [n.clone() for n in after] + if arg.type in (syms.comparison, syms.not_test, syms.and_test, + syms.or_test, syms.test, syms.lambdef, syms.argument): +- arg = self.parenthesize(arg) ++ arg = parenthesize(arg) + if len(before) == 1: + before = before[0] + else: +@@ -98,12 +98,12 @@ + n_op = pytree.Node(syms.comp_op, (n_not, n_op)) + new = pytree.Node(syms.comparison, (arg, n_op, before)) + if after: +- new = self.parenthesize(new) ++ new = parenthesize(new) + new = pytree.Node(syms.power, (new,) + tuple(after)) + if node.parent.type in (syms.comparison, syms.expr, syms.xor_expr, + syms.and_expr, syms.shift_expr, + syms.arith_expr, syms.term, + syms.factor, syms.power): +- new = self.parenthesize(new) ++ new = parenthesize(new) + new.set_prefix(prefix) + return new +Index: Lib/lib2to3/fixes/fix_urllib.py +=================================================================== +--- Lib/lib2to3/fixes/fix_urllib.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_urllib.py (.../branches/release26-maint) (Revision 70449) +@@ -15,7 +15,10 @@ + '_urlopener', 'urlcleanup']), + ('urllib.parse', + ['quote', 'quote_plus', 'unquote', 'unquote_plus', +- 'urlencode', 'pahtname2url', 'url2pathname']), ++ 'urlencode', 'pathname2url', 'url2pathname', 'splitattr', ++ 'splithost', 'splitnport', 'splitpasswd', 'splitport', ++ 'splitquery', 'splittag', 'splittype', 'splituser', ++ 'splitvalue', ]), + ('urllib.error', + ['ContentTooShortError'])], + 'urllib2' : [ +@@ -29,19 +32,19 @@ + 'AbstractBasicAuthHandler', + 'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler', + 'AbstractDigestAuthHandler', +- 'HTTPDigestAuthHander', 'ProxyDigestAuthHandler', ++ 'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler', + 'HTTPHandler', 'HTTPSHandler', 'FileHandler', + 'FTPHandler', 'CacheFTPHandler', + 'UnknownHandler']), + ('urllib.error', +- ['URLError', 'HTTPError'])], ++ ['URLError', 'HTTPError']), ++ ] + } + ++# Duplicate the url parsing functions for urllib2. ++MAPPING["urllib2"].append(MAPPING["urllib"][1]) + +-# def alternates(members): +-# return "(" + "|".join(map(repr, members)) + ")" + +- + def build_pattern(): + bare = set() + for old_module, changes in MAPPING.items(): + +Eigenschaftsänderungen: Lib/lib2to3/fixes/fix_urllib.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Lib/lib2to3/fixes/fix_imports.py +=================================================================== +--- Lib/lib2to3/fixes/fix_imports.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_imports.py (.../branches/release26-maint) (Revision 70449) +@@ -25,7 +25,6 @@ + 'tkFont': 'tkinter.font', + 'tkMessageBox': 'tkinter.messagebox', + 'ScrolledText': 'tkinter.scrolledtext', +- 'turtle': 'tkinter.turtle', + 'Tkconstants': 'tkinter.constants', + 'Tix': 'tkinter.tix', + 'Tkinter': 'tkinter', +@@ -42,6 +41,8 @@ + 'DocXMLRPCServer': 'xmlrpc.server', + 'SimpleXMLRPCServer': 'xmlrpc.server', + 'httplib': 'http.client', ++ 'htmlentitydefs' : 'html.entities', ++ 'HTMLParser' : 'html.parser', + 'Cookie': 'http.cookies', + 'cookielib': 'http.cookiejar', + 'BaseHTTPServer': 'http.server', +@@ -64,16 +65,17 @@ + mod_list = ' | '.join(["module_name='%s'" % key for key in mapping]) + bare_names = alternates(mapping.keys()) + +- yield """name_import=import_name< 'import' ((%s) +- | dotted_as_names< any* (%s) any* >) > ++ yield """name_import=import_name< 'import' ((%s) | ++ multiple_imports=dotted_as_names< any* (%s) any* >) > + """ % (mod_list, mod_list) + yield """import_from< 'from' (%s) 'import' ['('] + ( any | import_as_name< any 'as' any > | + import_as_names< any* >) [')'] > + """ % mod_list +- yield """import_name< 'import' +- dotted_as_name< (%s) 'as' any > > +- """ % mod_list ++ yield """import_name< 'import' (dotted_as_name< (%s) 'as' any > | ++ multiple_imports=dotted_as_names< ++ any* dotted_as_name< (%s) 'as' any > any* >) > ++ """ % (mod_list, mod_list) + + # Find usages of module members in code e.g. thread.foo(bar) + yield "power< bare_with_attr=(%s) trailer<'.' any > any* >" % bare_names +@@ -86,6 +88,10 @@ + # This is overridden in fix_imports2. + mapping = MAPPING + ++ # We want to run this fixer late, so fix_import doesn't try to make stdlib ++ # renames into relative imports. ++ run_order = 6 ++ + def build_pattern(self): + return "|".join(build_pattern(self.mapping)) + +@@ -100,8 +106,8 @@ + match = super(FixImports, self).match + results = match(node) + if results: +- # Module usage could be in the trailier of an attribute lookup, so +- # we might have nested matches when "bare_with_attr" is present. ++ # Module usage could be in the trailer of an attribute lookup, so we ++ # might have nested matches when "bare_with_attr" is present. + if "bare_with_attr" not in results and \ + any([match(obj) for obj in attr_chain(node, "parent")]): + return False +@@ -115,12 +121,20 @@ + def transform(self, node, results): + import_mod = results.get("module_name") + if import_mod: +- new_name = self.mapping[(import_mod or mod_name).value] ++ new_name = self.mapping[import_mod.value] ++ import_mod.replace(Name(new_name, prefix=import_mod.get_prefix())) + if "name_import" in results: + # If it's not a "from x import x, y" or "import x as y" import, + # marked its usage to be replaced. + self.replace[import_mod.value] = new_name +- import_mod.replace(Name(new_name, prefix=import_mod.get_prefix())) ++ if "multiple_imports" in results: ++ # This is a nasty hack to fix multiple imports on a ++ # line (e.g., "import StringIO, urlparse"). The problem is that I ++ # can't figure out an easy way to make a pattern recognize the ++ # keys of MAPPING randomly sprinkled in an import statement. ++ results = self.match(node) ++ if results: ++ self.transform(node, results) + else: + # Replace usage of the module. + bare_name = results["bare_with_attr"][0] +Index: Lib/lib2to3/fixes/fix_reduce.py +=================================================================== +--- Lib/lib2to3/fixes/fix_reduce.py (.../tags/r261) (Revision 0) ++++ Lib/lib2to3/fixes/fix_reduce.py (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,33 @@ ++# Copyright 2008 Armin Ronacher. ++# Licensed to PSF under a Contributor Agreement. ++ ++"""Fixer for reduce(). ++ ++Makes sure reduce() is imported from the functools module if reduce is ++used in that module. ++""" ++ ++from .. import pytree ++from .. import fixer_base ++from ..fixer_util import Name, Attr, touch_import ++ ++ ++ ++class FixReduce(fixer_base.BaseFix): ++ ++ PATTERN = """ ++ power< 'reduce' ++ trailer< '(' ++ arglist< ( ++ (not(argument) any ',' ++ not(argument ++ > ++ """ ++ ++ def transform(self, node, results): ++ touch_import('functools', 'reduce', node) +Index: Lib/lib2to3/fixes/fix_repr.py +=================================================================== +--- Lib/lib2to3/fixes/fix_repr.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_repr.py (.../branches/release26-maint) (Revision 70449) +@@ -5,7 +5,7 @@ + + # Local imports + from .. import fixer_base +-from ..fixer_util import Call, Name ++from ..fixer_util import Call, Name, parenthesize + + + class FixRepr(fixer_base.BaseFix): +@@ -18,5 +18,5 @@ + expr = results["expr"].clone() + + if expr.type == self.syms.testlist1: +- expr = self.parenthesize(expr) ++ expr = parenthesize(expr) + return Call(Name("repr"), [expr], prefix=node.get_prefix()) +Index: Lib/lib2to3/fixes/fix_import.py +=================================================================== +--- Lib/lib2to3/fixes/fix_import.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_import.py (.../branches/release26-maint) (Revision 70449) +@@ -13,52 +13,78 @@ + # Local imports + from .. import fixer_base + from os.path import dirname, join, exists, pathsep +-from ..fixer_util import FromImport ++from ..fixer_util import FromImport, syms, token + ++ ++def traverse_imports(names): ++ """ ++ Walks over all the names imported in a dotted_as_names node. ++ """ ++ pending = [names] ++ while pending: ++ node = pending.pop() ++ if node.type == token.NAME: ++ yield node.value ++ elif node.type == syms.dotted_name: ++ yield "".join([ch.value for ch in node.children]) ++ elif node.type == syms.dotted_as_name: ++ pending.append(node.children[0]) ++ elif node.type == syms.dotted_as_names: ++ pending.extend(node.children[::-2]) ++ else: ++ raise AssertionError("unkown node type") ++ ++ + class FixImport(fixer_base.BaseFix): + + PATTERN = """ +- import_from< type='from' imp=any 'import' ['('] any [')'] > ++ import_from< 'from' imp=any 'import' ['('] any [')'] > + | +- import_name< type='import' imp=any > ++ import_name< 'import' imp=any > + """ + + def transform(self, node, results): + imp = results['imp'] + +- if unicode(imp).startswith('.'): +- # Already a new-style import +- return +- +- if not probably_a_local_import(unicode(imp), self.filename): +- # I guess this is a global import -- skip it! +- return +- +- if results['type'].value == 'from': ++ if node.type == syms.import_from: + # Some imps are top-level (eg: 'import ham') + # some are first level (eg: 'import ham.eggs') + # some are third level (eg: 'import ham.eggs as spam') + # Hence, the loop + while not hasattr(imp, 'value'): + imp = imp.children[0] +- imp.value = "." + imp.value +- node.changed() ++ if self.probably_a_local_import(imp.value): ++ imp.value = "." + imp.value ++ imp.changed() ++ return node + else: +- new = FromImport('.', getattr(imp, 'content', None) or [imp]) ++ have_local = False ++ have_absolute = False ++ for mod_name in traverse_imports(imp): ++ if self.probably_a_local_import(mod_name): ++ have_local = True ++ else: ++ have_absolute = True ++ if have_absolute: ++ if have_local: ++ # We won't handle both sibling and absolute imports in the ++ # same statement at the moment. ++ self.warning(node, "absolute and local imports together") ++ return ++ ++ new = FromImport('.', [imp]) + new.set_prefix(node.get_prefix()) +- node = new +- return node ++ return new + +-def probably_a_local_import(imp_name, file_path): +- # Must be stripped because the right space is included by the parser +- imp_name = imp_name.split('.', 1)[0].strip() +- base_path = dirname(file_path) +- base_path = join(base_path, imp_name) +- # If there is no __init__.py next to the file its not in a package +- # so can't be a relative import. +- if not exists(join(dirname(base_path), '__init__.py')): ++ def probably_a_local_import(self, imp_name): ++ imp_name = imp_name.split('.', 1)[0] ++ base_path = dirname(self.filename) ++ base_path = join(base_path, imp_name) ++ # If there is no __init__.py next to the file its not in a package ++ # so can't be a relative import. ++ if not exists(join(dirname(base_path), '__init__.py')): ++ return False ++ for ext in ['.py', pathsep, '.pyc', '.so', '.sl', '.pyd']: ++ if exists(base_path + ext): ++ return True + return False +- for ext in ['.py', pathsep, '.pyc', '.so', '.sl', '.pyd']: +- if exists(base_path + ext): +- return True +- return False +Index: Lib/lib2to3/fixes/fix_xrange.py +=================================================================== +--- Lib/lib2to3/fixes/fix_xrange.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_xrange.py (.../branches/release26-maint) (Revision 70449) +@@ -12,7 +12,9 @@ + class FixXrange(fixer_base.BaseFix): + + PATTERN = """ +- power< (name='range'|name='xrange') trailer< '(' [any] ')' > any* > ++ power< ++ (name='range'|name='xrange') trailer< '(' args=any ')' > ++ rest=any* > + """ + + def transform(self, node, results): +@@ -30,11 +32,14 @@ + + def transform_range(self, node, results): + if not self.in_special_context(node): +- arg = node.clone() +- arg.set_prefix("") +- call = Call(Name("list"), [arg]) +- call.set_prefix(node.get_prefix()) +- return call ++ range_call = Call(Name("range"), [results["args"].clone()]) ++ # Encase the range call in list(). ++ list_call = Call(Name("list"), [range_call], ++ prefix=node.get_prefix()) ++ # Put things that were after the range() call after the list call. ++ for n in results["rest"]: ++ list_call.append_child(n) ++ return list_call + return node + + P1 = "power< func=NAME trailer< '(' node=any ')' > any* >" +Index: Lib/lib2to3/fixes/fix_execfile.py +=================================================================== +--- Lib/lib2to3/fixes/fix_execfile.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_execfile.py (.../branches/release26-maint) (Revision 70449) +@@ -7,9 +7,9 @@ + exec() function. + """ + +-from .. import pytree + from .. import fixer_base +-from ..fixer_util import Comma, Name, Call, LParen, RParen, Dot ++from ..fixer_util import (Comma, Name, Call, LParen, RParen, Dot, Node, ++ ArgList, String, syms) + + + class FixExecfile(fixer_base.BaseFix): +@@ -22,16 +22,30 @@ + + def transform(self, node, results): + assert results +- syms = self.syms + filename = results["filename"] + globals = results.get("globals") + locals = results.get("locals") +- args = [Name('open'), LParen(), filename.clone(), RParen(), Dot(), +- Name('read'), LParen(), RParen()] +- args[0].set_prefix("") ++ ++ # Copy over the prefix from the right parentheses end of the execfile ++ # call. ++ execfile_paren = node.children[-1].children[-1].clone() ++ # Construct open().read(). ++ open_args = ArgList([filename.clone()], rparen=execfile_paren) ++ open_call = Node(syms.power, [Name("open"), open_args]) ++ read = [Node(syms.trailer, [Dot(), Name('read')]), ++ Node(syms.trailer, [LParen(), RParen()])] ++ open_expr = [open_call] + read ++ # Wrap the open call in a compile call. This is so the filename will be ++ # preserved in the execed code. ++ filename_arg = filename.clone() ++ filename_arg.set_prefix(" ") ++ exec_str = String("'exec'", " ") ++ compile_args = open_expr + [Comma(), filename_arg, Comma(), exec_str] ++ compile_call = Call(Name("compile"), compile_args, "") ++ # Finally, replace the execfile call with an exec call. ++ args = [compile_call] + if globals is not None: + args.extend([Comma(), globals.clone()]) + if locals is not None: + args.extend([Comma(), locals.clone()]) +- + return Call(Name("exec"), args, prefix=node.get_prefix()) +Index: Lib/lib2to3/fixes/fix_apply.py +=================================================================== +--- Lib/lib2to3/fixes/fix_apply.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_apply.py (.../branches/release26-maint) (Revision 70449) +@@ -9,7 +9,7 @@ + from .. import pytree + from ..pgen2 import token + from .. import fixer_base +-from ..fixer_util import Call, Comma ++from ..fixer_util import Call, Comma, parenthesize + + class FixApply(fixer_base.BaseFix): + +@@ -39,7 +39,7 @@ + (func.type != syms.power or + func.children[-2].type == token.DOUBLESTAR)): + # Need to parenthesize +- func = self.parenthesize(func) ++ func = parenthesize(func) + func.set_prefix("") + args = args.clone() + args.set_prefix("") +Index: Lib/lib2to3/fixes/fix_long.py +=================================================================== +--- Lib/lib2to3/fixes/fix_long.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_long.py (.../branches/release26-maint) (Revision 70449) +@@ -2,34 +2,21 @@ + # Licensed to PSF under a Contributor Agreement. + + """Fixer that turns 'long' into 'int' everywhere. +- +-This also strips the trailing 'L' or 'l' from long loterals. + """ + + # Local imports +-from .. import pytree + from .. import fixer_base +-from ..fixer_util import Name, Number ++from ..fixer_util import Name, Number, is_probably_builtin + + + class FixLong(fixer_base.BaseFix): + +- PATTERN = """ +- (long_type = 'long' | number = NUMBER) +- """ ++ PATTERN = "'long'" + +- static_long = Name("long") + static_int = Name("int") + + def transform(self, node, results): +- long_type = results.get("long_type") +- number = results.get("number") +- new = None +- if long_type: +- assert node == self.static_long, node ++ if is_probably_builtin(node): + new = self.static_int.clone() +- if number and node.value[-1] in ("l", "L"): +- new = Number(node.value[:-1]) +- if new is not None: + new.set_prefix(node.get_prefix()) + return new +Index: Lib/lib2to3/fixes/fix_intern.py +=================================================================== +--- Lib/lib2to3/fixes/fix_intern.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_intern.py (.../branches/release26-maint) (Revision 70449) +@@ -8,7 +8,7 @@ + # Local imports + from .. import pytree + from .. import fixer_base +-from ..fixer_util import Name, Attr ++from ..fixer_util import Name, Attr, touch_import + + + class FixIntern(fixer_base.BaseFix): +@@ -40,4 +40,5 @@ + newarglist, + results["rpar"].clone()])] + after) + new.set_prefix(node.get_prefix()) ++ touch_import(None, 'sys', node) + return new +Index: Lib/lib2to3/fixes/fix_isinstance.py +=================================================================== +--- Lib/lib2to3/fixes/fix_isinstance.py (.../tags/r261) (Revision 0) ++++ Lib/lib2to3/fixes/fix_isinstance.py (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,52 @@ ++# Copyright 2008 Armin Ronacher. ++# Licensed to PSF under a Contributor Agreement. ++ ++"""Fixer that cleans up a tuple argument to isinstance after the tokens ++in it were fixed. This is mainly used to remove double occurrences of ++tokens as a leftover of the long -> int / unicode -> str conversion. ++ ++eg. isinstance(x, (int, long)) -> isinstance(x, (int, int)) ++ -> isinstance(x, int) ++""" ++ ++from .. import fixer_base ++from ..fixer_util import token ++ ++ ++class FixIsinstance(fixer_base.BaseFix): ++ ++ PATTERN = """ ++ power< ++ 'isinstance' ++ trailer< '(' arglist< any ',' atom< '(' ++ args=testlist_gexp< any+ > ++ ')' > > ')' > ++ > ++ """ ++ ++ run_order = 6 ++ ++ def transform(self, node, results): ++ names_inserted = set() ++ testlist = results["args"] ++ args = testlist.children ++ new_args = [] ++ iterator = enumerate(args) ++ for idx, arg in iterator: ++ if arg.type == token.NAME and arg.value in names_inserted: ++ if idx < len(args) - 1 and args[idx + 1].type == token.COMMA: ++ iterator.next() ++ continue ++ else: ++ new_args.append(arg) ++ if arg.type == token.NAME: ++ names_inserted.add(arg.value) ++ if new_args and new_args[-1].type == token.COMMA: ++ del new_args[-1] ++ if len(new_args) == 1: ++ atom = testlist.parent ++ new_args[0].set_prefix(atom.get_prefix()) ++ atom.replace(new_args[0]) ++ else: ++ args[:] = new_args ++ node.changed() +Index: Lib/lib2to3/fixes/fix_metaclass.py +=================================================================== +--- Lib/lib2to3/fixes/fix_metaclass.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_metaclass.py (.../branches/release26-maint) (Revision 70449) +@@ -110,8 +110,11 @@ + if simple_node.type == syms.simple_stmt and simple_node.children: + expr_node = simple_node.children[0] + if expr_node.type == syms.expr_stmt and expr_node.children: +- leaf_node = expr_node.children[0] +- if leaf_node.value == '__metaclass__': ++ # Check if the expr_node is a simple assignment. ++ left_node = expr_node.children[0] ++ if isinstance(left_node, Leaf) and \ ++ left_node.value == '__metaclass__': ++ # We found a assignment to __metaclass__. + fixup_simple_stmt(node, i, simple_node) + remove_trailing_newline(simple_node) + yield (node, i, simple_node) +Index: Lib/lib2to3/fixes/fix_imports2.py +=================================================================== +--- Lib/lib2to3/fixes/fix_imports2.py (.../tags/r261) (Revision 70449) ++++ Lib/lib2to3/fixes/fix_imports2.py (.../branches/release26-maint) (Revision 70449) +@@ -11,6 +11,6 @@ + + class FixImports2(fix_imports.FixImports): + +- order = "post" ++ run_order = 7 + + mapping = MAPPING + +Eigenschaftsänderungen: Lib/lib2to3/fixes/fix_imports2.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + + +Eigenschaftsänderungen: Lib/lib2to3 +___________________________________________________________________ +Geändert: svnmerge-integrated + - /sandbox/trunk/2to3/lib2to3:1-67179 + + /sandbox/trunk/2to3/lib2to3:1-67373 + +Index: Lib/bdb.py +=================================================================== +--- Lib/bdb.py (.../tags/r261) (Revision 70449) ++++ Lib/bdb.py (.../branches/release26-maint) (Revision 70449) +@@ -347,7 +347,7 @@ + rv = frame.f_locals['__return__'] + s = s + '->' + s = s + repr.repr(rv) +- line = linecache.getline(filename, lineno) ++ line = linecache.getline(filename, lineno, frame.f_globals) + if line: s = s + lprefix + line.strip() + return s + +@@ -589,7 +589,7 @@ + name = frame.f_code.co_name + if not name: name = '???' + fn = self.canonic(frame.f_code.co_filename) +- line = linecache.getline(fn, frame.f_lineno) ++ line = linecache.getline(fn, frame.f_lineno, frame.f_globals) + print '+++', fn, frame.f_lineno, name, ':', line.strip() + def user_return(self, frame, retval): + print '+++ return', retval +Index: Lib/lib-tk/tkColorChooser.py +=================================================================== +--- Lib/lib-tk/tkColorChooser.py (.../tags/r261) (Revision 70449) ++++ Lib/lib-tk/tkColorChooser.py (.../branches/release26-maint) (Revision 70449) +@@ -34,19 +34,22 @@ + try: + # make sure initialcolor is a tk color string + color = self.options["initialcolor"] +- if type(color) == type(()): ++ if isinstance(color, tuple): + # assume an RGB triplet + self.options["initialcolor"] = "#%02x%02x%02x" % color + except KeyError: + pass + + def _fixresult(self, widget, result): ++ # result can be somethings: an empty tuple, an empty string or ++ # a Tcl_Obj, so this somewhat weird check handles that ++ if not result or not str(result): ++ return None, None # canceled ++ + # to simplify application code, the color chooser returns + # an RGB tuple together with the Tk color string +- if not result: +- return None, None # canceled + r, g, b = widget.winfo_rgb(result) +- return (r/256, g/256, b/256), result ++ return (r/256, g/256, b/256), str(result) + + + # +@@ -66,5 +69,4 @@ + # test stuff + + if __name__ == "__main__": +- + print "color", askcolor() +Index: Lib/lib-tk/ScrolledText.py +=================================================================== +--- Lib/lib-tk/ScrolledText.py (.../tags/r261) (Revision 70449) ++++ Lib/lib-tk/ScrolledText.py (.../branches/release26-maint) (Revision 70449) +@@ -1,43 +1,52 @@ +-# A ScrolledText widget feels like a text widget but also has a +-# vertical scroll bar on its right. (Later, options may be added to +-# add a horizontal bar as well, to make the bars disappear +-# automatically when not needed, to move them to the other side of the +-# window, etc.) +-# +-# Configuration options are passed to the Text widget. +-# A Frame widget is inserted between the master and the text, to hold +-# the Scrollbar widget. +-# Most methods calls are inherited from the Text widget; Pack methods +-# are redirected to the Frame widget however. ++"""A ScrolledText widget feels like a text widget but also has a ++vertical scroll bar on its right. (Later, options may be added to ++add a horizontal bar as well, to make the bars disappear ++automatically when not needed, to move them to the other side of the ++window, etc.) + +-from Tkinter import * +-from Tkinter import _cnfmerge ++Configuration options are passed to the Text widget. ++A Frame widget is inserted between the master and the text, to hold ++the Scrollbar widget. ++Most methods calls are inherited from the Text widget; Pack, Grid and ++Place methods are redirected to the Frame widget however. ++""" + ++__all__ = ['ScrolledText'] ++ ++from Tkinter import Frame, Text, Scrollbar, Pack, Grid, Place ++from Tkconstants import RIGHT, LEFT, Y, BOTH ++ + class ScrolledText(Text): +- def __init__(self, master=None, cnf=None, **kw): +- if cnf is None: +- cnf = {} +- if kw: +- cnf = _cnfmerge((cnf, kw)) +- fcnf = {} +- for k in cnf.keys(): +- if type(k) == ClassType or k == 'name': +- fcnf[k] = cnf[k] +- del cnf[k] +- self.frame = Frame(master, **fcnf) +- self.vbar = Scrollbar(self.frame, name='vbar') ++ def __init__(self, master=None, **kw): ++ self.frame = Frame(master) ++ self.vbar = Scrollbar(self.frame) + self.vbar.pack(side=RIGHT, fill=Y) +- cnf['name'] = 'text' +- Text.__init__(self, self.frame, **cnf) +- self.pack(side=LEFT, fill=BOTH, expand=1) +- self['yscrollcommand'] = self.vbar.set ++ ++ kw.update({'yscrollcommand': self.vbar.set}) ++ Text.__init__(self, self.frame, **kw) ++ self.pack(side=LEFT, fill=BOTH, expand=True) + self.vbar['command'] = self.yview + + # Copy geometry methods of self.frame -- hack! +- methods = Pack.__dict__.keys() +- methods = methods + Grid.__dict__.keys() +- methods = methods + Place.__dict__.keys() ++ methods = vars(Pack).keys() + vars(Grid).keys() + vars(Place).keys() + + for m in methods: + if m[0] != '_' and m != 'config' and m != 'configure': + setattr(self, m, getattr(self.frame, m)) ++ ++ def __str__(self): ++ return str(self.frame) ++ ++ ++def example(): ++ import __main__ ++ from Tkconstants import END ++ ++ stext = ScrolledText(bg='white', height=10) ++ stext.insert(END, __main__.__doc__) ++ stext.pack(fill=BOTH, side=LEFT, expand=True) ++ stext.focus_set() ++ stext.mainloop() ++ ++if __name__ == "__main__": ++ example() +Index: Lib/lib-tk/turtle.py +=================================================================== +--- Lib/lib-tk/turtle.py (.../tags/r261) (Revision 70449) ++++ Lib/lib-tk/turtle.py (.../branches/release26-maint) (Revision 70449) +@@ -38,7 +38,7 @@ + ----- turtle.py + + This module is an extended reimplementation of turtle.py from the +-Python standard distribution up to Python 2.5. (See: http:\\www.python.org) ++Python standard distribution up to Python 2.5. (See: http://www.python.org) + + It tries to keep the merits of turtle.py and to be (nearly) 100% + compatible with it. This means in the first place to enable the +@@ -54,8 +54,8 @@ + + - Different turtle shapes, gif-images as turtle shapes, user defined + and user controllable turtle shapes, among them compound +- (multicolored) shapes. Turtle shapes can be stgretched and tilted, which +- makes turtles zu very versatile geometrical objects. ++ (multicolored) shapes. Turtle shapes can be stretched and tilted, which ++ makes turtles very versatile geometrical objects. + + - Fine control over turtle movement and screen updates via delay(), + and enhanced tracer() and speed() methods. +@@ -64,7 +64,7 @@ + following the early Logo traditions. This reduces the boring work of + typing long sequences of commands, which often occur in a natural way + when kids try to program fancy pictures on their first encounter with +- turtle graphcis. ++ turtle graphics. + + - Turtles now have an undo()-method with configurable undo-buffer. + +@@ -91,12 +91,12 @@ + + - If configured appropriately the module reads in docstrings from a docstring + dictionary in some different language, supplied separately and replaces +- the english ones by those read in. There is a utility function +- write_docstringdict() to write a dictionary with the original (english) ++ the English ones by those read in. There is a utility function ++ write_docstringdict() to write a dictionary with the original (English) + docstrings to disc, so it can serve as a template for translations. + + Behind the scenes there are some features included with possible +-extensionsin in mind. These will be commented and documented elsewhere. ++extensions in in mind. These will be commented and documented elsewhere. + + """ + +@@ -299,7 +299,7 @@ + + ############################################################################## + ### From here up to line : Tkinter - Interface for turtle.py ### +-### May be replaced by an interface to some different graphcis-toolkit ### ++### May be replaced by an interface to some different graphics toolkit ### + ############################################################################## + + ## helper functions for Scrolled Canvas, to forward Canvas-methods +@@ -382,7 +382,7 @@ + self._rootwindow.bind('', self.onResize) + + def reset(self, canvwidth=None, canvheight=None, bg = None): +- """Ajust canvas and scrollbars according to given canvas size.""" ++ """Adjust canvas and scrollbars according to given canvas size.""" + if canvwidth: + self.canvwidth = canvwidth + if canvheight: +@@ -777,7 +777,7 @@ + self.cv.coords(item, *newcoordlist) + + def _resize(self, canvwidth=None, canvheight=None, bg=None): +- """Resize the canvas, the turtles are drawing on. Does ++ """Resize the canvas the turtles are drawing on. Does + not alter the drawing window. + """ + # needs amendment +@@ -952,7 +952,7 @@ + def clear(self): + """Delete all drawings and all turtles from the TurtleScreen. + +- Reset empty TurtleScreen to it's initial state: white background, ++ Reset empty TurtleScreen to its initial state: white background, + no backgroundimage, no eventbindings and tracing on. + + No argument. +@@ -1318,7 +1318,7 @@ + fun -- a function with no arguments + key -- a string: key (e.g. "a") or key-symbol (e.g. "space") + +- In order ro be able to register key-events, TurtleScreen ++ In order to be able to register key-events, TurtleScreen + must have focus. (See method listen.) + + Example (for a TurtleScreen instance named screen +@@ -1400,7 +1400,7 @@ + self._bgpicname = picname + + def screensize(self, canvwidth=None, canvheight=None, bg=None): +- """Resize the canvas, the turtles are drawing on. ++ """Resize the canvas the turtles are drawing on. + + Optional arguments: + canvwidth -- positive integer, new width of canvas in pixels +@@ -1693,8 +1693,8 @@ + + No arguments. + +- Move turtle to the origin - coordinates (0,0) and set it's +- heading to it's start-orientation (which depends on mode). ++ Move turtle to the origin - coordinates (0,0) and set its ++ heading to its start-orientation (which depends on mode). + + Example (for a Turtle instance named turtle): + >>> turtle.home() +@@ -2266,7 +2266,7 @@ + "outline" : positive number + "tilt" : number + +- This dicionary can be used as argument for a subsequent ++ This dictionary can be used as argument for a subsequent + pen()-call to restore the former pen-state. Moreover one + or more of these attributes can be provided as keyword-arguments. + This can be used to set several pen attributes in one statement. +@@ -2414,7 +2414,7 @@ + class RawTurtle(TPen, TNavigator): + """Animation part of the RawTurtle. + Puts RawTurtle upon a TurtleScreen and provides tools for +- it's animation. ++ its animation. + """ + screens = [] + +@@ -2459,7 +2459,7 @@ + self._update() + + def reset(self): +- """Delete the turtle's drawings and restore it's default values. ++ """Delete the turtle's drawings and restore its default values. + + No argument. + , +@@ -2749,7 +2749,7 @@ + + Return the current tilt-angle, i. e. the angle between the + orientation of the turtleshape and the heading of the turtle +- (it's direction of movement). ++ (its direction of movement). + + Examples (for a Turtle instance named turtle): + >>> turtle.shape("circle") +@@ -2794,7 +2794,7 @@ + + def _drawturtle(self): + """Manages the correct rendering of the turtle with respect to +- it's shape, resizemode, strech and tilt etc.""" ++ its shape, resizemode, strech and tilt etc.""" + screen = self.screen + shape = screen._shapes[self.turtle.shapeIndex] + ttype = shape._type +@@ -2848,7 +2848,7 @@ + ############################## stamp stuff ############################### + + def stamp(self): +- """Stamp a copy of the turtleshape onto the canvas and return it's id. ++ """Stamp a copy of the turtleshape onto the canvas and return its id. + + No argument. + +Index: Lib/lib-tk/Tkinter.py +=================================================================== +--- Lib/lib-tk/Tkinter.py (.../tags/r261) (Revision 70449) ++++ Lib/lib-tk/Tkinter.py (.../branches/release26-maint) (Revision 70449) +@@ -3032,7 +3032,8 @@ + forwards=None, backwards=None, exact=None, + regexp=None, nocase=None, count=None, elide=None): + """Search PATTERN beginning from INDEX until STOPINDEX. +- Return the index of the first character of a match or an empty string.""" ++ Return the index of the first character of a match or an ++ empty string.""" + args = [self._w, 'search'] + if forwards: args.append('-forwards') + if backwards: args.append('-backwards') +@@ -3041,11 +3042,11 @@ + if nocase: args.append('-nocase') + if elide: args.append('-elide') + if count: args.append('-count'); args.append(count) +- if pattern[0] == '-': args.append('--') ++ if pattern and pattern[0] == '-': args.append('--') + args.append(pattern) + args.append(index) + if stopindex: args.append(stopindex) +- return self.tk.call(tuple(args)) ++ return str(self.tk.call(tuple(args))) + def see(self, index): + """Scroll such that the character at INDEX is visible.""" + self.tk.call(self._w, 'see', index) +Index: Lib/lib-tk/FixTk.py +=================================================================== +--- Lib/lib-tk/FixTk.py (.../tags/r261) (Revision 70449) ++++ Lib/lib-tk/FixTk.py (.../branches/release26-maint) (Revision 70449) +@@ -10,6 +10,40 @@ + # \..\tcl, so anything close to + # the real Tcl library will do. + ++# Expand symbolic links on Vista ++try: ++ import ctypes ++ ctypes.windll.kernel32.GetFinalPathNameByHandleW ++except (ImportError, AttributeError): ++ def convert_path(s): ++ return s ++else: ++ def convert_path(s): ++ if isinstance(s, str): ++ s = s.decode("mbcs") ++ hdir = ctypes.windll.kernel32.\ ++ CreateFileW(s, 0x80, # FILE_READ_ATTRIBUTES ++ 1, # FILE_SHARE_READ ++ None, 3, # OPEN_EXISTING ++ 0x02000000, # FILE_FLAG_BACKUP_SEMANTICS ++ None) ++ if hdir == -1: ++ # Cannot open directory, give up ++ return s ++ buf = ctypes.create_unicode_buffer(u"", 32768) ++ res = ctypes.windll.kernel32.\ ++ GetFinalPathNameByHandleW(hdir, buf, len(buf), ++ 0) # VOLUME_NAME_DOS ++ ctypes.windll.kernel32.CloseHandle(hdir) ++ if res == 0: ++ # Conversion failed (e.g. network location) ++ return s ++ s = buf[:res] ++ # Ignore leading \\?\ ++ if s.startswith(u"\\\\?\\"): ++ s = s[4:] ++ return s ++ + prefix = os.path.join(sys.prefix,"tcl") + if not os.path.exists(prefix): + # devdir/../tcltk/lib +@@ -17,6 +51,7 @@ + prefix = os.path.abspath(prefix) + # if this does not exist, no further search is needed + if os.path.exists(prefix): ++ prefix = convert_path(prefix) + if not os.environ.has_key("TCL_LIBRARY"): + for name in os.listdir(prefix): + if name.startswith("tcl"): +Index: Lib/zipfile.py +=================================================================== +--- Lib/zipfile.py (.../tags/r261) (Revision 70449) ++++ Lib/zipfile.py (.../branches/release26-maint) (Revision 70449) +@@ -2,7 +2,7 @@ + Read and write ZIP files. + """ + import struct, os, time, sys, shutil +-import binascii, cStringIO ++import binascii, cStringIO, stat + + try: + import zlib # We may need its compression method +@@ -26,7 +26,7 @@ + + error = BadZipfile # The exception raised by this module + +-ZIP64_LIMIT= (1 << 31) - 1 ++ZIP64_LIMIT = (1 << 31) - 1 + ZIP_FILECOUNT_LIMIT = 1 << 16 + ZIP_MAX_COMMENT = (1 << 16) - 1 + +@@ -196,13 +196,9 @@ + # Append a blank comment and record start offset + endrec.append("") + endrec.append(filesize - sizeEndCentDir) +- if endrec[_ECD_OFFSET] == 0xffffffff: +- # the value for the "offset of the start of the central directory" +- # indicates that there is a "Zip64 end of central directory" +- # structure present, so go look for it +- return _EndRecData64(fpin, -sizeEndCentDir, endrec) + +- return endrec ++ # Try to read the "Zip64 end of central directory" structure ++ return _EndRecData64(fpin, -sizeEndCentDir, endrec) + + # Either this is not a ZIP file, or it is a ZIP file with an archive + # comment. Search the end of the file for the "end of central directory" +@@ -223,12 +219,11 @@ + # Append the archive comment and start offset + endrec.append(comment) + endrec.append(maxCommentStart + start) +- if endrec[_ECD_OFFSET] == 0xffffffff: +- # There is apparently a "Zip64 end of central directory" +- # structure present, so go look for it +- return _EndRecData64(fpin, start - filesize, endrec) +- return endrec + ++ # Try to read the "Zip64 end of central directory" structure ++ return _EndRecData64(fpin, maxCommentStart + start - filesize, ++ endrec) ++ + # Unable to find a valid end of central directory structure + return + +@@ -945,11 +940,11 @@ + """ + # build the destination pathname, replacing + # forward slashes to platform specific separators. +- if targetpath[-1:] == "/": ++ if targetpath[-1:] in (os.path.sep, os.path.altsep): + targetpath = targetpath[:-1] + + # don't include leading "/" from file name if present +- if os.path.isabs(member.filename): ++ if member.filename[0] == '/': + targetpath = os.path.join(targetpath, member.filename[1:]) + else: + targetpath = os.path.join(targetpath, member.filename) +@@ -961,6 +956,10 @@ + if upperdirs and not os.path.exists(upperdirs): + os.makedirs(upperdirs) + ++ if member.filename[-1] == '/': ++ os.mkdir(targetpath) ++ return targetpath ++ + source = self.open(member, pwd=pwd) + target = file(targetpath, "wb") + shutil.copyfileobj(source, target) +@@ -1000,6 +999,7 @@ + "Attempt to write to ZIP archive that was already closed") + + st = os.stat(filename) ++ isdir = stat.S_ISDIR(st.st_mode) + mtime = time.localtime(st.st_mtime) + date_time = mtime[0:6] + # Create ZipInfo instance to store file information +@@ -1008,6 +1008,8 @@ + arcname = os.path.normpath(os.path.splitdrive(arcname)[1]) + while arcname[0] in (os.sep, os.altsep): + arcname = arcname[1:] ++ if isdir: ++ arcname += '/' + zinfo = ZipInfo(arcname, date_time) + zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes + if compress_type is None: +@@ -1021,6 +1023,16 @@ + + self._writecheck(zinfo) + self._didModify = True ++ ++ if isdir: ++ zinfo.file_size = 0 ++ zinfo.compress_size = 0 ++ zinfo.CRC = 0 ++ self.filelist.append(zinfo) ++ self.NameToInfo[zinfo.filename] = zinfo ++ self.fp.write(zinfo.FileHeader()) ++ return ++ + fp = open(filename, "rb") + # Must overwrite CRC and sizes with correct data later + zinfo.CRC = CRC = 0 +@@ -1175,19 +1187,26 @@ + + pos2 = self.fp.tell() + # Write end-of-zip-archive record ++ centDirCount = count ++ centDirSize = pos2 - pos1 + centDirOffset = pos1 +- if pos1 > ZIP64_LIMIT: ++ if (centDirCount >= ZIP_FILECOUNT_LIMIT or ++ centDirOffset > ZIP64_LIMIT or ++ centDirSize > ZIP64_LIMIT): + # Need to write the ZIP64 end-of-archive records + zip64endrec = struct.pack( + structEndArchive64, stringEndArchive64, +- 44, 45, 45, 0, 0, count, count, pos2 - pos1, pos1) ++ 44, 45, 45, 0, 0, centDirCount, centDirCount, ++ centDirSize, centDirOffset) + self.fp.write(zip64endrec) + + zip64locrec = struct.pack( + structEndArchive64Locator, + stringEndArchive64Locator, 0, pos2, 1) + self.fp.write(zip64locrec) +- centDirOffset = 0xFFFFFFFF ++ centDirCount = min(centDirCount, 0xFFFF) ++ centDirSize = min(centDirSize, 0xFFFFFFFF) ++ centDirOffset = min(centDirOffset, 0xFFFFFFFF) + + # check for valid comment length + if len(self.comment) >= ZIP_MAX_COMMENT: +@@ -1197,9 +1216,8 @@ + self.comment = self.comment[:ZIP_MAX_COMMENT] + + endrec = struct.pack(structEndArchive, stringEndArchive, +- 0, 0, count % ZIP_FILECOUNT_LIMIT, +- count % ZIP_FILECOUNT_LIMIT, pos2 - pos1, +- centDirOffset, len(self.comment)) ++ 0, 0, centDirCount, centDirCount, ++ centDirSize, centDirOffset, len(self.comment)) + self.fp.write(endrec) + self.fp.write(self.comment) + self.fp.flush() +Index: Lib/doctest.py +=================================================================== +--- Lib/doctest.py (.../tags/r261) (Revision 70449) ++++ Lib/doctest.py (.../branches/release26-maint) (Revision 70449) +@@ -820,7 +820,15 @@ + # given object's docstring. + try: + file = inspect.getsourcefile(obj) or inspect.getfile(obj) +- source_lines = linecache.getlines(file) ++ if module is not None: ++ # Supply the module globals in case the module was ++ # originally loaded via a PEP 302 loader and ++ # file is not a valid filesystem path ++ source_lines = linecache.getlines(file, module.__dict__) ++ else: ++ # No access to a loader, so assume it's a normal ++ # filesystem path ++ source_lines = linecache.getlines(file) + if not source_lines: + source_lines = None + except TypeError: +@@ -836,6 +844,8 @@ + globs = globs.copy() + if extraglobs is not None: + globs.update(extraglobs) ++ if '__name__' not in globs: ++ globs['__name__'] = '__main__' # provide a default module name + + # Recursively expore `obj`, extracting DocTests. + tests = [] +@@ -854,12 +864,12 @@ + """ + if module is None: + return True ++ elif inspect.getmodule(object) is not None: ++ return module is inspect.getmodule(object) + elif inspect.isfunction(object): + return module.__dict__ is object.func_globals + elif inspect.isclass(object): + return module.__name__ == object.__module__ +- elif inspect.getmodule(object) is not None: +- return module is inspect.getmodule(object) + elif hasattr(object, '__module__'): + return module.__name__ == object.__module__ + elif isinstance(object, property): +@@ -1433,8 +1443,10 @@ + d = self._name2ft + for name, (f, t) in other._name2ft.items(): + if name in d: +- print "*** DocTestRunner.merge: '" + name + "' in both" \ +- " testers; summing outcomes." ++ # Don't print here by default, since doing ++ # so breaks some of the buildbots ++ #print "*** DocTestRunner.merge: '" + name + "' in both" \ ++ # " testers; summing outcomes." + f2, t2 = d[name] + f = f + f2 + t = t + t2 +@@ -1927,6 +1939,8 @@ + globs = globs.copy() + if extraglobs is not None: + globs.update(extraglobs) ++ if '__name__' not in globs: ++ globs['__name__'] = '__main__' + + if raise_on_error: + runner = DebugRunner(verbose=verbose, optionflags=optionflags) +Index: Lib/httplib.py +=================================================================== +--- Lib/httplib.py (.../tags/r261) (Revision 70449) ++++ Lib/httplib.py (.../branches/release26-maint) (Revision 70449) +@@ -616,7 +616,7 @@ + while amt > 0: + chunk = self.fp.read(min(amt, MAXAMOUNT)) + if not chunk: +- raise IncompleteRead(s) ++ raise IncompleteRead(''.join(s), amt) + s.append(chunk) + amt -= len(chunk) + return ''.join(s) +@@ -1130,9 +1130,18 @@ + pass + + class IncompleteRead(HTTPException): +- def __init__(self, partial): ++ def __init__(self, partial, expected=None): + self.args = partial, + self.partial = partial ++ self.expected = expected ++ def __repr__(self): ++ if self.expected is not None: ++ e = ', %i more expected' % self.expected ++ else: ++ e = '' ++ return 'IncompleteRead(%i bytes read%s)' % (len(self.partial), e) ++ def __str__(self): ++ return repr(self) + + class ImproperConnectionState(HTTPException): + pass +Index: Lib/linecache.py +=================================================================== +--- Lib/linecache.py (.../tags/r261) (Revision 70449) ++++ Lib/linecache.py (.../branches/release26-maint) (Revision 70449) +@@ -88,21 +88,20 @@ + get_source = getattr(loader, 'get_source', None) + + if name and get_source: +- if basename.startswith(name.split('.')[-1]+'.'): +- try: +- data = get_source(name) +- except (ImportError, IOError): +- pass +- else: +- if data is None: +- # No luck, the PEP302 loader cannot find the source +- # for this module. +- return [] +- cache[filename] = ( +- len(data), None, +- [line+'\n' for line in data.splitlines()], fullname +- ) +- return cache[filename][2] ++ try: ++ data = get_source(name) ++ except (ImportError, IOError): ++ pass ++ else: ++ if data is None: ++ # No luck, the PEP302 loader cannot find the source ++ # for this module. ++ return [] ++ cache[filename] = ( ++ len(data), None, ++ [line+'\n' for line in data.splitlines()], fullname ++ ) ++ return cache[filename][2] + + # Try looking through the module search path. + +Index: Lib/subprocess.py +=================================================================== +--- Lib/subprocess.py (.../tags/r261) (Revision 70449) ++++ Lib/subprocess.py (.../branches/release26-maint) (Revision 70449) +@@ -594,21 +594,13 @@ + c2pread, c2pwrite, + errread, errwrite) + +- # On Windows, you cannot just redirect one or two handles: You +- # either have to redirect all three or none. If the subprocess +- # user has only redirected one or two handles, we are +- # automatically creating PIPEs for the rest. We should close +- # these after the process is started. See bug #1124861. + if mswindows: +- if stdin is None and p2cwrite is not None: +- os.close(p2cwrite) +- p2cwrite = None +- if stdout is None and c2pread is not None: +- os.close(c2pread) +- c2pread = None +- if stderr is None and errread is not None: +- os.close(errread) +- errread = None ++ if p2cwrite is not None: ++ p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0) ++ if c2pread is not None: ++ c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0) ++ if errread is not None: ++ errread = msvcrt.open_osfhandle(errread.Detach(), 0) + + if p2cwrite is not None: + self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) +@@ -692,13 +684,10 @@ + + if stdin is None: + p2cread = GetStdHandle(STD_INPUT_HANDLE) +- if p2cread is not None: +- pass +- elif stdin is None or stdin == PIPE: ++ if p2cread is None: ++ p2cread, _ = CreatePipe(None, 0) ++ elif stdin == PIPE: + p2cread, p2cwrite = CreatePipe(None, 0) +- # Detach and turn into fd +- p2cwrite = p2cwrite.Detach() +- p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0) + elif isinstance(stdin, int): + p2cread = msvcrt.get_osfhandle(stdin) + else: +@@ -708,13 +697,10 @@ + + if stdout is None: + c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) +- if c2pwrite is not None: +- pass +- elif stdout is None or stdout == PIPE: ++ if c2pwrite is None: ++ _, c2pwrite = CreatePipe(None, 0) ++ elif stdout == PIPE: + c2pread, c2pwrite = CreatePipe(None, 0) +- # Detach and turn into fd +- c2pread = c2pread.Detach() +- c2pread = msvcrt.open_osfhandle(c2pread, 0) + elif isinstance(stdout, int): + c2pwrite = msvcrt.get_osfhandle(stdout) + else: +@@ -724,13 +710,10 @@ + + if stderr is None: + errwrite = GetStdHandle(STD_ERROR_HANDLE) +- if errwrite is not None: +- pass +- elif stderr is None or stderr == PIPE: ++ if errwrite is None: ++ _, errwrite = CreatePipe(None, 0) ++ elif stderr == PIPE: + errread, errwrite = CreatePipe(None, 0) +- # Detach and turn into fd +- errread = errread.Detach() +- errread = msvcrt.open_osfhandle(errread, 0) + elif stderr == STDOUT: + errwrite = c2pwrite + elif isinstance(stderr, int): +@@ -1103,6 +1086,9 @@ + if data != "": + os.waitpid(self.pid, 0) + child_exception = pickle.loads(data) ++ for fd in (p2cwrite, c2pread, errread): ++ if fd is not None: ++ os.close(fd) + raise child_exception + + +Index: Lib/test/test_urllib2_localnet.py +=================================================================== +--- Lib/test/test_urllib2_localnet.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_urllib2_localnet.py (.../branches/release26-maint) (Revision 70449) +@@ -474,7 +474,7 @@ + # domain will be spared to serve its defined + # purpose. + # urllib2.urlopen, "http://www.sadflkjsasadf.com/") +- urllib2.urlopen, "http://www.python.invalid./") ++ urllib2.urlopen, "http://sadflkjsasf.i.nvali.d/") + + + def test_main(): +Index: Lib/test/test_xmlrpc.py +=================================================================== +--- Lib/test/test_xmlrpc.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_xmlrpc.py (.../branches/release26-maint) (Revision 70449) +@@ -9,6 +9,7 @@ + import mimetools + import httplib + import socket ++import StringIO + import os + from test import test_support + +@@ -639,9 +640,93 @@ + os.remove("xmldata.txt") + os.remove(test_support.TESTFN) + ++class FakeSocket: ++ ++ def __init__(self): ++ self.data = StringIO.StringIO() ++ ++ def send(self, buf): ++ self.data.write(buf) ++ return len(buf) ++ ++ def sendall(self, buf): ++ self.data.write(buf) ++ ++ def getvalue(self): ++ return self.data.getvalue() ++ ++ def makefile(self, x, y): ++ raise RuntimeError ++ ++class FakeTransport(xmlrpclib.Transport): ++ """A Transport instance that records instead of sending a request. ++ ++ This class replaces the actual socket used by httplib with a ++ FakeSocket object that records the request. It doesn't provide a ++ response. ++ """ ++ ++ def make_connection(self, host): ++ conn = xmlrpclib.Transport.make_connection(self, host) ++ conn._conn.sock = self.fake_socket = FakeSocket() ++ return conn ++ ++class TransportSubclassTestCase(unittest.TestCase): ++ ++ def issue_request(self, transport_class): ++ """Return an HTTP request made via transport_class.""" ++ transport = transport_class() ++ proxy = xmlrpclib.ServerProxy("http://example.com/", ++ transport=transport) ++ try: ++ proxy.pow(6, 8) ++ except RuntimeError: ++ return transport.fake_socket.getvalue() ++ return None ++ ++ def test_custom_user_agent(self): ++ class TestTransport(FakeTransport): ++ ++ def send_user_agent(self, conn): ++ xmlrpclib.Transport.send_user_agent(self, conn) ++ conn.putheader("X-Test", "test_custom_user_agent") ++ ++ req = self.issue_request(TestTransport) ++ self.assert_("X-Test: test_custom_user_agent\r\n" in req) ++ ++ def test_send_host(self): ++ class TestTransport(FakeTransport): ++ ++ def send_host(self, conn, host): ++ xmlrpclib.Transport.send_host(self, conn, host) ++ conn.putheader("X-Test", "test_send_host") ++ ++ req = self.issue_request(TestTransport) ++ self.assert_("X-Test: test_send_host\r\n" in req) ++ ++ def test_send_request(self): ++ class TestTransport(FakeTransport): ++ ++ def send_request(self, conn, url, body): ++ xmlrpclib.Transport.send_request(self, conn, url, body) ++ conn.putheader("X-Test", "test_send_request") ++ ++ req = self.issue_request(TestTransport) ++ self.assert_("X-Test: test_send_request\r\n" in req) ++ ++ def test_send_content(self): ++ class TestTransport(FakeTransport): ++ ++ def send_content(self, conn, body): ++ conn.putheader("X-Test", "test_send_content") ++ xmlrpclib.Transport.send_content(self, conn, body) ++ ++ req = self.issue_request(TestTransport) ++ self.assert_("X-Test: test_send_content\r\n" in req) ++ + def test_main(): + xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase, +- BinaryTestCase, FaultTestCase] ++ BinaryTestCase, FaultTestCase, TransportSubclassTestCase] + + # The test cases against a SimpleXMLRPCServer raise a socket error + # 10035 (WSAEWOULDBLOCK) in the server thread handle_request call when +Index: Lib/test/test_io.py +=================================================================== +--- Lib/test/test_io.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_io.py (.../branches/release26-maint) (Revision 70449) +@@ -232,6 +232,17 @@ + else: + self.fail("1/0 didn't raise an exception") + ++ # issue 5008 ++ def test_append_mode_tell(self): ++ with io.open(test_support.TESTFN, "wb") as f: ++ f.write(b"xxx") ++ with io.open(test_support.TESTFN, "ab", buffering=0) as f: ++ self.assertEqual(f.tell(), 3) ++ with io.open(test_support.TESTFN, "ab") as f: ++ self.assertEqual(f.tell(), 3) ++ with io.open(test_support.TESTFN, "a") as f: ++ self.assert_(f.tell() > 0) ++ + def test_destructor(self): + record = [] + class MyFileIO(io.FileIO): +@@ -272,6 +283,30 @@ + self.assertRaises(ValueError, io.open, test_support.TESTFN, 'w', + closefd=False) + ++ def testReadClosed(self): ++ with io.open(test_support.TESTFN, "w") as f: ++ f.write("egg\n") ++ with io.open(test_support.TESTFN, "r") as f: ++ file = io.open(f.fileno(), "r", closefd=False) ++ self.assertEqual(file.read(), "egg\n") ++ file.seek(0) ++ file.close() ++ self.assertRaises(ValueError, file.read) ++ ++ def test_no_closefd_with_filename(self): ++ # can't use closefd in combination with a file name ++ self.assertRaises(ValueError, ++ io.open, test_support.TESTFN, "r", closefd=False) ++ ++ def test_closefd_attr(self): ++ with io.open(test_support.TESTFN, "wb") as f: ++ f.write(b"egg\n") ++ with io.open(test_support.TESTFN, "r") as f: ++ self.assertEqual(f.buffer.raw.closefd, True) ++ file = io.open(f.fileno(), "r", closefd=False) ++ self.assertEqual(file.buffer.raw.closefd, False) ++ ++ + class MemorySeekTestMixin: + + def testInit(self): +@@ -530,8 +565,9 @@ + r = MockRawIO(()) + w = MockRawIO() + pair = io.BufferedRWPair(r, w) ++ self.assertFalse(pair.closed) + +- # XXX need implementation ++ # XXX More Tests + + + class BufferedRandomTest(unittest.TestCase): +@@ -656,8 +692,9 @@ + @classmethod + def lookupTestDecoder(cls, name): + if cls.codecEnabled and name == 'test_decoder': ++ latin1 = codecs.lookup('latin-1') + return codecs.CodecInfo( +- name='test_decoder', encode=None, decode=None, ++ name='test_decoder', encode=latin1.encode, decode=None, + incrementalencoder=None, + streamreader=None, streamwriter=None, + incrementaldecoder=cls) +@@ -816,9 +853,12 @@ + [ '\r\n', [ "unix\nwindows\r\n", "os9\rlast\nnonl" ] ], + [ '\r', [ "unix\nwindows\r", "\nos9\r", "last\nnonl" ] ], + ] ++ encodings = ( ++ 'utf-8', 'latin-1', ++ 'utf-16', 'utf-16-le', 'utf-16-be', ++ 'utf-32', 'utf-32-le', 'utf-32-be', ++ ) + +- encodings = ('utf-8', 'latin-1') +- + # Try a range of buffer sizes to test the case where \r is the last + # character in TextIOWrapper._pending_line. + for encoding in encodings: +@@ -1171,60 +1211,91 @@ + + self.assertEqual(buffer.seekable(), txt.seekable()) + +- def test_newline_decoder(self): +- import codecs +- decoder = codecs.getincrementaldecoder("utf-8")() +- decoder = io.IncrementalNewlineDecoder(decoder, translate=True) ++ def check_newline_decoder_utf8(self, decoder): ++ # UTF-8 specific tests for a newline decoder ++ def _check_decode(b, s, **kwargs): ++ # We exercise getstate() / setstate() as well as decode() ++ state = decoder.getstate() ++ self.assertEquals(decoder.decode(b, **kwargs), s) ++ decoder.setstate(state) ++ self.assertEquals(decoder.decode(b, **kwargs), s) + +- self.assertEquals(decoder.decode(b'\xe8\xa2\x88'), u"\u8888") ++ _check_decode(b'\xe8\xa2\x88', "\u8888") + +- self.assertEquals(decoder.decode(b'\xe8'), u"") +- self.assertEquals(decoder.decode(b'\xa2'), u"") +- self.assertEquals(decoder.decode(b'\x88'), u"\u8888") ++ _check_decode(b'\xe8', "") ++ _check_decode(b'\xa2', "") ++ _check_decode(b'\x88', "\u8888") + +- self.assertEquals(decoder.decode(b'\xe8'), u"") ++ _check_decode(b'\xe8', "") ++ _check_decode(b'\xa2', "") ++ _check_decode(b'\x88', "\u8888") ++ ++ _check_decode(b'\xe8', "") + self.assertRaises(UnicodeDecodeError, decoder.decode, b'', final=True) + +- decoder.setstate((b'', 0)) +- self.assertEquals(decoder.decode(b'\n'), u"\n") +- self.assertEquals(decoder.decode(b'\r'), u"") +- self.assertEquals(decoder.decode(b'', final=True), u"\n") +- self.assertEquals(decoder.decode(b'\r', final=True), u"\n") ++ decoder.reset() ++ _check_decode(b'\n', "\n") ++ _check_decode(b'\r', "") ++ _check_decode(b'', "\n", final=True) ++ _check_decode(b'\r', "\n", final=True) + +- self.assertEquals(decoder.decode(b'\r'), u"") +- self.assertEquals(decoder.decode(b'a'), u"\na") ++ _check_decode(b'\r', "") ++ _check_decode(b'a', "\na") + +- self.assertEquals(decoder.decode(b'\r\r\n'), u"\n\n") +- self.assertEquals(decoder.decode(b'\r'), u"") +- self.assertEquals(decoder.decode(b'\r'), u"\n") +- self.assertEquals(decoder.decode(b'\na'), u"\na") ++ _check_decode(b'\r\r\n', "\n\n") ++ _check_decode(b'\r', "") ++ _check_decode(b'\r', "\n") ++ _check_decode(b'\na', "\na") + +- self.assertEquals(decoder.decode(b'\xe8\xa2\x88\r\n'), u"\u8888\n") +- self.assertEquals(decoder.decode(b'\xe8\xa2\x88'), u"\u8888") +- self.assertEquals(decoder.decode(b'\n'), u"\n") +- self.assertEquals(decoder.decode(b'\xe8\xa2\x88\r'), u"\u8888") +- self.assertEquals(decoder.decode(b'\n'), u"\n") ++ _check_decode(b'\xe8\xa2\x88\r\n', "\u8888\n") ++ _check_decode(b'\xe8\xa2\x88', "\u8888") ++ _check_decode(b'\n', "\n") ++ _check_decode(b'\xe8\xa2\x88\r', "\u8888") ++ _check_decode(b'\n', "\n") + +- decoder = codecs.getincrementaldecoder("utf-8")() +- decoder = io.IncrementalNewlineDecoder(decoder, translate=True) ++ def check_newline_decoder(self, decoder, encoding): ++ result = [] ++ encoder = codecs.getincrementalencoder(encoding)() ++ def _decode_bytewise(s): ++ for b in encoder.encode(s): ++ result.append(decoder.decode(b)) + self.assertEquals(decoder.newlines, None) +- decoder.decode(b"abc\n\r") +- self.assertEquals(decoder.newlines, u'\n') +- decoder.decode(b"\nabc") ++ _decode_bytewise("abc\n\r") ++ self.assertEquals(decoder.newlines, '\n') ++ _decode_bytewise("\nabc") + self.assertEquals(decoder.newlines, ('\n', '\r\n')) +- decoder.decode(b"abc\r") ++ _decode_bytewise("abc\r") + self.assertEquals(decoder.newlines, ('\n', '\r\n')) +- decoder.decode(b"abc") ++ _decode_bytewise("abc") + self.assertEquals(decoder.newlines, ('\r', '\n', '\r\n')) +- decoder.decode(b"abc\r") ++ _decode_bytewise("abc\r") ++ self.assertEquals("".join(result), "abc\n\nabcabc\nabcabc") + decoder.reset() +- self.assertEquals(decoder.decode(b"abc"), "abc") ++ self.assertEquals(decoder.decode("abc".encode(encoding)), "abc") + self.assertEquals(decoder.newlines, None) + ++ def test_newline_decoder(self): ++ encodings = ( ++ 'utf-8', 'latin-1', ++ 'utf-16', 'utf-16-le', 'utf-16-be', ++ 'utf-32', 'utf-32-le', 'utf-32-be', ++ ) ++ for enc in encodings: ++ decoder = codecs.getincrementaldecoder(enc)() ++ decoder = io.IncrementalNewlineDecoder(decoder, translate=True) ++ self.check_newline_decoder(decoder, enc) ++ decoder = codecs.getincrementaldecoder("utf-8")() ++ decoder = io.IncrementalNewlineDecoder(decoder, translate=True) ++ self.check_newline_decoder_utf8(decoder) ++ ++ + # XXX Tests for open() + + class MiscIOTest(unittest.TestCase): + ++ def tearDown(self): ++ test_support.unlink(test_support.TESTFN) ++ + def testImport__all__(self): + for name in io.__all__: + obj = getattr(io, name, None) +@@ -1237,6 +1308,34 @@ + self.assert_(issubclass(obj, io.IOBase)) + + ++ def test_attributes(self): ++ f = io.open(test_support.TESTFN, "wb", buffering=0) ++ self.assertEquals(f.mode, "wb") ++ f.close() ++ ++ f = io.open(test_support.TESTFN, "U") ++ self.assertEquals(f.name, test_support.TESTFN) ++ self.assertEquals(f.buffer.name, test_support.TESTFN) ++ self.assertEquals(f.buffer.raw.name, test_support.TESTFN) ++ self.assertEquals(f.mode, "U") ++ self.assertEquals(f.buffer.mode, "rb") ++ self.assertEquals(f.buffer.raw.mode, "rb") ++ f.close() ++ ++ f = io.open(test_support.TESTFN, "w+") ++ self.assertEquals(f.mode, "w+") ++ self.assertEquals(f.buffer.mode, "rb+") # Does it really matter? ++ self.assertEquals(f.buffer.raw.mode, "rb+") ++ ++ g = io.open(f.fileno(), "wb", closefd=False) ++ self.assertEquals(g.mode, "wb") ++ self.assertEquals(g.raw.mode, "wb") ++ self.assertEquals(g.name, f.fileno()) ++ self.assertEquals(g.raw.name, f.fileno()) ++ f.close() ++ g.close() ++ ++ + def test_main(): + test_support.run_unittest(IOTest, BytesIOTest, StringIOTest, + BufferedReaderTest, BufferedWriterTest, +Index: Lib/test/test_dict.py +=================================================================== +--- Lib/test/test_dict.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_dict.py (.../branches/release26-maint) (Revision 70449) +@@ -2,6 +2,7 @@ + from test import test_support + + import UserDict, random, string ++import gc, weakref + + + class DictTest(unittest.TestCase): +@@ -554,6 +555,19 @@ + pass + d = {} + ++ def test_container_iterator(self): ++ # Bug #3680: tp_traverse was not implemented for dictiter objects ++ class C(object): ++ pass ++ iterators = (dict.iteritems, dict.itervalues, dict.iterkeys) ++ for i in iterators: ++ obj = C() ++ ref = weakref.ref(obj) ++ container = {obj: 1} ++ obj.x = i(container) ++ del obj, container ++ gc.collect() ++ self.assert_(ref() is None, "Cycle was not collected") + + + from test import mapping_tests +Index: Lib/test/test_set.py +=================================================================== +--- Lib/test/test_set.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_set.py (.../branches/release26-maint) (Revision 70449) +@@ -1,6 +1,7 @@ + import unittest + from test import test_support +-from weakref import proxy ++import gc ++import weakref + import operator + import copy + import pickle +@@ -221,7 +222,7 @@ + self.failIf(set('cbs').issuperset('a')) + + def test_pickling(self): +- for i in (0, 1, 2): ++ for i in range(pickle.HIGHEST_PROTOCOL + 1): + p = pickle.dumps(self.s, i) + dup = pickle.loads(p) + self.assertEqual(self.s, dup, "%s != %s" % (self.s, dup)) +@@ -322,6 +323,18 @@ + self.assertEqual(sum(elem.hash_count for elem in d), n) + self.assertEqual(d3, dict.fromkeys(d, 123)) + ++ def test_container_iterator(self): ++ # Bug #3680: tp_traverse was not implemented for set iterator object ++ class C(object): ++ pass ++ obj = C() ++ ref = weakref.ref(obj) ++ container = set([obj, 1]) ++ obj.x = iter(container) ++ del obj, container ++ gc.collect() ++ self.assert_(ref() is None, "Cycle was not collected") ++ + class TestSet(TestJointOps): + thetype = set + +@@ -538,7 +551,7 @@ + + def test_weakref(self): + s = self.thetype('gallahad') +- p = proxy(s) ++ p = weakref.proxy(s) + self.assertEqual(str(p), str(s)) + s = None + self.assertRaises(ReferenceError, str, p) +Index: Lib/test/test_kqueue.py +=================================================================== +--- Lib/test/test_kqueue.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_kqueue.py (.../branches/release26-maint) (Revision 70449) +@@ -120,12 +120,15 @@ + client.send("Hello!") + server.send("world!!!") + +- events = kq.control(None, 4, 1) + # We may need to call it several times +- for i in range(5): ++ for i in range(10): ++ events = kq.control(None, 4, 1) + if len(events) == 4: + break +- events = kq.control(None, 4, 1) ++ time.sleep(1.0) ++ else: ++ self.fail('timeout waiting for event notifications') ++ + events = [(e.ident, e.filter, e.flags) for e in events] + events.sort() + +Index: Lib/test/test_inspect.py +=================================================================== +--- Lib/test/test_inspect.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_inspect.py (.../branches/release26-maint) (Revision 70449) +@@ -16,6 +16,9 @@ + # getclasstree, getargspec, getargvalues, formatargspec, formatargvalues, + # currentframe, stack, trace, isdatadescriptor + ++# NOTE: There are some additional tests relating to interaction with ++# zipimport in the test_zipimport_support test module. ++ + modfile = mod.__file__ + if modfile.endswith(('c', 'o')): + modfile = modfile[:-1] +Index: Lib/test/test_array.py +=================================================================== +--- Lib/test/test_array.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_array.py (.../branches/release26-maint) (Revision 70449) +@@ -7,7 +7,7 @@ + from test import test_support + from weakref import proxy + import array, cStringIO +-from cPickle import loads, dumps ++from cPickle import loads, dumps, HIGHEST_PROTOCOL + + class ArraySubclass(array.array): + pass +@@ -97,7 +97,7 @@ + self.assertEqual(a, b) + + def test_pickle(self): +- for protocol in (0, 1, 2): ++ for protocol in range(HIGHEST_PROTOCOL + 1): + a = array.array(self.typecode, self.example) + b = loads(dumps(a, protocol)) + self.assertNotEqual(id(a), id(b)) +@@ -112,7 +112,7 @@ + self.assertEqual(type(a), type(b)) + + def test_pickle_for_empty_array(self): +- for protocol in (0, 1, 2): ++ for protocol in range(HIGHEST_PROTOCOL + 1): + a = array.array(self.typecode) + b = loads(dumps(a, protocol)) + self.assertNotEqual(id(a), id(b)) +Index: Lib/test/test_itertools.py +=================================================================== +--- Lib/test/test_itertools.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_itertools.py (.../branches/release26-maint) (Revision 70449) +@@ -71,11 +71,11 @@ + self.assertRaises(TypeError, list, chain.from_iterable([2, 3])) + + def test_combinations(self): +- self.assertRaises(TypeError, combinations, 'abc') # missing r argument ++ self.assertRaises(TypeError, combinations, 'abc') # missing r argument + self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments + self.assertRaises(TypeError, combinations, None) # pool is not iterable + self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative +- self.assertRaises(ValueError, combinations, 'abc', 32) # r is too big ++ self.assertEqual(list(combinations('abc', 32)), []) # r > n + self.assertEqual(list(combinations(range(4), 3)), + [(0,1,2), (0,1,3), (0,2,3), (1,2,3)]) + +@@ -83,6 +83,8 @@ + 'Pure python version shown in the docs' + pool = tuple(iterable) + n = len(pool) ++ if r > n: ++ return + indices = range(r) + yield tuple(pool[i] for i in indices) + while 1: +@@ -106,9 +108,9 @@ + + for n in range(7): + values = [5*x-12 for x in range(n)] +- for r in range(n+1): ++ for r in range(n+2): + result = list(combinations(values, r)) +- self.assertEqual(len(result), fact(n) / fact(r) / fact(n-r)) # right number of combs ++ self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs + self.assertEqual(len(result), len(set(result))) # no repeats + self.assertEqual(result, sorted(result)) # lexicographic order + for c in result: +@@ -119,7 +121,7 @@ + self.assertEqual(list(c), + [e for e in values if e in c]) # comb is a subsequence of the input iterable + self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version +- self.assertEqual(result, list(combinations2(values, r))) # matches first pure python version ++ self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version + + # Test implementation detail: tuple re-use + self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1) +@@ -130,7 +132,7 @@ + self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments + self.assertRaises(TypeError, permutations, None) # pool is not iterable + self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative +- self.assertRaises(ValueError, permutations, 'abc', 32) # r is too big ++ self.assertEqual(list(permutations('abc', 32)), []) # r > n + self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None + self.assertEqual(list(permutations(range(3), 2)), + [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)]) +@@ -140,6 +142,8 @@ + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r ++ if r > n: ++ return + indices = range(n) + cycles = range(n, n-r, -1) + yield tuple(pool[i] for i in indices[:r]) +@@ -168,9 +172,9 @@ + + for n in range(7): + values = [5*x-12 for x in range(n)] +- for r in range(n+1): ++ for r in range(n+2): + result = list(permutations(values, r)) +- self.assertEqual(len(result), fact(n) / fact(n-r)) # right number of perms ++ self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r)) # right number of perms + self.assertEqual(len(result), len(set(result))) # no repeats + self.assertEqual(result, sorted(result)) # lexicographic order + for p in result: +@@ -178,7 +182,7 @@ + self.assertEqual(len(set(p)), r) # no duplicate elements + self.assert_(all(e in values for e in p)) # elements taken from input iterable + self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version +- self.assertEqual(result, list(permutations2(values, r))) # matches first pure python version ++ self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version + if r == n: + self.assertEqual(result, list(permutations(values, None))) # test r as None + self.assertEqual(result, list(permutations(values))) # test default r +@@ -1196,9 +1200,9 @@ + ... "Return function(0), function(1), ..." + ... return imap(function, count(start)) + +->>> def nth(iterable, n): +-... "Returns the nth item or empty list" +-... return list(islice(iterable, n, n+1)) ++>>> def nth(iterable, n, default=None): ++... "Returns the nth item or a default value" ++... return next(islice(iterable, n, None), default) + + >>> def quantify(iterable, pred=bool): + ... "Count how many times the predicate is true" +@@ -1252,11 +1256,9 @@ + ... nexts = cycle(islice(nexts, pending)) + + >>> def powerset(iterable): +-... "powerset('ab') --> set([]), set(['a']), set(['b']), set(['a', 'b'])" +-... # Recipe credited to Eric Raymond +-... pairs = [(2**i, x) for i, x in enumerate(iterable)] +-... for n in xrange(2**len(pairs)): +-... yield set(x for m, x in pairs if m&n) ++... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" ++... s = list(iterable) ++... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) + + >>> def compress(data, selectors): + ... "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F" +@@ -1266,6 +1268,8 @@ + ... "combinations_with_replacement('ABC', 3) --> AA AB AC BB BC CC" + ... pool = tuple(iterable) + ... n = len(pool) ++... if not n and r: ++... return + ... indices = [0] * r + ... yield tuple(pool[i] for i in indices) + ... while 1: +@@ -1277,6 +1281,30 @@ + ... indices[i:] = [indices[i] + 1] * (r - i) + ... yield tuple(pool[i] for i in indices) + ++>>> def unique_everseen(iterable, key=None): ++... "List unique elements, preserving order. Remember all elements ever seen." ++... # unique_everseen('AAAABBBCCDAABBB') --> A B C D ++... # unique_everseen('ABBCcAD', str.lower) --> A B C D ++... seen = set() ++... seen_add = seen.add ++... if key is None: ++... for element in iterable: ++... if element not in seen: ++... seen_add(element) ++... yield element ++... else: ++... for element in iterable: ++... k = key(element) ++... if k not in seen: ++... seen_add(k) ++... yield element ++ ++>>> def unique_justseen(iterable, key=None): ++... "List unique elements, preserving order. Remember only the element just seen." ++... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B ++... # unique_justseen('ABBCcAD', str.lower) --> A B C A D ++... return imap(next, imap(itemgetter(1), groupby(iterable, key))) ++ + This is not part of the examples but it tests to make sure the definitions + perform as purported. + +@@ -1290,8 +1318,11 @@ + [0, 2, 4, 6] + + >>> nth('abcde', 3) +-['d'] ++'d' + ++>>> nth('abcde', 9) is None ++True ++ + >>> quantify(xrange(99), lambda x: x%2==0) + 50 + +@@ -1330,8 +1361,8 @@ + >>> list(roundrobin('abc', 'd', 'ef')) + ['a', 'd', 'e', 'b', 'f', 'c'] + +->>> map(sorted, powerset('ab')) +-[[], ['a'], ['b'], ['a', 'b']] ++>>> list(powerset([1,2,3])) ++[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] + + >>> list(compress('abcdef', [1,0,1,0,1,1])) + ['a', 'c', 'e', 'f'] +@@ -1339,6 +1370,38 @@ + >>> list(combinations_with_replacement('abc', 2)) + [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')] + ++>>> list(combinations_with_replacement('01', 3)) ++[('0', '0', '0'), ('0', '0', '1'), ('0', '1', '1'), ('1', '1', '1')] ++ ++>>> def combinations_with_replacement2(iterable, r): ++... 'Alternate version that filters from product()' ++... pool = tuple(iterable) ++... n = len(pool) ++... for indices in product(range(n), repeat=r): ++... if sorted(indices) == list(indices): ++... yield tuple(pool[i] for i in indices) ++ ++>>> list(combinations_with_replacement('abc', 2)) == list(combinations_with_replacement2('abc', 2)) ++True ++ ++>>> list(combinations_with_replacement('01', 3)) == list(combinations_with_replacement2('01', 3)) ++True ++ ++>>> list(combinations_with_replacement('2310', 6)) == list(combinations_with_replacement2('2310', 6)) ++True ++ ++>>> list(unique_everseen('AAAABBBCCDAABBB')) ++['A', 'B', 'C', 'D'] ++ ++>>> list(unique_everseen('ABBCcAD', str.lower)) ++['A', 'B', 'C', 'D'] ++ ++>>> list(unique_justseen('AAAABBBCCDAABBB')) ++['A', 'B', 'C', 'D', 'A', 'B'] ++ ++>>> list(unique_justseen('ABBCcAD', str.lower)) ++['A', 'B', 'C', 'A', 'D'] ++ + """ + + __test__ = {'libreftest' : libreftest} +Index: Lib/test/test_unicode.py +=================================================================== +--- Lib/test/test_unicode.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_unicode.py (.../branches/release26-maint) (Revision 70449) +@@ -1036,73 +1036,73 @@ + self.assertEqual(u'{0:>15s}'.format(G(u'data')), u' string is data') + self.assertEqual(u'{0!s}'.format(G(u'data')), u'string is data') + +- self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007, +- month=8, +- day=27)), +- "date: 2007-08-27") ++ self.assertEqual(u"{0:date: %Y-%m-%d}".format(I(year=2007, ++ month=8, ++ day=27)), ++ u"date: 2007-08-27") + + # test deriving from a builtin type and overriding __format__ +- self.assertEqual("{0}".format(J(10)), "20") ++ self.assertEqual(u"{0}".format(J(10)), u"20") + + + # string format specifiers +- self.assertEqual('{0:}'.format('a'), 'a') ++ self.assertEqual(u'{0:}'.format('a'), u'a') + + # computed format specifiers +- self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello') +- self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello') +- self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello') +- self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ') +- self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ') ++ self.assertEqual(u"{0:.{1}}".format(u'hello world', 5), u'hello') ++ self.assertEqual(u"{0:.{1}s}".format(u'hello world', 5), u'hello') ++ self.assertEqual(u"{0:.{precision}s}".format('hello world', precision=5), u'hello') ++ self.assertEqual(u"{0:{width}.{precision}s}".format('hello world', width=10, precision=5), u'hello ') ++ self.assertEqual(u"{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), u'hello ') + + # test various errors +- self.assertRaises(ValueError, '{'.format) +- self.assertRaises(ValueError, '}'.format) +- self.assertRaises(ValueError, 'a{'.format) +- self.assertRaises(ValueError, 'a}'.format) +- self.assertRaises(ValueError, '{a'.format) +- self.assertRaises(ValueError, '}a'.format) +- self.assertRaises(IndexError, '{0}'.format) +- self.assertRaises(IndexError, '{1}'.format, 'abc') +- self.assertRaises(KeyError, '{x}'.format) +- self.assertRaises(ValueError, "}{".format) +- self.assertRaises(ValueError, "{".format) +- self.assertRaises(ValueError, "}".format) +- self.assertRaises(ValueError, "abc{0:{}".format) +- self.assertRaises(ValueError, "{0".format) +- self.assertRaises(IndexError, "{0.}".format) +- self.assertRaises(ValueError, "{0.}".format, 0) +- self.assertRaises(IndexError, "{0[}".format) +- self.assertRaises(ValueError, "{0[}".format, []) +- self.assertRaises(KeyError, "{0]}".format) +- self.assertRaises(ValueError, "{0.[]}".format, 0) +- self.assertRaises(ValueError, "{0..foo}".format, 0) +- self.assertRaises(ValueError, "{0[0}".format, 0) +- self.assertRaises(ValueError, "{0[0:foo}".format, 0) +- self.assertRaises(KeyError, "{c]}".format) +- self.assertRaises(ValueError, "{{ {{{0}}".format, 0) +- self.assertRaises(ValueError, "{0}}".format, 0) +- self.assertRaises(KeyError, "{foo}".format, bar=3) +- self.assertRaises(ValueError, "{0!x}".format, 3) +- self.assertRaises(ValueError, "{0!}".format, 0) +- self.assertRaises(ValueError, "{0!rs}".format, 0) +- self.assertRaises(ValueError, "{!}".format) +- self.assertRaises(ValueError, "{:}".format) +- self.assertRaises(ValueError, "{:s}".format) +- self.assertRaises(ValueError, "{}".format) ++ self.assertRaises(ValueError, u'{'.format) ++ self.assertRaises(ValueError, u'}'.format) ++ self.assertRaises(ValueError, u'a{'.format) ++ self.assertRaises(ValueError, u'a}'.format) ++ self.assertRaises(ValueError, u'{a'.format) ++ self.assertRaises(ValueError, u'}a'.format) ++ self.assertRaises(IndexError, u'{0}'.format) ++ self.assertRaises(IndexError, u'{1}'.format, u'abc') ++ self.assertRaises(KeyError, u'{x}'.format) ++ self.assertRaises(ValueError, u"}{".format) ++ self.assertRaises(ValueError, u"{".format) ++ self.assertRaises(ValueError, u"}".format) ++ self.assertRaises(ValueError, u"abc{0:{}".format) ++ self.assertRaises(ValueError, u"{0".format) ++ self.assertRaises(IndexError, u"{0.}".format) ++ self.assertRaises(ValueError, u"{0.}".format, 0) ++ self.assertRaises(IndexError, u"{0[}".format) ++ self.assertRaises(ValueError, u"{0[}".format, []) ++ self.assertRaises(KeyError, u"{0]}".format) ++ self.assertRaises(ValueError, u"{0.[]}".format, 0) ++ self.assertRaises(ValueError, u"{0..foo}".format, 0) ++ self.assertRaises(ValueError, u"{0[0}".format, 0) ++ self.assertRaises(ValueError, u"{0[0:foo}".format, 0) ++ self.assertRaises(KeyError, u"{c]}".format) ++ self.assertRaises(ValueError, u"{{ {{{0}}".format, 0) ++ self.assertRaises(ValueError, u"{0}}".format, 0) ++ self.assertRaises(KeyError, u"{foo}".format, bar=3) ++ self.assertRaises(ValueError, u"{0!x}".format, 3) ++ self.assertRaises(ValueError, u"{0!}".format, 0) ++ self.assertRaises(ValueError, u"{0!rs}".format, 0) ++ self.assertRaises(ValueError, u"{!}".format) ++ self.assertRaises(ValueError, u"{:}".format) ++ self.assertRaises(ValueError, u"{:s}".format) ++ self.assertRaises(ValueError, u"{}".format) + + # can't have a replacement on the field name portion +- self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4) ++ self.assertRaises(TypeError, u'{0[{1}]}'.format, u'abcdefg', 4) + + # exceed maximum recursion depth +- self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '') +- self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format, ++ self.assertRaises(ValueError, u"{0:{1:{2}}}".format, u'abc', u's', u'') ++ self.assertRaises(ValueError, u"{0:{1:{2:{3:{4:{5:{6}}}}}}}".format, + 0, 1, 2, 3, 4, 5, 6, 7) + + # string format spec errors +- self.assertRaises(ValueError, "{0:-s}".format, '') +- self.assertRaises(ValueError, format, "", "-") +- self.assertRaises(ValueError, "{0:=s}".format, '') ++ self.assertRaises(ValueError, u"{0:-s}".format, u'') ++ self.assertRaises(ValueError, format, u"", u"-") ++ self.assertRaises(ValueError, u"{0:=s}".format, u'') + + # test combining string and unicode + self.assertEqual(u"foo{0}".format('bar'), u'foobar') +Index: Lib/test/test_socket.py +=================================================================== +--- Lib/test/test_socket.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_socket.py (.../branches/release26-maint) (Revision 70449) +@@ -584,6 +584,10 @@ + # Testing shutdown() + msg = self.cli_conn.recv(1024) + self.assertEqual(msg, MSG) ++ # wait for _testShutdown to finish: on OS X, when the server ++ # closes the connection the client also becomes disconnected, ++ # and the client's shutdown call will fail. (Issue #4397.) ++ self.done.wait() + + def _testShutdown(self): + self.serv_conn.send(MSG) +Index: Lib/test/test_shutil.py +=================================================================== +--- Lib/test/test_shutil.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_shutil.py (.../branches/release26-maint) (Revision 70449) +@@ -340,7 +340,29 @@ + dst = os.path.join(self.src_dir, "bar") + self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst) + ++ def test_destinsrc_false_negative(self): ++ os.mkdir(TESTFN) ++ try: ++ for src, dst in [('srcdir', 'srcdir/dest')]: ++ src = os.path.join(TESTFN, src) ++ dst = os.path.join(TESTFN, dst) ++ self.assert_(shutil.destinsrc(src, dst), ++ msg='destinsrc() wrongly concluded that ' ++ 'dst (%s) is not in src (%s)' % (dst, src)) ++ finally: ++ shutil.rmtree(TESTFN, ignore_errors=True) + ++ def test_destinsrc_false_positive(self): ++ os.mkdir(TESTFN) ++ try: ++ for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]: ++ src = os.path.join(TESTFN, src) ++ dst = os.path.join(TESTFN, dst) ++ self.failIf(shutil.destinsrc(src, dst), ++ msg='destinsrc() wrongly concluded that ' ++ 'dst (%s) is in src (%s)' % (dst, src)) ++ finally: ++ shutil.rmtree(TESTFN, ignore_errors=True) + + def test_main(): + test_support.run_unittest(TestShutil, TestMove) +Index: Lib/test/test_with.py +=================================================================== +--- Lib/test/test_with.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_with.py (.../branches/release26-maint) (Revision 70449) +@@ -503,7 +503,37 @@ + + self.assertRaises(GeneratorExit, shouldThrow) + ++ def testErrorsInBool(self): ++ # issue4589: __exit__ return code may raise an exception ++ # when looking at its truth value. + ++ class cm(object): ++ def __init__(self, bool_conversion): ++ class Bool: ++ def __nonzero__(self): ++ return bool_conversion() ++ self.exit_result = Bool() ++ def __enter__(self): ++ return 3 ++ def __exit__(self, a, b, c): ++ return self.exit_result ++ ++ def trueAsBool(): ++ with cm(lambda: True): ++ self.fail("Should NOT see this") ++ trueAsBool() ++ ++ def falseAsBool(): ++ with cm(lambda: False): ++ self.fail("Should raise") ++ self.assertRaises(AssertionError, falseAsBool) ++ ++ def failAsBool(): ++ with cm(lambda: 1//0): ++ self.fail("Should NOT see this") ++ self.assertRaises(ZeroDivisionError, failAsBool) ++ ++ + class NonLocalFlowControlTestCase(unittest.TestCase): + + def testWithBreak(self): +Index: Lib/test/test_file.py +=================================================================== +--- Lib/test/test_file.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_file.py (.../branches/release26-maint) (Revision 70449) +@@ -120,9 +120,24 @@ + except: + self.assertEquals(self.f.__exit__(*sys.exc_info()), None) + ++ def testReadWhenWriting(self): ++ self.assertRaises(IOError, self.f.read) + + class OtherFileTests(unittest.TestCase): + ++ def testOpenDir(self): ++ this_dir = os.path.dirname(__file__) ++ for mode in (None, "w"): ++ try: ++ if mode: ++ f = open(this_dir, mode) ++ else: ++ f = open(this_dir) ++ except IOError as e: ++ self.assertEqual(e.filename, this_dir) ++ else: ++ self.fail("opening a directory didn't raise an IOError") ++ + def testModeStrings(self): + # check invalid mode strings + for mode in ("", "aU", "wU+"): +@@ -531,7 +546,21 @@ + finally: + sys.stdout = save_stdout + ++ def test_del_stdout_before_print(self): ++ # Issue 4597: 'print' with no argument wasn't reporting when ++ # sys.stdout was deleted. ++ save_stdout = sys.stdout ++ del sys.stdout ++ try: ++ print ++ except RuntimeError as e: ++ self.assertEquals(str(e), "lost sys.stdout") ++ else: ++ self.fail("Expected RuntimeError") ++ finally: ++ sys.stdout = save_stdout + ++ + def test_main(): + # Historically, these tests have been sloppy about removing TESTFN. + # So get rid of it no matter what. +Index: Lib/test/test_logging.py +=================================================================== +--- Lib/test/test_logging.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_logging.py (.../branches/release26-maint) (Revision 70449) +@@ -25,6 +25,7 @@ + import logging.handlers + import logging.config + ++import codecs + import copy + import cPickle + import cStringIO +@@ -859,6 +860,7 @@ + ('foo', 'DEBUG', '3'), + ]) + ++ + class EncodingTest(BaseTest): + def test_encoding_plain_file(self): + # In Python 2.x, a plain file object is treated as having no encoding. +@@ -885,6 +887,27 @@ + if os.path.isfile(fn): + os.remove(fn) + ++ def test_encoding_cyrillic_unicode(self): ++ log = logging.getLogger("test") ++ #Get a message in Unicode: Do svidanya in Cyrillic (meaning goodbye) ++ message = u'\u0434\u043e \u0441\u0432\u0438\u0434\u0430\u043d\u0438\u044f' ++ #Ensure it's written in a Cyrillic encoding ++ writer_class = codecs.getwriter('cp1251') ++ stream = cStringIO.StringIO() ++ writer = writer_class(stream, 'strict') ++ handler = logging.StreamHandler(writer) ++ log.addHandler(handler) ++ try: ++ log.warning(message) ++ finally: ++ log.removeHandler(handler) ++ handler.close() ++ # check we wrote exactly those bytes, ignoring trailing \n etc ++ s = stream.getvalue() ++ #Compare against what the data should be when encoded in CP-1251 ++ self.assertEqual(s, '\xe4\xee \xf1\xe2\xe8\xe4\xe0\xed\xe8\xff\n') ++ ++ + # Set the locale to the platform-dependent default. I have no idea + # why the test does this, but in any case we save the current locale + # first and restore it at the end. +Index: Lib/test/test_os.py +=================================================================== +--- Lib/test/test_os.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_os.py (.../branches/release26-maint) (Revision 70449) +@@ -533,6 +533,69 @@ + def test_chmod(self): + self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0) + ++class TestInvalidFD(unittest.TestCase): ++ singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat", ++ "fstatvfs", "fsync", "tcgetpgrp", "ttyname"] ++ #singles.append("close") ++ #We omit close because it doesn'r raise an exception on some platforms ++ def get_single(f): ++ def helper(self): ++ if hasattr(os, f): ++ self.check(getattr(os, f)) ++ return helper ++ for f in singles: ++ locals()["test_"+f] = get_single(f) ++ ++ def check(self, f, *args): ++ self.assertRaises(OSError, f, test_support.make_bad_fd(), *args) ++ ++ def test_isatty(self): ++ if hasattr(os, "isatty"): ++ self.assertEqual(os.isatty(test_support.make_bad_fd()), False) ++ ++ def test_closerange(self): ++ if hasattr(os, "closerange"): ++ fd = test_support.make_bad_fd() ++ self.assertEqual(os.closerange(fd, fd + 10), None) ++ ++ def test_dup2(self): ++ if hasattr(os, "dup2"): ++ self.check(os.dup2, 20) ++ ++ def test_fchmod(self): ++ if hasattr(os, "fchmod"): ++ self.check(os.fchmod, 0) ++ ++ def test_fchown(self): ++ if hasattr(os, "fchown"): ++ self.check(os.fchown, -1, -1) ++ ++ def test_fpathconf(self): ++ if hasattr(os, "fpathconf"): ++ self.check(os.fpathconf, "PC_NAME_MAX") ++ ++ #this is a weird one, it raises IOError unlike the others ++ def test_ftruncate(self): ++ if hasattr(os, "ftruncate"): ++ self.assertRaises(IOError, os.ftruncate, test_support.make_bad_fd(), ++ 0) ++ ++ def test_lseek(self): ++ if hasattr(os, "lseek"): ++ self.check(os.lseek, 0, 0) ++ ++ def test_read(self): ++ if hasattr(os, "read"): ++ self.check(os.read, 1) ++ ++ def test_tcsetpgrpt(self): ++ if hasattr(os, "tcsetpgrp"): ++ self.check(os.tcsetpgrp, 0) ++ ++ def test_write(self): ++ if hasattr(os, "write"): ++ self.check(os.write, " ") ++ + if sys.platform != 'win32': + class Win32ErrorTests(unittest.TestCase): + pass +@@ -547,7 +610,8 @@ + MakedirTests, + DevNullTests, + URandomTests, +- Win32ErrorTests ++ Win32ErrorTests, ++ TestInvalidFD + ) + + if __name__ == "__main__": +Index: Lib/test/test_tarfile.py +=================================================================== +--- Lib/test/test_tarfile.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_tarfile.py (.../branches/release26-maint) (Revision 70449) +@@ -256,17 +256,14 @@ + def test_extractall(self): + # Test if extractall() correctly restores directory permissions + # and times (see issue1735). +- if sys.platform == "win32": +- # Win32 has no support for utime() on directories or +- # fine grained permissions. +- return +- + tar = tarfile.open(tarname, encoding="iso8859-1") + directories = [t for t in tar if t.isdir()] + tar.extractall(TEMPDIR, directories) + for tarinfo in directories: + path = os.path.join(TEMPDIR, tarinfo.name) +- self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777) ++ if sys.platform != "win32": ++ # Win32 has no support for fine grained permissions. ++ self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777) + self.assertEqual(tarinfo.mtime, os.path.getmtime(path)) + tar.close() + +Index: Lib/test/test_fractions.py +=================================================================== +--- Lib/test/test_fractions.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_fractions.py (.../branches/release26-maint) (Revision 70449) +@@ -139,6 +139,8 @@ + def testFromFloat(self): + self.assertRaises(TypeError, F.from_float, 3+4j) + self.assertEquals((10, 1), _components(F.from_float(10))) ++ bigint = 1234567890123456789 ++ self.assertEquals((bigint, 1), _components(F.from_float(bigint))) + self.assertEquals((0, 1), _components(F.from_float(-0.0))) + self.assertEquals((10, 1), _components(F.from_float(10.0))) + self.assertEquals((-5, 2), _components(F.from_float(-2.5))) +@@ -392,6 +394,11 @@ + self.assertEqual(id(r), id(copy(r))) + self.assertEqual(id(r), id(deepcopy(r))) + ++ def test_slots(self): ++ # Issue 4998 ++ r = F(13, 7) ++ self.assertRaises(AttributeError, setattr, r, 'a', 10) ++ + def test_main(): + run_unittest(FractionTest, GcdTest) + +Index: Lib/test/test_parser.py +=================================================================== +--- Lib/test/test_parser.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_parser.py (.../branches/release26-maint) (Revision 70449) +@@ -200,6 +200,16 @@ + self.check_suite("with open('x'): pass\n") + self.check_suite("with open('x') as f: pass\n") + ++ def test_try_stmt(self): ++ self.check_suite("try: pass\nexcept: pass\n") ++ self.check_suite("try: pass\nfinally: pass\n") ++ self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n") ++ self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n" ++ "finally: pass\n") ++ self.check_suite("try: pass\nexcept: pass\nelse: pass\n") ++ self.check_suite("try: pass\nexcept: pass\nelse: pass\n" ++ "finally: pass\n") ++ + def test_position(self): + # An absolutely minimal test of position information. Better + # tests would be a big project. +Index: Lib/test/list_tests.py +=================================================================== +--- Lib/test/list_tests.py (.../tags/r261) (Revision 70449) ++++ Lib/test/list_tests.py (.../branches/release26-maint) (Revision 70449) +@@ -84,6 +84,8 @@ + self.assertRaises(StopIteration, r.next) + self.assertEqual(list(reversed(self.type2test())), + self.type2test()) ++ # Bug 3689: make sure list-reversed-iterator doesn't have __len__ ++ self.assertRaises(TypeError, len, reversed([1,2,3])) + + def test_setitem(self): + a = self.type2test([0, 1]) +Index: Lib/test/test_iterlen.py +=================================================================== +--- Lib/test/test_iterlen.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_iterlen.py (.../branches/release26-maint) (Revision 70449) +@@ -195,6 +195,46 @@ + d.extend(xrange(20)) + self.assertEqual(len(it), 0) + ++## -- Check to make sure exceptions are not suppressed by __length_hint__() ++ ++ ++class BadLen(object): ++ def __iter__(self): return iter(range(10)) ++ def __len__(self): ++ raise RuntimeError('hello') ++ ++class BadLengthHint(object): ++ def __iter__(self): return iter(range(10)) ++ def __length_hint__(self): ++ raise RuntimeError('hello') ++ ++class NoneLengthHint(object): ++ def __iter__(self): return iter(range(10)) ++ def __length_hint__(self): ++ return None ++ ++class TestLengthHintExceptions(unittest.TestCase): ++ ++ def test_issue1242657(self): ++ self.assertRaises(RuntimeError, list, BadLen()) ++ self.assertRaises(RuntimeError, list, BadLengthHint()) ++ self.assertRaises(RuntimeError, [].extend, BadLen()) ++ self.assertRaises(RuntimeError, [].extend, BadLengthHint()) ++ self.assertRaises(RuntimeError, zip, BadLen()) ++ self.assertRaises(RuntimeError, zip, BadLengthHint()) ++ self.assertRaises(RuntimeError, filter, None, BadLen()) ++ self.assertRaises(RuntimeError, filter, None, BadLengthHint()) ++ self.assertRaises(RuntimeError, map, chr, BadLen()) ++ self.assertRaises(RuntimeError, map, chr, BadLengthHint()) ++ b = bytearray(range(10)) ++ self.assertRaises(RuntimeError, b.extend, BadLen()) ++ self.assertRaises(RuntimeError, b.extend, BadLengthHint()) ++ ++ def test_invalid_hint(self): ++ # Make sure an invalid result doesn't muck-up the works ++ self.assertEqual(list(NoneLengthHint()), list(range(10))) ++ ++ + def test_main(): + unittests = [ + TestRepeat, +@@ -209,6 +249,7 @@ + TestSet, + TestList, + TestListReversed, ++ TestLengthHintExceptions, + ] + test_support.run_unittest(*unittests) + +Index: Lib/test/test_doctest.py +=================================================================== +--- Lib/test/test_doctest.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_doctest.py (.../branches/release26-maint) (Revision 70449) +@@ -6,6 +6,9 @@ + import doctest + import warnings + ++# NOTE: There are some additional tests relating to interaction with ++# zipimport in the test_zipimport_support test module. ++ + ###################################################################### + ## Sample Objects (used by test cases) + ###################################################################### +@@ -369,7 +372,7 @@ + >>> tests = finder.find(sample_func) + + >>> print tests # doctest: +ELLIPSIS +- [] ++ [] + + The exact name depends on how test_doctest was invoked, so allow for + leading path components. +Index: Lib/test/test_httplib.py +=================================================================== +--- Lib/test/test_httplib.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_httplib.py (.../branches/release26-maint) (Revision 70449) +@@ -107,19 +107,23 @@ + for hp in ("www.python.org:abc", "www.python.org:"): + self.assertRaises(httplib.InvalidURL, httplib.HTTP, hp) + +- for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b", 8000), ++ for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b", ++ 8000), + ("www.python.org:80", "www.python.org", 80), + ("www.python.org", "www.python.org", 80), + ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80)): + http = httplib.HTTP(hp) + c = http._conn +- if h != c.host: self.fail("Host incorrectly parsed: %s != %s" % (h, c.host)) +- if p != c.port: self.fail("Port incorrectly parsed: %s != %s" % (p, c.host)) ++ if h != c.host: ++ self.fail("Host incorrectly parsed: %s != %s" % (h, c.host)) ++ if p != c.port: ++ self.fail("Port incorrectly parsed: %s != %s" % (p, c.host)) + + def test_response_headers(self): + # test response with multiple message headers with the same field name. + text = ('HTTP/1.1 200 OK\r\n' +- 'Set-Cookie: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"\r\n' ++ 'Set-Cookie: Customer="WILE_E_COYOTE";' ++ ' Version="1"; Path="/acme"\r\n' + 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";' + ' Path="/acme"\r\n' + '\r\n' +@@ -181,19 +185,39 @@ + resp.read() + except httplib.IncompleteRead, i: + self.assertEquals(i.partial, 'hello world') ++ self.assertEqual(repr(i),'IncompleteRead(11 bytes read)') ++ self.assertEqual(str(i),'IncompleteRead(11 bytes read)') + else: + self.fail('IncompleteRead expected') + finally: + resp.close() + + def test_negative_content_length(self): +- sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n') ++ sock = FakeSocket('HTTP/1.1 200 OK\r\n' ++ 'Content-Length: -1\r\n\r\nHello\r\n') + resp = httplib.HTTPResponse(sock, method="GET") + resp.begin() + self.assertEquals(resp.read(), 'Hello\r\n') + resp.close() + ++ def test_incomplete_read(self): ++ sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n') ++ resp = httplib.HTTPResponse(sock, method="GET") ++ resp.begin() ++ try: ++ resp.read() ++ except httplib.IncompleteRead as i: ++ self.assertEquals(i.partial, 'Hello\r\n') ++ self.assertEqual(repr(i), ++ "IncompleteRead(7 bytes read, 3 more expected)") ++ self.assertEqual(str(i), ++ "IncompleteRead(7 bytes read, 3 more expected)") ++ else: ++ self.fail('IncompleteRead expected') ++ finally: ++ resp.close() + ++ + class OfflineTest(TestCase): + def test_responses(self): + self.assertEquals(httplib.responses[httplib.NOT_FOUND], "Not Found") +Index: Lib/test/zipdir.zip +=================================================================== +Kann nicht anzeigen: Dateityp ist als binär angegeben. +svn:mime-type = application/octet-stream + +Eigenschaftsänderungen: Lib/test/zipdir.zip +___________________________________________________________________ +Hinzugefügt: svn:mime-type + + application/octet-stream + +Index: Lib/test/pickletester.py +=================================================================== +--- Lib/test/pickletester.py (.../tags/r261) (Revision 70449) ++++ Lib/test/pickletester.py (.../branches/release26-maint) (Revision 70449) +@@ -480,14 +480,21 @@ + + if have_unicode: + def test_unicode(self): +- endcases = [unicode(''), unicode('<\\u>'), unicode('<\\\u1234>'), +- unicode('<\n>'), unicode('<\\>')] ++ endcases = [u'', u'<\\u>', u'<\\\u1234>', u'<\n>', ++ u'<\\>', u'<\\\U00012345>'] + for proto in protocols: + for u in endcases: + p = self.dumps(u, proto) + u2 = self.loads(p) + self.assertEqual(u2, u) + ++ def test_unicode_high_plane(self): ++ t = u'\U00012345' ++ for proto in protocols: ++ p = self.dumps(t, proto) ++ t2 = self.loads(p) ++ self.assertEqual(t2, t) ++ + def test_ints(self): + import sys + for proto in protocols: +@@ -528,6 +535,16 @@ + got = self.loads(p) + self.assertEqual(n, got) + ++ def test_float(self): ++ test_values = [0.0, 4.94e-324, 1e-310, 7e-308, 6.626e-34, 0.1, 0.5, ++ 3.14, 263.44582062374053, 6.022e23, 1e30] ++ test_values = test_values + [-x for x in test_values] ++ for proto in protocols: ++ for value in test_values: ++ pickle = self.dumps(value, proto) ++ got = self.loads(pickle) ++ self.assertEqual(value, got) ++ + @run_with_locale('LC_ALL', 'de_DE', 'fr_FR') + def test_float_format(self): + # make sure that floats are formatted locale independent +Index: Lib/test/decimaltestdata/extra.decTest +=================================================================== +--- Lib/test/decimaltestdata/extra.decTest (.../tags/r261) (Revision 70449) ++++ Lib/test/decimaltestdata/extra.decTest (.../branches/release26-maint) (Revision 70449) +@@ -154,6 +154,23 @@ + extr1302 fma 0E123 -Inf sNaN789 -> NaN Invalid_operation + extr1302 fma -Inf 0E-456 sNaN148 -> NaN Invalid_operation + ++-- max/min/max_mag/min_mag bug in 2.5.2/2.6/3.0: max(NaN, finite) gave ++-- incorrect answers when the finite number required rounding; similarly ++-- for the other thre functions ++maxexponent: 999 ++minexponent: -999 ++precision: 6 ++rounding: half_even ++extr1400 max NaN 1234567 -> 1.23457E+6 Inexact Rounded ++extr1401 max 3141590E-123 NaN1729 -> 3.14159E-117 Rounded ++extr1402 max -7.654321 -NaN -> -7.65432 Inexact Rounded ++extr1410 min -NaN -765432.1 -> -765432 Inexact Rounded ++extr1411 min 3141592 NaN -> 3.14159E+6 Inexact Rounded ++extr1420 max_mag 0.1111111 -NaN123 -> 0.111111 Inexact Rounded ++extr1421 max_mag NaN999999999 0.001234567 -> 0.00123457 Inexact Rounded ++extr1430 min_mag 9181716151 -NaN -> 9.18172E+9 Inexact Rounded ++extr1431 min_mag NaN4 1.818180E100 -> 1.81818E+100 Rounded ++ + -- Tests for the is_* boolean operations + precision: 9 + maxExponent: 999 +Index: Lib/test/test_zipimport_support.py +=================================================================== +--- Lib/test/test_zipimport_support.py (.../tags/r261) (Revision 0) ++++ Lib/test/test_zipimport_support.py (.../branches/release26-maint) (Revision 70449) +@@ -0,0 +1,232 @@ ++# This test module covers support in various parts of the standard library ++# for working with modules located inside zipfiles ++# The tests are centralised in this fashion to make it easy to drop them ++# if a platform doesn't support zipimport ++import unittest ++import test.test_support ++import os ++import os.path ++import sys ++import textwrap ++import zipfile ++import zipimport ++import doctest ++import inspect ++import linecache ++import pdb ++ ++verbose = test.test_support.verbose ++ ++# Library modules covered by this test set ++# pdb (Issue 4201) ++# inspect (Issue 4223) ++# doctest (Issue 4197) ++ ++# Other test modules with zipimport related tests ++# test_zipimport (of course!) ++# test_cmd_line_script (covers the zipimport support in runpy) ++ ++# Retrieve some helpers from other test cases ++from test import test_doctest, sample_doctest ++from test.test_importhooks import ImportHooksBaseTestCase ++from test.test_cmd_line_script import temp_dir, _run_python, \ ++ _spawn_python, _kill_python, \ ++ _make_test_script, \ ++ _compile_test_script, \ ++ _make_test_zip, _make_test_pkg ++ ++ ++def _run_object_doctest(obj, module): ++ # Direct doctest output (normally just errors) to real stdout; doctest ++ # output shouldn't be compared by regrtest. ++ save_stdout = sys.stdout ++ sys.stdout = test.test_support.get_original_stdout() ++ try: ++ finder = doctest.DocTestFinder(verbose=verbose, recurse=False) ++ runner = doctest.DocTestRunner(verbose=verbose) ++ # Use the object's fully qualified name if it has one ++ # Otherwise, use the module's name ++ try: ++ name = "%s.%s" % (obj.__module__, obj.__name__) ++ except AttributeError: ++ name = module.__name__ ++ for example in finder.find(obj, name, module): ++ runner.run(example) ++ f, t = runner.failures, runner.tries ++ if f: ++ raise test.test_support.TestFailed("%d of %d doctests failed" % (f, t)) ++ finally: ++ sys.stdout = save_stdout ++ if verbose: ++ print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t) ++ return f, t ++ ++ ++ ++class ZipSupportTests(ImportHooksBaseTestCase): ++ # We use the ImportHooksBaseTestCase to restore ++ # the state of the import related information ++ # in the sys module after each test ++ # We also clear the linecache and zipimport cache ++ # just to avoid any bogus errors due to name reuse in the tests ++ def setUp(self): ++ linecache.clearcache() ++ zipimport._zip_directory_cache.clear() ++ ImportHooksBaseTestCase.setUp(self) ++ ++ ++ def test_inspect_getsource_issue4223(self): ++ test_src = "def foo(): pass\n" ++ with temp_dir() as d: ++ init_name = _make_test_script(d, '__init__', test_src) ++ name_in_zip = os.path.join('zip_pkg', ++ os.path.basename(init_name)) ++ zip_name, run_name = _make_test_zip(d, 'test_zip', ++ init_name, name_in_zip) ++ os.remove(init_name) ++ sys.path.insert(0, zip_name) ++ import zip_pkg ++ self.assertEqual(inspect.getsource(zip_pkg.foo), test_src) ++ ++ def test_doctest_issue4197(self): ++ # To avoid having to keep two copies of the doctest module's ++ # unit tests in sync, this test works by taking the source of ++ # test_doctest itself, rewriting it a bit to cope with a new ++ # location, and then throwing it in a zip file to make sure ++ # everything still works correctly ++ test_src = inspect.getsource(test_doctest) ++ test_src = test_src.replace( ++ "from test import test_doctest", ++ "import test_zipped_doctest as test_doctest") ++ test_src = test_src.replace("test.test_doctest", ++ "test_zipped_doctest") ++ test_src = test_src.replace("test.sample_doctest", ++ "sample_zipped_doctest") ++ sample_src = inspect.getsource(sample_doctest) ++ sample_src = sample_src.replace("test.test_doctest", ++ "test_zipped_doctest") ++ with temp_dir() as d: ++ script_name = _make_test_script(d, 'test_zipped_doctest', ++ test_src) ++ zip_name, run_name = _make_test_zip(d, 'test_zip', ++ script_name) ++ z = zipfile.ZipFile(zip_name, 'a') ++ z.writestr("sample_zipped_doctest.py", sample_src) ++ z.close() ++ if verbose: ++ zip_file = zipfile.ZipFile(zip_name, 'r') ++ print 'Contents of %r:' % zip_name ++ zip_file.printdir() ++ zip_file.close() ++ os.remove(script_name) ++ sys.path.insert(0, zip_name) ++ import test_zipped_doctest ++ # Some of the doc tests depend on the colocated text files ++ # which aren't available to the zipped version (the doctest ++ # module currently requires real filenames for non-embedded ++ # tests). So we're forced to be selective about which tests ++ # to run. ++ # doctest could really use some APIs which take a text ++ # string or a file object instead of a filename... ++ known_good_tests = [ ++ test_zipped_doctest.SampleClass, ++ test_zipped_doctest.SampleClass.NestedClass, ++ test_zipped_doctest.SampleClass.NestedClass.__init__, ++ test_zipped_doctest.SampleClass.__init__, ++ test_zipped_doctest.SampleClass.a_classmethod, ++ test_zipped_doctest.SampleClass.a_property, ++ test_zipped_doctest.SampleClass.a_staticmethod, ++ test_zipped_doctest.SampleClass.double, ++ test_zipped_doctest.SampleClass.get, ++ test_zipped_doctest.SampleNewStyleClass, ++ test_zipped_doctest.SampleNewStyleClass.__init__, ++ test_zipped_doctest.SampleNewStyleClass.double, ++ test_zipped_doctest.SampleNewStyleClass.get, ++ test_zipped_doctest.old_test1, ++ test_zipped_doctest.old_test2, ++ test_zipped_doctest.old_test3, ++ test_zipped_doctest.old_test4, ++ test_zipped_doctest.sample_func, ++ test_zipped_doctest.test_DocTest, ++ test_zipped_doctest.test_DocTestParser, ++ test_zipped_doctest.test_DocTestRunner.basics, ++ test_zipped_doctest.test_DocTestRunner.exceptions, ++ test_zipped_doctest.test_DocTestRunner.option_directives, ++ test_zipped_doctest.test_DocTestRunner.optionflags, ++ test_zipped_doctest.test_DocTestRunner.verbose_flag, ++ test_zipped_doctest.test_Example, ++ test_zipped_doctest.test_debug, ++ test_zipped_doctest.test_pdb_set_trace, ++ test_zipped_doctest.test_pdb_set_trace_nested, ++ test_zipped_doctest.test_testsource, ++ test_zipped_doctest.test_trailing_space_in_test, ++ test_zipped_doctest.test_DocTestSuite, ++ test_zipped_doctest.test_DocTestFinder, ++ ] ++ # These remaining tests are the ones which need access ++ # to the data files, so we don't run them ++ fail_due_to_missing_data_files = [ ++ test_zipped_doctest.test_DocFileSuite, ++ test_zipped_doctest.test_testfile, ++ test_zipped_doctest.test_unittest_reportflags, ++ ] ++ for obj in known_good_tests: ++ _run_object_doctest(obj, test_zipped_doctest) ++ ++ def test_doctest_main_issue4197(self): ++ test_src = textwrap.dedent("""\ ++ class Test: ++ ">>> 'line 2'" ++ pass ++ ++ import doctest ++ doctest.testmod() ++ """) ++ pattern = 'File "%s", line 2, in %s' ++ with temp_dir() as d: ++ script_name = _make_test_script(d, 'script', test_src) ++ exit_code, data = _run_python(script_name) ++ expected = pattern % (script_name, "__main__.Test") ++ if verbose: ++ print "Expected line", expected ++ print "Got stdout:" ++ print data ++ self.assert_(expected in data) ++ zip_name, run_name = _make_test_zip(d, "test_zip", ++ script_name, '__main__.py') ++ exit_code, data = _run_python(zip_name) ++ expected = pattern % (run_name, "__main__.Test") ++ if verbose: ++ print "Expected line", expected ++ print "Got stdout:" ++ print data ++ self.assert_(expected in data) ++ ++ def test_pdb_issue4201(self): ++ test_src = textwrap.dedent("""\ ++ def f(): ++ pass ++ ++ import pdb ++ pdb.runcall(f) ++ """) ++ with temp_dir() as d: ++ script_name = _make_test_script(d, 'script', test_src) ++ p = _spawn_python(script_name) ++ p.stdin.write('l\n') ++ data = _kill_python(p) ++ self.assert_(script_name in data) ++ zip_name, run_name = _make_test_zip(d, "test_zip", ++ script_name, '__main__.py') ++ p = _spawn_python(zip_name) ++ p.stdin.write('l\n') ++ data = _kill_python(p) ++ self.assert_(run_name in data) ++ ++ ++def test_main(): ++ test.test_support.run_unittest(ZipSupportTests) ++ test.test_support.reap_children() ++ ++if __name__ == '__main__': ++ test_main() + +Eigenschaftsänderungen: Lib/test/test_zipimport_support.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native +Hinzugefügt: svn:keywords + + Id + +Index: Lib/test/test_mmap.py +=================================================================== +--- Lib/test/test_mmap.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_mmap.py (.../branches/release26-maint) (Revision 70449) +@@ -41,6 +41,10 @@ + self.assertEqual(m[0], '\0') + self.assertEqual(m[0:3], '\0\0\0') + ++ # Shouldn't crash on boundary (Issue #5292) ++ self.assertRaises(IndexError, m.__getitem__, len(m)) ++ self.assertRaises(IndexError, m.__setitem__, len(m), '\0') ++ + # Modify the file's content + m[0] = '3' + m[PAGESIZE +3: PAGESIZE +3+3] = 'bar' +@@ -413,6 +417,27 @@ + m = mmap.mmap(f.fileno(), mapsize - halfsize, offset=halfsize) + self.assertEqual(m[0:3], 'foo') + f.close() ++ ++ # Try resizing map ++ try: ++ m.resize(512) ++ except SystemError: ++ pass ++ else: ++ # resize() is supported ++ self.assertEqual(len(m), 512) ++ # Check that we can no longer seek beyond the new size. ++ self.assertRaises(ValueError, m.seek, 513, 0) ++ # Check that the content is not changed ++ self.assertEqual(m[0:3], 'foo') ++ ++ # Check that the underlying file is truncated too ++ f = open(TESTFN) ++ f.seek(0, 2) ++ self.assertEqual(f.tell(), halfsize + 512) ++ f.close() ++ self.assertEqual(m.size(), halfsize + 512) ++ + m.close() + + finally: +@@ -442,7 +467,89 @@ + self.assert_(issubclass(mmap.error, EnvironmentError)) + self.assert_("mmap.error" in str(mmap.error)) + ++ def test_io_methods(self): ++ data = "0123456789" ++ open(TESTFN, "wb").write("x"*len(data)) ++ f = open(TESTFN, "r+b") ++ m = mmap.mmap(f.fileno(), len(data)) ++ f.close() ++ # Test write_byte() ++ for i in xrange(len(data)): ++ self.assertEquals(m.tell(), i) ++ m.write_byte(data[i:i+1]) ++ self.assertEquals(m.tell(), i+1) ++ self.assertRaises(ValueError, m.write_byte, "x") ++ self.assertEquals(m[:], data) ++ # Test read_byte() ++ m.seek(0) ++ for i in xrange(len(data)): ++ self.assertEquals(m.tell(), i) ++ self.assertEquals(m.read_byte(), data[i:i+1]) ++ self.assertEquals(m.tell(), i+1) ++ self.assertRaises(ValueError, m.read_byte) ++ # Test read() ++ m.seek(3) ++ self.assertEquals(m.read(3), "345") ++ self.assertEquals(m.tell(), 6) ++ # Test write() ++ m.seek(3) ++ m.write("bar") ++ self.assertEquals(m.tell(), 6) ++ self.assertEquals(m[:], "012bar6789") ++ m.seek(8) ++ self.assertRaises(ValueError, m.write, "bar") + ++ if os.name == 'nt': ++ def test_tagname(self): ++ data1 = "0123456789" ++ data2 = "abcdefghij" ++ assert len(data1) == len(data2) ++ ++ # Test same tag ++ m1 = mmap.mmap(-1, len(data1), tagname="foo") ++ m1[:] = data1 ++ m2 = mmap.mmap(-1, len(data2), tagname="foo") ++ m2[:] = data2 ++ self.assertEquals(m1[:], data2) ++ self.assertEquals(m2[:], data2) ++ m2.close() ++ m1.close() ++ ++ # Test differnt tag ++ m1 = mmap.mmap(-1, len(data1), tagname="foo") ++ m1[:] = data1 ++ m2 = mmap.mmap(-1, len(data2), tagname="boo") ++ m2[:] = data2 ++ self.assertEquals(m1[:], data1) ++ self.assertEquals(m2[:], data2) ++ m2.close() ++ m1.close() ++ ++ def test_crasher_on_windows(self): ++ # Should not crash (Issue 1733986) ++ m = mmap.mmap(-1, 1000, tagname="foo") ++ try: ++ mmap.mmap(-1, 5000, tagname="foo")[:] # same tagname, but larger size ++ except: ++ pass ++ m.close() ++ ++ # Should not crash (Issue 5385) ++ open(TESTFN, "wb").write("x"*10) ++ f = open(TESTFN, "r+b") ++ m = mmap.mmap(f.fileno(), 0) ++ f.close() ++ try: ++ m.resize(0) # will raise WindowsError ++ except: ++ pass ++ try: ++ m[:] ++ except: ++ pass ++ m.close() ++ ++ + def test_main(): + run_unittest(MmapTests) + +Index: Lib/test/test_locale.py +=================================================================== +--- Lib/test/test_locale.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_locale.py (.../branches/release26-maint) (Revision 70449) +@@ -105,6 +105,32 @@ + } + + ++class FrFRCookedTest(BaseCookedTest): ++ # A cooked "fr_FR" locale with a space character as decimal separator ++ # and a non-ASCII currency symbol. ++ ++ cooked_values = { ++ 'currency_symbol': '\xe2\x82\xac', ++ 'decimal_point': ',', ++ 'frac_digits': 2, ++ 'grouping': [3, 3, 0], ++ 'int_curr_symbol': 'EUR ', ++ 'int_frac_digits': 2, ++ 'mon_decimal_point': ',', ++ 'mon_grouping': [3, 3, 0], ++ 'mon_thousands_sep': ' ', ++ 'n_cs_precedes': 0, ++ 'n_sep_by_space': 1, ++ 'n_sign_posn': 1, ++ 'negative_sign': '-', ++ 'p_cs_precedes': 0, ++ 'p_sep_by_space': 1, ++ 'p_sign_posn': 1, ++ 'positive_sign': '', ++ 'thousands_sep': ' ' ++ } ++ ++ + class BaseFormattingTest(object): + # + # Utility functions for formatting tests +@@ -152,6 +178,12 @@ + self._test_format("%+d", 4200, grouping=True, out='+4%s200' % self.sep) + self._test_format("%+d", -4200, grouping=True, out='-4%s200' % self.sep) + ++ def test_integer_grouping_and_padding(self): ++ self._test_format("%10d", 4200, grouping=True, ++ out=('4%s200' % self.sep).rjust(10)) ++ self._test_format("%-10d", -4200, grouping=True, ++ out=('-4%s200' % self.sep).ljust(10)) ++ + def test_simple(self): + self._test_format("%f", 1024, grouping=0, out='1024.000000') + self._test_format("%f", 102, grouping=0, out='102.000000') +@@ -223,6 +255,49 @@ + self._test_format("%9.2f", 12345.67, grouping=True, out=' 12345.67') + + ++class TestFrFRNumberFormatting(FrFRCookedTest, BaseFormattingTest): ++ # Test number formatting with a cooked "fr_FR" locale. ++ ++ def test_decimal_point(self): ++ self._test_format("%.2f", 12345.67, out='12345,67') ++ ++ def test_grouping(self): ++ self._test_format("%.2f", 345.67, grouping=True, out='345,67') ++ self._test_format("%.2f", 12345.67, grouping=True, out='12 345,67') ++ ++ def test_grouping_and_padding(self): ++ self._test_format("%6.2f", 345.67, grouping=True, out='345,67') ++ self._test_format("%7.2f", 345.67, grouping=True, out=' 345,67') ++ self._test_format("%8.2f", 12345.67, grouping=True, out='12 345,67') ++ self._test_format("%9.2f", 12345.67, grouping=True, out='12 345,67') ++ self._test_format("%10.2f", 12345.67, grouping=True, out=' 12 345,67') ++ self._test_format("%-6.2f", 345.67, grouping=True, out='345,67') ++ self._test_format("%-7.2f", 345.67, grouping=True, out='345,67 ') ++ self._test_format("%-8.2f", 12345.67, grouping=True, out='12 345,67') ++ self._test_format("%-9.2f", 12345.67, grouping=True, out='12 345,67') ++ self._test_format("%-10.2f", 12345.67, grouping=True, out='12 345,67 ') ++ ++ def test_integer_grouping(self): ++ self._test_format("%d", 200, grouping=True, out='200') ++ self._test_format("%d", 4200, grouping=True, out='4 200') ++ ++ def test_integer_grouping_and_padding(self): ++ self._test_format("%4d", 4200, grouping=True, out='4 200') ++ self._test_format("%5d", 4200, grouping=True, out='4 200') ++ self._test_format("%10d", 4200, grouping=True, out='4 200'.rjust(10)) ++ self._test_format("%-4d", 4200, grouping=True, out='4 200') ++ self._test_format("%-5d", 4200, grouping=True, out='4 200') ++ self._test_format("%-10d", 4200, grouping=True, out='4 200'.ljust(10)) ++ ++ def test_currency(self): ++ euro = u'\u20ac'.encode('utf-8') ++ self._test_currency(50000, "50000,00 " + euro) ++ self._test_currency(50000, "50 000,00 " + euro, grouping=True) ++ # XXX is the trailing space a bug? ++ self._test_currency(50000, "50 000,00 EUR ", ++ grouping=True, international=True) ++ ++ + class TestStringMethods(BaseLocalizedTest): + locale_type = locale.LC_CTYPE + +@@ -277,7 +352,8 @@ + tests = [ + TestMiscellaneous, + TestEnUSNumberFormatting, +- TestCNumberFormatting ++ TestCNumberFormatting, ++ TestFrFRNumberFormatting, + ] + # TestSkipped can't be raised inside unittests, handle it manually instead + try: +Index: Lib/test/test_cgi.py +=================================================================== +--- Lib/test/test_cgi.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_cgi.py (.../branches/release26-maint) (Revision 70449) +@@ -354,7 +354,33 @@ + self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')], + cgi.parse_qsl('a=A1&b=B2&B=B3')) + ++ def test_parse_header(self): ++ self.assertEqual( ++ cgi.parse_header("text/plain"), ++ ("text/plain", {})) ++ self.assertEqual( ++ cgi.parse_header("text/vnd.just.made.this.up ; "), ++ ("text/vnd.just.made.this.up", {})) ++ self.assertEqual( ++ cgi.parse_header("text/plain;charset=us-ascii"), ++ ("text/plain", {"charset": "us-ascii"})) ++ self.assertEqual( ++ cgi.parse_header('text/plain ; charset="us-ascii"'), ++ ("text/plain", {"charset": "us-ascii"})) ++ self.assertEqual( ++ cgi.parse_header('text/plain ; charset="us-ascii"; another=opt'), ++ ("text/plain", {"charset": "us-ascii", "another": "opt"})) ++ self.assertEqual( ++ cgi.parse_header('attachment; filename="silly.txt"'), ++ ("attachment", {"filename": "silly.txt"})) ++ self.assertEqual( ++ cgi.parse_header('attachment; filename="strange;name"'), ++ ("attachment", {"filename": "strange;name"})) ++ self.assertEqual( ++ cgi.parse_header('attachment; filename="strange;name";size=123;'), ++ ("attachment", {"filename": "strange;name", "size": "123"})) + ++ + def test_main(): + run_unittest(CgiTests) + +Index: Lib/test/test_textwrap.py +=================================================================== +--- Lib/test/test_textwrap.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_textwrap.py (.../branches/release26-maint) (Revision 70449) +@@ -174,7 +174,7 @@ + text = ("Python 1.0.0 was released on 1994-01-26. Python 1.0.1 was\n" + "released on 1994-02-15.") + +- self.check_wrap(text, 30, ['Python 1.0.0 was released on', ++ self.check_wrap(text, 35, ['Python 1.0.0 was released on', + '1994-01-26. Python 1.0.1 was', + 'released on 1994-02-15.']) + self.check_wrap(text, 40, ['Python 1.0.0 was released on 1994-01-26.', +@@ -353,6 +353,14 @@ + otext = self.wrapper.fill(text) + assert isinstance(otext, unicode) + ++ def test_no_split_at_umlaut(self): ++ text = u"Die Empf\xe4nger-Auswahl" ++ self.check_wrap(text, 13, [u"Die", u"Empf\xe4nger-", u"Auswahl"]) ++ ++ def test_umlaut_followed_by_dash(self): ++ text = u"aa \xe4\xe4-\xe4\xe4" ++ self.check_wrap(text, 7, [u"aa \xe4\xe4-", u"\xe4\xe4"]) ++ + def test_split(self): + # Ensure that the standard _split() method works as advertised + # in the comments +Index: Lib/test/test_urllibnet.py +=================================================================== +--- Lib/test/test_urllibnet.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_urllibnet.py (.../branches/release26-maint) (Revision 70449) +@@ -137,7 +137,7 @@ + # domain will be spared to serve its defined + # purpose. + # urllib.urlopen, "http://www.sadflkjsasadf.com/") +- urllib.urlopen, "http://www.python.invalid./") ++ urllib.urlopen, "http://sadflkjsasf.i.nvali.d/") + + class urlretrieveNetworkTests(unittest.TestCase): + """Tests urllib.urlretrieve using the network.""" +Index: Lib/test/test_deque.py +=================================================================== +--- Lib/test/test_deque.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_deque.py (.../branches/release26-maint) (Revision 70449) +@@ -1,7 +1,8 @@ + from collections import deque + import unittest + from test import test_support, seq_tests +-from weakref import proxy ++import gc ++import weakref + import copy + import cPickle as pickle + import random +@@ -373,7 +374,7 @@ + + def test_pickle(self): + d = deque(xrange(200)) +- for i in (0, 1, 2): ++ for i in range(pickle.HIGHEST_PROTOCOL + 1): + s = pickle.dumps(d, i) + e = pickle.loads(s) + self.assertNotEqual(id(d), id(e)) +@@ -382,7 +383,7 @@ + ## def test_pickle_recursive(self): + ## d = deque('abc') + ## d.append(d) +-## for i in (0, 1, 2): ++## for i in range(pickle.HIGHEST_PROTOCOL + 1): + ## e = pickle.loads(pickle.dumps(d, i)) + ## self.assertNotEqual(id(d), id(e)) + ## self.assertEqual(id(e), id(e[-1])) +@@ -418,6 +419,22 @@ + d.append(1) + gc.collect() + ++ def test_container_iterator(self): ++ # Bug #3680: tp_traverse was not implemented for deque iterator objects ++ class C(object): ++ pass ++ for i in range(2): ++ obj = C() ++ ref = weakref.ref(obj) ++ if i == 0: ++ container = deque([obj, 1]) ++ else: ++ container = reversed(deque([obj, 1])) ++ obj.x = iter(container) ++ del obj, container ++ gc.collect() ++ self.assert_(ref() is None, "Cycle was not collected") ++ + class TestVariousIteratorArgs(unittest.TestCase): + + def test_constructor(self): +@@ -528,7 +545,7 @@ + + def test_weakref(self): + d = deque('gallahad') +- p = proxy(d) ++ p = weakref.proxy(d) + self.assertEqual(str(p), str(d)) + d = None + self.assertRaises(ReferenceError, str, p) +Index: Lib/test/test_datetime.py +=================================================================== +--- Lib/test/test_datetime.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_datetime.py (.../branches/release26-maint) (Revision 70449) +@@ -856,7 +856,24 @@ + # A naive object replaces %z and %Z w/ empty strings. + self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") + ++ #make sure that invalid format specifiers are handled correctly ++ #self.assertRaises(ValueError, t.strftime, "%e") ++ #self.assertRaises(ValueError, t.strftime, "%") ++ #self.assertRaises(ValueError, t.strftime, "%#") + ++ #oh well, some systems just ignore those invalid ones. ++ #at least, excercise them to make sure that no crashes ++ #are generated ++ for f in ["%e", "%", "%#"]: ++ try: ++ t.strftime(f) ++ except ValueError: ++ pass ++ ++ #check that this standard extension works ++ t.strftime("%f") ++ ++ + def test_format(self): + dt = self.theclass(2007, 9, 10) + self.assertEqual(dt.__format__(''), str(dt)) +Index: Lib/test/test_fileio.py +=================================================================== +--- Lib/test/test_fileio.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_fileio.py (.../branches/release26-maint) (Revision 70449) +@@ -7,7 +7,8 @@ + from array import array + from weakref import proxy + +-from test.test_support import TESTFN, findfile, check_warnings, run_unittest ++from test.test_support import (TESTFN, findfile, check_warnings, run_unittest, ++ make_bad_fd) + from UserList import UserList + + import _fileio +@@ -50,7 +51,7 @@ + # verify expected attributes exist + f = self.f + +- self.assertEquals(f.mode, "w") ++ self.assertEquals(f.mode, "wb") + self.assertEquals(f.closed, False) + + # verify the attributes are readonly +@@ -109,6 +110,7 @@ + _fileio._FileIO('.', 'r') + except IOError as e: + self.assertNotEqual(e.errno, 0) ++ self.assertEqual(e.filename, ".") + else: + self.fail("Should have raised IOError") + +@@ -160,7 +162,7 @@ + + def testModeStrings(self): + # check invalid mode strings +- for mode in ("", "aU", "wU+", "rb", "rt"): ++ for mode in ("", "aU", "wU+", "rw", "rt"): + try: + f = _fileio._FileIO(TESTFN, mode) + except ValueError: +@@ -175,6 +177,10 @@ + f.close() + os.unlink(TESTFN) + ++ def testInvalidFd(self): ++ self.assertRaises(ValueError, _fileio._FileIO, -10) ++ self.assertRaises(OSError, _fileio._FileIO, make_bad_fd()) ++ + def testBadModeArgument(self): + # verify that we get a sensible error message for bad mode argument + bad_mode = "qwerty" +Index: Lib/test/test_hotshot.py +=================================================================== +--- Lib/test/test_hotshot.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_hotshot.py (.../branches/release26-maint) (Revision 70449) +@@ -3,6 +3,8 @@ + import os + import pprint + import unittest ++import _hotshot ++import gc + + from test import test_support + +@@ -124,6 +126,10 @@ + if os.path.exists(test_support.TESTFN): + os.remove(test_support.TESTFN) + ++ def test_logreader_eof_error(self): ++ self.assertRaises((IOError, EOFError), _hotshot.logreader, ".") ++ gc.collect() ++ + def test_main(): + test_support.run_unittest(HotShotTestCase) + +Index: Lib/test/test_decimal.py +=================================================================== +--- Lib/test/test_decimal.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_decimal.py (.../branches/release26-maint) (Revision 70449) +@@ -30,6 +30,7 @@ + import pickle, copy + import unittest + from decimal import * ++import numbers + from test.test_support import (TestSkipped, run_unittest, run_doctest, + is_resource_enabled) + import random +@@ -168,7 +169,6 @@ + -context.Emin > DEC_MAX_MATH): + return True + if not v._is_special and v and ( +- len(v._int) > DEC_MAX_MATH or + v.adjusted() > DEC_MAX_MATH or + v.adjusted() < 1-2*DEC_MAX_MATH): + return True +@@ -704,6 +704,12 @@ + ('.0g', '-sNaN', '-sNaN'), + + ('', '1.00', '1.00'), ++ ++ # check alignment ++ ('<6', '123', '123 '), ++ ('>6', '123', ' 123'), ++ ('^6', '123', ' 123 '), ++ ('=+6', '123', '+ 123'), + ] + for fmt, d, result in test_values: + self.assertEqual(format(Decimal(d), fmt), result) +@@ -1335,6 +1341,12 @@ + + class DecimalPythonAPItests(unittest.TestCase): + ++ def test_abc(self): ++ self.assert_(issubclass(Decimal, numbers.Number)) ++ self.assert_(not issubclass(Decimal, numbers.Real)) ++ self.assert_(isinstance(Decimal(0), numbers.Number)) ++ self.assert_(not isinstance(Decimal(0), numbers.Real)) ++ + def test_pickle(self): + d = Decimal('-3.141590000') + p = pickle.dumps(d) +Index: Lib/test/test_struct.py +=================================================================== +--- Lib/test/test_struct.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_struct.py (.../branches/release26-maint) (Revision 70449) +@@ -2,6 +2,8 @@ + import unittest + import struct + import warnings ++warnings.filterwarnings("ignore", "struct integer overflow masking is deprecated", ++ DeprecationWarning) + + from functools import wraps + from test.test_support import TestFailed, verbose, run_unittest +@@ -461,6 +463,11 @@ + self.check_float_coerce(endian + fmt, 1.0) + self.check_float_coerce(endian + fmt, 1.5) + ++ def test_issue4228(self): ++ # Packing a long may yield either 32 or 64 bits ++ x = struct.pack('L', -1)[:4] ++ self.assertEqual(x, '\xff'*4) ++ + def test_unpack_from(self): + test_string = 'abcd01234' + fmt = '4s' +Index: Lib/test/test_subprocess.py +=================================================================== +--- Lib/test/test_subprocess.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_subprocess.py (.../branches/release26-maint) (Revision 70449) +@@ -486,6 +486,22 @@ + else: + self.fail("Expected TypeError") + ++ def test_leaking_fds_on_error(self): ++ # see bug #5179: Popen leaks file descriptors to PIPEs if ++ # the child fails to execute; this will eventually exhaust ++ # the maximum number of open fds. 1024 seems a very common ++ # value for that limit, but Windows has 2048, so we loop ++ # 1024 times (each call leaked two fds). ++ for i in range(1024): ++ try: ++ subprocess.Popen(['nonexisting_i_hope'], ++ stdout=subprocess.PIPE, ++ stderr=subprocess.PIPE) ++ # Windows raises IOError ++ except (IOError, OSError), err: ++ if err.errno != 2: # ignore "no such file" ++ raise ++ + # + # POSIX tests + # +Index: Lib/test/test_zipimport.py +=================================================================== +--- Lib/test/test_zipimport.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_zipimport.py (.../branches/release26-maint) (Revision 70449) +@@ -214,16 +214,24 @@ + zi = zipimport.zipimporter(TEMP_ZIP) + self.assertEquals(zi.archive, TEMP_ZIP) + self.assertEquals(zi.is_package(TESTPACK), True) +- zi.load_module(TESTPACK) ++ mod = zi.load_module(TESTPACK) ++ self.assertEquals(zi._get_filename(TESTPACK), mod.__file__) + + self.assertEquals(zi.is_package(packdir + '__init__'), False) + self.assertEquals(zi.is_package(packdir + TESTPACK2), True) + self.assertEquals(zi.is_package(packdir2 + TESTMOD), False) + +- mod_name = packdir2 + TESTMOD +- mod = __import__(module_path_to_dotted_name(mod_name)) ++ mod_path = packdir2 + TESTMOD ++ mod_name = module_path_to_dotted_name(mod_path) ++ pkg = __import__(mod_name) ++ mod = sys.modules[mod_name] + self.assertEquals(zi.get_source(TESTPACK), None) +- self.assertEquals(zi.get_source(mod_name), None) ++ self.assertEquals(zi.get_source(mod_path), None) ++ self.assertEquals(zi._get_filename(mod_path), mod.__file__) ++ # To pass in the module name instead of the path, we must use the right importer ++ loader = mod.__loader__ ++ self.assertEquals(loader.get_source(mod_name), None) ++ self.assertEquals(loader._get_filename(mod_name), mod.__file__) + + # test prefix and archivepath members + zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK) +@@ -251,15 +259,23 @@ + self.assertEquals(zi.archive, TEMP_ZIP) + self.assertEquals(zi.prefix, packdir) + self.assertEquals(zi.is_package(TESTPACK2), True) +- zi.load_module(TESTPACK2) ++ mod = zi.load_module(TESTPACK2) ++ self.assertEquals(zi._get_filename(TESTPACK2), mod.__file__) + + self.assertEquals(zi.is_package(TESTPACK2 + os.sep + '__init__'), False) + self.assertEquals(zi.is_package(TESTPACK2 + os.sep + TESTMOD), False) + +- mod_name = TESTPACK2 + os.sep + TESTMOD +- mod = __import__(module_path_to_dotted_name(mod_name)) ++ mod_path = TESTPACK2 + os.sep + TESTMOD ++ mod_name = module_path_to_dotted_name(mod_path) ++ pkg = __import__(mod_name) ++ mod = sys.modules[mod_name] + self.assertEquals(zi.get_source(TESTPACK2), None) +- self.assertEquals(zi.get_source(mod_name), None) ++ self.assertEquals(zi.get_source(mod_path), None) ++ self.assertEquals(zi._get_filename(mod_path), mod.__file__) ++ # To pass in the module name instead of the path, we must use the right importer ++ loader = mod.__loader__ ++ self.assertEquals(loader.get_source(mod_name), None) ++ self.assertEquals(loader._get_filename(mod_name), mod.__file__) + finally: + z.close() + os.remove(TEMP_ZIP) +Index: Lib/test/test_cmd_line_script.py +=================================================================== +--- Lib/test/test_cmd_line_script.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_cmd_line_script.py (.../branches/release26-maint) (Revision 70449) +@@ -75,36 +75,66 @@ + compiled_name = script_name + 'o' + return compiled_name + +-def _make_test_zip(zip_dir, zip_basename, script_name): ++def _make_test_zip(zip_dir, zip_basename, script_name, name_in_zip=None): + zip_filename = zip_basename+os.extsep+'zip' + zip_name = os.path.join(zip_dir, zip_filename) + zip_file = zipfile.ZipFile(zip_name, 'w') +- zip_file.write(script_name, os.path.basename(script_name)) ++ if name_in_zip is None: ++ name_in_zip = os.path.basename(script_name) ++ zip_file.write(script_name, name_in_zip) + zip_file.close() +- # if verbose: ++ #if verbose: + # zip_file = zipfile.ZipFile(zip_name, 'r') + # print 'Contents of %r:' % zip_name + # zip_file.printdir() + # zip_file.close() +- return zip_name ++ return zip_name, os.path.join(zip_name, name_in_zip) + + def _make_test_pkg(pkg_dir): + os.mkdir(pkg_dir) + _make_test_script(pkg_dir, '__init__', '') + ++def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, ++ source=test_source, depth=1): ++ init_name = _make_test_script(zip_dir, '__init__', '') ++ init_basename = os.path.basename(init_name) ++ script_name = _make_test_script(zip_dir, script_basename, source) ++ pkg_names = [os.sep.join([pkg_name]*i) for i in range(1, depth+1)] ++ script_name_in_zip = os.path.join(pkg_names[-1], os.path.basename(script_name)) ++ zip_filename = zip_basename+os.extsep+'zip' ++ zip_name = os.path.join(zip_dir, zip_filename) ++ zip_file = zipfile.ZipFile(zip_name, 'w') ++ for name in pkg_names: ++ init_name_in_zip = os.path.join(name, init_basename) ++ zip_file.write(init_name, init_name_in_zip) ++ zip_file.write(script_name, script_name_in_zip) ++ zip_file.close() ++ os.unlink(init_name) ++ os.unlink(script_name) ++ #if verbose: ++ # zip_file = zipfile.ZipFile(zip_name, 'r') ++ # print 'Contents of %r:' % zip_name ++ # zip_file.printdir() ++ # zip_file.close() ++ return zip_name, os.path.join(zip_name, script_name_in_zip) ++ + # There's no easy way to pass the script directory in to get + # -m to work (avoiding that is the whole point of making + # directories and zipfiles executable!) + # So we fake it for testing purposes with a custom launch script + launch_source = """\ + import sys, os.path, runpy +-sys.path[0:0] = os.path.dirname(__file__) ++sys.path.insert(0, %s) + runpy._run_module_as_main(%r) + """ + +-def _make_launch_script(script_dir, script_basename, module_name): +- return _make_test_script(script_dir, script_basename, +- launch_source % module_name) ++def _make_launch_script(script_dir, script_basename, module_name, path=None): ++ if path is None: ++ path = "os.path.dirname(__file__)" ++ else: ++ path = repr(path) ++ source = launch_source % (path, module_name) ++ return _make_test_script(script_dir, script_basename, source) + + class CmdLineTest(unittest.TestCase): + def _check_script(self, script_name, expected_file, +@@ -155,15 +185,15 @@ + def test_zipfile(self): + with temp_dir() as script_dir: + script_name = _make_test_script(script_dir, '__main__') +- zip_name = _make_test_zip(script_dir, 'test_zip', script_name) +- self._check_script(zip_name, None, zip_name, '') ++ zip_name, run_name = _make_test_zip(script_dir, 'test_zip', script_name) ++ self._check_script(zip_name, run_name, zip_name, '') + + def test_zipfile_compiled(self): + with temp_dir() as script_dir: + script_name = _make_test_script(script_dir, '__main__') + compiled_name = _compile_test_script(script_name) +- zip_name = _make_test_zip(script_dir, 'test_zip', compiled_name) +- self._check_script(zip_name, None, zip_name, '') ++ zip_name, run_name = _make_test_zip(script_dir, 'test_zip', compiled_name) ++ self._check_script(zip_name, run_name, zip_name, '') + + def test_module_in_package(self): + with temp_dir() as script_dir: +@@ -171,10 +201,21 @@ + _make_test_pkg(pkg_dir) + script_name = _make_test_script(pkg_dir, 'script') + launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script') +- self._check_script(launch_name, script_name, +- script_name, 'test_pkg') ++ self._check_script(launch_name, script_name, script_name, 'test_pkg') + ++ def test_module_in_package_in_zipfile(self): ++ with temp_dir() as script_dir: ++ zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script') ++ launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script', zip_name) ++ self._check_script(launch_name, run_name, run_name, 'test_pkg') + ++ def test_module_in_subpackage_in_zipfile(self): ++ with temp_dir() as script_dir: ++ zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2) ++ launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name) ++ self._check_script(launch_name, run_name, run_name, 'test_pkg.test_pkg') ++ ++ + def test_main(): + test.test_support.run_unittest(CmdLineTest) + test.test_support.reap_children() +Index: Lib/test/test_import.py +=================================================================== +--- Lib/test/test_import.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_import.py (.../branches/release26-maint) (Revision 70449) +@@ -5,6 +5,7 @@ + import sys + import py_compile + import warnings ++import marshal + from test.test_support import unlink, TESTFN, unload, run_unittest, check_warnings + + +@@ -231,6 +232,97 @@ + else: + self.fail("import by path didn't raise an exception") + ++class TestPycRewriting(unittest.TestCase): ++ # Test that the `co_filename` attribute on code objects always points ++ # to the right file, even when various things happen (e.g. both the .py ++ # and the .pyc file are renamed). ++ ++ module_name = "unlikely_module_name" ++ module_source = """ ++import sys ++code_filename = sys._getframe().f_code.co_filename ++module_filename = __file__ ++constant = 1 ++def func(): ++ pass ++func_filename = func.func_code.co_filename ++""" ++ dir_name = os.path.abspath(TESTFN) ++ file_name = os.path.join(dir_name, module_name) + os.extsep + "py" ++ compiled_name = file_name + ("c" if __debug__ else "o") ++ ++ def setUp(self): ++ self.sys_path = sys.path[:] ++ self.orig_module = sys.modules.pop(self.module_name, None) ++ os.mkdir(self.dir_name) ++ with open(self.file_name, "w") as f: ++ f.write(self.module_source) ++ sys.path.insert(0, self.dir_name) ++ ++ def tearDown(self): ++ sys.path[:] = self.sys_path ++ if self.orig_module is not None: ++ sys.modules[self.module_name] = self.orig_module ++ else: ++ del sys.modules[self.module_name] ++ for file_name in self.file_name, self.compiled_name: ++ if os.path.exists(file_name): ++ os.remove(file_name) ++ if os.path.exists(self.dir_name): ++ shutil.rmtree(self.dir_name) ++ ++ def import_module(self): ++ ns = globals() ++ __import__(self.module_name, ns, ns) ++ return sys.modules[self.module_name] ++ ++ def test_basics(self): ++ mod = self.import_module() ++ self.assertEqual(mod.module_filename, self.file_name) ++ self.assertEqual(mod.code_filename, self.file_name) ++ self.assertEqual(mod.func_filename, self.file_name) ++ del sys.modules[self.module_name] ++ mod = self.import_module() ++ self.assertEqual(mod.module_filename, self.compiled_name) ++ self.assertEqual(mod.code_filename, self.file_name) ++ self.assertEqual(mod.func_filename, self.file_name) ++ ++ def test_incorrect_code_name(self): ++ py_compile.compile(self.file_name, dfile="another_module.py") ++ mod = self.import_module() ++ self.assertEqual(mod.module_filename, self.compiled_name) ++ self.assertEqual(mod.code_filename, self.file_name) ++ self.assertEqual(mod.func_filename, self.file_name) ++ ++ def test_module_without_source(self): ++ target = "another_module.py" ++ py_compile.compile(self.file_name, dfile=target) ++ os.remove(self.file_name) ++ mod = self.import_module() ++ self.assertEqual(mod.module_filename, self.compiled_name) ++ self.assertEqual(mod.code_filename, target) ++ self.assertEqual(mod.func_filename, target) ++ ++ def test_foreign_code(self): ++ py_compile.compile(self.file_name) ++ with open(self.compiled_name, "rb") as f: ++ header = f.read(8) ++ code = marshal.load(f) ++ constants = list(code.co_consts) ++ foreign_code = test_main.func_code ++ pos = constants.index(1) ++ constants[pos] = foreign_code ++ code = type(code)(code.co_argcount, code.co_nlocals, code.co_stacksize, ++ code.co_flags, code.co_code, tuple(constants), ++ code.co_names, code.co_varnames, code.co_filename, ++ code.co_name, code.co_firstlineno, code.co_lnotab, ++ code.co_freevars, code.co_cellvars) ++ with open(self.compiled_name, "wb") as f: ++ f.write(header) ++ marshal.dump(code, f) ++ mod = self.import_module() ++ self.assertEqual(mod.constant.co_filename, foreign_code.co_filename) ++ + class PathsTests(unittest.TestCase): + path = TESTFN + +@@ -297,7 +389,7 @@ + self.assertRaises(ValueError, check_relative) + + def test_main(verbose=None): +- run_unittest(ImportTest, PathsTests, RelativeImport) ++ run_unittest(ImportTest, TestPycRewriting, PathsTests, RelativeImport) + + if __name__ == '__main__': + # test needs to be a package, so we can do relative import +Index: Lib/test/test_bytes.py +=================================================================== +--- Lib/test/test_bytes.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_bytes.py (.../branches/release26-maint) (Revision 70449) +@@ -725,7 +725,7 @@ + # Issue 4348. Make sure that operations that don't mutate the array + # copy the bytes. + b = bytearray(b'abc') +- #self.assertFalse(b is b.replace(b'abc', b'cde', 0)) ++ self.assertFalse(b is b.replace(b'abc', b'cde', 0)) + + t = bytearray([i for i in range(256)]) + x = bytearray(b'') +@@ -752,6 +752,38 @@ + self.assertEqual(b, b"") + self.assertEqual(c, b"") + ++ # XXX memoryview not available ++ def XXXtest_resize_forbidden(self): ++ # #4509: can't resize a bytearray when there are buffer exports, even ++ # if it wouldn't reallocate the underlying buffer. ++ # Furthermore, no destructive changes to the buffer may be applied ++ # before raising the error. ++ b = bytearray(range(10)) ++ v = memoryview(b) ++ def resize(n): ++ b[1:-1] = range(n + 1, 2*n - 1) ++ resize(10) ++ orig = b[:] ++ self.assertRaises(BufferError, resize, 11) ++ self.assertEquals(b, orig) ++ self.assertRaises(BufferError, resize, 9) ++ self.assertEquals(b, orig) ++ self.assertRaises(BufferError, resize, 0) ++ self.assertEquals(b, orig) ++ # Other operations implying resize ++ self.assertRaises(BufferError, b.pop, 0) ++ self.assertEquals(b, orig) ++ self.assertRaises(BufferError, b.remove, b[1]) ++ self.assertEquals(b, orig) ++ def delitem(): ++ del b[1] ++ self.assertRaises(BufferError, delitem) ++ self.assertEquals(b, orig) ++ # deleting a non-contiguous slice ++ def delslice(): ++ b[1:-1:2] = b"" ++ self.assertRaises(BufferError, delslice) ++ self.assertEquals(b, orig) + + class AssortedBytesTest(unittest.TestCase): + # +@@ -840,11 +872,19 @@ + + def test_translate(self): + b = b'hello' ++ ba = bytearray(b) + rosetta = bytearray(range(0, 256)) + rosetta[ord('o')] = ord('e') + c = b.translate(rosetta, b'l') + self.assertEqual(b, b'hello') + self.assertEqual(c, b'hee') ++ c = ba.translate(rosetta, b'l') ++ self.assertEqual(ba, b'hello') ++ self.assertEqual(c, b'hee') ++ c = b.translate(None, b'e') ++ self.assertEqual(c, b'hllo') ++ self.assertRaises(TypeError, b.translate, b'a'*256, None) ++ self.assertRaises(TypeError, ba.translate, b'a'*256, None) + + def test_split_bytearray(self): + self.assertEqual(b'a b'.split(memoryview(b' ')), [b'a', b'b']) +Index: Lib/test/test_hash.py +=================================================================== +--- Lib/test/test_hash.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_hash.py (.../branches/release26-maint) (Revision 70449) +@@ -111,9 +111,32 @@ + self.assertFalse(isinstance(obj, Hashable), repr(obj)) + + ++# Issue #4701: Check that some builtin types are correctly hashable ++# (This test only used to fail in Python 3.0, but has been included ++# in 2.x along with the lazy call to PyType_Ready in PyObject_Hash) ++class DefaultIterSeq(object): ++ seq = range(10) ++ def __len__(self): ++ return len(self.seq) ++ def __getitem__(self, index): ++ return self.seq[index] ++ ++class HashBuiltinsTestCase(unittest.TestCase): ++ hashes_to_check = [xrange(10), ++ enumerate(xrange(10)), ++ iter(DefaultIterSeq()), ++ iter(lambda: 0, 0), ++ ] ++ ++ def test_hashes(self): ++ _default_hash = object.__hash__ ++ for obj in self.hashes_to_check: ++ self.assertEqual(hash(obj), _default_hash(obj)) ++ + def test_main(): + test_support.run_unittest(HashEqualityTestCase, +- HashInheritanceTestCase) ++ HashInheritanceTestCase, ++ HashBuiltinsTestCase) + + + if __name__ == "__main__": +Index: Lib/test/test_multiprocessing.py +=================================================================== +--- Lib/test/test_multiprocessing.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_multiprocessing.py (.../branches/release26-maint) (Revision 70449) +@@ -829,11 +829,17 @@ + obj3 = val3.get_obj() + self.assertEqual(lock, lock3) + +- arr4 = self.RawValue('i', 5) ++ arr4 = self.Value('i', 5, lock=False) + self.assertFalse(hasattr(arr4, 'get_lock')) + self.assertFalse(hasattr(arr4, 'get_obj')) + ++ self.assertRaises(AttributeError, self.Value, 'i', 5, lock='navalue') + ++ arr5 = self.RawValue('i', 5) ++ self.assertFalse(hasattr(arr5, 'get_lock')) ++ self.assertFalse(hasattr(arr5, 'get_obj')) ++ ++ + class _TestArray(BaseTestCase): + + def f(self, seq): +@@ -887,10 +893,16 @@ + obj3 = arr3.get_obj() + self.assertEqual(lock, lock3) + +- arr4 = self.RawArray('i', range(10)) ++ arr4 = self.Array('i', range(10), lock=False) + self.assertFalse(hasattr(arr4, 'get_lock')) + self.assertFalse(hasattr(arr4, 'get_obj')) ++ self.assertRaises(AttributeError, ++ self.Array, 'i', range(10), lock='notalock') + ++ arr5 = self.RawArray('i', range(10)) ++ self.assertFalse(hasattr(arr5, 'get_lock')) ++ self.assertFalse(hasattr(arr5, 'get_obj')) ++ + # + # + # +Index: Lib/test/test_zipfile.py +=================================================================== +--- Lib/test/test_zipfile.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_zipfile.py (.../branches/release26-maint) (Revision 70449) +@@ -11,9 +11,10 @@ + from random import randint, random + + import test.test_support as support +-from test.test_support import TESTFN, run_unittest ++from test.test_support import TESTFN, run_unittest, findfile + + TESTFN2 = TESTFN + "2" ++TESTFNDIR = TESTFN + "d" + FIXEDTEST_SIZE = 1000 + + SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'), +@@ -982,7 +983,29 @@ + def tearDown(self): + os.remove(TESTFN2) + ++class TestWithDirectory(unittest.TestCase): ++ def setUp(self): ++ os.mkdir(TESTFN2) + ++ def testExtractDir(self): ++ zipf = zipfile.ZipFile(findfile("zipdir.zip")) ++ zipf.extractall(TESTFN2) ++ self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a"))) ++ self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b"))) ++ self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c"))) ++ ++ def testStoreDir(self): ++ os.mkdir(os.path.join(TESTFN2, "x")) ++ zipf = zipfile.ZipFile(TESTFN, "w") ++ zipf.write(os.path.join(TESTFN2, "x"), "x") ++ self.assertTrue(zipf.filelist[0].filename.endswith("x/")) ++ ++ def tearDown(self): ++ shutil.rmtree(TESTFN2) ++ if os.path.exists(TESTFN): ++ os.remove(TESTFN) ++ ++ + class UniversalNewlineTests(unittest.TestCase): + def setUp(self): + self.line_gen = ["Test of zipfile line %d." % i for i in xrange(FIXEDTEST_SIZE)] +@@ -1090,6 +1113,7 @@ + def test_main(): + run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, + PyZipFileTests, DecryptionTests, TestsWithMultipleOpens, ++ TestWithDirectory, + UniversalNewlineTests, TestsWithRandomBinaryFiles) + + if __name__ == "__main__": +Index: Lib/test/test_urllib2.py +=================================================================== +--- Lib/test/test_urllib2.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_urllib2.py (.../branches/release26-maint) (Revision 70449) +@@ -1104,7 +1104,52 @@ + else: + self.assert_(False) + ++class RequestTests(unittest.TestCase): + ++ def setUp(self): ++ self.get = urllib2.Request("http://www.python.org/~jeremy/") ++ self.post = urllib2.Request("http://www.python.org/~jeremy/", ++ "data", ++ headers={"X-Test": "test"}) ++ ++ def test_method(self): ++ self.assertEqual("POST", self.post.get_method()) ++ self.assertEqual("GET", self.get.get_method()) ++ ++ def test_add_data(self): ++ self.assert_(not self.get.has_data()) ++ self.assertEqual("GET", self.get.get_method()) ++ self.get.add_data("spam") ++ self.assert_(self.get.has_data()) ++ self.assertEqual("POST", self.get.get_method()) ++ ++ def test_get_full_url(self): ++ self.assertEqual("http://www.python.org/~jeremy/", ++ self.get.get_full_url()) ++ ++ def test_selector(self): ++ self.assertEqual("/~jeremy/", self.get.get_selector()) ++ req = urllib2.Request("http://www.python.org/") ++ self.assertEqual("/", req.get_selector()) ++ ++ def test_get_type(self): ++ self.assertEqual("http", self.get.get_type()) ++ ++ def test_get_host(self): ++ self.assertEqual("www.python.org", self.get.get_host()) ++ ++ def test_get_host_unquote(self): ++ req = urllib2.Request("http://www.%70ython.org/") ++ self.assertEqual("www.python.org", req.get_host()) ++ ++ def test_proxy(self): ++ self.assert_(not self.get.has_proxy()) ++ self.get.set_proxy("www.perl.org", "http") ++ self.assert_(self.get.has_proxy()) ++ self.assertEqual("www.python.org", self.get.get_origin_req_host()) ++ self.assertEqual("www.perl.org", self.get.get_host()) ++ ++ + def test_main(verbose=None): + from test import test_urllib2 + test_support.run_doctest(test_urllib2, verbose) +@@ -1112,7 +1157,8 @@ + tests = (TrivialTests, + OpenerDirectorTests, + HandlerTests, +- MiscTests) ++ MiscTests, ++ RequestTests) + test_support.run_unittest(*tests) + + if __name__ == "__main__": +Index: Lib/test/test_support.py +=================================================================== +--- Lib/test/test_support.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_support.py (.../branches/release26-maint) (Revision 70449) +@@ -357,6 +357,18 @@ + withcommas = ", ".join(reprpairs) + return "{%s}" % withcommas + ++def make_bad_fd(): ++ """ ++ Create an invalid file descriptor by opening and closing a file and return ++ its fd. ++ """ ++ file = open(TESTFN, "wb") ++ try: ++ return file.fileno() ++ finally: ++ file.close() ++ unlink(TESTFN) ++ + def check_syntax_error(testcase, statement): + try: + compile(statement, '', 'exec') +Index: Lib/test/test_collections.py +=================================================================== +--- Lib/test/test_collections.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_collections.py (.../branches/release26-maint) (Revision 70449) +@@ -154,8 +154,25 @@ + self.assertEqual(p, q) + self.assertEqual(p._fields, q._fields) + +-class TestOneTrickPonyABCs(unittest.TestCase): ++class ABCTestCase(unittest.TestCase): + ++ def validate_abstract_methods(self, abc, *names): ++ methodstubs = dict.fromkeys(names, lambda s, *args: 0) ++ ++ # everything should work will all required methods are present ++ C = type('C', (abc,), methodstubs) ++ C() ++ ++ # instantiation should fail if a required method is missing ++ for name in names: ++ stubs = methodstubs.copy() ++ del stubs[name] ++ C = type('C', (abc,), stubs) ++ self.assertRaises(TypeError, C, name) ++ ++ ++class TestOneTrickPonyABCs(ABCTestCase): ++ + def test_Hashable(self): + # Check some non-hashables + non_samples = [list(), set(), dict()] +@@ -180,6 +197,7 @@ + __eq__ = Hashable.__eq__ # Silence Py3k warning + self.assertEqual(hash(H()), 0) + self.failIf(issubclass(int, H)) ++ self.validate_abstract_methods(Hashable, '__hash__') + + def test_Iterable(self): + # Check some non-iterables +@@ -203,6 +221,7 @@ + return super(I, self).__iter__() + self.assertEqual(list(I()), []) + self.failIf(issubclass(str, I)) ++ self.validate_abstract_methods(Iterable, '__iter__') + + def test_Iterator(self): + non_samples = [None, 42, 3.14, 1j, "".encode('ascii'), "", (), [], +@@ -221,6 +240,7 @@ + for x in samples: + self.failUnless(isinstance(x, Iterator), repr(x)) + self.failUnless(issubclass(type(x), Iterator), repr(type(x))) ++ self.validate_abstract_methods(Iterator, 'next') + + def test_Sized(self): + non_samples = [None, 42, 3.14, 1j, +@@ -237,6 +257,7 @@ + for x in samples: + self.failUnless(isinstance(x, Sized), repr(x)) + self.failUnless(issubclass(type(x), Sized), repr(type(x))) ++ self.validate_abstract_methods(Sized, '__len__') + + def test_Container(self): + non_samples = [None, 42, 3.14, 1j, +@@ -253,6 +274,7 @@ + for x in samples: + self.failUnless(isinstance(x, Container), repr(x)) + self.failUnless(issubclass(type(x), Container), repr(type(x))) ++ self.validate_abstract_methods(Container, '__contains__') + + def test_Callable(self): + non_samples = [None, 42, 3.14, 1j, +@@ -271,6 +293,7 @@ + for x in samples: + self.failUnless(isinstance(x, Callable), repr(x)) + self.failUnless(issubclass(type(x), Callable), repr(type(x))) ++ self.validate_abstract_methods(Callable, '__call__') + + def test_direct_subclassing(self): + for B in Hashable, Iterable, Iterator, Sized, Container, Callable: +@@ -289,7 +312,7 @@ + self.failUnless(issubclass(C, B)) + + +-class TestCollectionABCs(unittest.TestCase): ++class TestCollectionABCs(ABCTestCase): + + # XXX For now, we only test some virtual inheritance properties. + # We should also test the proper behavior of the collection ABCs +@@ -299,6 +322,7 @@ + for sample in [set, frozenset]: + self.failUnless(isinstance(sample(), Set)) + self.failUnless(issubclass(sample, Set)) ++ self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') + + def test_hash_Set(self): + class OneTwoThreeSet(Set): +@@ -320,22 +344,60 @@ + self.failUnless(issubclass(set, MutableSet)) + self.failIf(isinstance(frozenset(), MutableSet)) + self.failIf(issubclass(frozenset, MutableSet)) ++ self.validate_abstract_methods(MutableSet, '__contains__', '__iter__', '__len__', ++ 'add', 'discard') + ++ def test_issue_4920(self): ++ # MutableSet.pop() method did not work ++ class MySet(collections.MutableSet): ++ __slots__=['__s'] ++ def __init__(self,items=None): ++ if items is None: ++ items=[] ++ self.__s=set(items) ++ def __contains__(self,v): ++ return v in self.__s ++ def __iter__(self): ++ return iter(self.__s) ++ def __len__(self): ++ return len(self.__s) ++ def add(self,v): ++ result=v not in self.__s ++ self.__s.add(v) ++ return result ++ def discard(self,v): ++ result=v in self.__s ++ self.__s.discard(v) ++ return result ++ def __repr__(self): ++ return "MySet(%s)" % repr(list(self)) ++ s = MySet([5,43,2,1]) ++ self.assertEqual(s.pop(), 1) ++ + def test_Mapping(self): + for sample in [dict]: + self.failUnless(isinstance(sample(), Mapping)) + self.failUnless(issubclass(sample, Mapping)) ++ self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', ++ '__getitem__') + + def test_MutableMapping(self): + for sample in [dict]: + self.failUnless(isinstance(sample(), MutableMapping)) + self.failUnless(issubclass(sample, MutableMapping)) ++ self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__', ++ '__getitem__', '__setitem__', '__delitem__') + + def test_Sequence(self): + for sample in [tuple, list, str]: + self.failUnless(isinstance(sample(), Sequence)) + self.failUnless(issubclass(sample, Sequence)) + self.failUnless(issubclass(basestring, Sequence)) ++ self.failUnless(isinstance(range(10), Sequence)) ++ self.failUnless(issubclass(xrange, Sequence)) ++ self.failUnless(issubclass(str, Sequence)) ++ self.validate_abstract_methods(Sequence, '__contains__', '__iter__', '__len__', ++ '__getitem__') + + def test_MutableSequence(self): + for sample in [tuple, str]: +@@ -345,6 +407,8 @@ + self.failUnless(isinstance(sample(), MutableSequence)) + self.failUnless(issubclass(sample, MutableSequence)) + self.failIf(issubclass(basestring, MutableSequence)) ++ self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__', ++ '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert') + + import doctest, collections + +Index: Lib/test/test_ast.py +=================================================================== +--- Lib/test/test_ast.py (.../tags/r261) (Revision 70449) ++++ Lib/test/test_ast.py (.../branches/release26-maint) (Revision 70449) +@@ -271,7 +271,6 @@ + self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None)) + self.assertRaises(ValueError, ast.literal_eval, 'foo()') + +- + def test_main(): + test_support.run_unittest(AST_Tests, ASTHelpers_Test) + +Index: Lib/locale.py +=================================================================== +--- Lib/locale.py (.../tags/r261) (Revision 70449) ++++ Lib/locale.py (.../branches/release26-maint) (Revision 70449) +@@ -108,6 +108,19 @@ + # Author: Martin von Loewis + # improved by Georg Brandl + ++# Iterate over grouping intervals ++def _grouping_intervals(grouping): ++ for interval in grouping: ++ # if grouping is -1, we are done ++ if interval == CHAR_MAX: ++ return ++ # 0: re-use last group ad infinitum ++ if interval == 0: ++ while True: ++ yield last_interval ++ yield interval ++ last_interval = interval ++ + #perform the grouping from right to left + def _group(s, monetary=False): + conv = localeconv() +@@ -117,36 +130,42 @@ + return (s, 0) + result = "" + seps = 0 +- spaces = "" + if s[-1] == ' ': +- sp = s.find(' ') +- spaces = s[sp:] +- s = s[:sp] +- while s and grouping: +- # if grouping is -1, we are done +- if grouping[0] == CHAR_MAX: ++ stripped = s.rstrip() ++ right_spaces = s[len(stripped):] ++ s = stripped ++ else: ++ right_spaces = '' ++ left_spaces = '' ++ groups = [] ++ for interval in _grouping_intervals(grouping): ++ if not s or s[-1] not in "0123456789": ++ # only non-digit characters remain (sign, spaces) ++ left_spaces = s ++ s = '' + break +- # 0: re-use last group ad infinitum +- elif grouping[0] != 0: +- #process last group +- group = grouping[0] +- grouping = grouping[1:] +- if result: +- result = s[-group:] + thousands_sep + result +- seps += 1 +- else: +- result = s[-group:] +- s = s[:-group] +- if s and s[-1] not in "0123456789": +- # the leading string is only spaces and signs +- return s + result + spaces, seps +- if not result: +- return s + spaces, seps ++ groups.append(s[-interval:]) ++ s = s[:-interval] + if s: +- result = s + thousands_sep + result +- seps += 1 +- return result + spaces, seps ++ groups.append(s) ++ groups.reverse() ++ return ( ++ left_spaces + thousands_sep.join(groups) + right_spaces, ++ len(groups) - 1 ++ ) + ++# Strip a given amount of excess padding from the given string ++def _strip_padding(s, amount): ++ lpos = 0 ++ while amount and s[lpos] == ' ': ++ lpos += 1 ++ amount -= 1 ++ rpos = len(s) - 1 ++ while amount and s[rpos] == ' ': ++ rpos -= 1 ++ amount -= 1 ++ return s[lpos:rpos+1] ++ + def format(percent, value, grouping=False, monetary=False, *additional): + """Returns the locale-aware substitution of a %? specifier + (percent). +@@ -170,14 +189,14 @@ + decimal_point = localeconv()[monetary and 'mon_decimal_point' + or 'decimal_point'] + formatted = decimal_point.join(parts) +- while seps: +- sp = formatted.find(' ') +- if sp == -1: break +- formatted = formatted[:sp] + formatted[sp+1:] +- seps -= 1 ++ if seps: ++ formatted = _strip_padding(formatted, seps) + elif percent[-1] in 'diu': ++ seps = 0 + if grouping: +- formatted = _group(formatted, monetary=monetary)[0] ++ formatted, seps = _group(formatted, monetary=monetary) ++ if seps: ++ formatted = _strip_padding(formatted, seps) + return formatted + + import re, operator +Index: Lib/plat-mac/videoreader.py +=================================================================== +--- Lib/plat-mac/videoreader.py (.../tags/r261) (Revision 70449) ++++ Lib/plat-mac/videoreader.py (.../branches/release26-maint) (Revision 70449) +@@ -18,7 +18,7 @@ + from Carbon import QDOffscreen + from Carbon import Res + try: +- import MediaDescr ++ from Carbon import MediaDescr + except ImportError: + def _audiodescr(data): + return None +Index: Lib/plat-mac/EasyDialogs.py +=================================================================== +--- Lib/plat-mac/EasyDialogs.py (.../tags/r261) (Revision 70449) ++++ Lib/plat-mac/EasyDialogs.py (.../branches/release26-maint) (Revision 70449) +@@ -573,7 +573,7 @@ + del d + + def _process_Nav_args(dftflags, **args): +- import aepack ++ import Carbon.AppleEvents + import Carbon.AE + import Carbon.File + for k in args.keys(): +@@ -585,11 +585,14 @@ + if args.has_key('defaultLocation') and \ + not isinstance(args['defaultLocation'], Carbon.AE.AEDesc): + defaultLocation = args['defaultLocation'] +- if isinstance(defaultLocation, (Carbon.File.FSSpec, Carbon.File.FSRef)): +- args['defaultLocation'] = aepack.pack(defaultLocation) ++ if isinstance(defaultLocation, Carbon.File.FSSpec): ++ args['defaultLocation'] = Carbon.AE.AECreateDesc( ++ Carbon.AppleEvents.typeFSS, defaultLocation.data) + else: +- defaultLocation = Carbon.File.FSRef(defaultLocation) +- args['defaultLocation'] = aepack.pack(defaultLocation) ++ if not isinstance(defaultLocation, Carbon.File.FSRef): ++ defaultLocation = Carbon.File.FSRef(defaultLocation) ++ args['defaultLocation'] = Carbon.AE.AECreateDesc( ++ Carbon.AppleEvents.typeFSRef, defaultLocation.data) + if args.has_key('typeList') and not isinstance(args['typeList'], Carbon.Res.ResourceType): + typeList = args['typeList'][:] + # Workaround for OSX typeless files: +Index: Lib/plat-mac/macostools.py +=================================================================== +--- Lib/plat-mac/macostools.py (.../tags/r261) (Revision 70449) ++++ Lib/plat-mac/macostools.py (.../branches/release26-maint) (Revision 70449) +@@ -62,8 +62,15 @@ + if os.sep == ':' and not ':' in head: + head = head + ':' + mkdirs(head) +- os.mkdir(dst, 0777) + ++ try: ++ os.mkdir(dst, 0777) ++ except OSError, e: ++ # be happy if someone already created the path ++ if e.errno != errno.EEXIST: ++ raise ++ ++ + def touched(dst): + """Tell the finder a file has changed. No-op on MacOSX.""" + import warnings +Index: Makefile.pre.in +=================================================================== +--- Makefile.pre.in (.../tags/r261) (Revision 70449) ++++ Makefile.pre.in (.../branches/release26-maint) (Revision 70449) +@@ -412,14 +412,18 @@ + + libpython$(VERSION).so: $(LIBRARY_OBJS) + if test $(INSTSONAME) != $(LDLIBRARY); then \ +- $(LDSHARED) $(LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ $(LDSHARED) $(LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + $(LN) -f $(INSTSONAME) $@; \ +- else\ +- $(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ else \ ++ $(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + fi + ++libpython$(VERSION).dylib: $(LIBRARY_OBJS) ++ $(CC) -dynamiclib -Wl,-single_module $(LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ ++ + libpython$(VERSION).sl: $(LIBRARY_OBJS) +- $(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST) ++ $(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST) + + # This rule is here for OPENSTEP/Rhapsody/MacOSX. It builds a temporary + # minimal framework (not including the Lib directory and such) in the current +@@ -561,6 +565,9 @@ + Objects/unicodeobject.o: $(srcdir)/Objects/unicodeobject.c \ + $(STRINGLIB_HEADERS) + ++Objects/bytearrayobject.o: $(srcdir)/Objects/bytearrayobject.c \ ++ $(STRINGLIB_HEADERS) ++ + Objects/stringobject.o: $(srcdir)/Objects/stringobject.c \ + $(STRINGLIB_HEADERS) + +@@ -581,6 +588,7 @@ + Include/ast.h \ + Include/bitset.h \ + Include/boolobject.h \ ++ Include/bytearrayobject.h \ + Include/bytes_methods.h \ + Include/bytesobject.h \ + Include/bufferobject.h \ +@@ -768,13 +776,13 @@ + fi; \ + done + $(INSTALL_PROGRAM) $(BUILDPYTHON) $(DESTDIR)$(BINDIR)/python$(VERSION)$(EXE) +- if test -f libpython$(VERSION)$(SO); then \ +- if test "$(SO)" = .dll; then \ +- $(INSTALL_SHARED) libpython$(VERSION)$(SO) $(DESTDIR)$(BINDIR); \ ++ if test -f $(LDLIBRARY); then \ ++ if test -n "$(DLLLIBRARY)" ; then \ ++ $(INSTALL_SHARED) $(DLLLIBRARY) $(DESTDIR)$(BINDIR); \ + else \ +- $(INSTALL_SHARED) libpython$(VERSION)$(SO) $(DESTDIR)$(LIBDIR)/$(INSTSONAME); \ +- if test libpython$(VERSION)$(SO) != $(INSTSONAME); then \ +- (cd $(DESTDIR)$(LIBDIR); $(LN) -sf $(INSTSONAME) libpython$(VERSION)$(SO)); \ ++ $(INSTALL_SHARED) $(LDLIBRARY) $(DESTDIR)$(LIBDIR)/$(INSTSONAME); \ ++ if test $(LDLIBRARY) != $(INSTSONAME); then \ ++ (cd $(DESTDIR)$(LIBDIR); $(LN) -sf $(INSTSONAME) $(LDLIBRARY)) \ + fi \ + fi; \ + else true; \ +@@ -905,7 +913,7 @@ + export PYTHONPATH; PYTHONPATH="`pwd`/Lib"; \ + export DYLD_FRAMEWORK_PATH; DYLD_FRAMEWORK_PATH="`pwd`"; \ + export EXE; EXE="$(BUILDEXE)"; \ +- cd $(srcdir)/Lib/$(PLATDIR); ./regen ++ cd $(srcdir)/Lib/$(PLATDIR); $(RUNSHARED) ./regen + + # Install the include files + INCLDIRSTOMAKE=$(INCLUDEDIR) $(CONFINCLUDEDIR) $(INCLUDEPY) $(CONFINCLUDEPY) +@@ -1068,7 +1076,7 @@ + # This installs the Demos and Tools into the applications directory. + # It is not part of a normal frameworkinstall + frameworkinstallextras: +- cd Mac && Make installextras DESTDIR="$(DESTDIR)" ++ cd Mac && $(MAKE) installextras DESTDIR="$(DESTDIR)" + + # This installs a few of the useful scripts in Tools/scripts + scriptsinstall: +Index: Modules/_ssl.c +=================================================================== +--- Modules/_ssl.c (.../tags/r261) (Revision 70449) ++++ Modules/_ssl.c (.../branches/release26-maint) (Revision 70449) +@@ -1542,7 +1542,7 @@ + for (i = 0; i < _ssl_locks_count; i++) { + _ssl_locks[i] = PyThread_allocate_lock(); + if (_ssl_locks[i] == NULL) { +- int j; ++ unsigned int j; + for (j = 0; j < i; j++) { + PyThread_free_lock(_ssl_locks[j]); + } +Index: Modules/_tkinter.c +=================================================================== +--- Modules/_tkinter.c (.../tags/r261) (Revision 70449) ++++ Modules/_tkinter.c (.../branches/release26-maint) (Revision 70449) +@@ -1256,7 +1256,9 @@ + *(e->res) = Tkapp_CallResult(e->self); + } + LEAVE_PYTHON +- done: ++ ++ Tkapp_CallDeallocArgs(objv, objStore, objc); ++done: + /* Wake up calling thread. */ + Tcl_MutexLock(&call_mutex); + Tcl_ConditionNotify(&e->done); +@@ -1284,8 +1286,7 @@ + int objc, i; + PyObject *res = NULL; + TkappObject *self = (TkappObject*)selfptr; +- /* Could add TCL_EVAL_GLOBAL if wrapped by GlobalCall... */ +- int flags = TCL_EVAL_DIRECT; ++ int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL; + + /* If args is a single tuple, replace with contents of tuple */ + if (1 == PyTuple_Size(args)){ +@@ -2029,7 +2030,7 @@ + return PythonCmd_Error(interp); + } + else { +- Tcl_SetObjResult(Tkapp_Interp(self), obj_res); ++ Tcl_SetObjResult(interp, obj_res); + rv = TCL_OK; + } + +Index: Modules/_ctypes/callproc.c +=================================================================== +--- Modules/_ctypes/callproc.c (.../tags/r261) (Revision 70449) ++++ Modules/_ctypes/callproc.c (.../branches/release26-maint) (Revision 70449) +@@ -664,6 +664,7 @@ + return 0; + #else + int size = PyUnicode_GET_SIZE(obj); ++ pa->ffi_type = &ffi_type_pointer; + size += 1; /* terminating NUL */ + size *= sizeof(wchar_t); + pa->value.p = PyMem_Malloc(size); +Index: Modules/_ctypes/cfield.c +=================================================================== +--- Modules/_ctypes/cfield.c (.../tags/r261) (Revision 70449) ++++ Modules/_ctypes/cfield.c (.../branches/release26-maint) (Revision 70449) +@@ -1452,11 +1452,14 @@ + size += 1; /* terminating NUL */ + size *= sizeof(wchar_t); + buffer = (wchar_t *)PyMem_Malloc(size); +- if (!buffer) ++ if (!buffer) { ++ Py_DECREF(value); + return PyErr_NoMemory(); ++ } + memset(buffer, 0, size); + keep = PyCObject_FromVoidPtr(buffer, PyMem_Free); + if (!keep) { ++ Py_DECREF(value); + PyMem_Free(buffer); + return NULL; + } +Index: Modules/mmapmodule.c +=================================================================== +--- Modules/mmapmodule.c (.../tags/r261) (Revision 70449) ++++ Modules/mmapmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -112,7 +112,7 @@ + #ifdef MS_WINDOWS + if (m_obj->data != NULL) + UnmapViewOfFile (m_obj->data); +- if (m_obj->map_handle != INVALID_HANDLE_VALUE) ++ if (m_obj->map_handle != NULL) + CloseHandle (m_obj->map_handle); + if (m_obj->file_handle != INVALID_HANDLE_VALUE) + CloseHandle (m_obj->file_handle); +@@ -147,9 +147,9 @@ + UnmapViewOfFile(self->data); + self->data = NULL; + } +- if (self->map_handle != INVALID_HANDLE_VALUE) { ++ if (self->map_handle != NULL) { + CloseHandle(self->map_handle); +- self->map_handle = INVALID_HANDLE_VALUE; ++ self->map_handle = NULL; + } + if (self->file_handle != INVALID_HANDLE_VALUE) { + CloseHandle(self->file_handle); +@@ -173,7 +173,7 @@ + #ifdef MS_WINDOWS + #define CHECK_VALID(err) \ + do { \ +- if (self->map_handle == INVALID_HANDLE_VALUE) { \ ++ if (self->map_handle == NULL) { \ + PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ + return err; \ + } \ +@@ -365,10 +365,17 @@ + + if (!is_writeable(self)) + return NULL; +- *(self->data+self->pos) = value; +- self->pos += 1; +- Py_INCREF(Py_None); +- return Py_None; ++ ++ if (self->pos < self->size) { ++ *(self->data+self->pos) = value; ++ self->pos += 1; ++ Py_INCREF(Py_None); ++ return Py_None; ++ } ++ else { ++ PyErr_SetString(PyExc_ValueError, "write byte out of range"); ++ return NULL; ++ } + } + + static PyObject * +@@ -434,8 +441,10 @@ + DWORD off_hi, off_lo, newSizeLow, newSizeHigh; + /* First, unmap the file view */ + UnmapViewOfFile(self->data); ++ self->data = NULL; + /* Close the mapping object */ + CloseHandle(self->map_handle); ++ self->map_handle = NULL; + /* Move to the desired EOF position */ + #if SIZEOF_SIZE_T > 4 + newSizeHigh = (DWORD)((self->offset + new_size) >> 32); +@@ -444,7 +453,7 @@ + off_lo = (DWORD)(self->offset & 0xFFFFFFFF); + #else + newSizeHigh = 0; +- newSizeLow = (DWORD)new_size; ++ newSizeLow = (DWORD)(self->offset + new_size); + off_hi = 0; + off_lo = (DWORD)self->offset; + #endif +@@ -472,6 +481,8 @@ + return Py_None; + } else { + dwErrCode = GetLastError(); ++ CloseHandle(self->map_handle); ++ self->map_handle = NULL; + } + } else { + dwErrCode = GetLastError(); +@@ -490,7 +501,7 @@ + } else { + void *newmap; + +- if (ftruncate(self->fd, new_size) == -1) { ++ if (ftruncate(self->fd, self->offset + new_size) == -1) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } +@@ -731,7 +742,7 @@ + return NULL; + if (i < 0) + i += self->size; +- if (i < 0 || (size_t)i > self->size) { ++ if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, + "mmap index out of range"); + return NULL; +@@ -872,7 +883,7 @@ + return -1; + if (i < 0) + i += self->size; +- if (i < 0 || (size_t)i > self->size) { ++ if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, + "mmap index out of range"); + return -1; +@@ -1272,7 +1283,7 @@ + destruct the object in the face of failure */ + m_obj->data = NULL; + m_obj->file_handle = INVALID_HANDLE_VALUE; +- m_obj->map_handle = INVALID_HANDLE_VALUE; ++ m_obj->map_handle = NULL; + m_obj->tagname = NULL; + m_obj->offset = offset; + +@@ -1366,11 +1377,14 @@ + dwDesiredAccess, + off_hi, + off_lo, +- 0); ++ m_obj->size); + if (m_obj->data != NULL) + return (PyObject *)m_obj; +- else ++ else { + dwErr = GetLastError(); ++ CloseHandle(m_obj->map_handle); ++ m_obj->map_handle = NULL; ++ } + } else + dwErr = GetLastError(); + Py_DECREF(m_obj); +Index: Modules/_hotshot.c +=================================================================== +--- Modules/_hotshot.c (.../tags/r261) (Revision 70449) ++++ Modules/_hotshot.c (.../branches/release26-maint) (Revision 70449) +@@ -1357,20 +1357,16 @@ + self->logfp = fopen(filename, "rb"); + if (self->logfp == NULL) { + PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename); +- Py_DECREF(self); +- self = NULL; +- goto finally; ++ goto error; + } + self->info = PyDict_New(); +- if (self->info == NULL) { +- Py_DECREF(self); +- goto finally; +- } ++ if (self->info == NULL) ++ goto error; + /* read initial info */ + for (;;) { + if ((c = fgetc(self->logfp)) == EOF) { + eof_error(self); +- break; ++ goto error; + } + if (c != WHAT_ADD_INFO) { + ungetc(c, self->logfp); +@@ -1383,13 +1379,15 @@ + else + PyErr_SetString(PyExc_RuntimeError, + "unexpected error"); +- break; ++ goto error; + } + } + } + } +- finally: + return (PyObject *) self; ++ error: ++ Py_DECREF(self); ++ return NULL; + } + + +Index: Modules/_fileio.c +=================================================================== +--- Modules/_fileio.c (.../tags/r261) (Revision 70449) ++++ Modules/_fileio.c (.../branches/release26-maint) (Revision 70449) +@@ -41,6 +41,9 @@ + + #define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type)) + ++static PyObject * ++portable_lseek(int fd, PyObject *posobj, int whence); ++ + /* Returns 0 on success, errno (which is < 0) on failure. */ + static int + internal_close(PyFileIOObject *self) +@@ -61,10 +64,7 @@ + fileio_close(PyFileIOObject *self) + { + if (!self->closefd) { +- if (PyErr_WarnEx(PyExc_RuntimeWarning, +- "Trying to close unclosable fd!", 3) < 0) { +- return NULL; +- } ++ self->fd = -1; + Py_RETURN_NONE; + } + errno = internal_close(self); +@@ -101,7 +101,7 @@ + directories, so we need a check. */ + + static int +-dircheck(PyFileIOObject* self) ++dircheck(PyFileIOObject* self, char *name) + { + #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR) + struct stat buf; +@@ -112,8 +112,8 @@ + PyObject *exc; + internal_close(self); + +- exc = PyObject_CallFunction(PyExc_IOError, "(is)", +- EISDIR, msg); ++ exc = PyObject_CallFunction(PyExc_IOError, "(iss)", ++ EISDIR, msg, name); + PyErr_SetObject(PyExc_IOError, exc); + Py_XDECREF(exc); + return -1; +@@ -122,7 +122,25 @@ + return 0; + } + ++static int ++check_fd(int fd) ++{ ++#if defined(HAVE_FSTAT) ++ struct stat buf; ++ if (fstat(fd, &buf) < 0 && errno == EBADF) { ++ PyObject *exc; ++ char *msg = strerror(EBADF); ++ exc = PyObject_CallFunction(PyExc_OSError, "(is)", ++ EBADF, msg); ++ PyErr_SetObject(PyExc_OSError, exc); ++ Py_XDECREF(exc); ++ return -1; ++ } ++#endif ++ return 0; ++} + ++ + static int + fileio_init(PyObject *oself, PyObject *args, PyObject *kwds) + { +@@ -154,6 +172,8 @@ + "Negative filedescriptor"); + return -1; + } ++ if (check_fd(fd)) ++ return -1; + } + else { + PyErr_Clear(); +@@ -211,6 +231,8 @@ + flags |= O_CREAT; + append = 1; + break; ++ case 'b': ++ break; + case '+': + if (plus) + goto bad_mode; +@@ -266,16 +288,27 @@ + Py_END_ALLOW_THREADS + if (self->fd < 0) { + #ifdef MS_WINDOWS +- PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); +-#else +- PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); ++ if (widename != NULL) ++ PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); ++ else + #endif ++ PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); + goto error; + } +- if(dircheck(self) < 0) ++ if(dircheck(self, name) < 0) + goto error; + } + ++ if (append) { ++ /* For consistent behaviour, we explicitly seek to the ++ end of file (otherwise, it might be done only on the ++ first write()). */ ++ PyObject *pos = portable_lseek(self->fd, NULL, 2); ++ if (pos == NULL) ++ goto error; ++ Py_DECREF(pos); ++ } ++ + goto done; + + error: +@@ -685,12 +718,12 @@ + { + if (self->readable) { + if (self->writable) +- return "r+"; ++ return "rb+"; + else +- return "r"; ++ return "rb"; + } + else +- return "w"; ++ return "wb"; + } + + static PyObject * +@@ -821,6 +854,12 @@ + } + + static PyObject * ++get_closefd(PyFileIOObject *self, void *closure) ++{ ++ return PyBool_FromLong((long)(self->closefd)); ++} ++ ++static PyObject * + get_mode(PyFileIOObject *self, void *closure) + { + return PyString_FromString(mode_string(self)); +@@ -828,6 +867,8 @@ + + static PyGetSetDef fileio_getsetlist[] = { + {"closed", (getter)get_closed, NULL, "True if the file is closed"}, ++ {"closefd", (getter)get_closefd, NULL, ++ "True if the file descriptor will be closed"}, + {"mode", (getter)get_mode, NULL, "String giving the file mode"}, + {0}, + }; +Index: Modules/parsermodule.c +=================================================================== +--- Modules/parsermodule.c (.../tags/r261) (Revision 70449) ++++ Modules/parsermodule.c (.../branches/release26-maint) (Revision 70449) +@@ -2057,6 +2057,7 @@ + + /* try_stmt: + * 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] ++ ['finally' ':' suite] + * | 'try' ':' suite 'finally' ':' suite + * + */ +@@ -2082,36 +2083,35 @@ + PyErr_Format(parser_error, + "Illegal number of children for try/%s node.", name); + } +- /* Skip past except_clause sections: */ ++ /* Handle try/finally statement */ ++ if (res && (TYPE(CHILD(tree, pos)) == NAME) && ++ (strcmp(STR(CHILD(tree, pos)), "finally") == 0)) { ++ res = (validate_numnodes(tree, 6, "try/finally") ++ && validate_colon(CHILD(tree, 4)) ++ && validate_suite(CHILD(tree, 5))); ++ return (res); ++ } ++ /* try/except statement: skip past except_clause sections */ + while (res && (TYPE(CHILD(tree, pos)) == except_clause)) { + res = (validate_except_clause(CHILD(tree, pos)) + && validate_colon(CHILD(tree, pos + 1)) + && validate_suite(CHILD(tree, pos + 2))); + pos += 3; + } +- if (res && (pos < nch)) { +- res = validate_ntype(CHILD(tree, pos), NAME); +- if (res && (strcmp(STR(CHILD(tree, pos)), "finally") == 0)) +- res = (validate_numnodes(tree, 6, "try/finally") +- && validate_colon(CHILD(tree, 4)) +- && validate_suite(CHILD(tree, 5))); +- else if (res) { +- if (nch == (pos + 3)) { +- res = ((strcmp(STR(CHILD(tree, pos)), "except") == 0) +- || (strcmp(STR(CHILD(tree, pos)), "else") == 0)); +- if (!res) +- err_string("illegal trailing triple in try statement"); +- } +- else if (nch == (pos + 6)) { +- res = (validate_name(CHILD(tree, pos), "except") +- && validate_colon(CHILD(tree, pos + 1)) +- && validate_suite(CHILD(tree, pos + 2)) +- && validate_name(CHILD(tree, pos + 3), "else")); +- } +- else +- res = validate_numnodes(tree, pos + 3, "try/except"); +- } ++ /* skip else clause */ ++ if (res && (TYPE(CHILD(tree, pos)) == NAME) && ++ (strcmp(STR(CHILD(tree, pos)), "else") == 0)) { ++ res = (validate_colon(CHILD(tree, pos + 1)) ++ && validate_suite(CHILD(tree, pos + 2))); ++ pos += 3; + } ++ if (res && pos < nch) { ++ /* last clause must be a finally */ ++ res = (validate_name(CHILD(tree, pos), "finally") ++ && validate_numnodes(tree, pos + 3, "try/except/finally") ++ && validate_colon(CHILD(tree, pos + 1)) ++ && validate_suite(CHILD(tree, pos + 2))); ++ } + return (res); + } + +Index: Modules/cmathmodule.c +=================================================================== +--- Modules/cmathmodule.c (.../tags/r261) (Revision 70449) ++++ Modules/cmathmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -368,7 +368,7 @@ + + PyDoc_STRVAR(c_cos_doc, + "cos(x)\n" +-"n" ++"\n" + "Return the cosine of x."); + + +@@ -427,7 +427,7 @@ + + PyDoc_STRVAR(c_cosh_doc, + "cosh(x)\n" +-"n" ++"\n" + "Return the hyperbolic cosine of x."); + + +Index: Modules/_testcapimodule.c +=================================================================== +--- Modules/_testcapimodule.c (.../tags/r261) (Revision 70449) ++++ Modules/_testcapimodule.c (.../branches/release26-maint) (Revision 70449) +@@ -173,6 +173,106 @@ + } + + ++/* Issue #4701: Check that PyObject_Hash implicitly calls ++ * PyType_Ready if it hasn't already been called ++ */ ++static PyTypeObject _HashInheritanceTester_Type = { ++ PyObject_HEAD_INIT(NULL) ++ 0, /* Number of items for varobject */ ++ "hashinheritancetester", /* Name of this type */ ++ sizeof(PyObject), /* Basic object size */ ++ 0, /* Item size for varobject */ ++ (destructor)PyObject_Del, /* tp_dealloc */ ++ 0, /* tp_print */ ++ 0, /* tp_getattr */ ++ 0, /* tp_setattr */ ++ 0, /* tp_compare */ ++ 0, /* tp_repr */ ++ 0, /* tp_as_number */ ++ 0, /* tp_as_sequence */ ++ 0, /* tp_as_mapping */ ++ 0, /* tp_hash */ ++ 0, /* tp_call */ ++ 0, /* tp_str */ ++ PyObject_GenericGetAttr, /* tp_getattro */ ++ 0, /* tp_setattro */ ++ 0, /* tp_as_buffer */ ++ Py_TPFLAGS_DEFAULT, /* tp_flags */ ++ 0, /* tp_doc */ ++ 0, /* tp_traverse */ ++ 0, /* tp_clear */ ++ 0, /* tp_richcompare */ ++ 0, /* tp_weaklistoffset */ ++ 0, /* tp_iter */ ++ 0, /* tp_iternext */ ++ 0, /* tp_methods */ ++ 0, /* tp_members */ ++ 0, /* tp_getset */ ++ 0, /* tp_base */ ++ 0, /* tp_dict */ ++ 0, /* tp_descr_get */ ++ 0, /* tp_descr_set */ ++ 0, /* tp_dictoffset */ ++ 0, /* tp_init */ ++ 0, /* tp_alloc */ ++ PyType_GenericNew, /* tp_new */ ++}; ++ ++static PyObject* ++test_lazy_hash_inheritance(PyObject* self) ++{ ++ PyTypeObject *type; ++ PyObject *obj; ++ long hash; ++ ++ type = &_HashInheritanceTester_Type; ++ obj = PyObject_New(PyObject, type); ++ if (obj == NULL) { ++ PyErr_Clear(); ++ PyErr_SetString( ++ TestError, ++ "test_lazy_hash_inheritance: failed to create object"); ++ return NULL; ++ } ++ ++ if (type->tp_dict != NULL) { ++ PyErr_SetString( ++ TestError, ++ "test_lazy_hash_inheritance: type initialised too soon"); ++ Py_DECREF(obj); ++ return NULL; ++ } ++ ++ hash = PyObject_Hash(obj); ++ if ((hash == -1) && PyErr_Occurred()) { ++ PyErr_Clear(); ++ PyErr_SetString( ++ TestError, ++ "test_lazy_hash_inheritance: could not hash object"); ++ Py_DECREF(obj); ++ return NULL; ++ } ++ ++ if (type->tp_dict == NULL) { ++ PyErr_SetString( ++ TestError, ++ "test_lazy_hash_inheritance: type not initialised by hash()"); ++ Py_DECREF(obj); ++ return NULL; ++ } ++ ++ if (type->tp_hash != PyType_Type.tp_hash) { ++ PyErr_SetString( ++ TestError, ++ "test_lazy_hash_inheritance: unexpected hash function"); ++ Py_DECREF(obj); ++ return NULL; ++ } ++ ++ Py_RETURN_NONE; ++} ++ ++ + /* Tests of PyLong_{As, From}{Unsigned,}Long(), and (#ifdef HAVE_LONG_LONG) + PyLong_{As, From}{Unsigned,}LongLong(). + +@@ -474,6 +574,8 @@ + + #ifdef Py_USING_UNICODE + ++static volatile int x; ++ + /* Test the u and u# codes for PyArg_ParseTuple. May leak memory in case + of an error. + */ +@@ -486,7 +588,7 @@ + + /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */ + /* Just use the macro and check that it compiles */ +- int x = Py_UNICODE_ISSPACE(25); ++ x = Py_UNICODE_ISSPACE(25); + + tuple = PyTuple_New(1); + if (tuple == NULL) +@@ -519,6 +621,32 @@ + } + + static PyObject * ++test_empty_argparse(PyObject *self) ++{ ++ /* Test that formats can begin with '|'. See issue #4720. */ ++ PyObject *tuple, *dict = NULL; ++ static char *kwlist[] = {NULL}; ++ int result; ++ tuple = PyTuple_New(0); ++ if (!tuple) ++ return NULL; ++ if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0) ++ goto done; ++ dict = PyDict_New(); ++ if (!dict) ++ goto done; ++ result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist); ++ done: ++ Py_DECREF(tuple); ++ Py_XDECREF(dict); ++ if (result < 0) ++ return NULL; ++ else { ++ Py_RETURN_NONE; ++ } ++} ++ ++static PyObject * + codec_incrementalencoder(PyObject *self, PyObject *args) + { + const char *encoding, *errors = NULL; +@@ -777,9 +905,11 @@ + {"test_config", (PyCFunction)test_config, METH_NOARGS}, + {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS}, + {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS}, ++ {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS}, + {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS}, + {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS}, + {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS}, ++ {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS}, + {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS}, + {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS}, + {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS, +@@ -962,6 +1092,8 @@ + if (m == NULL) + return; + ++ Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type; ++ + Py_TYPE(&test_structmembersType)=&PyType_Type; + Py_INCREF(&test_structmembersType); + PyModule_AddObject(m, "test_structmembersType", (PyObject *)&test_structmembersType); +Index: Modules/_collectionsmodule.c +=================================================================== +--- Modules/_collectionsmodule.c (.../tags/r261) (Revision 70449) ++++ Modules/_collectionsmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -958,7 +958,7 @@ + { + dequeiterobject *it; + +- it = PyObject_New(dequeiterobject, &dequeiter_type); ++ it = PyObject_GC_New(dequeiterobject, &dequeiter_type); + if (it == NULL) + return NULL; + it->b = deque->leftblock; +@@ -967,14 +967,22 @@ + it->deque = deque; + it->state = deque->state; + it->counter = deque->len; ++ PyObject_GC_Track(it); + return (PyObject *)it; + } + ++static int ++dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg) ++{ ++ Py_VISIT(dio->deque); ++ return 0; ++} ++ + static void + dequeiter_dealloc(dequeiterobject *dio) + { + Py_XDECREF(dio->deque); +- Py_TYPE(dio)->tp_free(dio); ++ PyObject_GC_Del(dio); + } + + static PyObject * +@@ -1039,9 +1047,9 @@ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ +- Py_TPFLAGS_DEFAULT, /* tp_flags */ ++ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ +- 0, /* tp_traverse */ ++ (traverseproc)dequeiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +@@ -1060,7 +1068,7 @@ + { + dequeiterobject *it; + +- it = PyObject_New(dequeiterobject, &dequereviter_type); ++ it = PyObject_GC_New(dequeiterobject, &dequereviter_type); + if (it == NULL) + return NULL; + it->b = deque->rightblock; +@@ -1069,6 +1077,7 @@ + it->deque = deque; + it->state = deque->state; + it->counter = deque->len; ++ PyObject_GC_Track(it); + return (PyObject *)it; + } + +@@ -1121,9 +1130,9 @@ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ +- Py_TPFLAGS_DEFAULT, /* tp_flags */ ++ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ +- 0, /* tp_traverse */ ++ (traverseproc)dequeiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +Index: Modules/main.c +=================================================================== +--- Modules/main.c (.../tags/r261) (Revision 70449) ++++ Modules/main.c (.../branches/release26-maint) (Revision 70449) +@@ -86,7 +86,7 @@ + -x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\ + "; + static char *usage_4 = "\ +--3 : warn about Python 3.x incompatibilities\n\ ++-3 : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix\n\ + file : program read from script file\n\ + - : program read from stdin (default; interactive mode if a tty)\n\ + arg ...: arguments passed to program in sys.argv[1:]\n\n\ +@@ -317,6 +317,8 @@ + + case '3': + Py_Py3kWarningFlag++; ++ if (!Py_DivisionWarningFlag) ++ Py_DivisionWarningFlag = 1; + break; + + case 'Q': +Index: Modules/itertoolsmodule.c +=================================================================== +--- Modules/itertoolsmodule.c (.../tags/r261) (Revision 70449) ++++ Modules/itertoolsmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -2059,10 +2059,6 @@ + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } +- if (r > n) { +- PyErr_SetString(PyExc_ValueError, "r cannot be bigger than the iterable"); +- goto error; +- } + + indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL) { +@@ -2082,7 +2078,7 @@ + co->indices = indices; + co->result = NULL; + co->r = r; +- co->stopped = 0; ++ co->stopped = r > n ? 1 : 0; + + return (PyObject *)co; + +@@ -2318,10 +2314,6 @@ + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } +- if (r > n) { +- PyErr_SetString(PyExc_ValueError, "r cannot be bigger than the iterable"); +- goto error; +- } + + indices = PyMem_Malloc(n * sizeof(Py_ssize_t)); + cycles = PyMem_Malloc(r * sizeof(Py_ssize_t)); +@@ -2345,7 +2337,7 @@ + po->cycles = cycles; + po->result = NULL; + po->r = r; +- po->stopped = 0; ++ po->stopped = r > n ? 1 : 0; + + return (PyObject *)po; + +Index: Modules/mathmodule.c +=================================================================== +--- Modules/mathmodule.c (.../tags/r261) (Revision 70449) ++++ Modules/mathmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -137,6 +137,58 @@ + } + + /* ++ Various platforms (Solaris, OpenBSD) do nonstandard things for log(0), ++ log(-ve), log(NaN). Here are wrappers for log and log10 that deal with ++ special values directly, passing positive non-special values through to ++ the system log/log10. ++ */ ++ ++static double ++m_log(double x) ++{ ++ if (Py_IS_FINITE(x)) { ++ if (x > 0.0) ++ return log(x); ++ errno = EDOM; ++ if (x == 0.0) ++ return -Py_HUGE_VAL; /* log(0) = -inf */ ++ else ++ return Py_NAN; /* log(-ve) = nan */ ++ } ++ else if (Py_IS_NAN(x)) ++ return x; /* log(nan) = nan */ ++ else if (x > 0.0) ++ return x; /* log(inf) = inf */ ++ else { ++ errno = EDOM; ++ return Py_NAN; /* log(-inf) = nan */ ++ } ++} ++ ++static double ++m_log10(double x) ++{ ++ if (Py_IS_FINITE(x)) { ++ if (x > 0.0) ++ return log10(x); ++ errno = EDOM; ++ if (x == 0.0) ++ return -Py_HUGE_VAL; /* log10(0) = -inf */ ++ else ++ return Py_NAN; /* log10(-ve) = nan */ ++ } ++ else if (Py_IS_NAN(x)) ++ return x; /* log10(nan) = nan */ ++ else if (x > 0.0) ++ return x; /* log10(inf) = inf */ ++ else { ++ errno = EDOM; ++ return Py_NAN; /* log10(-inf) = nan */ ++ } ++} ++ ++ ++/* + math_1 is used to wrap a libm function f that takes a double + arguments and returns a double. + +@@ -578,7 +630,10 @@ + return NULL; + } + +-PyDoc_STRVAR(math_factorial_doc, "Return n!"); ++PyDoc_STRVAR(math_factorial_doc, ++"factorial(x) -> Integral\n" ++"\n" ++"Find x!. Raise a ValueError if x is negative or non-integral."); + + static PyObject * + math_trunc(PyObject *self, PyObject *number) +@@ -712,7 +767,7 @@ + "modf(x)\n" + "\n" + "Return the fractional and integer parts of x. Both results carry the sign\n" +-"of x. The integer part is returned as a real."); ++"of x and are floats."); + + /* A decent logarithm is easy to compute even for huge longs, but libm can't + do that by itself -- loghelper can. func is log or log10, and name is +@@ -758,11 +813,11 @@ + if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base)) + return NULL; + +- num = loghelper(arg, log, "log"); ++ num = loghelper(arg, m_log, "log"); + if (num == NULL || base == NULL) + return num; + +- den = loghelper(base, log, "log"); ++ den = loghelper(base, m_log, "log"); + if (den == NULL) { + Py_DECREF(num); + return NULL; +@@ -781,7 +836,7 @@ + static PyObject * + math_log10(PyObject *self, PyObject *arg) + { +- return loghelper(arg, log10, "log10"); ++ return loghelper(arg, m_log10, "log10"); + } + + PyDoc_STRVAR(math_log10_doc, +Index: Modules/socketmodule.c +=================================================================== +--- Modules/socketmodule.c (.../tags/r261) (Revision 70449) ++++ Modules/socketmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -3334,7 +3334,11 @@ + #ifdef HAVE_GETHOSTBYNAME_R_3_ARG + struct hostent_data data; + #else +- char buf[16384]; ++ /* glibcs up to 2.10 assume that the buf argument to ++ gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc ++ does not ensure. The attribute below instructs the compiler ++ to maintain this alignment. */ ++ char buf[16384] Py_ALIGNED(8); + int buf_len = (sizeof buf) - 1; + int errnop; + #endif +Index: Modules/_multiprocessing/semaphore.c +=================================================================== +--- Modules/_multiprocessing/semaphore.c (.../tags/r261) (Revision 70449) ++++ Modules/_multiprocessing/semaphore.c (.../branches/release26-maint) (Revision 70449) +@@ -512,7 +512,6 @@ + static PyObject * + semlock_iszero(SemLockObject *self) + { +- int sval; + #if HAVE_BROKEN_SEM_GETVALUE + if (sem_trywait(self->handle) < 0) { + if (errno == EAGAIN) +@@ -524,6 +523,7 @@ + Py_RETURN_FALSE; + } + #else ++ int sval; + if (SEM_GETVALUE(self->handle, &sval) < 0) + return mp_SetError(NULL, MP_STANDARD_ERROR); + return PyBool_FromLong((long)sval == 0); +Index: Modules/dbmmodule.c +=================================================================== +--- Modules/dbmmodule.c (.../tags/r261) (Revision 70449) ++++ Modules/dbmmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -21,6 +21,9 @@ + #elif defined(HAVE_GDBM_NDBM_H) + #include + static char *which_dbm = "GNU gdbm"; ++#elif defined(HAVE_GDBM_DASH_NDBM_H) ++#include ++static char *which_dbm = "GNU gdbm"; + #elif defined(HAVE_BERKDB_H) + #include + static char *which_dbm = "Berkeley DB"; +Index: Modules/zipimport.c +=================================================================== +--- Modules/zipimport.c (.../tags/r261) (Revision 70449) ++++ Modules/zipimport.c (.../branches/release26-maint) (Revision 70449) +@@ -369,6 +369,29 @@ + return NULL; + } + ++/* Return a string matching __file__ for the named module */ ++static PyObject * ++zipimporter_get_filename(PyObject *obj, PyObject *args) ++{ ++ ZipImporter *self = (ZipImporter *)obj; ++ PyObject *code; ++ char *fullname, *modpath; ++ int ispackage; ++ ++ if (!PyArg_ParseTuple(args, "s:zipimporter._get_filename", ++ &fullname)) ++ return NULL; ++ ++ /* Deciding the filename requires working out where the code ++ would come from if the module was actually loaded */ ++ code = get_module_code(self, fullname, &ispackage, &modpath); ++ if (code == NULL) ++ return NULL; ++ Py_DECREF(code); /* Only need the path info */ ++ ++ return PyString_FromString(modpath); ++} ++ + /* Return a bool signifying whether the module is a package or not. */ + static PyObject * + zipimporter_is_package(PyObject *obj, PyObject *args) +@@ -528,6 +551,12 @@ + is the module couldn't be found, return None if the archive does\n\ + contain the module, but has no source for it."); + ++ ++PyDoc_STRVAR(doc_get_filename, ++"_get_filename(fullname) -> filename string.\n\ ++\n\ ++Return the filename for the specified module."); ++ + static PyMethodDef zipimporter_methods[] = { + {"find_module", zipimporter_find_module, METH_VARARGS, + doc_find_module}, +@@ -539,6 +568,8 @@ + doc_get_code}, + {"get_source", zipimporter_get_source, METH_VARARGS, + doc_get_source}, ++ {"_get_filename", zipimporter_get_filename, METH_VARARGS, ++ doc_get_filename}, + {"is_package", zipimporter_is_package, METH_VARARGS, + doc_is_package}, + {NULL, NULL} /* sentinel */ +Index: Modules/_struct.c +=================================================================== +--- Modules/_struct.c (.../tags/r261) (Revision 70449) ++++ Modules/_struct.c (.../branches/release26-maint) (Revision 70449) +@@ -663,7 +663,7 @@ + return -1; + #if (SIZEOF_LONG > SIZEOF_INT) + if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX))) +- return _range_error(f, 0); ++ RANGE_ERROR(x, f, 0, -1); + #endif + y = (int)x; + memcpy(p, (char *)&y, sizeof y); +@@ -675,12 +675,12 @@ + { + unsigned long x; + unsigned int y; +- if (get_ulong(v, &x) < 0) +- return _range_error(f, 1); ++ if (get_wrapped_ulong(v, &x) < 0) ++ return -1; + y = (unsigned int)x; + #if (SIZEOF_LONG > SIZEOF_INT) + if (x > ((unsigned long)UINT_MAX)) +- return _range_error(f, 1); ++ RANGE_ERROR(y, f, 1, -1); + #endif + memcpy(p, (char *)&y, sizeof y); + return 0; +@@ -700,8 +700,8 @@ + np_ulong(char *p, PyObject *v, const formatdef *f) + { + unsigned long x; +- if (get_ulong(v, &x) < 0) +- return _range_error(f, 1); ++ if (get_wrapped_ulong(v, &x) < 0) ++ return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; + } +Index: Modules/gcmodule.c +=================================================================== +--- Modules/gcmodule.c (.../tags/r261) (Revision 70449) ++++ Modules/gcmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -740,6 +740,24 @@ + (void)PyFloat_ClearFreeList(); + } + ++static double ++get_time(void) ++{ ++ double result = 0; ++ if (tmod != NULL) { ++ PyObject *f = PyObject_CallMethod(tmod, "time", NULL); ++ if (f == NULL) { ++ PyErr_Clear(); ++ } ++ else { ++ if (PyFloat_Check(f)) ++ result = PyFloat_AsDouble(f); ++ Py_DECREF(f); ++ } ++ } ++ return result; ++} ++ + /* This is the main function. Read this to understand how the + * collection process works. */ + static Py_ssize_t +@@ -762,16 +780,7 @@ + } + + if (debug & DEBUG_STATS) { +- if (tmod != NULL) { +- PyObject *f = PyObject_CallMethod(tmod, "time", NULL); +- if (f == NULL) { +- PyErr_Clear(); +- } +- else { +- t1 = PyFloat_AsDouble(f); +- Py_DECREF(f); +- } +- } ++ t1 = get_time(); + PySys_WriteStderr("gc: collecting generation %d...\n", + generation); + PySys_WriteStderr("gc: objects in each generation:"); +@@ -844,17 +853,6 @@ + if (debug & DEBUG_COLLECTABLE) { + debug_cycle("collectable", FROM_GC(gc)); + } +- if (tmod != NULL && (debug & DEBUG_STATS)) { +- PyObject *f = PyObject_CallMethod(tmod, "time", NULL); +- if (f == NULL) { +- PyErr_Clear(); +- } +- else { +- t1 = PyFloat_AsDouble(f)-t1; +- Py_DECREF(f); +- PySys_WriteStderr("gc: %.4fs elapsed.\n", t1); +- } +- } + } + + /* Clear weakrefs and invoke callbacks as necessary. */ +@@ -876,14 +874,19 @@ + debug_cycle("uncollectable", FROM_GC(gc)); + } + if (debug & DEBUG_STATS) { ++ double t2 = get_time(); + if (m == 0 && n == 0) +- PySys_WriteStderr("gc: done.\n"); ++ PySys_WriteStderr("gc: done"); + else + PySys_WriteStderr( + "gc: done, " + "%" PY_FORMAT_SIZE_T "d unreachable, " +- "%" PY_FORMAT_SIZE_T "d uncollectable.\n", ++ "%" PY_FORMAT_SIZE_T "d uncollectable", + n+m, n); ++ if (t1 && t2) { ++ PySys_WriteStderr(", %.4fs elapsed", t2-t1); ++ } ++ PySys_WriteStderr(".\n"); + } + + /* Append instances in the uncollectable set to a Python +Index: Modules/posixmodule.c +=================================================================== +--- Modules/posixmodule.c (.../tags/r261) (Revision 70449) ++++ Modules/posixmodule.c (.../branches/release26-maint) (Revision 70449) +@@ -2393,13 +2393,27 @@ + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { +- Py_UNICODE woutbuf[MAX_PATH*2]; ++ Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); ++ Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; + Py_UNICODE *wtemp; +- if (!GetFullPathNameW(PyUnicode_AS_UNICODE(po), +- sizeof(woutbuf)/sizeof(woutbuf[0]), +- woutbuf, &wtemp)) +- return win32_error("GetFullPathName", ""); +- return PyUnicode_FromUnicode(woutbuf, wcslen(woutbuf)); ++ DWORD result; ++ PyObject *v; ++ result = GetFullPathNameW(wpath, ++ sizeof(woutbuf)/sizeof(woutbuf[0]), ++ woutbuf, &wtemp); ++ if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { ++ woutbufp = malloc(result * sizeof(Py_UNICODE)); ++ if (!woutbufp) ++ return PyErr_NoMemory(); ++ result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); ++ } ++ if (result) ++ v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); ++ else ++ v = win32_error_unicode("GetFullPathNameW", wpath); ++ if (woutbufp != woutbuf) ++ free(woutbufp); ++ return v; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ +@@ -5947,10 +5961,6 @@ + + + #ifdef HAVE_TIMES +-#ifndef HZ +-#define HZ 60 /* Universal constant :-) */ +-#endif /* HZ */ +- + #if defined(PYCC_VACPP) && defined(PYOS_OS2) + static long + system_uptime(void) +@@ -5976,6 +5986,8 @@ + (double)system_uptime() / 1000); + } + #else /* not OS2 */ ++#define NEED_TICKS_PER_SECOND ++static long ticks_per_second = -1; + static PyObject * + posix_times(PyObject *self, PyObject *noargs) + { +@@ -5986,11 +5998,11 @@ + if (c == (clock_t) -1) + return posix_error(); + return Py_BuildValue("ddddd", +- (double)t.tms_utime / HZ, +- (double)t.tms_stime / HZ, +- (double)t.tms_cutime / HZ, +- (double)t.tms_cstime / HZ, +- (double)c / HZ); ++ (double)t.tms_utime / ticks_per_second, ++ (double)t.tms_stime / ticks_per_second, ++ (double)t.tms_cutime / ticks_per_second, ++ (double)t.tms_cstime / ticks_per_second, ++ (double)c / ticks_per_second); + } + #endif /* not OS2 */ + #endif /* HAVE_TIMES */ +@@ -8952,6 +8964,15 @@ + + statvfs_result_desc.name = MODNAME ".statvfs_result"; + PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); ++#ifdef NEED_TICKS_PER_SECOND ++# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK) ++ ticks_per_second = sysconf(_SC_CLK_TCK); ++# elif defined(HZ) ++ ticks_per_second = HZ; ++# else ++ ticks_per_second = 60; /* magic fallback value; may be bogus */ ++# endif ++#endif + } + Py_INCREF((PyObject*) &StatResultType); + PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); +Index: Modules/cPickle.c +=================================================================== +--- Modules/cPickle.c (.../tags/r261) (Revision 70449) ++++ Modules/cPickle.c (.../branches/release26-maint) (Revision 70449) +@@ -18,6 +18,14 @@ + #define HIGHEST_PROTOCOL 2 + + /* ++ * Note: The UNICODE macro controls the TCHAR meaning of the win32 API. Since ++ * all headers have already been included here, we can safely redefine it. ++ */ ++#ifdef UNICODE ++# undef UNICODE ++#endif ++ ++/* + * Pickle opcodes. These must be kept in synch with pickle.py. Extensive + * docs are in pickletools.py. + */ +@@ -1255,42 +1263,91 @@ + /* A copy of PyUnicode_EncodeRawUnicodeEscape() that also translates + backslash and newline characters to \uXXXX escapes. */ + static PyObject * +-modified_EncodeRawUnicodeEscape(const Py_UNICODE *s, int size) ++modified_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size) + { +- PyObject *repr; +- char *p; +- char *q; ++ PyObject *repr; ++ char *p; ++ char *q; + +- static const char *hexdigit = "0123456789ABCDEF"; ++ static const char *hexdigit = "0123456789abcdef"; ++#ifdef Py_UNICODE_WIDE ++ const Py_ssize_t expandsize = 10; ++#else ++ const Py_ssize_t expandsize = 6; ++#endif + +- repr = PyString_FromStringAndSize(NULL, 6 * size); +- if (repr == NULL) +- return NULL; +- if (size == 0) +- return repr; ++ if (size > PY_SSIZE_T_MAX / expandsize) ++ return PyErr_NoMemory(); + +- p = q = PyString_AS_STRING(repr); +- while (size-- > 0) { +- Py_UNICODE ch = *s++; +- /* Map 16-bit characters to '\uxxxx' */ +- if (ch >= 256 || ch == '\\' || ch == '\n') { +- *p++ = '\\'; +- *p++ = 'u'; +- *p++ = hexdigit[(ch >> 12) & 0xf]; +- *p++ = hexdigit[(ch >> 8) & 0xf]; +- *p++ = hexdigit[(ch >> 4) & 0xf]; +- *p++ = hexdigit[ch & 15]; +- } +- /* Copy everything else as-is */ +- else +- *p++ = (char) ch; ++ repr = PyString_FromStringAndSize(NULL, expandsize * size); ++ if (repr == NULL) ++ return NULL; ++ if (size == 0) ++ return repr; ++ ++ p = q = PyString_AS_STRING(repr); ++ while (size-- > 0) { ++ Py_UNICODE ch = *s++; ++#ifdef Py_UNICODE_WIDE ++ /* Map 32-bit characters to '\Uxxxxxxxx' */ ++ if (ch >= 0x10000) { ++ *p++ = '\\'; ++ *p++ = 'U'; ++ *p++ = hexdigit[(ch >> 28) & 0xf]; ++ *p++ = hexdigit[(ch >> 24) & 0xf]; ++ *p++ = hexdigit[(ch >> 20) & 0xf]; ++ *p++ = hexdigit[(ch >> 16) & 0xf]; ++ *p++ = hexdigit[(ch >> 12) & 0xf]; ++ *p++ = hexdigit[(ch >> 8) & 0xf]; ++ *p++ = hexdigit[(ch >> 4) & 0xf]; ++ *p++ = hexdigit[ch & 15]; ++ } ++ else ++#else ++ /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */ ++ if (ch >= 0xD800 && ch < 0xDC00) { ++ Py_UNICODE ch2; ++ Py_UCS4 ucs; ++ ++ ch2 = *s++; ++ size--; ++ if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { ++ ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000; ++ *p++ = '\\'; ++ *p++ = 'U'; ++ *p++ = hexdigit[(ucs >> 28) & 0xf]; ++ *p++ = hexdigit[(ucs >> 24) & 0xf]; ++ *p++ = hexdigit[(ucs >> 20) & 0xf]; ++ *p++ = hexdigit[(ucs >> 16) & 0xf]; ++ *p++ = hexdigit[(ucs >> 12) & 0xf]; ++ *p++ = hexdigit[(ucs >> 8) & 0xf]; ++ *p++ = hexdigit[(ucs >> 4) & 0xf]; ++ *p++ = hexdigit[ucs & 0xf]; ++ continue; ++ } ++ /* Fall through: isolated surrogates are copied as-is */ ++ s--; ++ size++; + } +- *p = '\0'; +- _PyString_Resize(&repr, p - q); +- return repr; ++#endif ++ /* Map 16-bit characters to '\uxxxx' */ ++ if (ch >= 256 || ch == '\\' || ch == '\n') { ++ *p++ = '\\'; ++ *p++ = 'u'; ++ *p++ = hexdigit[(ch >> 12) & 0xf]; ++ *p++ = hexdigit[(ch >> 8) & 0xf]; ++ *p++ = hexdigit[(ch >> 4) & 0xf]; ++ *p++ = hexdigit[ch & 15]; ++ } ++ /* Copy everything else as-is */ ++ else ++ *p++ = (char) ch; ++ } ++ *p = '\0'; ++ _PyString_Resize(&repr, p - q); ++ return repr; + } + +- + static int + save_unicode(Picklerobject *self, PyObject *args, int doput) + { +@@ -3408,7 +3465,8 @@ + errno = 0; + d = PyOS_ascii_strtod(s, &endptr); + +- if (errno || (endptr[0] != '\n') || (endptr[1] != '\0')) { ++ if ((errno == ERANGE && !(fabs(d) <= 1.0)) || ++ (endptr[0] != '\n') || (endptr[1] != '\0')) { + PyErr_SetString(PyExc_ValueError, + "could not convert string to float"); + goto finally; + +Eigenschaftsänderungen: . +___________________________________________________________________ +Geändert: svnmerge-blocked + - /python/trunk:66721-66722,66744-66745,66752,66756,66763-66765,66768,66791-66792,66822-66823,66832,66836,66852,66857,66868,66878,66894,66902,66912,66989,66994,67013,67015,67049,67065 + + /python/trunk:66721-66722,66744-66745,66752,66756,66763-66765,66768,66791-66792,66822-66823,66832,66836,66852,66857,66868,66878,66894,66902,66912,66989,66994,67013,67015,67049,67065,67171,67226,67234,67287,67342,67348-67349,67353,67396,67407,67411,67442,67511,67521,67536-67537,67543,67572,67584,67587,67601,67614,67628,67818,67822,67850,67857,67902,67946,67954,67976,67978-67980,67985,68089,68092,68119,68150,68153,68156,68158,68163,68167,68176,68203,68208-68209,68231,68238,68240,68243,68319,68381,68395,68415,68425,68432,68455,68458-68462,68484-68485,68496,68498,68532,68542,68544-68546,68559-68560,68562,68565-68569,68571,68592,68597,68603-68604,68648,68665,68764,68766,68773,68785,68789,68792-68793,68803,68805,68831,68840,68843,68845,68850,68853,68881,68884,68892,68925,68927,68929,68933,68941,68943,68953,68985,68998,69001,69010,69012,69018,69039,69050,69053,69060-69063,69169,69195,69211-69212,69252-69253,69285,69324,69330-69332,69342,69356,69360,69366,69377,69385,69404,69419-69420,69425,69460,69467,69470,69474,69566,69594,69609-69610,69666,69692-69693,69700,69710,69724,69861,69874,69878,69881,69902,69976,70003,70007,70017,70049,70094,70212,70223,70308,70364,70378,70439,70444 +Geändert: svnmerge-integrated + - /python/trunk:1-66720,66723-66743,66746-66751,66753-66755,66757-66762,66766-66767,66769-66790,66793-66821,66824-66831,66833-66835,66837-66851,66853-66856,66858-66867,66869-66877,66879-66893,66895-66901,66903-66911,66913-66988,66990-66993,66995-67012,67014,67016-67048,67050-67064,67066-67125,67143,67149,67180,67227,67246,67266,67278-67279,67283,67291,67318,67320,67343,67365,67373,67414,67419,67428,67449,67455,67458,67467 + + /python/trunk:1-66720,66723-66743,66746-66751,66753-66755,66757-66762,66766-66767,66769-66790,66793-66821,66824-66831,66833-66835,66837-66851,66853-66856,66858-66867,66869-66877,66879-66893,66895-66901,66903-66911,66913-66988,66990-66993,66995-67012,67014,67016-67048,67050-67064,67066-67170,67172-67225,67227-67233,67235-67286,67288-67341,67343-67347,67350-67352,67354-67395,67397-67406,67408-67410,67412-67441,67443-67510,67512-67520,67522-67535,67538-67542,67544-67571,67573-67583,67585-67586,67588-67600,67602-67613,67615-67627,67629-67817,67819-67821,67823-67849,67851-67856,67858-67901,67903-67945,67947-67953,67955-67975,67977,67981-67984,67986-68088,68090-68091,68093-68118,68120-68131,68133-68149,68151-68152,68154-68155,68157,68159-68162,68164-68166,68168-68175,68177-68202,68204-68207,68210-68222,68232,68276,68288-68295,68297-68298,68300-68301,68303,68305-68310,68312-68313,68315-68318,68320-68380,68382-68394,68396-68414,68416-68424,68426-68431,68433-68454,68456-68457,68463-68475,68477-68483,68486,68488-68495,68497,68499-68515,68521-68531,68533-68541,68543,68547-68558,68561,68563-68564,68570,68572-68591,68593-68595,68598-68602,68606,68608-68617,68619-68622,68625-68627,68629-68632,68634-68647,68649-68664,68666,68668-68675,68677-68704,68707-68721,68723-68738,68740-68749,68751-68759,68761-68762,68765,68767,68769-68771,68774-68775,68778-68784,68786,68788,68790-68791,68794-68796,68798-68800,68802,68804,68806,68808-68810,68812-68825,68827-68828,68830,68832-68838,68841,68844,68846-68849,68851-68852,68854-68861,68863-68873,68875-68880,68882-68883,68885-68891,68893-68914,68916-68924,68926,68928,68930-68932,68934-68940,68944,68946-68952,68954-68963,68965-68984,68986-68997,68999-69000,69002,69004-69009,69011,69013,69015-69017,69019-69022,69024-69038,69040-69049,69051-69052,69054-69059,69064-69069,69071-69073,69075-69079,69081-69084,69086,69088-69111,69114-69128,69132-69133,69135-69138,69142,69144-69145,69147-69148,69150-69153,69160,69162-69168,69170-69194,69196-69210,69213-69226,69228-69236,69238-69239,69241,69243-69251,69254-69256,69258-69259,69261,69263-69267,69269-69270,69274-69275,69277-69284,69286-69301,69306-69314,69316-69321,69323,69325-69329,69333-69341,69343-69355,69357-69359,69361-69363,69367-69372,69375-69376,69378-69384,69386-69388,69390-69393,69395-69403,69405-69409,69411-69412,69414,69416,69418,69421-69424,69426-69434,69436-69441,69444-69446,69448-69458,69461-69465,69468-69469,69471-69472,69475-69479,69482-69494,69496-69497,69499-69508,69510-69515,69517-69518,69523-69524,69526-69527,69529,69531-69560,69562-69565,69567-69577,69581,69584-69588,69590,69592,69595-69601,69603,69605-69608,69611-69616,69618,69620-69632,69635-69638,69640-69665,69667-69671,69673-69684,69686-69687,69691,69694-69699,69701-69702,69705-69708,69711-69714,69718-69723,69725-69730,69732-69738,69740-69742,69744-69747,69749-69750,69752-69756,69758-69760,69762-69764,69766-69769,69771,69773-69776,69778-69794,69796-69810,69812-69836,69839-69845,69847-69854,69856-69860,69862-69869,69872-69873,69875-69877,69879-69880,69882-69888,69890-69896,69905,70052,70056,70062,70078,70086,70088,70107,70137,70167,70169,70172,70176,70189,70193,70197,70218-70219,70356,70368,70430,70448 + --- python2.6-2.6.1.orig/debian/patches/series +++ python2.6-2.6.1/debian/patches/series @@ -0,0 +1,22 @@ +deb-setup +deb-locations +locale-module +distutils-link +distutils-sysconfig +test-sundry +tkinter-import +link-opt +egg-info-no-version +debug-build +hotshot-import +profile-doc +subprocess-eintr-safety +webbrowser +linecache +doc-nodownload + +# FIXME +#arm-float, for arm only + +# FIXME +# enable-fpectl, if enabled --- python2.6-2.6.1.orig/debian/patches/arm-float.dpatch +++ python2.6-2.6.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); + } --- python2.6-2.6.1.orig/debian/patches/webbrowser.dpatch +++ python2.6-2.6.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")) --- python2.6-2.6.1.orig/debian/patches/apport-support.dpatch +++ python2.6-2.6.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() + --- python2.6-2.6.1.orig/debian/patches/debug-build.dpatch +++ python2.6-2.6.1/debian/patches/debug-build.dpatch @@ -0,0 +1,147 @@ +#! /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 2008-05-22 18:05:31.000000000 +0200 ++++ ./Python/sysmodule.c 2008-05-22 18:07:52.000000000 +0200 +@@ -1394,6 +1394,12 @@ + FlagsType.tp_init = NULL; + FlagsType.tp_new = NULL; + ++#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-05-22 18:05:31.000000000 +0200 ++++ ./Python/dynload_shlib.c 2008-05-22 18:06:13.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-22 18:05:31.000000000 +0200 ++++ ./Lib/distutils/command/build.py 2008-05-22 18:14:43.000000000 +0200 +@@ -95,7 +95,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 2008-05-22 18:05:31.000000000 +0200 ++++ ./Lib/distutils/sysconfig.py 2008-05-22 18:06:13.000000000 +0200 +@@ -81,7 +81,8 @@ + if not os.path.exists(inc_dir): + inc_dir = os.path.join(os.path.dirname(base), "Include") + return inc_dir +- return os.path.join(prefix, "include", "python" + get_python_version()) ++ return os.path.join(prefix, "include", ++ "python" + get_python_version() + (sys.pydebug and '_d' or '')) + elif os.name == "nt": + return os.path.join(prefix, "include") + elif os.name == "mac": +@@ -220,7 +221,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 2008-05-22 18:05:31.000000000 +0200 ++++ ./Makefile.pre.in 2008-05-22 18:06:13.000000000 +0200 +@@ -96,8 +96,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 +@@ -110,6 +110,8 @@ + EXE= @EXEEXT@ + BUILDEXE= @BUILDEXEEXT@ + ++DEBUG_EXT= @DEBUG_EXT@ ++ + # Short name and location for Mac OS X Python framework + UNIVERSALSDK=@UNIVERSALSDK@ + PYTHONFRAMEWORK= @PYTHONFRAMEWORK@ +@@ -919,8 +921,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) + libainstall: all + @for i in $(LIBDIR) $(LIBP) $(LIBPL); \ + do \ +--- ./configure.in.orig 2008-05-22 18:05:31.000000000 +0200 ++++ ./configure.in 2008-05-22 18:06:13.000000000 +0200 +@@ -752,6 +752,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? + +@@ -1473,7 +1479,7 @@ + esac + ;; + CYGWIN*) SO=.dll;; +- *) SO=.so;; ++ *) SO=$DEBUG_EXT.so;; + esac + else + # this might also be a termcap variable, see #610332 --- python2.6-2.6.1.orig/debian/patches/pydebug-path.dpatch +++ python2.6-2.6.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': --- python2.6-2.6.1.orig/debian/patches/profiled-build.dpatch +++ python2.6-2.6.1/debian/patches/profiled-build.dpatch @@ -0,0 +1,36 @@ +#! /bin/sh -e + +# DP: Fix profiled build; don't use Python/thread.gc*, gcc complains + +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~ 2008-11-14 12:13:11.000000000 +0100 ++++ Makefile.pre.in 2008-11-14 14:54:20.000000000 +0100 +@@ -375,6 +375,8 @@ + ./$(BUILDPYTHON) $(PROFILE_TASK) + + build_all_use_profile: ++ : # FIXME: gcc error ++ rm -f Python/thread.gc* + $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-use" + + coverage: --- python2.6-2.6.1.orig/debian/patches/site-builddir.diff +++ python2.6-2.6.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) --- python2.6-2.6.1.orig/debian/patches/patchlevel.dpatch +++ python2.6-2.6.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 >= ... */ --- python2.6-2.6.1.orig/debian/patches/subprocess-eintr-safety.dpatch +++ python2.6-2.6.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) --- python2.6-2.6.1.orig/debian/patches/no-large-file-support.dpatch +++ python2.6-2.6.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 --- python2.6-2.6.1.orig/debian/patches/tkinter-import.dpatch +++ python2.6-2.6.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/lib-tk/Tkinter.py~ 2008-05-23 13:49:08.000000000 +0200 ++++ Lib/lib-tk/Tkinter.py 2008-05-23 13:51:24.000000000 +0200 +@@ -36,7 +36,10 @@ + if sys.platform == "win32": + # Attempt to configure Tcl/Tk without requiring PATH + import FixTk +-import _tkinter # If this fails your Python may not be configured for Tk ++try: ++ import _tkinter ++except ImportError, msg: ++ raise ImportError, str(msg) + ', please install the python-tk package' + tkinter = _tkinter # b/w compat for export + TclError = _tkinter.TclError + from types import * --- python2.6-2.6.1.orig/debian/patches/deb-setup.dpatch +++ python2.6-2.6.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~ 2002-08-02 20:02:01.000000000 +0200 ++++ setup.py 2002-08-02 20:13:25.000000000 +0200 +@@ -227,8 +227,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') + + if os.path.normpath(sys.prefix) != '/usr': + add_dir_to_list(self.compiler.library_dirs, --- python2.6-2.6.1.orig/debian/patches/platform-lsbrelease.dpatch +++ python2.6-2.6.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~ 2008-09-04 13:15:14.000000000 +0200 ++++ Lib/platform.py 2009-03-18 19:48:17.000000000 +0100 +@@ -286,6 +286,10 @@ + if parsed != output: + print (input, parsed) + ++_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, +@@ -310,6 +314,25 @@ + args given as parameters. + + """ ++ # check for the Debian/Ubuntu /etc/lsb-release file first, needed so ++ # that the distribution doesn't get identified as Debian. ++ try: ++ etclsbrel = open("/etc/lsb-release", "rU") ++ for line in etclsbrel: ++ m = _distributor_id_file_re.search(line) ++ if m: ++ _u_distname = m.group(1).strip() ++ m = _release_file_re.search(line) ++ if m: ++ _u_version = m.group(1).strip() ++ m = _codename_file_re.search(line) ++ if m: ++ _u_id = m.group(1).strip() ++ if _u_distname and _u_version: ++ return (_u_distname, _u_version, _u_id) ++ except (EnvironmentError, UnboundLocalError): ++ pass ++ + try: + etc = os.listdir('/etc') + except os.error: --- python2.6-2.6.1.orig/debian/patches/hotshot-import.dpatch +++ python2.6-2.6.1/debian/patches/hotshot-import.dpatch @@ -0,0 +1,40 @@ +#! /bin/sh -e + +# DP: hotshot: Check for the availability of the profile and pstats modules. + +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/hotshot/stats.py~ 2007-02-16 17:57:29.000000000 +0100 ++++ Lib/hotshot/stats.py 2007-03-01 22:07:02.000000000 +0100 +@@ -1,7 +1,10 @@ + """Statistics analyzer for HotShot.""" + +-import profile +-import pstats ++try: ++ import profile ++ import pstats ++except ImportError, e: ++ raise ImportError, str(e) + '; please install the python-profiler package' + + import hotshot.log + --- python2.6-2.6.1.orig/debian/patches/cthreads.dpatch +++ python2.6-2.6.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" --- python2.6-2.6.1.orig/debian/patches/profiled-build2.dpatch +++ python2.6-2.6.1/debian/patches/profiled-build2.dpatch @@ -0,0 +1,40 @@ +#! /bin/sh -e + +# DP: Fix profiled build; don't use Python/thread.gc*, gcc complains + +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 2009-02-11 12:50:56.000000000 +0100 ++++ Makefile.pre.in 2009-02-11 12:51:30.000000000 +0100 +@@ -370,9 +370,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* + $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-use" + + coverage: --- python2.6-2.6.1.orig/debian/patches/site-locations.dpatch +++ python2.6-2.6.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")) --- python2.6-2.6.1.orig/debian/patches/db4.6.dpatch +++ python2.6-2.6.1/debian/patches/db4.6.dpatch @@ -0,0 +1,36 @@ +#! /bin/sh -e + +# DP: Add support for db4.6. + +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~ 2008-05-05 22:21:38.000000000 +0200 ++++ setup.py 2008-05-23 13:04:00.000000000 +0200 +@@ -685,7 +685,7 @@ + # a release. Most open source OSes come with one or more + # versions of BerkeleyDB already installed. + +- max_db_ver = (4, 5) # XXX(gregory.p.smith): 4.6 "works" but seems to ++ max_db_ver = (4, 6) # XXX(gregory.p.smith): 4.6 "works" but seems to + # have issues on many platforms. I've temporarily + # disabled 4.6 to see what the odd platform + # buildbots say. --- python2.6-2.6.1.orig/debian/patches/test-sundry.dpatch +++ python2.6-2.6.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-22 18:02:34.000000000 +0200 ++++ Lib/test/test_sundry.py 2008-05-22 18:03:58.000000000 +0200 +@@ -65,7 +65,11 @@ + import os2emxpath + import pdb + import posixfile +- import pstats ++ try: ++ import pstats # separated out into the python-profiler package ++ except ImportError: ++ if test_support.verbose: ++ print "skipping profile and pstats" + import py_compile + import rexec + import rlcompleter --- python2.6-2.6.1.orig/debian/patches/langpack-gettext.dpatch +++ python2.6-2.6.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 + + --- python2.6-2.6.1.orig/debian/patches/libre.diff +++ python2.6-2.6.1/debian/patches/libre.diff @@ -0,0 +1,9 @@ +--- Doc/lib/libre.tex~ 2003-07-25 09:29:22.000000000 +0200 ++++ Doc/lib/libre.tex 2003-07-25 09:30:58.000000000 +0200 +@@ -919,5 +919,5 @@ + Starting with Python 2.3, simple uses of the \regexp{*?} pattern are + special-cased to avoid recursion. Thus, the above regular expression + can avoid recursion by being recast as +-\regexp{Begin [a-zA-Z0-9_ ]*?end}. As a further benefit, such regular ++`Begin [a-zA-Z0-9_ ]*?end'. As a further benefit, such regular + expressions will run faster than their recursive equivalents. --- python2.6-2.6.1.orig/debian/patches/deb-locations.dpatch +++ python2.6-2.6.1/debian/patches/deb-locations.dpatch @@ -0,0 +1,130 @@ +#! /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 not os.environ.has_key("PYTHONDOCS") 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: +--- ./Demo/scripts/ftpstats.py.orig 2008-05-22 17:50:31.000000000 +0200 ++++ ./Demo/scripts/ftpstats.py 2008-05-22 17:51:11.000000000 +0200 +@@ -6,7 +6,8 @@ + # 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. ++# Default file for Debian GNU/Linux is /var/log/xferlog; ++# a "-" means read stdandard input. + + # The script must be run on the host where the ftp daemon runs. + # (At CWI this is currently buizerd.) +@@ -34,7 +35,7 @@ + maxitems = string.atoi(a) + if o == '-s': + search = a +- file = '/usr/adm/ftpd' ++ file = '/var/log/xferlog' + if args: file = args[0] + if file == '-': + f = sys.stdin +--- ./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 --- python2.6-2.6.1.orig/debian/patches/distutils-link.dpatch +++ python2.6-2.6.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~ 2004-08-29 18:40:55.000000000 +0200 ++++ Lib/distutils/unixccompiler.py 2005-03-18 17:54:16.066246856 +0100 +@@ -148,7 +148,12 @@ + objects, output_dir = self._fix_object_args(objects, output_dir) + libraries, library_dirs, runtime_library_dirs = \ + self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) +- ++ # filter out standard library paths, which are not explicitely needed ++ # for linking ++ library_dirs = [dir for dir in library_dirs ++ if not dir in ('/lib', '/lib64', '/usr/lib', '/usr/lib64')] ++ runtime_library_dirs = [dir for dir in runtime_library_dirs ++ if not dir in ('/lib', '/lib64', '/usr/lib', '/usr/lib64')] + lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, + libraries) + if type(output_dir) not in (StringType, NoneType): --- python2.6-2.6.1.orig/debian/patches/link-opt.dpatch +++ python2.6-2.6.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 + +--- Modules/_ctypes/libffi/fficonfig.py.in~ 2008-06-02 20:41:30.000000000 +0200 ++++ Modules/_ctypes/libffi/fficonfig.py.in 2009-03-18 13:09:00.000000000 +0100 +@@ -4,7 +4,7 @@ + + ffi_platforms = { + 'MIPS_IRIX': ['src/mips/ffi.c', 'src/mips/o32.S', 'src/mips/n32.S'], +- 'MIPS_LINUX': ['src/mips/ffi.c', 'src/mips/o32.S'], ++ 'MIPS': ['src/mips/ffi.c', 'src/mips/o32.S'], + 'X86': ['src/x86/ffi.c', 'src/x86/sysv.S'], + 'X86_FREEBSD': ['src/x86/ffi.c', 'src/x86/sysv.S'], + 'X86_WIN32': ['src/x86/ffi.c', 'src/x86/win32.S'], --- python2.6-2.6.1.orig/debian/patches/template.dpatch +++ python2.6-2.6.1/debian/patches/template.dpatch @@ -0,0 +1,32 @@ +#! /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 + #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 + +# append the patch here and adjust the -p? flag in the patch calls. --- python2.6-2.6.1.orig/debian/patches/egg-info-no-version.dpatch +++ python2.6-2.6.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] --- python2.6-2.6.1.orig/Python/importdl.c +++ python2.6-2.6.1/Python/importdl.c @@ -17,6 +17,8 @@ const char *pathname, FILE *fp); +PyObject * +_check_for_multiple_distdirs(enum filetype, const char *, const char *); PyObject * _PyImport_LoadDynamicModule(char *name, char *pathname, FILE *fp) @@ -71,6 +73,7 @@ PySys_WriteStderr( "import %s # dynamically loaded from %s\n", name, pathname); + _check_for_multiple_distdirs(C_EXTENSION, name, pathname); Py_INCREF(m); return m; } --- python2.6-2.6.1.orig/Python/import.c +++ python2.6-2.6.1/Python/import.c @@ -110,6 +110,32 @@ }; #endif +#define DISTDIR1 "/var/lib/python-support/" +#define DISTDIR2 "/usr/lib/python2.6/site-packages/" + +PyObject * +_check_for_multiple_distdirs(enum filetype type, + const char *name, const char *pathname) +{ + char *dcheck = getenv("DCHECK"); + int dowarn = 0; + + if (!dcheck) + return NULL; + + if (!strncmp(pathname, DISTDIR1, strlen(DISTDIR1)) + || !strncmp(pathname, DISTDIR2, strlen(DISTDIR2))) + dowarn = 1; + + if (dowarn) { + char buf[100 + strlen(name) + strlen(pathname)]; + sprintf(buf, + "deb-sitedir: imported %s from outside distribution sitedir %s", + name, pathname); + PyErr_WarnEx(PyExc_DeprecationWarning, buf, 1); + } + return NULL; +} /* Initialize things */ @@ -805,6 +831,7 @@ if (Py_VerboseFlag) PySys_WriteStderr("import %s # precompiled from %s\n", name, cpathname); + _check_for_multiple_distdirs(PY_COMPILED, name, cpathname); m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname); Py_DECREF(co); @@ -953,6 +980,7 @@ if (Py_VerboseFlag) PySys_WriteStderr("import %s # precompiled from %s\n", name, cpathname); + _check_for_multiple_distdirs(PY_SOURCE, name, cpathname); pathname = cpathname; } else { @@ -962,6 +990,7 @@ if (Py_VerboseFlag) PySys_WriteStderr("import %s # from %s\n", name, pathname); + _check_for_multiple_distdirs(PY_SOURCE, name, pathname); if (cpathname) { PyObject *ro = PySys_GetObject("dont_write_bytecode"); if (ro == NULL || !PyObject_IsTrue(ro)) @@ -1001,6 +1030,7 @@ if (Py_VerboseFlag) PySys_WriteStderr("import %s # directory %s\n", name, pathname); + _check_for_multiple_distdirs(PKG_DIRECTORY, name, pathname); d = PyModule_GetDict(m); file = PyString_FromString(pathname); if (file == NULL) @@ -1946,6 +1976,7 @@ if (Py_VerboseFlag) PySys_WriteStderr("import %s # frozen%s\n", name, ispackage ? " package" : ""); + _check_for_multiple_distdirs(PY_FROZEN, name, ispackage ? " package" : ""); co = PyMarshal_ReadObjectFromString((char *)p->code, size); if (co == NULL) return -1;