From python-3000-checkins at python.org Mon Nov 3 21:31:38 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Mon, 3 Nov 2008 21:31:38 +0100 (CET)
Subject: [Python-3000-checkins] r67088 - in python/branches/py3k:
Doc/ACKS.txt Include/compile.h Lib/modulefinder.py
Lib/test/test_descr.py Lib/test/test_io.py
Lib/test/test_modulefinder.py Lib/test/test_parser.py
Misc/ACKS Modules/_fileio.c Modules/parsermodule.c
Python/future.c Tools/scripts/findnocoding.py
Message-ID: <20081103203138.E69B31E400C@bag.python.org>
Author: benjamin.peterson
Date: Mon Nov 3 21:31:38 2008
New Revision: 67088
Log:
Merged revisions 67028,67040,67044,67046,67052,67065,67070,67077,67082 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67028 | benjamin.peterson | 2008-10-25 18:27:07 -0500 (Sat, 25 Oct 2008) | 1 line
don't use a catch-all
........
r67040 | armin.rigo | 2008-10-28 12:01:21 -0500 (Tue, 28 Oct 2008) | 5 lines
Fix one of the tests: it relied on being present in an "output test" in
order to actually test what it was supposed to test, i.e. that the code
in the __del__ method did not crash. Use instead the new helper
test_support.captured_output().
........
r67044 | amaury.forgeotdarc | 2008-10-29 18:15:57 -0500 (Wed, 29 Oct 2008) | 3 lines
Correct error message in io.open():
closefd=True is the only accepted value with a file name.
........
r67046 | thomas.heller | 2008-10-30 15:18:13 -0500 (Thu, 30 Oct 2008) | 2 lines
Fixed a modulefinder crash on certain relative imports.
........
r67052 | christian.heimes | 2008-10-30 16:26:15 -0500 (Thu, 30 Oct 2008) | 1 line
Issue #4237: io.FileIO() was raising invalid warnings caused by insufficient initialization of PyFileIOObject struct members.
........
r67065 | benjamin.peterson | 2008-10-30 18:59:18 -0500 (Thu, 30 Oct 2008) | 1 line
move unprefixed error into .c file
........
r67070 | benjamin.peterson | 2008-10-31 15:41:44 -0500 (Fri, 31 Oct 2008) | 1 line
rephrase has_key doc
........
r67077 | benjamin.peterson | 2008-11-03 09:14:51 -0600 (Mon, 03 Nov 2008) | 1 line
#4048 make the parser module accept relative imports as valid
........
r67082 | hirokazu.yamamoto | 2008-11-03 12:03:06 -0600 (Mon, 03 Nov 2008) | 2 lines
Issue #3774: Fixed an error when create a Tkinter menu item without command
and then remove it. Written by Guilherme Polo (gpolo).
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Doc/ACKS.txt
python/branches/py3k/Include/compile.h
python/branches/py3k/Lib/modulefinder.py
python/branches/py3k/Lib/test/test_descr.py
python/branches/py3k/Lib/test/test_io.py
python/branches/py3k/Lib/test/test_modulefinder.py
python/branches/py3k/Lib/test/test_parser.py
python/branches/py3k/Misc/ACKS
python/branches/py3k/Modules/_fileio.c
python/branches/py3k/Modules/parsermodule.c
python/branches/py3k/Python/future.c
python/branches/py3k/Tools/scripts/findnocoding.py
Modified: python/branches/py3k/Doc/ACKS.txt
==============================================================================
--- python/branches/py3k/Doc/ACKS.txt (original)
+++ python/branches/py3k/Doc/ACKS.txt Mon Nov 3 21:31:38 2008
@@ -16,6 +16,7 @@
* A. Amoroso
* Pehr Anderson
* Oliver Andrich
+ * Heidi Annexstad
* Jes?s Cea Avi?n
* Daniel Barclay
* Chris Barker
Modified: python/branches/py3k/Include/compile.h
==============================================================================
--- python/branches/py3k/Include/compile.h (original)
+++ python/branches/py3k/Include/compile.h Mon Nov 3 21:31:38 2008
@@ -32,8 +32,6 @@
PyCompilerFlags *, PyArena *);
PyAPI_FUNC(PyFutureFeatures *) PyFuture_FromAST(struct _mod *, const char *);
-#define ERR_LATE_FUTURE \
-"from __future__ imports must occur at the beginning of the file"
#ifdef __cplusplus
}
Modified: python/branches/py3k/Lib/modulefinder.py
==============================================================================
--- python/branches/py3k/Lib/modulefinder.py (original)
+++ python/branches/py3k/Lib/modulefinder.py Mon Nov 3 21:31:38 2008
@@ -310,7 +310,10 @@
def _add_badmodule(self, name, caller):
if name not in self.badmodules:
self.badmodules[name] = {}
- self.badmodules[name][caller.__name__] = 1
+ if caller:
+ self.badmodules[name][caller.__name__] = 1
+ else:
+ self.badmodules[name]["-"] = 1
def _safe_import_hook(self, name, caller, fromlist, level=-1):
# wrapper for self.import_hook() that won't raise ImportError
Modified: python/branches/py3k/Lib/test/test_descr.py
==============================================================================
--- python/branches/py3k/Lib/test/test_descr.py (original)
+++ python/branches/py3k/Lib/test/test_descr.py Mon Nov 3 21:31:38 2008
@@ -1020,14 +1020,10 @@
def __del__(self_):
self.assertEqual(self_.a, 1)
self.assertEqual(self_.b, 2)
-
- save_stderr = sys.stderr
- sys.stderr = sys.stdout
- h = H()
- try:
+ with test_support.captured_output('stderr') as s:
+ h = H()
del h
- finally:
- sys.stderr = save_stderr
+ self.assertEqual(s.getvalue(), '')
def test_slots_special(self):
# Testing __dict__ and __weakref__ in __slots__...
Modified: python/branches/py3k/Lib/test/test_io.py
==============================================================================
--- python/branches/py3k/Lib/test/test_io.py (original)
+++ python/branches/py3k/Lib/test/test_io.py Mon Nov 3 21:31:38 2008
@@ -1245,6 +1245,7 @@
self.assertRaises(ValueError, io.FileIO, "/some/invalid/name", "rt")
self.assertEqual(w.warnings, [])
+
def test_main():
support.run_unittest(IOTest, BytesIOTest, StringIOTest,
BufferedReaderTest, BufferedWriterTest,
Modified: python/branches/py3k/Lib/test/test_modulefinder.py
==============================================================================
--- python/branches/py3k/Lib/test/test_modulefinder.py (original)
+++ python/branches/py3k/Lib/test/test_modulefinder.py Mon Nov 3 21:31:38 2008
@@ -190,6 +190,19 @@
a/b/c/f.py
"""]
+relative_import_test_3 = [
+ "a.module",
+ ["a", "a.module"],
+ ["a.bar"],
+ [],
+ """\
+a/__init__.py
+ def foo(): pass
+a/module.py
+ from . import foo
+ from . import bar
+"""]
+
def open_file(path):
##print "#", os.path.abspath(path)
dirname = os.path.dirname(path)
@@ -256,6 +269,9 @@
def test_relative_imports_2(self):
self._do_test(relative_import_test_2)
+ def test_relative_imports_3(self):
+ self._do_test(relative_import_test_3)
+
def test_main():
distutils.log.set_threshold(distutils.log.WARN)
support.run_unittest(ModuleFinderTest)
Modified: python/branches/py3k/Lib/test/test_parser.py
==============================================================================
--- python/branches/py3k/Lib/test/test_parser.py (original)
+++ python/branches/py3k/Lib/test/test_parser.py Mon Nov 3 21:31:38 2008
@@ -1,4 +1,5 @@
import parser
+import os
import unittest
import sys
from test import support
@@ -172,6 +173,7 @@
"from sys.path import (dirname, basename as my_basename)")
self.check_suite(
"from sys.path import (dirname, basename as my_basename,)")
+ self.check_suite("from .bogus import x")
def test_basic_import_statement(self):
self.check_suite("import sys")
Modified: python/branches/py3k/Misc/ACKS
==============================================================================
--- python/branches/py3k/Misc/ACKS (original)
+++ python/branches/py3k/Misc/ACKS Mon Nov 3 21:31:38 2008
@@ -61,6 +61,7 @@
Steven Bethard
Stephen Bevan
Ron Bickers
+David Binger
Dominic Binks
Philippe Biondi
Stuart Bishop
Modified: python/branches/py3k/Modules/_fileio.c
==============================================================================
--- python/branches/py3k/Modules/_fileio.c (original)
+++ python/branches/py3k/Modules/_fileio.c Mon Nov 3 21:31:38 2008
@@ -251,7 +251,7 @@
self->closefd = 1;
if (!closefd) {
PyErr_SetString(PyExc_ValueError,
- "Cannot use closefd=True with file name");
+ "Cannot use closefd=False with file name");
goto error;
}
Modified: python/branches/py3k/Modules/parsermodule.c
==============================================================================
--- python/branches/py3k/Modules/parsermodule.c (original)
+++ python/branches/py3k/Modules/parsermodule.c Mon Nov 3 21:31:38 2008
@@ -1710,10 +1710,10 @@
count_from_dots(node *tree)
{
int i;
- for (i = 0; i < NCH(tree); i++)
+ for (i = 1; i < NCH(tree); i++)
if (TYPE(CHILD(tree, i)) != DOT)
break;
- return i;
+ return i-1;
}
/* 'from' ('.'* dotted_name | '.') 'import' ('*' | '(' import_as_names ')' |
Modified: python/branches/py3k/Python/future.c
==============================================================================
--- python/branches/py3k/Python/future.c (original)
+++ python/branches/py3k/Python/future.c Mon Nov 3 21:31:38 2008
@@ -8,6 +8,8 @@
#include "symtable.h"
#define UNDEFINED_FUTURE_FEATURE "future feature %.100s is not defined"
+#define ERR_LATE_FUTURE \
+"from __future__ imports must occur at the beginning of the file"
static int
future_check_features(PyFutureFeatures *ff, stmt_ty s, const char *filename)
Modified: python/branches/py3k/Tools/scripts/findnocoding.py
==============================================================================
--- python/branches/py3k/Tools/scripts/findnocoding.py (original)
+++ python/branches/py3k/Tools/scripts/findnocoding.py Mon Nov 3 21:31:38 2008
@@ -12,7 +12,7 @@
# our pysource module finds Python source files
try:
import pysource
-except:
+except ImportError:
# emulate the module with a simple os.walk
class pysource:
has_python_ext = looks_like_python = can_be_compiled = None
From python-3000-checkins at python.org Mon Nov 3 22:29:10 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Mon, 3 Nov 2008 22:29:10 +0100 (CET)
Subject: [Python-3000-checkins] r67090 -
python/branches/py3k/Lib/test/test_descr.py
Message-ID: <20081103212910.3FEEA1E4002@bag.python.org>
Author: benjamin.peterson
Date: Mon Nov 3 22:29:09 2008
New Revision: 67090
Log:
fix test_descr
Modified:
python/branches/py3k/Lib/test/test_descr.py
Modified: python/branches/py3k/Lib/test/test_descr.py
==============================================================================
--- python/branches/py3k/Lib/test/test_descr.py (original)
+++ python/branches/py3k/Lib/test/test_descr.py Mon Nov 3 22:29:09 2008
@@ -1020,7 +1020,7 @@
def __del__(self_):
self.assertEqual(self_.a, 1)
self.assertEqual(self_.b, 2)
- with test_support.captured_output('stderr') as s:
+ with support.captured_output('stderr') as s:
h = H()
del h
self.assertEqual(s.getvalue(), '')
From python-3000-checkins at python.org Tue Nov 4 01:31:31 2008
From: python-3000-checkins at python.org (hirokazu.yamamoto)
Date: Tue, 4 Nov 2008 01:31:31 +0100 (CET)
Subject: [Python-3000-checkins] r67092 - in python/branches/py3k:
Lib/pickle.py Modules/_pickle.c
Message-ID: <20081104003131.DC3CA1E4002@bag.python.org>
Author: hirokazu.yamamoto
Date: Tue Nov 4 01:31:31 2008
New Revision: 67092
Log:
Blocked revisions 67002 via svnmerge
........
r67002 | hirokazu.yamamoto | 2008-10-23 09:37:33 +0900 | 1 line
Issue #4183: Some tests didn't run with pickle.HIGHEST_PROTOCOL.
........
Modified:
python/branches/py3k/Lib/pickle.py
python/branches/py3k/Modules/_pickle.c
Modified: python/branches/py3k/Lib/pickle.py
==============================================================================
--- python/branches/py3k/Lib/pickle.py (original)
+++ python/branches/py3k/Lib/pickle.py Tue Nov 4 01:31:31 2008
@@ -345,6 +345,9 @@
else:
self.write(PERSID + str(pid).encode("ascii") + b'\n')
+ def _isiter(self, obj):
+ return hasattr(obj, '__next__') and hasattr(obj, '__iter__')
+
def save_reduce(self, func, args, state=None,
listitems=None, dictitems=None, obj=None):
# This API is called by some subclasses
@@ -357,6 +360,16 @@
if not hasattr(func, '__call__'):
raise PicklingError("func from save_reduce() should be callable")
+ # Assert that listitems is an iterator
+ if listitems is not None and not self._isiter(listitems):
+ raise PicklingError("listitems from save_reduce() should be an "
+ "iterator")
+
+ # Assert that dictitems is an iterator
+ if dictitems is not None and not self._isiter(dictitems):
+ raise PicklingError("dictitems from save_reduce() should be an "
+ "iterator")
+
save = self.save
write = self.write
Modified: python/branches/py3k/Modules/_pickle.c
==============================================================================
--- python/branches/py3k/Modules/_pickle.c (original)
+++ python/branches/py3k/Modules/_pickle.c Tue Nov 4 01:31:31 2008
@@ -1963,7 +1963,6 @@
PyObject *state = NULL;
PyObject *listitems = Py_None;
PyObject *dictitems = Py_None;
- Py_ssize_t size;
int use_newobj = self->proto >= 2;
@@ -1971,13 +1970,6 @@
const char build_op = BUILD;
const char newobj_op = NEWOBJ;
- size = PyTuple_Size(args);
- if (size < 2 || size > 5) {
- PyErr_SetString(PicklingError, "tuple returned by "
- "__reduce__ must contain 2 through 5 elements");
- return -1;
- }
-
if (!PyArg_UnpackTuple(args, "save_reduce", 2, 5,
&callable, &argtup, &state, &listitems, &dictitems))
return -1;
@@ -2154,6 +2146,7 @@
PyObject *reduce_value = NULL;
PyObject *memo_key = NULL;
int status = 0;
+ Py_ssize_t size;
if (Py_EnterRecursiveCall(" while pickling an object") < 0)
return -1;
@@ -2332,6 +2325,13 @@
goto error;
}
+ size = PyTuple_Size(reduce_value);
+ if (size < 2 || size > 5) {
+ PyErr_SetString(PicklingError, "tuple returned by "
+ "__reduce__ must contain 2 through 5 elements");
+ goto error;
+ }
+
status = save_reduce(self, reduce_value, obj);
if (0) {
From python-3000-checkins at python.org Tue Nov 4 01:35:10 2008
From: python-3000-checkins at python.org (hirokazu.yamamoto)
Date: Tue, 4 Nov 2008 01:35:10 +0100 (CET)
Subject: [Python-3000-checkins] r67093 - in python/branches/py3k:
Lib/pickle.py Modules/_pickle.c
Message-ID: <20081104003510.CF7F41E4029@bag.python.org>
Author: hirokazu.yamamoto
Date: Tue Nov 4 01:35:10 2008
New Revision: 67093
Log:
Sorry, r67092 is commit miss....
Modified:
python/branches/py3k/Lib/pickle.py
python/branches/py3k/Modules/_pickle.c
Modified: python/branches/py3k/Lib/pickle.py
==============================================================================
--- python/branches/py3k/Lib/pickle.py (original)
+++ python/branches/py3k/Lib/pickle.py Tue Nov 4 01:35:10 2008
@@ -345,9 +345,6 @@
else:
self.write(PERSID + str(pid).encode("ascii") + b'\n')
- def _isiter(self, obj):
- return hasattr(obj, '__next__') and hasattr(obj, '__iter__')
-
def save_reduce(self, func, args, state=None,
listitems=None, dictitems=None, obj=None):
# This API is called by some subclasses
@@ -360,16 +357,6 @@
if not hasattr(func, '__call__'):
raise PicklingError("func from save_reduce() should be callable")
- # Assert that listitems is an iterator
- if listitems is not None and not self._isiter(listitems):
- raise PicklingError("listitems from save_reduce() should be an "
- "iterator")
-
- # Assert that dictitems is an iterator
- if dictitems is not None and not self._isiter(dictitems):
- raise PicklingError("dictitems from save_reduce() should be an "
- "iterator")
-
save = self.save
write = self.write
Modified: python/branches/py3k/Modules/_pickle.c
==============================================================================
--- python/branches/py3k/Modules/_pickle.c (original)
+++ python/branches/py3k/Modules/_pickle.c Tue Nov 4 01:35:10 2008
@@ -1963,6 +1963,7 @@
PyObject *state = NULL;
PyObject *listitems = Py_None;
PyObject *dictitems = Py_None;
+ Py_ssize_t size;
int use_newobj = self->proto >= 2;
@@ -1970,6 +1971,13 @@
const char build_op = BUILD;
const char newobj_op = NEWOBJ;
+ size = PyTuple_Size(args);
+ if (size < 2 || size > 5) {
+ PyErr_SetString(PicklingError, "tuple returned by "
+ "__reduce__ must contain 2 through 5 elements");
+ return -1;
+ }
+
if (!PyArg_UnpackTuple(args, "save_reduce", 2, 5,
&callable, &argtup, &state, &listitems, &dictitems))
return -1;
@@ -2146,7 +2154,6 @@
PyObject *reduce_value = NULL;
PyObject *memo_key = NULL;
int status = 0;
- Py_ssize_t size;
if (Py_EnterRecursiveCall(" while pickling an object") < 0)
return -1;
@@ -2325,13 +2332,6 @@
goto error;
}
- size = PyTuple_Size(reduce_value);
- if (size < 2 || size > 5) {
- PyErr_SetString(PicklingError, "tuple returned by "
- "__reduce__ must contain 2 through 5 elements");
- goto error;
- }
-
status = save_reduce(self, reduce_value, obj);
if (0) {
From python-3000-checkins at python.org Tue Nov 4 07:26:28 2008
From: python-3000-checkins at python.org (hirokazu.yamamoto)
Date: Tue, 4 Nov 2008 07:26:28 +0100 (CET)
Subject: [Python-3000-checkins] r67095 -
python/branches/py3k/Lib/tkinter/__init__.py
Message-ID: <20081104062628.06F131E4002@bag.python.org>
Author: hirokazu.yamamoto
Date: Tue Nov 4 07:26:27 2008
New Revision: 67095
Log:
Issue #3774: Fixed an error when create a Tkinter menu item without command
and then remove it. Written by Guilherme Polo (gpolo). Ported r67082.
Modified:
python/branches/py3k/Lib/tkinter/__init__.py
Modified: python/branches/py3k/Lib/tkinter/__init__.py
==============================================================================
--- python/branches/py3k/Lib/tkinter/__init__.py (original)
+++ python/branches/py3k/Lib/tkinter/__init__.py Tue Nov 4 07:26:27 2008
@@ -1913,6 +1913,8 @@
cnf = _cnfmerge((cnf, kw))
self.widgetName = widgetName
BaseWidget._setup(self, master, cnf)
+ if self._tclCommands is None:
+ self._tclCommands = []
classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
for k, v in classes:
del cnf[k]
@@ -2648,21 +2650,20 @@
"""Add separator at INDEX."""
self.insert(index, 'separator', cnf or kw)
def delete(self, index1, index2=None):
- """Delete menu items between INDEX1 and INDEX2 (not included)."""
+ """Delete menu items between INDEX1 and INDEX2 (included)."""
if index2 is None:
index2 = index1
- cmds = []
- (num_index1, num_index2) = (self.index(index1), self.index(index2))
- if (num_index1 is not None) and (num_index2 is not None):
- for i in range(num_index1, num_index2 + 1):
- if 'command' in self.entryconfig(i):
- c = str(self.entrycget(i, 'command'))
- if c in self._tclCommands:
- cmds.append(c)
- self.tk.call(self._w, 'delete', index1, index2)
- for c in cmds:
- self.deletecommand(c)
+ num_index1, num_index2 = self.index(index1), self.index(index2)
+ if (num_index1 is None) or (num_index2 is None):
+ num_index1, num_index2 = 0, -1
+
+ for i in range(num_index1, num_index2 + 1):
+ if 'command' in self.entryconfig(i):
+ c = str(self.entrycget(i, 'command'))
+ if c:
+ self.deletecommand(c)
+ self.tk.call(self._w, 'delete', index1, index2)
def entrycget(self, index, option):
"""Return the resource value of an menu item for OPTION at INDEX."""
return self.tk.call(self._w, 'entrycget', index, '-' + option)
From python-3000-checkins at python.org Tue Nov 4 21:45:30 2008
From: python-3000-checkins at python.org (martin.v.loewis)
Date: Tue, 4 Nov 2008 21:45:30 +0100 (CET)
Subject: [Python-3000-checkins] r67100 - in python/branches/py3k: Misc/NEWS
Modules/_multiprocessing/multiprocessing.h Modules/readline.c
configure configure.in setup.py
Message-ID: <20081104204530.5AEAA1E4054@bag.python.org>
Author: martin.v.loewis
Date: Tue Nov 4 21:45:29 2008
New Revision: 67100
Log:
Merged revisions 67098 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67098 | martin.v.loewis | 2008-11-04 21:40:09 +0100 (Di, 04 Nov 2008) | 2 lines
Issue #4204: Fixed module build errors on FreeBSD 4.
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Misc/NEWS
python/branches/py3k/Modules/_multiprocessing/multiprocessing.h
python/branches/py3k/Modules/readline.c
python/branches/py3k/configure
python/branches/py3k/configure.in
python/branches/py3k/setup.py
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Tue Nov 4 21:45:29 2008
@@ -96,6 +96,8 @@
- Issue #4018: Disable "for me" installations on Vista.
+- Issue #4204: Fixed module build errors on FreeBSD 4.
+
Tools/Demos
-----------
Modified: python/branches/py3k/Modules/_multiprocessing/multiprocessing.h
==============================================================================
--- python/branches/py3k/Modules/_multiprocessing/multiprocessing.h (original)
+++ python/branches/py3k/Modules/_multiprocessing/multiprocessing.h Tue Nov 4 21:45:29 2008
@@ -20,7 +20,9 @@
# define SEM_VALUE_MAX LONG_MAX
#else
# include /* O_CREAT and O_EXCL */
+# include
# include
+# include
# include /* htonl() and ntohl() */
# if HAVE_SEM_OPEN
# include
Modified: python/branches/py3k/Modules/readline.c
==============================================================================
--- python/branches/py3k/Modules/readline.c (original)
+++ python/branches/py3k/Modules/readline.c Tue Nov 4 21:45:29 2008
@@ -35,7 +35,11 @@
#define completion_matches(x, y) \
rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
#else
+#if defined(_RL_FUNCTION_TYPEDEF)
extern char **completion_matches(char *, rl_compentry_func_t *);
+#else
+extern char **completion_matches(char *, CPFunction *);
+#endif
#endif
static void
@@ -213,7 +217,11 @@
default completion display. */
rl_completion_display_matches_hook =
completion_display_matches_hook ?
+#if defined(_RL_FUNCTION_TYPEDEF)
(rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
+#else
+ (VFunction *)on_completion_display_matches_hook : 0;
+#endif
#endif
return result;
Modified: python/branches/py3k/configure
==============================================================================
--- python/branches/py3k/configure (original)
+++ python/branches/py3k/configure Tue Nov 4 21:45:29 2008
@@ -2098,11 +2098,18 @@
# but used in struct sockaddr.sa_family. Reported by Tim Rice.
SCO_SV/3.2)
define_xopen_source=no;;
- # On FreeBSD 4.8 and MacOS X 10.2, a bug in ncurses.h means that
- # it craps out if _XOPEN_EXTENDED_SOURCE is defined. Apparently,
- # this is fixed in 10.3, which identifies itself as Darwin/7.*
- # This should hopefully be fixed in FreeBSD 4.9
- FreeBSD/4.8* | Darwin/6* )
+ # On FreeBSD 4, the math functions C89 does not cover are never defined
+ # with _XOPEN_SOURCE and __BSD_VISIBLE does not re-enable them.
+ FreeBSD/4.*)
+ define_xopen_source=no;;
+ # On MacOS X 10.2, a bug in ncurses.h means that it craps out if
+ # _XOPEN_EXTENDED_SOURCE is defined. Apparently, this is fixed in 10.3, which
+ # identifies itself as Darwin/7.*
+ # On Mac OS X 10.4, defining _POSIX_C_SOURCE or _XOPEN_SOURCE
+ # disables platform specific features beyond repair.
+ # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE
+ # has no effect, don't bother defining them
+ Darwin/[6789].*)
define_xopen_source=no;;
# On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but
# used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined
@@ -2114,13 +2121,6 @@
define_xopen_source=no
fi
;;
- # On Mac OS X 10.4, defining _POSIX_C_SOURCE or _XOPEN_SOURCE
- # disables platform specific features beyond repair.
- # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE
- # has no effect, don't bother defining them
- Darwin/[789].*)
- define_xopen_source=no
- ;;
# On QNX 6.3.2, defining _XOPEN_SOURCE prevents netdb.h from
# defining NI_NUMERICHOST.
QNX/6.3.2)
Modified: python/branches/py3k/configure.in
==============================================================================
--- python/branches/py3k/configure.in (original)
+++ python/branches/py3k/configure.in Tue Nov 4 21:45:29 2008
@@ -275,11 +275,18 @@
# but used in struct sockaddr.sa_family. Reported by Tim Rice.
SCO_SV/3.2)
define_xopen_source=no;;
- # On FreeBSD 4.8 and MacOS X 10.2, a bug in ncurses.h means that
- # it craps out if _XOPEN_EXTENDED_SOURCE is defined. Apparently,
- # this is fixed in 10.3, which identifies itself as Darwin/7.*
- # This should hopefully be fixed in FreeBSD 4.9
- FreeBSD/4.8* | Darwin/6* )
+ # On FreeBSD 4, the math functions C89 does not cover are never defined
+ # with _XOPEN_SOURCE and __BSD_VISIBLE does not re-enable them.
+ FreeBSD/4.*)
+ define_xopen_source=no;;
+ # On MacOS X 10.2, a bug in ncurses.h means that it craps out if
+ # _XOPEN_EXTENDED_SOURCE is defined. Apparently, this is fixed in 10.3, which
+ # identifies itself as Darwin/7.*
+ # On Mac OS X 10.4, defining _POSIX_C_SOURCE or _XOPEN_SOURCE
+ # disables platform specific features beyond repair.
+ # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE
+ # has no effect, don't bother defining them
+ Darwin/@<:@6789@:>@.*)
define_xopen_source=no;;
# On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but
# used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined
@@ -291,13 +298,6 @@
define_xopen_source=no
fi
;;
- # On Mac OS X 10.4, defining _POSIX_C_SOURCE or _XOPEN_SOURCE
- # disables platform specific features beyond repair.
- # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE
- # has no effect, don't bother defining them
- Darwin/@<:@789@:>@.*)
- define_xopen_source=no
- ;;
# On QNX 6.3.2, defining _XOPEN_SOURCE prevents netdb.h from
# defining NI_NUMERICHOST.
QNX/6.3.2)
Modified: python/branches/py3k/setup.py
==============================================================================
--- python/branches/py3k/setup.py (original)
+++ python/branches/py3k/setup.py Tue Nov 4 21:45:29 2008
@@ -1011,7 +1011,7 @@
)
libraries = []
- elif platform in ('freebsd5', 'freebsd6', 'freebsd7', 'freebsd8'):
+ elif platform in ('freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'freebsd8'):
# FreeBSD's P1003.1b semaphore support is very experimental
# and has many known problems. (as of June 2008)
macros = dict( # FreeBSD
From python-3000-checkins at python.org Wed Nov 5 20:30:32 2008
From: python-3000-checkins at python.org (christian.heimes)
Date: Wed, 5 Nov 2008 20:30:32 +0100 (CET)
Subject: [Python-3000-checkins] r67106 - in python/branches/py3k:
Doc/library/io.rst Lib/test/test_io.py Misc/NEWS Modules/_fileio.c
Message-ID: <20081105193032.C45051E4002@bag.python.org>
Author: christian.heimes
Date: Wed Nov 5 20:30:32 2008
New Revision: 67106
Log:
Fixed 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.
Approved by Barry
Modified:
python/branches/py3k/Doc/library/io.rst
python/branches/py3k/Lib/test/test_io.py
python/branches/py3k/Misc/NEWS
python/branches/py3k/Modules/_fileio.c
Modified: python/branches/py3k/Doc/library/io.rst
==============================================================================
--- python/branches/py3k/Doc/library/io.rst (original)
+++ python/branches/py3k/Doc/library/io.rst Wed Nov 5 20:30:32 2008
@@ -213,8 +213,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
Modified: python/branches/py3k/Lib/test/test_io.py
==============================================================================
--- python/branches/py3k/Lib/test/test_io.py (original)
+++ python/branches/py3k/Lib/test/test_io.py Wed Nov 5 20:30:32 2008
@@ -272,6 +272,29 @@
self.assertRaises(ValueError, io.open, support.TESTFN, 'w',
closefd=False)
+ def testReadClosed(self):
+ with io.open(support.TESTFN, "w") as f:
+ f.write("egg\n")
+ with io.open(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, support.TESTFN, "r", closefd=False)
+
+ def test_closefd_attr(self):
+ with io.open(support.TESTFN, "wb") as f:
+ f.write(b"egg\n")
+ with io.open(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):
@@ -1237,15 +1260,6 @@
else:
self.assert_(issubclass(obj, io.IOBase))
- def test_fileio_warnings(self):
- with support.check_warnings() as w:
- self.assertEqual(w.warnings, [])
- self.assertRaises(TypeError, io.FileIO, [])
- self.assertEqual(w.warnings, [])
- self.assertRaises(ValueError, io.FileIO, "/some/invalid/name", "rt")
- self.assertEqual(w.warnings, [])
-
-
def test_main():
support.run_unittest(IOTest, BytesIOTest, StringIOTest,
BufferedReaderTest, BufferedWriterTest,
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Nov 5 20:30:32 2008
@@ -15,6 +15,11 @@
Core and Builtins
-----------------
+- 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 #3626: On cygwin, starting python with a non-existent script name
would not display anything if the file name is only 1 character long.
Modified: python/branches/py3k/Modules/_fileio.c
==============================================================================
--- python/branches/py3k/Modules/_fileio.c (original)
+++ python/branches/py3k/Modules/_fileio.c Wed Nov 5 20:30:32 2008
@@ -61,10 +61,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);
@@ -821,6 +818,12 @@
}
static PyObject *
+get_closefd(PyFileIOObject *self, void *closure)
+{
+ return PyBool_FromLong((long)(self->closefd));
+}
+
+static PyObject *
get_mode(PyFileIOObject *self, void *closure)
{
return PyUnicode_FromString(mode_string(self));
@@ -828,6 +831,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},
};
From python-3000-checkins at python.org Wed Nov 5 20:39:50 2008
From: python-3000-checkins at python.org (christian.heimes)
Date: Wed, 5 Nov 2008 20:39:50 +0100 (CET)
Subject: [Python-3000-checkins] r67107 - in python/branches/py3k:
Doc/library/imaplib.rst Lib/imaplib.py Misc/NEWS
Message-ID: <20081105193950.EB8D11E4002@bag.python.org>
Author: christian.heimes
Date: Wed Nov 5 20:39:50 2008
New Revision: 67107
Log:
Issue #1210: Fixed imaplib
Patch by Victor Stinner, reviewed by Barry Warsaw.
Modified:
python/branches/py3k/Doc/library/imaplib.rst
python/branches/py3k/Lib/imaplib.py
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Doc/library/imaplib.rst
==============================================================================
--- python/branches/py3k/Doc/library/imaplib.rst (original)
+++ python/branches/py3k/Doc/library/imaplib.rst Wed Nov 5 20:39:50 2008
@@ -75,7 +75,7 @@
This is a subclass derived from :class:`IMAP4` that connects to the
``stdin/stdout`` file descriptors created by passing *command* to
- ``os.popen2()``.
+ ``subprocess.Popen()``.
The following utility functions are defined:
@@ -468,13 +468,6 @@
Allow simple extension commands notified by server in ``CAPABILITY`` response.
-Instances of :class:`IMAP4_SSL` have just one additional method:
-
-
-.. method:: IMAP4_SSL.ssl()
-
- Returns SSLObject instance used for the secure connection with the server.
-
The following attributes are defined on instances of :class:`IMAP4`:
Modified: python/branches/py3k/Lib/imaplib.py
==============================================================================
--- python/branches/py3k/Lib/imaplib.py (original)
+++ python/branches/py3k/Lib/imaplib.py Wed Nov 5 20:39:50 2008
@@ -22,14 +22,14 @@
__version__ = "2.58"
-import binascii, os, random, re, socket, sys, time
+import binascii, random, re, socket, subprocess, sys, time
__all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple",
"Int2AP", "ParseFlags", "Time2Internaldate"]
# Globals
-CRLF = '\r\n'
+CRLF = b'\r\n'
Debug = 0
IMAP4_PORT = 143
IMAP4_SSL_PORT = 993
@@ -81,19 +81,19 @@
# Patterns to match server responses
-Continuation = re.compile(r'\+( (?P.*))?')
-Flags = re.compile(r'.*FLAGS \((?P[^\)]*)\)')
-InternalDate = re.compile(r'.*INTERNALDATE "'
- r'(?P[ 0123][0-9])-(?P[A-Z][a-z][a-z])-(?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'"')
-Literal = re.compile(r'.*{(?P\d+)}$', re.ASCII)
-MapCRLF = re.compile(r'\r\n|\r|\n')
-Response_code = re.compile(r'\[(?P[A-Z-]+)( (?P[^\]]*))?\]')
-Untagged_response = re.compile(r'\* (?P[A-Z-]+)( (?P.*))?')
+Continuation = re.compile(br'\+( (?P.*))?')
+Flags = re.compile(br'.*FLAGS \((?P[^\)]*)\)')
+InternalDate = re.compile(br'.*INTERNALDATE "'
+ br'(?P[ 0123][0-9])-(?P[A-Z][a-z][a-z])-(?P[0-9][0-9][0-9][0-9])'
+ br' (?P[0-9][0-9]):(?P[0-9][0-9]):(?P[0-9][0-9])'
+ br' (?P[-+])(?P[0-9][0-9])(?P[0-9][0-9])'
+ br'"')
+Literal = re.compile(br'.*{(?P\d+)}$', re.ASCII)
+MapCRLF = re.compile(br'\r\n|\r|\n')
+Response_code = re.compile(br'\[(?P[A-Z-]+)( (?P[^\]]*))?\]')
+Untagged_response = re.compile(br'\* (?P[A-Z-]+)( (?P.*))?')
Untagged_status = re.compile(
- r'\* (?P\d+) (?P[A-Z-]+)( (?P.*))?', re.ASCII)
+ br'\* (?P\d+) (?P[A-Z-]+)( (?P.*))?', re.ASCII)
@@ -147,7 +147,7 @@
class abort(error): pass # Service errors - close and retry
class readonly(abort): pass # Mailbox status changed to READ-ONLY
- mustquote = re.compile(r"[^\w!#$%&'*+,.:;<=>?^`|~-]", re.ASCII)
+ mustquote = re.compile(br"[^\w!#$%&'*+,.:;<=>?^`|~-]", re.ASCII)
def __init__(self, host = '', port = IMAP4_PORT):
self.debug = Debug
@@ -167,9 +167,9 @@
# and compile tagged response matcher.
self.tagpre = Int2AP(random.randint(4096, 65535))
- self.tagre = re.compile(r'(?P'
+ self.tagre = re.compile(br'(?P'
+ self.tagpre
- + r'\d+) (?P[A-Z]+) (?P.*)', re.ASCII)
+ + br'\d+) (?P[A-Z]+) (?P.*)', re.ASCII)
# Get server welcome message,
# request and store CAPABILITY response.
@@ -193,7 +193,9 @@
typ, dat = self.capability()
if dat == [None]:
raise self.error('no CAPABILITY response from server')
- self.capabilities = tuple(dat[-1].upper().split())
+ dat = str(dat[-1], "ASCII")
+ dat = dat.upper()
+ self.capabilities = tuple(dat.split())
if __debug__:
if self.debug >= 3:
@@ -219,6 +221,11 @@
# Overridable methods
+ def _create_socket(self):
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.connect((self.host, self.port))
+ return sock
+
def open(self, host = '', port = IMAP4_PORT):
"""Setup connection to remote server on "host:port"
(default: localhost:standard IMAP4 port).
@@ -227,14 +234,21 @@
"""
self.host = host
self.port = port
- self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.sock.connect((host, port))
+ self.sock = self._create_socket()
self.file = self.sock.makefile('rb')
def read(self, size):
"""Read 'size' bytes from remote."""
- return self.file.read(size)
+ chunks = []
+ read = 0
+ while read < size:
+ data = self.file.read(min(size-read, 4096))
+ if not data:
+ break
+ read += len(data)
+ chunks.append(data)
+ return b''.join(chunks)
def readline(self):
@@ -791,12 +805,12 @@
def _append_untagged(self, typ, dat):
-
- if dat is None: dat = ''
+ if dat is None:
+ dat = b''
ur = self.untagged_responses
if __debug__:
if self.debug >= 5:
- self._mesg('untagged_responses[%s] %s += ["%s"]' %
+ self._mesg('untagged_responses[%s] %s += ["%r"]' %
(typ, len(ur.get(typ,'')), dat))
if typ in ur:
ur[typ].append(dat)
@@ -828,10 +842,14 @@
raise self.readonly('mailbox status changed to READ-ONLY')
tag = self._new_tag()
- data = '%s %s' % (tag, name)
+ name = bytes(name, 'ASCII')
+ data = tag + b' ' + name
for arg in args:
if arg is None: continue
- data = '%s %s' % (data, self._checkquote(arg))
+ if isinstance(arg, str):
+ arg = bytes(arg, "ASCII")
+ #data = data + b' ' + self._checkquote(arg)
+ data = data + b' ' + arg
literal = self.literal
if literal is not None:
@@ -840,16 +858,16 @@
literator = literal
else:
literator = None
- data = '%s {%s}' % (data, len(literal))
+ data = data + bytes(' {%s}' % len(literal), 'ASCII')
if __debug__:
if self.debug >= 4:
- self._mesg('> %s' % data)
+ self._mesg('> %r' % data)
else:
- self._log('> %s' % data)
+ self._log('> %r' % data)
try:
- self.send('%s%s' % (data, CRLF))
+ self.send(data + CRLF)
except (socket.error, OSError) as val:
raise self.abort('socket error: %s' % val)
@@ -915,6 +933,7 @@
raise self.abort('unexpected tagged response: %s' % resp)
typ = self.mo.group('type')
+ typ = str(typ, 'ASCII')
dat = self.mo.group('data')
self.tagged_commands[tag] = (typ, [dat])
else:
@@ -936,9 +955,10 @@
raise self.abort("unexpected response: '%s'" % resp)
typ = self.mo.group('type')
+ typ = str(typ, 'ascii')
dat = self.mo.group('data')
- if dat is None: dat = '' # Null untagged response
- if dat2: dat = dat + ' ' + dat2
+ if dat is None: dat = b'' # Null untagged response
+ if dat2: dat = dat + b' ' + dat2
# Is there a literal to come?
@@ -965,11 +985,13 @@
# Bracketed response information?
if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
- self._append_untagged(self.mo.group('type'), self.mo.group('data'))
+ typ = self.mo.group('type')
+ typ = str(typ, "ASCII")
+ self._append_untagged(typ, self.mo.group('data'))
if __debug__:
if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
- self._mesg('%s response: %s' % (typ, dat))
+ self._mesg('%s response: %r' % (typ, dat))
return resp
@@ -1007,9 +1029,9 @@
line = line[:-2]
if __debug__:
if self.debug >= 4:
- self._mesg('< %s' % line)
+ self._mesg('< %r' % line)
else:
- self._log('< %s' % line)
+ self._log('< %r' % line)
return line
@@ -1021,13 +1043,13 @@
self.mo = cre.match(s)
if __debug__:
if self.mo is not None and self.debug >= 5:
- self._mesg("\tmatched r'%s' => %r" % (cre.pattern, self.mo.groups()))
+ self._mesg("\tmatched r'%r' => %r" % (cre.pattern, self.mo.groups()))
return self.mo is not None
def _new_tag(self):
- tag = '%s%s' % (self.tagpre, self.tagnum)
+ tag = self.tagpre + bytes(str(self.tagnum), 'ASCII')
self.tagnum = self.tagnum + 1
self.tagged_commands[tag] = None
return tag
@@ -1038,8 +1060,6 @@
# Must quote command args if non-alphanumeric chars present,
# and not already quoted.
- if type(arg) is not type(''):
- return arg
if len(arg) >= 2 and (arg[0],arg[-1]) in (('(',')'),('"','"')):
return arg
if arg and self.mustquote.search(arg) is None:
@@ -1049,10 +1069,10 @@
def _quote(self, arg):
- arg = arg.replace('\\', '\\\\')
- arg = arg.replace('"', '\\"')
+ arg = arg.replace(b'\\', b'\\\\')
+ arg = arg.replace(b'"', b'\\"')
- return '"%s"' % arg
+ return b'"' + arg + b'"'
def _simple_command(self, name, *args):
@@ -1061,7 +1081,6 @@
def _untagged_response(self, typ, dat, name):
-
if typ == 'NO':
return typ, dat
if not name in self.untagged_responses:
@@ -1137,73 +1156,17 @@
self.certfile = certfile
IMAP4.__init__(self, host, port)
+ def _create_socket(self):
+ sock = IMAP4._create_socket(self)
+ return ssl.wrap_socket(sock, self.keyfile, self.certfile)
- def open(self, host = '', port = IMAP4_SSL_PORT):
+ def open(self, host='', port=IMAP4_SSL_PORT):
"""Setup connection to remote server on "host:port".
(default: localhost:standard IMAP4 SSL port).
This connection will be used by the routines:
read, readline, send, shutdown.
"""
- self.host = host
- self.port = port
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.connect((host, port))
- self.sock = ssl.wrap_socket(sock, self.keyfile, self.certfile)
- self.file = self.sock.makefile('rb')
-
-
- def read(self, size):
- """Read 'size' bytes from remote."""
- # sslobj.read() sometimes returns < size bytes
- chunks = []
- read = 0
- while read < size:
- data = self.sslobj.read(min(size-read, 16384))
- read += len(data)
- chunks.append(data)
-
- return b''.join(chunks)
-
-
- def readline(self):
- """Read line from remote."""
- line = []
- while 1:
- char = self.sslobj.read(1)
- line.append(char)
- if char == b"\n": return b''.join(line)
-
-
- def send(self, data):
- """Send data to remote."""
- bytes = len(data)
- while bytes > 0:
- sent = self.sslobj.write(data)
- if sent == bytes:
- break # avoid copy
- data = data[sent:]
- bytes = bytes - sent
-
-
- def shutdown(self):
- """Close I/O established in "open"."""
- self.sock.close()
-
-
- def socket(self):
- """Return socket instance used to connect to IMAP4 server.
-
- socket = .socket()
- """
- return self.sock
-
-
- def ssl(self):
- """Return SSLObject instance used to communicate with the IMAP4 server.
-
- ssl = ssl.wrap_socket(.socket)
- """
- return self.sock
+ IMAP4.open(self, host, port)
__all__.append("IMAP4_SSL")
@@ -1214,7 +1177,7 @@
Instantiate with: IMAP4_stream(command)
- where "command" is a string that can be passed to os.popen2()
+ where "command" is a string that can be passed to subprocess.Popen()
for more documentation see the docstring of the parent class IMAP4.
"""
@@ -1234,8 +1197,11 @@
self.port = None
self.sock = None
self.file = None
- self.writefile, self.readfile = os.popen2(self.command)
-
+ self.process = subprocess.Popen(self.command,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ shell=True, close_fds=True)
+ self.writefile = self.process.stdin
+ self.readfile = self.process.stdout
def read(self, size):
"""Read 'size' bytes from remote."""
@@ -1257,6 +1223,7 @@
"""Close I/O established in "open"."""
self.readfile.close()
self.writefile.close()
+ self.process.wait()
@@ -1355,11 +1322,11 @@
"""Convert integer to A-P string representation."""
- val = ''; AP = 'ABCDEFGHIJKLMNOP'
+ val = b''; AP = b'ABCDEFGHIJKLMNOP'
num = int(abs(num))
while num:
num, mod = divmod(num, 16)
- val = AP[mod] + val
+ val = AP[mod:mod+1] + val
return val
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Nov 5 20:39:50 2008
@@ -15,6 +15,8 @@
Core and Builtins
-----------------
+- Issue #1210: Fixed imaplib and its documentation.
+
- 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``
From python-3000-checkins at python.org Wed Nov 5 20:44:22 2008
From: python-3000-checkins at python.org (christian.heimes)
Date: Wed, 5 Nov 2008 20:44:22 +0100 (CET)
Subject: [Python-3000-checkins] r67108 - in python/branches/py3k:
Lib/nntplib.py Misc/NEWS
Message-ID: <20081105194422.44FCB1E4002@bag.python.org>
Author: christian.heimes
Date: Wed Nov 5 20:44:21 2008
New Revision: 67108
Log:
Issue #3714: nntplib module broken by str to unicode conversion
Patch by Victor, Reviewed by Barry
Modified:
python/branches/py3k/Lib/nntplib.py
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Lib/nntplib.py
==============================================================================
--- python/branches/py3k/Lib/nntplib.py (original)
+++ python/branches/py3k/Lib/nntplib.py Wed Nov 5 20:44:21 2008
@@ -7,7 +7,7 @@
>>> resp, count, first, last, name = s.group('comp.lang.python')
>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last)
Group comp.lang.python has 51 articles, range 5770 to 5821
->>> resp, subs = s.xhdr('subject', first + '-' + last)
+>>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last))
>>> resp = s.quit()
>>>
@@ -15,7 +15,7 @@
Error responses are turned into exceptions.
To post an article from a file:
->>> f = open(filename, 'r') # file containing article, including header
+>>> f = open(filename, 'rb') # file containing article, including header
>>> resp = s.post(f)
>>>
@@ -81,11 +81,11 @@
# Response numbers that are followed by additional text (e.g. article)
-LONGRESP = ['100', '215', '220', '221', '222', '224', '230', '231', '282']
+LONGRESP = [b'100', b'215', b'220', b'221', b'222', b'224', b'230', b'231', b'282']
# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
-CRLF = '\r\n'
+CRLF = b'\r\n'
@@ -128,7 +128,7 @@
# error 500, probably 'not implemented'
pass
except NNTPTemporaryError as e:
- if user and e.response[:3] == '480':
+ if user and e.response.startswith(b'480'):
# Need authorization before 'mode reader'
readermode_afterauth = 1
else:
@@ -148,13 +148,13 @@
# Perform NNRP authentication if needed.
if user:
resp = self.shortcmd('authinfo user '+user)
- if resp[:3] == '381':
+ if resp.startswith(b'381'):
if not password:
raise NNTPReplyError(resp)
else:
resp = self.shortcmd(
'authinfo pass '+password)
- if resp[:3] != '281':
+ if not resp.startswith(b'281'):
raise NNTPPermanentError(resp)
if readermode_afterauth:
try:
@@ -196,6 +196,7 @@
def putcmd(self, line):
"""Internal: send one command to the server (through putline())."""
if self.debugging: print('*cmd*', repr(line))
+ line = bytes(line, "ASCII")
self.putline(line)
def getline(self):
@@ -205,8 +206,10 @@
if self.debugging > 1:
print('*get*', repr(line))
if not line: raise EOFError
- if line[-2:] == CRLF: line = line[:-2]
- elif line[-1:] in CRLF: line = line[:-1]
+ if line[-2:] == CRLF:
+ line = line[:-2]
+ elif line[-1:] in CRLF:
+ line = line[:-1]
return line
def getresp(self):
@@ -215,11 +218,11 @@
resp = self.getline()
if self.debugging: print('*resp*', repr(resp))
c = resp[:1]
- if c == '4':
+ if c == b'4':
raise NNTPTemporaryError(resp)
- if c == '5':
+ if c == b'5':
raise NNTPPermanentError(resp)
- if c not in '123':
+ if c not in b'123':
raise NNTPProtocolError(resp)
return resp
@@ -239,12 +242,12 @@
list = []
while 1:
line = self.getline()
- if line == '.':
+ if line == b'.':
break
- if line[:2] == '..':
+ if line.startswith(b'..'):
line = line[1:]
if file:
- file.write(line + "\n")
+ file.write(line + b'\n')
else:
list.append(line)
finally:
@@ -312,16 +315,16 @@
resp, lines = self.descriptions(group)
if len(lines) == 0:
- return ""
+ return b''
else:
return lines[0][1]
def descriptions(self, group_pattern):
"""Get descriptions for a range of groups."""
- line_pat = re.compile("^(?P[^ \t]+)[ \t]+(.*)$")
+ line_pat = re.compile(b'^(?P[^ \t]+)[ \t]+(.*)$')
# Try the more std (acc. to RFC2980) LIST NEWSGROUPS first
resp, raw_lines = self.longcmd('LIST NEWSGROUPS ' + group_pattern)
- if resp[:3] != "215":
+ if not resp.startswith(b'215'):
# Now the deprecated XGTITLE. This either raises an error
# or succeeds with the same output structure as LIST
# NEWSGROUPS.
@@ -344,7 +347,7 @@
- name: the group name"""
resp = self.shortcmd('GROUP ' + name)
- if resp[:3] != '211':
+ if not resp.startswith(b'211'):
raise NNTPReplyError(resp)
words = resp.split()
count = first = last = 0
@@ -368,11 +371,11 @@
def statparse(self, resp):
"""Internal: parse the response of a STAT, NEXT or LAST command."""
- if resp[:2] != '22':
+ if not resp.startswith(b'22'):
raise NNTPReplyError(resp)
words = resp.split()
nr = 0
- id = ''
+ id = b''
n = len(words)
if n > 1:
nr = words[1]
@@ -393,7 +396,7 @@
- nr: the article number
- id: the message id"""
- return self.statcmd('STAT ' + id)
+ return self.statcmd('STAT {0}'.format(id))
def next(self):
"""Process a NEXT command. No arguments. Return as for STAT."""
@@ -418,7 +421,7 @@
- id: message id
- list: the lines of the article's header"""
- return self.artcmd('HEAD ' + id)
+ return self.artcmd('HEAD {0}'.format(id))
def body(self, id, file=None):
"""Process a BODY command. Argument:
@@ -431,7 +434,7 @@
- list: the lines of the article's body or an empty list
if file was used"""
- return self.artcmd('BODY ' + id, file)
+ return self.artcmd('BODY {0}'.format(id), file)
def article(self, id):
"""Process an ARTICLE command. Argument:
@@ -442,7 +445,7 @@
- id: message id
- list: the lines of the article"""
- return self.artcmd('ARTICLE ' + id)
+ return self.artcmd('ARTICLE {0}'.format(id))
def slave(self):
"""Process a SLAVE command. Returns:
@@ -458,8 +461,8 @@
- resp: server response if successful
- list: list of (nr, value) strings"""
- pat = re.compile('^([0-9]+) ?(.*)\n?')
- resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str, file)
+ pat = re.compile(b'^([0-9]+) ?(.*)\n?')
+ resp, lines = self.longcmd('XHDR {0} {1}'.format(hdr, str), file)
for i in range(len(lines)):
line = lines[i]
m = pat.match(line)
@@ -476,10 +479,10 @@
- list: list of (art-nr, subject, poster, date,
id, references, size, lines)"""
- resp, lines = self.longcmd('XOVER ' + start + '-' + end, file)
+ resp, lines = self.longcmd('XOVER {0}-{1}'.format(start, end), file)
xover_lines = []
for line in lines:
- elem = line.split("\t")
+ elem = line.split(b'\t')
try:
xover_lines.append((elem[0],
elem[1],
@@ -500,7 +503,7 @@
- resp: server response if successful
- list: list of (name,title) strings"""
- line_pat = re.compile("^([^ \t]+)[ \t]+(.*)$")
+ line_pat = re.compile(b'^([^ \t]+)[ \t]+(.*)$')
resp, raw_lines = self.longcmd('XGTITLE ' + group, file)
lines = []
for raw_line in raw_lines:
@@ -516,8 +519,8 @@
resp: server response if successful
path: directory path to article"""
- resp = self.shortcmd("XPATH " + id)
- if resp[:3] != '223':
+ resp = self.shortcmd('XPATH {0}'.format(id))
+ if not resp.startswith(b'223'):
raise NNTPReplyError(resp)
try:
[resp_num, path] = resp.split()
@@ -535,7 +538,7 @@
time: Time suitable for newnews/newgroups commands etc."""
resp = self.shortcmd("DATE")
- if resp[:3] != '111':
+ if not resp.startswith(b'111'):
raise NNTPReplyError(resp)
elem = resp.split()
if len(elem) != 2:
@@ -546,29 +549,30 @@
raise NNTPDataError(resp)
return resp, date, time
-
- def post(self, f):
- """Process a POST command. Arguments:
- - f: file containing the article
- Returns:
- - resp: server response if successful"""
-
- resp = self.shortcmd('POST')
+ def _post(self, command, f):
+ resp = self.shortcmd(command)
# Raises error_??? if posting is not allowed
- if resp[0] != '3':
+ if not resp.startswith(b'3'):
raise NNTPReplyError(resp)
while 1:
line = f.readline()
if not line:
break
- if line[-1] == '\n':
+ if line.endswith(b'\n'):
line = line[:-1]
- if line[:1] == '.':
- line = '.' + line
+ if line.startswith(b'.'):
+ line = b'.' + line
self.putline(line)
- self.putline('.')
+ self.putline(b'.')
return self.getresp()
+ def post(self, f):
+ """Process a POST command. Arguments:
+ - f: file containing the article
+ Returns:
+ - resp: server response if successful"""
+ return self._post('POST', f)
+
def ihave(self, id, f):
"""Process an IHAVE command. Arguments:
- id: message-id of the article
@@ -576,22 +580,7 @@
Returns:
- resp: server response if successful
Note that if the server refuses the article an exception is raised."""
-
- resp = self.shortcmd('IHAVE ' + id)
- # Raises error_??? if the server already has it
- if resp[0] != '3':
- raise NNTPReplyError(resp)
- while 1:
- line = f.readline()
- if not line:
- break
- if line[-1] == '\n':
- line = line[:-1]
- if line[:1] == '.':
- line = '.' + line
- self.putline(line)
- self.putline('.')
- return self.getresp()
+ return self._post('IHAVE {0}'.format(id), f)
def quit(self):
"""Process a QUIT command and close the socket. Returns:
@@ -620,7 +609,7 @@
resp, count, first, last, name = s.group('comp.lang.python')
print(resp)
print('Group', name, 'has', count, 'articles, range', first, 'to', last)
- resp, subs = s.xhdr('subject', first + '-' + last)
+ resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last))
print(resp)
for item in subs:
print("%7s %s" % item)
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Nov 5 20:44:21 2008
@@ -15,6 +15,8 @@
Core and Builtins
-----------------
+- Issue #3714: Fixed nntplib by using bytes where appropriate.
+
- Issue #1210: Fixed imaplib and its documentation.
- Issue #4233: Changed semantic of ``_fileio.FileIO``'s ``close()``
From python-3000-checkins at python.org Wed Nov 5 20:48:28 2008
From: python-3000-checkins at python.org (christian.heimes)
Date: Wed, 5 Nov 2008 20:48:28 +0100 (CET)
Subject: [Python-3000-checkins] r67109 - in python/branches/py3k:
Lib/poplib.py Lib/test/test_poplib.py Misc/NEWS
Message-ID: <20081105194828.634FF1E4037@bag.python.org>
Author: christian.heimes
Date: Wed Nov 5 20:48:27 2008
New Revision: 67109
Log:
Fixed issue #3727: poplib module broken by str to unicode conversion
Victor strikes again! Assisted by Barry
Modified:
python/branches/py3k/Lib/poplib.py
python/branches/py3k/Lib/test/test_poplib.py
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Lib/poplib.py
==============================================================================
--- python/branches/py3k/Lib/poplib.py (original)
+++ python/branches/py3k/Lib/poplib.py Wed Nov 5 20:48:27 2008
@@ -75,26 +75,30 @@
above.
"""
+ encoding = 'UTF-8'
def __init__(self, host, port=POP3_PORT,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.host = host
self.port = port
- self.sock = socket.create_connection((host, port), timeout)
+ self.sock = self._create_socket(timeout)
self.file = self.sock.makefile('rb')
self._debugging = 0
self.welcome = self._getresp()
+ def _create_socket(self, timeout):
+ return socket.create_connection((self.host, self.port), timeout)
def _putline(self, line):
if self._debugging > 1: print('*put*', repr(line))
- self.sock.sendall('%s%s' % (line, CRLF))
+ self.sock.sendall(line + CRLF)
# Internal: send one command to the server (through _putline())
def _putcmd(self, line):
if self._debugging: print('*cmd*', repr(line))
+ line = bytes(line, self.encoding)
self._putline(line)
@@ -123,8 +127,7 @@
def _getresp(self):
resp, o = self._getline()
if self._debugging > 1: print('*resp*', repr(resp))
- c = resp[:1]
- if c != b'+':
+ if not resp.startswith(b'+'):
raise error_proto(resp)
return resp
@@ -136,7 +139,7 @@
list = []; octets = 0
line, o = self._getline()
while line != b'.':
- if line[:2] == b'..':
+ if line.startswith(b'..'):
o = o-1
line = line[1:]
octets = octets + o
@@ -266,25 +269,26 @@
return self._shortcmd('RPOP %s' % user)
- timestamp = re.compile(r'\+OK.*(<[^>]+>)')
+ timestamp = re.compile(br'\+OK.*(<[^>]+>)')
- def apop(self, user, secret):
+ def apop(self, user, password):
"""Authorisation
- only possible if server has supplied a timestamp in initial greeting.
Args:
- user - mailbox user;
- secret - secret shared between client and server.
+ user - mailbox user;
+ password - mailbox password.
NB: mailbox is locked by server from here to 'quit()'
"""
+ secret = bytes(secret, self.encoding)
m = self.timestamp.match(self.welcome)
if not m:
raise error_proto('-ERR APOP not supported by server')
import hashlib
- digest = hashlib.md5(m.group(1)+secret).digest()
- digest = ''.join(map(lambda x:'%02x'%ord(x), digest))
+ digest = m.group(1)+secret
+ digest = hashlib.md5(digest).hexdigest()
return self._shortcmd('APOP %s %s' % (user, digest))
@@ -324,79 +328,19 @@
keyfile - PEM formatted file that countains your private key
certfile - PEM formatted certificate chain file
- See the methods of the parent class POP3 for more documentation.
+ See the methods of the parent class POP3 for more documentation.
"""
- def __init__(self, host, port = POP3_SSL_PORT, keyfile = None, certfile = None):
- self.host = host
- self.port = port
+ def __init__(self, host, port=POP3_SSL_PORT,
+ keyfile=None, certfile=None,
+ timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.keyfile = keyfile
self.certfile = certfile
- self.buffer = ""
- msg = "getaddrinfo returns an empty list"
- self.sock = None
- for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
- af, socktype, proto, canonname, sa = res
- try:
- self.sock = socket.socket(af, socktype, proto)
- self.sock.connect(sa)
- except socket.error as msg:
- if self.sock:
- self.sock.close()
- self.sock = None
- continue
- break
- if not self.sock:
- raise socket.error(msg)
- self.file = self.sock.makefile('rb')
- self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
- self._debugging = 0
- self.welcome = self._getresp()
-
- def _fillBuffer(self):
- localbuf = self.sslobj.read()
- if len(localbuf) == 0:
- raise error_proto('-ERR EOF')
- self.buffer += localbuf
-
- def _getline(self):
- line = ""
- renewline = re.compile(r'.*?\n')
- match = renewline.match(self.buffer)
- while not match:
- self._fillBuffer()
- match = renewline.match(self.buffer)
- line = match.group(0)
- self.buffer = renewline.sub('' ,self.buffer, 1)
- if self._debugging > 1: print('*get*', repr(line))
-
- octets = len(line)
- if line[-2:] == CRLF:
- return line[:-2], octets
- if line[0] == CR:
- return line[1:-1], octets
- return line[:-1], octets
-
- def _putline(self, line):
- if self._debugging > 1: print('*put*', repr(line))
- line += CRLF
- bytes = len(line)
- while bytes > 0:
- sent = self.sslobj.write(line)
- if sent == bytes:
- break # avoid copy
- line = line[sent:]
- bytes = bytes - sent
-
- def quit(self):
- """Signoff: commit changes on server, unlock mailbox, close connection."""
- try:
- resp = self._shortcmd('QUIT')
- except error_proto as val:
- resp = val
- self.sock.close()
- del self.sslobj, self.sock
- return resp
+ POP3.__init__(self, host, port, timeout)
+
+ def _create_socket(self, timeout):
+ sock = POP3._create_socket(self, timeout)
+ return ssl.wrap_socket(sock, self.keyfile, self.certfile)
__all__.append("POP3_SSL")
Modified: python/branches/py3k/Lib/test/test_poplib.py
==============================================================================
--- python/branches/py3k/Lib/test/test_poplib.py (original)
+++ python/branches/py3k/Lib/test/test_poplib.py Wed Nov 5 20:48:27 2008
@@ -1,43 +1,284 @@
-import socket
-import threading
+"""Test script for poplib module."""
+
+# Modified by Giampaolo Rodola' to give poplib.POP3 and poplib.POP3_SSL
+# a real test suite
+
import poplib
+import threading
+import asyncore
+import asynchat
+import socket
+import os
import time
from unittest import TestCase
-from test import support
+from test import support as test_support
-HOST = support.HOST
+HOST = test_support.HOST
+PORT = 0
-def server(evt, serv):
- serv.listen(5)
- try:
- conn, addr = serv.accept()
- except socket.timeout:
- pass
- else:
- conn.send(b"+ Hola mundo\n")
- conn.close()
- finally:
- serv.close()
- evt.set()
+# the dummy data returned by server when LIST and RETR commands are issued
+LIST_RESP = b'1 1\r\n2 2\r\n3 3\r\n4 4\r\n5 5\r\n.\r\n'
+RETR_RESP = b"""From: postmaster at python.org\
+\r\nContent-Type: text/plain\r\n\
+MIME-Version: 1.0\r\n\
+Subject: Dummy\r\n\
+\r\n\
+line1\r\n\
+line2\r\n\
+line3\r\n\
+.\r\n"""
+
+
+class DummyPOP3Handler(asynchat.async_chat):
+
+ def __init__(self, conn):
+ asynchat.async_chat.__init__(self, conn)
+ self.set_terminator(b"\r\n")
+ self.in_buffer = []
+ self.push('+OK dummy pop3 server ready.')
+
+ def collect_incoming_data(self, data):
+ self.in_buffer.append(data)
+
+ def found_terminator(self):
+ line = b''.join(self.in_buffer)
+ line = str(line, 'ISO-8859-1')
+ self.in_buffer = []
+ cmd = line.split(' ')[0].lower()
+ space = line.find(' ')
+ if space != -1:
+ arg = line[space + 1:]
+ else:
+ arg = ""
+ if hasattr(self, 'cmd_' + cmd):
+ method = getattr(self, 'cmd_' + cmd)
+ method(arg)
+ else:
+ self.push('-ERR unrecognized POP3 command "%s".' %cmd)
+
+ def handle_error(self):
+ raise
+
+ def push(self, data):
+ asynchat.async_chat.push(self, data.encode("ISO-8859-1") + b'\r\n')
+
+ def cmd_echo(self, arg):
+ # sends back the received string (used by the test suite)
+ self.push(arg)
+
+ def cmd_user(self, arg):
+ if arg != "guido":
+ self.push("-ERR no such user")
+ self.push('+OK password required')
+
+ def cmd_pass(self, arg):
+ if arg != "python":
+ self.push("-ERR wrong password")
+ self.push('+OK 10 messages')
+
+ def cmd_stat(self, arg):
+ self.push('+OK 10 100')
+
+ def cmd_list(self, arg):
+ if arg:
+ self.push('+OK %s %s' %(arg, arg))
+ else:
+ self.push('+OK')
+ asynchat.async_chat.push(self, LIST_RESP)
+
+ cmd_uidl = cmd_list
+
+ def cmd_retr(self, arg):
+ self.push('+OK %s bytes' %len(RETR_RESP))
+ asynchat.async_chat.push(self, RETR_RESP)
+
+ cmd_top = cmd_retr
+
+ def cmd_dele(self, arg):
+ self.push('+OK message marked for deletion.')
+
+ def cmd_noop(self, arg):
+ self.push('+OK done nothing.')
+
+ def cmd_rpop(self, arg):
+ self.push('+OK done nothing.')
+
+
+class DummyPOP3Server(asyncore.dispatcher, threading.Thread):
+
+ handler = DummyPOP3Handler
+
+ def __init__(self, address, af=socket.AF_INET):
+ threading.Thread.__init__(self)
+ asyncore.dispatcher.__init__(self)
+ self.create_socket(af, socket.SOCK_STREAM)
+ self.bind(address)
+ self.listen(5)
+ self.active = False
+ self.active_lock = threading.Lock()
+ self.host, self.port = self.socket.getsockname()[:2]
+
+ def start(self):
+ assert not self.active
+ self.__flag = threading.Event()
+ threading.Thread.start(self)
+ self.__flag.wait()
+
+ def run(self):
+ self.active = True
+ self.__flag.set()
+ while self.active and asyncore.socket_map:
+ self.active_lock.acquire()
+ asyncore.loop(timeout=0.1, count=1)
+ self.active_lock.release()
+ asyncore.close_all(ignore_all=True)
+
+ def stop(self):
+ assert self.active
+ self.active = False
+ self.join()
+
+ def handle_accept(self):
+ conn, addr = self.accept()
+ self.handler = self.handler(conn)
+ self.close()
+
+ def handle_connect(self):
+ self.close()
+ handle_read = handle_connect
+
+ def writable(self):
+ return 0
+
+ def handle_error(self):
+ raise
+
+
+class TestPOP3Class(TestCase):
+ def assertOK(self, resp):
+ self.assertTrue(resp.startswith(b"+OK"))
+
+ def setUp(self):
+ self.server = DummyPOP3Server((HOST, PORT))
+ self.server.start()
+ self.client = poplib.POP3(self.server.host, self.server.port)
+
+ def tearDown(self):
+ self.client.quit()
+ self.server.stop()
-class GeneralTests(TestCase):
+ def test_getwelcome(self):
+ self.assertEqual(self.client.getwelcome(), b'+OK dummy pop3 server ready.')
+
+ def test_exceptions(self):
+ self.assertRaises(poplib.error_proto, self.client._shortcmd, 'echo -err')
+
+ def test_user(self):
+ self.assertOK(self.client.user('guido'))
+ self.assertRaises(poplib.error_proto, self.client.user, 'invalid')
+
+ def test_pass_(self):
+ self.assertOK(self.client.pass_('python'))
+ self.assertRaises(poplib.error_proto, self.client.user, 'invalid')
+
+ def test_stat(self):
+ self.assertEqual(self.client.stat(), (10, 100))
+
+ def test_list(self):
+ self.assertEqual(self.client.list()[1:],
+ ([b'1 1', b'2 2', b'3 3', b'4 4', b'5 5'],
+ 25))
+ self.assertTrue(self.client.list('1').endswith(b"OK 1 1"))
+
+ def test_retr(self):
+ expected = (b'+OK 116 bytes',
+ [b'From: postmaster at python.org', b'Content-Type: text/plain',
+ b'MIME-Version: 1.0', b'Subject: Dummy',
+ b'', b'line1', b'line2', b'line3'],
+ 113)
+ foo = self.client.retr('foo')
+ self.assertEqual(foo, expected)
+
+ def test_dele(self):
+ self.assertOK(self.client.dele('foo'))
+
+ def test_noop(self):
+ self.assertOK(self.client.noop())
+
+ def test_rpop(self):
+ self.assertOK(self.client.rpop('foo'))
+
+ def test_top(self):
+ expected = (b'+OK 116 bytes',
+ [b'From: postmaster at python.org', b'Content-Type: text/plain',
+ b'MIME-Version: 1.0', b'Subject: Dummy', b'',
+ b'line1', b'line2', b'line3'],
+ 113)
+ self.assertEqual(self.client.top(1, 1), expected)
+
+ def test_uidl(self):
+ self.client.uidl()
+ self.client.uidl('foo')
+
+
+SUPPORTS_SSL = False
+if hasattr(poplib, 'POP3_SSL'):
+ import ssl
+
+ SUPPORTS_SSL = True
+ CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem")
+
+ class DummyPOP3_SSLHandler(DummyPOP3Handler):
+
+ def __init__(self, conn):
+ asynchat.async_chat.__init__(self, conn)
+ ssl_socket = ssl.wrap_socket(self.socket, certfile=CERTFILE,
+ server_side=True)
+ self.del_channel()
+ self.set_socket(ssl_socket)
+ self.set_terminator(b"\r\n")
+ self.in_buffer = []
+ self.push('+OK dummy pop3 server ready.')
+
+ class TestPOP3_SSLClass(TestPOP3Class):
+ # repeat previous tests by using poplib.POP3_SSL
+
+ def setUp(self):
+ self.server = DummyPOP3Server((HOST, PORT))
+ self.server.handler = DummyPOP3_SSLHandler
+ self.server.start()
+ self.client = poplib.POP3_SSL(self.server.host, self.server.port)
+
+ def test__all__(self):
+ self.assert_('POP3_SSL' in poplib.__all__)
+
+
+class TestTimeouts(TestCase):
def setUp(self):
self.evt = threading.Event()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(3)
- self.port = support.bind_port(self.sock)
- threading.Thread(target=server, args=(self.evt,self.sock)).start()
+ self.port = test_support.bind_port(self.sock)
+ threading.Thread(target=self.server, args=(self.evt,self.sock)).start()
time.sleep(.1)
def tearDown(self):
self.evt.wait()
- def testBasic(self):
- # connects
- pop = poplib.POP3(HOST, self.port)
- pop.sock.close()
+ def server(self, evt, serv):
+ serv.listen(5)
+ try:
+ conn, addr = serv.accept()
+ except socket.timeout:
+ pass
+ else:
+ conn.send(b"+ Hola mundo\n")
+ conn.close()
+ finally:
+ serv.close()
+ evt.set()
def testTimeoutDefault(self):
self.assertTrue(socket.getdefaulttimeout() is None)
@@ -65,8 +306,16 @@
pop.sock.close()
-def test_main(verbose=None):
- support.run_unittest(GeneralTests)
+def test_main():
+ tests = [TestPOP3Class, TestTimeouts]
+ if SUPPORTS_SSL:
+ tests.append(TestPOP3_SSLClass)
+ thread_info = test_support.threading_setup()
+ try:
+ test_support.run_unittest(*tests)
+ finally:
+ test_support.threading_cleanup(*thread_info)
+
if __name__ == '__main__':
test_main()
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Nov 5 20:48:27 2008
@@ -15,6 +15,8 @@
Core and Builtins
-----------------
+- Issue #3727: Fixed poplib
+
- Issue #3714: Fixed nntplib by using bytes where appropriate.
- Issue #1210: Fixed imaplib and its documentation.
From python-3000-checkins at python.org Wed Nov 5 22:34:59 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Wed, 5 Nov 2008 22:34:59 +0100 (CET)
Subject: [Python-3000-checkins] r67110 - python/branches/py3k
Message-ID: <20081105213459.C63201E400C@bag.python.org>
Author: benjamin.peterson
Date: Wed Nov 5 22:34:59 2008
New Revision: 67110
Log:
Blocked revisions 66878 via svnmerge
........
r66878 | benjamin.peterson | 2008-10-11 12:25:36 -0500 (Sat, 11 Oct 2008) | 4 lines
give poplib a real test suite
#4088 from Giampaolo Rodola'x
........
Modified:
python/branches/py3k/ (props changed)
From python-3000-checkins at python.org Wed Nov 5 22:42:46 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Wed, 5 Nov 2008 22:42:46 +0100 (CET)
Subject: [Python-3000-checkins] r67111 - in python/branches/py3k:
Doc/library/select.rst Doc/library/socket.rst
Lib/test/test_fileio.py Lib/test/test_io.py
Message-ID: <20081105214246.147581E4002@bag.python.org>
Author: benjamin.peterson
Date: Wed Nov 5 22:42:45 2008
New Revision: 67111
Log:
Merged revisions 67089,67091,67101 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67089 | benjamin.peterson | 2008-11-03 14:43:20 -0600 (Mon, 03 Nov 2008) | 1 line
clarify by splitting into multiple paragraphs
........
r67091 | benjamin.peterson | 2008-11-03 16:34:57 -0600 (Mon, 03 Nov 2008) | 1 line
move a FileIO test to test_fileio
........
r67101 | georg.brandl | 2008-11-04 14:49:35 -0600 (Tue, 04 Nov 2008) | 2 lines
#4167: fix markup glitches.
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Doc/library/select.rst
python/branches/py3k/Doc/library/socket.rst
python/branches/py3k/Lib/test/test_fileio.py
python/branches/py3k/Lib/test/test_io.py
Modified: python/branches/py3k/Doc/library/select.rst
==============================================================================
--- python/branches/py3k/Doc/library/select.rst (original)
+++ python/branches/py3k/Doc/library/select.rst Wed Nov 5 22:42:45 2008
@@ -355,7 +355,7 @@
Filter specific flags
- *:const:`KQ_FILTER_READ` and :const:`KQ_FILTER_WRITE` filter flags*
+ :const:`KQ_FILTER_READ` and :const:`KQ_FILTER_WRITE` filter flags
+----------------------------+--------------------------------------------+
| Constant | Meaning |
@@ -364,7 +364,7 @@
+----------------------------+--------------------------------------------+
- *:const:`KQ_FILTER_VNODE` filter flags*
+ :const:`KQ_FILTER_VNODE` filter flags
+----------------------------+--------------------------------------------+
| Constant | Meaning |
@@ -385,7 +385,7 @@
+----------------------------+--------------------------------------------+
- *:const:`KQ_FILTER_PROC` filter flags*
+ :const:`KQ_FILTER_PROC` filter flags
+----------------------------+--------------------------------------------+
| Constant | Meaning |
@@ -408,7 +408,7 @@
| :const:`KQ_NOTE_TRACKERR` | unable to attach to a child |
+----------------------------+--------------------------------------------+
- *:const:`KQ_FILTER_NETDEV` filter flags* [not available on Mac OS X]
+ :const:`KQ_FILTER_NETDEV` filter flags [not available on Mac OS X]
+----------------------------+--------------------------------------------+
| Constant | Meaning |
Modified: python/branches/py3k/Doc/library/socket.rst
==============================================================================
--- python/branches/py3k/Doc/library/socket.rst (original)
+++ python/branches/py3k/Doc/library/socket.rst Wed Nov 5 22:42:45 2008
@@ -260,11 +260,15 @@
.. function:: gethostname()
Return a string containing the hostname of the machine where the Python
- interpreter is currently executing. If you want to know the current machine's IP
- address, you may want to use ``gethostbyname(gethostname())``. This operation
- assumes that there is a valid address-to-host mapping for the host, and the
- assumption does not always hold. Note: :func:`gethostname` doesn't always return
- the fully qualified domain name; use ``getfqdn()`` (see above).
+ interpreter is currently executing.
+
+ If you want to know the current machine's IP address, you may want to use
+ ``gethostbyname(gethostname())``. This operation assumes that there is a
+ valid address-to-host mapping for the host, and the assumption does not
+ always hold.
+
+ Note: :func:`gethostname` doesn't always return the fully qualified domain
+ name; use ``getfqdn()`` (see above).
.. function:: gethostbyaddr(ip_address)
Modified: python/branches/py3k/Lib/test/test_fileio.py
==============================================================================
--- python/branches/py3k/Lib/test/test_fileio.py (original)
+++ python/branches/py3k/Lib/test/test_fileio.py Wed Nov 5 22:42:45 2008
@@ -6,7 +6,7 @@
from array import array
from weakref import proxy
-from test.support import TESTFN, findfile, run_unittest
+from test.support import TESTFN, findfile, check_warnings, run_unittest
from collections import UserList
import _fileio
@@ -240,6 +240,14 @@
def testInvalidInit(self):
self.assertRaises(TypeError, _fileio._FileIO, "1", 0, 0)
+ def testWarnings(self):
+ with check_warnings() as w:
+ self.assertEqual(w.warnings, [])
+ self.assertRaises(TypeError, _fileio._FileIO, [])
+ self.assertEqual(w.warnings, [])
+ self.assertRaises(ValueError, _fileio._FileIO, "/some/invalid/name", "rt")
+ self.assertEqual(w.warnings, [])
+
def test_main():
# Historically, these tests have been sloppy about removing TESTFN.
Modified: python/branches/py3k/Lib/test/test_io.py
==============================================================================
--- python/branches/py3k/Lib/test/test_io.py (original)
+++ python/branches/py3k/Lib/test/test_io.py Wed Nov 5 22:42:45 2008
@@ -1260,6 +1260,7 @@
else:
self.assert_(issubclass(obj, io.IOBase))
+
def test_main():
support.run_unittest(IOTest, BytesIOTest, StringIOTest,
BufferedReaderTest, BufferedWriterTest,
From python-3000-checkins at python.org Wed Nov 5 23:48:34 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Wed, 5 Nov 2008 23:48:34 +0100 (CET)
Subject: [Python-3000-checkins] r67112 - in python/branches/py3k:
Lib/test/test_frozen.py Misc/NEWS Python/import.c
Message-ID: <20081105224834.3CC581E4002@bag.python.org>
Author: benjamin.peterson
Date: Wed Nov 5 23:48:33 2008
New Revision: 67112
Log:
fix #4211: the __path__ of a frozen package should be a list
Modified:
python/branches/py3k/Lib/test/test_frozen.py
python/branches/py3k/Misc/NEWS
python/branches/py3k/Python/import.c
Modified: python/branches/py3k/Lib/test/test_frozen.py
==============================================================================
--- python/branches/py3k/Lib/test/test_frozen.py (original)
+++ python/branches/py3k/Lib/test/test_frozen.py Wed Nov 5 23:48:33 2008
@@ -22,6 +22,7 @@
self.assertEqual(len(dir(__phello__)), 7, dir(__phello__))
else:
self.assertEqual(len(dir(__phello__)), 8, dir(__phello__))
+ self.assertEquals(__phello__.__path__, [__phello__.__name__])
try:
import __phello__.spam
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Nov 5 23:48:33 2008
@@ -15,6 +15,9 @@
Core and Builtins
-----------------
+- Issue #4211: The __path__ attribute of frozen packages is now a list instead
+ of a string as required by PEP 302.
+
- Issue #3727: Fixed poplib
- Issue #3714: Fixed nntplib by using bytes where appropriate.
Modified: python/branches/py3k/Python/import.c
==============================================================================
--- python/branches/py3k/Python/import.c (original)
+++ python/branches/py3k/Python/import.c Wed Nov 5 23:48:33 2008
@@ -1293,37 +1293,16 @@
Py_DECREF(meta_path);
}
- if (path != NULL && PyUnicode_Check(path)) {
- /* The only type of submodule allowed inside a "frozen"
- package are other frozen modules or packages. */
- char *p = _PyUnicode_AsString(path);
- if (strlen(p) + 1 + strlen(name) >= (size_t)buflen) {
- PyErr_SetString(PyExc_ImportError,
- "full frozen module name too long");
- return NULL;
- }
- strcpy(buf, p);
- strcat(buf, ".");
- strcat(buf, name);
- strcpy(name, buf);
- if (find_frozen(name) != NULL) {
- strcpy(buf, name);
- return &fd_frozen;
- }
- PyErr_Format(PyExc_ImportError,
- "No frozen submodule named %.200s", name);
- return NULL;
+ if (find_frozen(fullname) != NULL) {
+ strcpy(buf, fullname);
+ return &fd_frozen;
}
+
if (path == NULL) {
if (is_builtin(name)) {
strcpy(buf, name);
return &fd_builtin;
}
- if ((find_frozen(name)) != NULL) {
- strcpy(buf, name);
- return &fd_frozen;
- }
-
#ifdef MS_COREDLL
fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
if (fp != NULL) {
@@ -1333,6 +1312,7 @@
#endif
path = PySys_GetObject("path");
}
+
if (path == NULL || !PyList_Check(path)) {
PyErr_SetString(PyExc_ImportError,
"sys.path must be a list of directory names");
@@ -1886,6 +1866,9 @@
{
struct _frozen *p;
+ if (!name)
+ return NULL;
+
for (p = PyImport_FrozenModules; ; p++) {
if (p->name == NULL)
return NULL;
@@ -1959,7 +1942,7 @@
}
if (ispackage) {
/* Set __path__ to the package name */
- PyObject *d, *s;
+ PyObject *d, *s, *l;
int err;
m = PyImport_AddModule(name);
if (m == NULL)
@@ -1968,8 +1951,14 @@
s = PyUnicode_InternFromString(name);
if (s == NULL)
goto err_return;
- err = PyDict_SetItemString(d, "__path__", s);
- Py_DECREF(s);
+ l = PyList_New(1);
+ if (l == NULL) {
+ Py_DECREF(s);
+ goto err_return;
+ }
+ PyList_SET_ITEM(l, 0, s);
+ err = PyDict_SetItemString(d, "__path__", l);
+ Py_DECREF(l);
if (err != 0)
goto err_return;
}
From python-3000-checkins at python.org Wed Nov 5 23:49:10 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Wed, 5 Nov 2008 23:49:10 +0100 (CET)
Subject: [Python-3000-checkins] r67113 - python/branches/py3k/Misc/NEWS
Message-ID: <20081105224910.444571E4002@bag.python.org>
Author: benjamin.peterson
Date: Wed Nov 5 23:49:09 2008
New Revision: 67113
Log:
period
Modified:
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Nov 5 23:49:09 2008
@@ -18,7 +18,7 @@
- Issue #4211: The __path__ attribute of frozen packages is now a list instead
of a string as required by PEP 302.
-- Issue #3727: Fixed poplib
+- Issue #3727: Fixed poplib.
- Issue #3714: Fixed nntplib by using bytes where appropriate.
From python-3000-checkins at python.org Thu Nov 6 04:29:33 2008
From: python-3000-checkins at python.org (barry.warsaw)
Date: Thu, 6 Nov 2008 04:29:33 +0100 (CET)
Subject: [Python-3000-checkins] r67114 - in python/branches/py3k:
Include/patchlevel.h Lib/distutils/__init__.py
Lib/idlelib/idlever.py Lib/pydoc_topics.py Misc/NEWS
Misc/RPM/python-3.0.spec README
Message-ID: <20081106032933.BD3F21E4002@bag.python.org>
Author: barry.warsaw
Date: Thu Nov 6 04:29:32 2008
New Revision: 67114
Log:
Bumping to 3.0rc2.
Modified:
python/branches/py3k/Include/patchlevel.h
python/branches/py3k/Lib/distutils/__init__.py
python/branches/py3k/Lib/idlelib/idlever.py
python/branches/py3k/Lib/pydoc_topics.py
python/branches/py3k/Misc/NEWS
python/branches/py3k/Misc/RPM/python-3.0.spec
python/branches/py3k/README
Modified: python/branches/py3k/Include/patchlevel.h
==============================================================================
--- python/branches/py3k/Include/patchlevel.h (original)
+++ python/branches/py3k/Include/patchlevel.h Thu Nov 6 04:29:32 2008
@@ -20,10 +20,10 @@
#define PY_MINOR_VERSION 0
#define PY_MICRO_VERSION 0
#define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_GAMMA
-#define PY_RELEASE_SERIAL 1
+#define PY_RELEASE_SERIAL 2
/* Version as a string */
-#define PY_VERSION "3.0rc1+"
+#define PY_VERSION "3.0rc2"
/*--end constants--*/
/* Subversion Revision number of this file (not of the repository) */
Modified: python/branches/py3k/Lib/distutils/__init__.py
==============================================================================
--- python/branches/py3k/Lib/distutils/__init__.py (original)
+++ python/branches/py3k/Lib/distutils/__init__.py Thu Nov 6 04:29:32 2008
@@ -20,5 +20,5 @@
#
#--start constants--
-__version__ = "3.0rc1"
+__version__ = "3.0rc2"
#--end constants--
Modified: python/branches/py3k/Lib/idlelib/idlever.py
==============================================================================
--- python/branches/py3k/Lib/idlelib/idlever.py (original)
+++ python/branches/py3k/Lib/idlelib/idlever.py Thu Nov 6 04:29:32 2008
@@ -1 +1 @@
-IDLE_VERSION = "3.0rc1"
+IDLE_VERSION = "3.0rc2"
Modified: python/branches/py3k/Lib/pydoc_topics.py
==============================================================================
--- python/branches/py3k/Lib/pydoc_topics.py (original)
+++ python/branches/py3k/Lib/pydoc_topics.py Thu Nov 6 04:29:32 2008
@@ -1,9 +1,9 @@
-# Autogenerated by Sphinx on Thu Oct 2 15:58:57 2008
+# Autogenerated by Sphinx on Wed Nov 5 22:25:20 2008
topics = {'assert': '\nThe ``assert`` statement\n************************\n\nAssert statements are a convenient way to insert debugging assertions\ninto a program:\n\n assert_stmt ::= "assert" expression ["," expression]\n\nThe simple form, ``assert expression``, is equivalent to\n\n if __debug__:\n if not expression: raise AssertionError\n\nThe extended form, ``assert expression1, expression2``, is equivalent\nto\n\n if __debug__:\n if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that ``__debug__`` and ``AssertionError``\nrefer to the built-in variables with those names. In the current\nimplementation, the built-in variable ``__debug__`` is ``True`` under\nnormal circumstances, ``False`` when optimization is requested\n(command line option -O). The current code generator emits no code\nfor an assert statement when optimization is requested at compile\ntime. Note that it is unnecessary to include the source code for the\nexpression that failed in the error message; it will be displayed as\npart of the stack trace.\n\nAssignments to ``__debug__`` are illegal. The value for the built-in\nvariable is determined when the interpreter starts.\n',
'assignment': '\nAssignment statements\n*********************\n\nAssignment statements are used to (re)bind names to values and to\nmodify attributes or items of mutable objects:\n\n assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)\n target_list ::= target ("," target)* [","]\n target ::= identifier\n | "(" target_list ")"\n | "[" target_list "]"\n | attributeref\n | subscription\n | slicing\n | "*" target\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn assignment statement evaluates the expression list (remember that\nthis can be a single expression or a comma-separated list, the latter\nyielding a tuple) and assigns the single resulting object to each of\nthe target lists, from left to right.\n\nAssignment is defined recursively depending on the form of the target\n(list). When a target is part of a mutable object (an attribute\nreference, subscription or slicing), the mutable object must\nultimately perform the assignment and decide about its validity, and\nmay raise an exception if the assignment is unacceptable. The rules\nobserved by various types and the exceptions raised are given with the\ndefinition of the object types (see section *The standard type\nhierarchy*).\n\nAssignment of an object to a target list, optionally enclosed in\nparentheses or square brackets, is recursively defined as follows.\n\n* If the target list is a single target: The object is assigned to\n that target.\n\n* If the target list is a comma-separated list of targets:\n\n * If the target list contains one target prefixed with an asterisk,\n called a "starred" target: The object must be a sequence with at\n least as many items as there are targets in the target list, minus\n one. The first items of the sequence are assigned, from left to\n right, to the targets before the starred target. The final items\n of the sequence are assigned to the targets after the starred\n target. A list of the remaining items in the sequence is then\n assigned to the starred target (the list can be empty).\n\n * Else: The object must be a sequence with the same number of items\n as there are targets in the target list, and the items are\n assigned, from left to right, to the corresponding targets.\n\nAssignment of an object to a single target is recursively defined as\nfollows.\n\n* If the target is an identifier (name):\n\n * If the name does not occur in a ``global`` or ``nonlocal``\n statement in the current code block: the name is bound to the\n object in the current local namespace.\n\n * Otherwise: the name is bound to the object in the global namespace\n or the outer namespace determined by ``nonlocal``, respectively.\n\n The name is rebound if it was already bound. This may cause the\n reference count for the object previously bound to the name to reach\n zero, causing the object to be deallocated and its destructor (if it\n has one) to be called.\n\n The name is rebound if it was already bound. This may cause the\n reference count for the object previously bound to the name to reach\n zero, causing the object to be deallocated and its destructor (if it\n has one) to be called.\n\n* If the target is a target list enclosed in parentheses or in square\n brackets: The object must be a sequence with the same number of\n items as there are targets in the target list, and its items are\n assigned, from left to right, to the corresponding targets.\n\n* If the target is an attribute reference: The primary expression in\n the reference is evaluated. It should yield an object with\n assignable attributes; if this is not the case, ``TypeError`` is\n raised. That object is then asked to assign the assigned object to\n the given attribute; if it cannot perform the assignment, it raises\n an exception (usually but not necessarily ``AttributeError``).\n\n* If the target is a subscription: The primary expression in the\n reference is evaluated. It should yield either a mutable sequence\n object (such as a list) or a mapping object (such as a dictionary).\n Next, the subscript expression is evaluated.\n\n If the primary is a mutable sequence object (such as a list), the\n subscript must yield an integer. If it is negative, the sequence\'s\n length is added to it. The resulting value must be a nonnegative\n integer less than the sequence\'s length, and the sequence is asked\n to assign the assigned object to its item with that index. If the\n index is out of range, ``IndexError`` is raised (assignment to a\n subscripted sequence cannot add new items to a list).\n\n If the primary is a mapping object (such as a dictionary), the\n subscript must have a type compatible with the mapping\'s key type,\n and the mapping is then asked to create a key/datum pair which maps\n the subscript to the assigned object. This can either replace an\n existing key/value pair with the same key value, or insert a new\n key/value pair (if no key with the same value existed).\n\n For user-defined objects, the ``__setitem__()`` method is called\n with appropriate arguments.\n\n* If the target is a slicing: The primary expression in the reference\n is evaluated. It should yield a mutable sequence object (such as a\n list). The assigned object should be a sequence object of the same\n type. Next, the lower and upper bound expressions are evaluated,\n insofar they are present; defaults are zero and the sequence\'s\n length. The bounds should evaluate to integers. If either bound is\n negative, the sequence\'s length is added to it. The resulting\n bounds are clipped to lie between zero and the sequence\'s length,\n inclusive. Finally, the sequence object is asked to replace the\n slice with the items of the assigned sequence. The length of the\n slice may be different from the length of the assigned sequence,\n thus changing the length of the target sequence, if the object\n allows it.\n\n(In the current implementation, the syntax for targets is taken to be\nthe same as for expressions, and invalid syntax is rejected during the\ncode generation phase, causing less detailed error messages.)\n\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are \'safe\' (for\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\ncollection of assigned-to variables are not safe! For instance, the\nfollowing program prints ``[0, 2]``:\n\n x = [0, 1]\n i = 0\n i, x[i] = 1, 2\n print(x)\n\nSee also:\n\n **PEP 3132** - Extended Iterable Unpacking\n The specification for the ``*target`` feature.\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n augmented_assignment_stmt ::= target augop (expression_list | yield_expression)\n augop ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the initial value is\nretrieved with a ``getattr()`` and the result is assigned with a\n``setattr()``. Notice that the two methods do not necessarily refer\nto the same variable. When ``getattr()`` refers to a class variable,\n``setattr()`` still writes to an instance variable. For example:\n\n class A:\n x = 3 # class variable\n a = A()\n a.x += 1 # writes a.x as 4 leaving A.x as 3\n',
'atom-identifiers': '\nIdentifiers (Names)\n*******************\n\nAn identifier occurring as an atom is a name. See section\n*Identifiers and keywords* for lexical definition and section *Naming\nand binding* for documentation of naming and binding.\n\nWhen the name is bound to an object, evaluation of the atom yields\nthat object. When a name is not bound, an attempt to evaluate it\nraises a ``NameError`` exception.\n\n**Private name mangling:** When an identifier that textually occurs in\na class definition begins with two or more underscore characters and\ndoes not end in two or more underscores, it is considered a *private\nname* of that class. Private names are transformed to a longer form\nbefore code is generated for them. The transformation inserts the\nclass name in front of the name, with leading underscores removed, and\na single underscore inserted in front of the class name. For example,\nthe identifier ``__spam`` occurring in a class named ``Ham`` will be\ntransformed to ``_Ham__spam``. This transformation is independent of\nthe syntactical context in which the identifier is used. If the\ntransformed name is extremely long (longer than 255 characters),\nimplementation defined truncation may happen. If the class name\nconsists only of underscores, no transformation is done.\n',
'atom-literals': "\nLiterals\n********\n\nPython supports string and bytes literals and various numeric\nliterals:\n\n literal ::= stringliteral | bytesliteral\n | integer | floatnumber | imagnumber\n\nEvaluation of a literal yields an object of the given type (string,\nbytes, integer, floating point number, complex number) with the given\nvalue. The value may be approximated in the case of floating point\nand imaginary (complex) literals. See section *Literals* for details.\n\nWith the exception of bytes literals, these all correspond to\nimmutable data types, and hence the object's identity is less\nimportant than its value. Multiple evaluations of literals with the\nsame value (either the same occurrence in the program text or a\ndifferent occurrence) may obtain the same object or a different object\nwith the same value.\n",
- 'attribute-access': '\nCustomizing attribute access\n****************************\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control over attribute access.\n\nobject.__getattribute__(self, name)\n\n Called unconditionally to implement attribute accesses for\n instances of the class. If the class also defines\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n builtin functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\n\n Called when an attribute assignment is attempted. This is called\n instead of the normal mechanism (i.e. store the value in the\n instance dictionary). *name* is the attribute name, *value* is the\n value to be assigned to it.\n\n If ``__setattr__()`` wants to assign to an instance attribute, it\n should call the base class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\nobject.__dir__(self)\n\n Called when ``dir()`` is called on the object. A list must be\n returned.\n\n\nImplementing Descriptors\n========================\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another class, known as the *owner* class. In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or ``None`` when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n====================\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to an object instance, ``a.x`` is transformed into the\n call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n If binding to a class, ``A.x`` is transformed into the call:\n ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n If ``a`` is an instance of ``super``, then the binding ``super(B,\n obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. Normally, data\ndescriptors define both ``__get__()`` and ``__set__()``, while non-\ndata descriptors have just the ``__get__()`` method. Data descriptors\nalways override a redefinition in an instance dictionary. In\ncontrast, non-data descriptors can be overridden by instances. [2]\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n=========\n\nBy default, instances of classes have a dictionary for attribute\nstorage. This wastes space for objects having very few instance\nvariables. The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable. Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__slots__\n\n This class variable can be assigned a string, iterable, or sequence\n of strings with variable names used by instances. If defined in a\n class, *__slots__* reserves space for the declared variables and\n prevents the automatic creation of *__dict__* and *__weakref__* for\n each instance.\n\n\nNotes on using *__slots__*\n--------------------------\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n attribute of that class will always be accessible, so a *__slots__*\n definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n variables not listed in the *__slots__* definition. Attempts to\n assign to an unlisted variable name raises ``AttributeError``. If\n dynamic assignment of new variables is desired, then add\n ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n descriptors (*Implementing Descriptors*) for each variable name. As\n a result, class attributes cannot be used to set default values for\n instance variables defined by *__slots__*; otherwise, the class\n attribute would overwrite the descriptor assignment.\n\n* If a class defines a slot also defined in a base class, the instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* The action of a *__slots__* declaration is limited to the class\n where it is defined. As a result, subclasses will have a *__dict__*\n unless they also define *__slots__*.\n\n* *__slots__* do not work for classes derived from "variable-length"\n built-in types such as ``int``, ``str`` and ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n',
+ 'attribute-access': '\nCustomizing attribute access\n****************************\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control over attribute access.\n\nobject.__getattribute__(self, name)\n\n Called unconditionally to implement attribute accesses for\n instances of the class. If the class also defines\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n builtin functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\n\n Called when an attribute assignment is attempted. This is called\n instead of the normal mechanism (i.e. store the value in the\n instance dictionary). *name* is the attribute name, *value* is the\n value to be assigned to it.\n\n If ``__setattr__()`` wants to assign to an instance attribute, it\n should call the base class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\nobject.__dir__(self)\n\n Called when ``dir()`` is called on the object. A list must be\n returned.\n\n\nImplementing Descriptors\n========================\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another class, known as the *owner* class. In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or ``None`` when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n====================\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to an object instance, ``a.x`` is transformed into the\n call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n If binding to a class, ``A.x`` is transformed into the call:\n ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n If ``a`` is an instance of ``super``, then the binding ``super(B,\n obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. Normally, data\ndescriptors define both ``__get__()`` and ``__set__()``, while non-\ndata descriptors have just the ``__get__()`` method. Data descriptors\nalways override a redefinition in an instance dictionary. In\ncontrast, non-data descriptors can be overridden by instances. [2]\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n=========\n\nBy default, instances of classes have a dictionary for attribute\nstorage. This wastes space for objects having very few instance\nvariables. The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable. Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__slots__\n\n This class variable can be assigned a string, iterable, or sequence\n of strings with variable names used by instances. If defined in a\n class, *__slots__* reserves space for the declared variables and\n prevents the automatic creation of *__dict__* and *__weakref__* for\n each instance.\n\n\nNotes on using *__slots__*\n--------------------------\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n attribute of that class will always be accessible, so a *__slots__*\n definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n variables not listed in the *__slots__* definition. Attempts to\n assign to an unlisted variable name raises ``AttributeError``. If\n dynamic assignment of new variables is desired, then add\n ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n descriptors (*Implementing Descriptors*) for each variable name. As\n a result, class attributes cannot be used to set default values for\n instance variables defined by *__slots__*; otherwise, the class\n attribute would overwrite the descriptor assignment.\n\n* If a class defines a slot also defined in a base class, the instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* The action of a *__slots__* declaration is limited to the class\n where it is defined. As a result, subclasses will have a *__dict__*\n unless they also define *__slots__*.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as ``int``, ``str`` and\n ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n',
'attribute-references': '\nAttribute references\n********************\n\nAn attribute reference is a primary followed by a period and a name:\n\n attributeref ::= primary "." identifier\n\nThe primary must evaluate to an object of a type that supports\nattribute references, which most objects do. This object is then\nasked to produce the attribute whose name is the identifier (which can\nbe customized by overriding the ``__getattr__()`` method). If this\nattribute is not available, the exception ``AttributeError`` is\nraised. Otherwise, the type and value of the object produced is\ndetermined by the object. Multiple evaluations of the same attribute\nreference may yield different objects.\n',
'augassign': '\nAugmented assignment statements\n*******************************\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n augmented_assignment_stmt ::= target augop (expression_list | yield_expression)\n augop ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the initial value is\nretrieved with a ``getattr()`` and the result is assigned with a\n``setattr()``. Notice that the two methods do not necessarily refer\nto the same variable. When ``getattr()`` refers to a class variable,\n``setattr()`` still writes to an instance variable. For example:\n\n class A:\n x = 3 # class variable\n a = A()\n a.x += 1 # writes a.x as 4 leaving A.x as 3\n',
'binary': '\nBinary arithmetic operations\n****************************\n\nThe binary arithmetic operations have the conventional priority\nlevels. Note that some of these operations also apply to certain non-\nnumeric types. Apart from the power operator, there are only two\nlevels, one for multiplicative operators and one for additive\noperators:\n\n m_expr ::= u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr\n | m_expr "%" u_expr\n a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr\n\nThe ``*`` (multiplication) operator yields the product of its\narguments. The arguments must either both be numbers, or one argument\nmust be an integer and the other must be a sequence. In the former\ncase, the numbers are converted to a common type and then multiplied\ntogether. In the latter case, sequence repetition is performed; a\nnegative repetition factor yields an empty sequence.\n\nThe ``/`` (division) and ``//`` (floor division) operators yield the\nquotient of their arguments. The numeric arguments are first\nconverted to a common type. Integer division yields a float, while\nfloor division of integers results in an integer; the result is that\nof mathematical division with the \'floor\' function applied to the\nresult. Division by zero raises the ``ZeroDivisionError`` exception.\n\nThe ``%`` (modulo) operator yields the remainder from the division of\nthe first argument by the second. The numeric arguments are first\nconverted to a common type. A zero right argument raises the\n``ZeroDivisionError`` exception. The arguments may be floating point\nnumbers, e.g., ``3.14%0.7`` equals ``0.34`` (since ``3.14`` equals\n``4*0.7 + 0.34``.) The modulo operator always yields a result with\nthe same sign as its second operand (or zero); the absolute value of\nthe result is strictly smaller than the absolute value of the second\noperand [1].\n\nThe floor division and modulo operators are connected by the following\nidentity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are\nalso connected with the built-in function ``divmod()``: ``divmod(x, y)\n== (x//y, x%y)``. [2].\n\nIn addition to performing the modulo operation on numbers, the ``%``\noperator is also overloaded by string objects to perform old-style\nstring formatting (also known as interpolation). The syntax for\nstring formatting is described in the Python Library Reference,\nsection *Old String Formatting Operations*.\n\nThe floor division operator, the modulo operator, and the ``divmod()``\nfunction are not defined for complex numbers. Instead, convert to a\nfloating point number using the ``abs()`` function if appropriate.\n\nThe ``+`` (addition) operator yields the sum of its arguments. The\narguments must either both be numbers or both sequences of the same\ntype. In the former case, the numbers are converted to a common type\nand then added together. In the latter case, the sequences are\nconcatenated.\n\nThe ``-`` (subtraction) operator yields the difference of its\narguments. The numeric arguments are first converted to a common\ntype.\n',
@@ -23,7 +23,7 @@
'context-managers': '\nWith Statement Context Managers\n*******************************\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code. Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The ``with``\n statement will bind this method\'s return value to the target(s)\n specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be ``None``.\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that ``__exit__()`` methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n',
'continue': '\nThe ``continue`` statement\n**************************\n\n continue_stmt ::= "continue"\n\n``continue`` may only occur syntactically nested in a ``for`` or\n``while`` loop, but not nested in a function or class definition or\n``finally`` clause within that loop. It continues with the next cycle\nof the nearest enclosing loop.\n\nWhen ``continue`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nstarting the next loop cycle.\n',
'conversions': '\nArithmetic conversions\n**********************\n\nWhen a description of an arithmetic operator below uses the phrase\n"the numeric arguments are converted to a common type," this means\nthat the operator implementation for built-in types works that way:\n\n* If either argument is a complex number, the other is converted to\n complex;\n\n* otherwise, if either argument is a floating point number, the other\n is converted to floating point;\n\n* otherwise, both must be integers and no conversion is necessary.\n\nSome additional rules apply for certain operators (e.g., a string left\nargument to the \'%\' operator). Extensions must define their own\nconversion behavior.\n',
- 'customization': '\nBasic customization\n*******************\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. ``__new__()`` is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of ``__new__()`` should be the new object instance (usually\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.last_traceback``. Circular references which are garbage are\n detected when the option cycle detector is enabled (it\'s on by\n default), but can only be cleaned up if there are no Python-\n level ``__del__()`` methods involved. Refer to the documentation\n for the ``gc`` module for more information about how\n ``__del__()`` methods are handled by the cycle detector,\n particularly the description of the ``garbage`` value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted. For this reason, ``__del__()`` methods should do\n the absolute minimum needed to maintain external invariants.\n Starting with version 1.5, Python guarantees that globals whose\n name begins with a single underscore are deleted from their\n module before other globals are deleted; if no other references\n to such globals exist, this may help in assuring that imported\n modules are still available at the time when the ``__del__()``\n method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function and by string\n conversions (reverse quotes) to compute the "official" string\n representation of an object. If at all possible, this should look\n like a valid Python expression that could be used to recreate an\n object with the same value (given an appropriate environment). If\n this is not possible, a string of the form ``<...some useful\n description...>`` should be returned. The return value must be a\n string object. If a class defines ``__repr__()`` but not\n ``__str__()``, then ``__repr__()`` is also used when an "informal"\n string representation of instances of that class is required.\n\n This is typically used for debugging, so it is important that the\n representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n Called by the ``str()`` built-in function and by the ``print()``\n function to compute the "informal" string representation of an\n object. This differs from ``__repr__()`` in that it does not have\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__format__(self, format_spec)\n\n Called by the ``format()`` built-in function (and by extension, the\n ``format()`` method of class ``str``) to produce a "formatted"\n string representation of an object. The ``format_spec`` argument is\n a string that contains a description of the formatting options\n desired. The interpretation of the ``format_spec`` argument is up\n to the type implementing ``__format__()``, however most classes\n will either delegate formatting to one of the built-in types, or\n use a similar formatting option syntax.\n\n See *Format Specification Mini-Language* for a description of the\n standard formatting syntax.\n\n The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n These are the so-called "rich comparison" methods. The\n correspondence between operator symbols and method names is as\n follows: ``xy`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\nobject.__hash__(self)\n\n Called for the key object for dictionary operations, and by the\n built-in function ``hash()``. Should return an integer usable as a\n hash value for dictionary operations. The only required property\n is that objects which compare equal have the same hash value; it is\n advised to somehow mix together (e.g., using exclusive or) the hash\n values for the components of the object that also play a part in\n comparison of objects.\n\n If a class does not define an ``__eq__()`` method it should not\n define a ``__hash__()`` operation either; if it defines\n ``__eq__()`` but not ``__hash__()``, its instances will not be\n usable as dictionary keys. If a class defines mutable objects and\n implements an ``__eq__()`` method, it should not implement\n ``__hash__()``, since the dictionary implementation requires that a\n key\'s hash value is immutable (if the object\'s hash value changes,\n it will be in the wrong hash bucket).\n\n User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__eq__()`` such that the hash value\n returned is no longer appropriate (e.g. by switching to a value-\n based concept of equality instead of the default identity based\n equality) can explicitly flag themselves as being unhashable by\n setting ``__hash__ = None`` in the class definition. Doing so means\n that not only will instances of the class raise an appropriate\n ``TypeError`` when a program attempts to retrieve their hash value,\n but they will also be correctly identified as unhashable when\n checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n which define their own ``__hash__()`` to explicitly raise\n ``TypeError``).\n\n If a class that overrrides ``__eq__()`` needs to retain the\n implementation of ``__hash__()`` from a parent class, the\n interpreter must be told this explicitly by setting ``__hash__ =\n .__hash__``. Otherwise the inheritance of\n ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n explicitly set to ``None``.\n\nobject.__bool__(self)\n\n Called to implement truth value testing, and the built-in operation\n ``bool()``; should return ``False`` or ``True``. When this method\n is not defined, ``__len__()`` is called, if it is defined (see\n below) and ``True`` is returned when the length is not zero. If a\n class defines neither ``__len__()`` nor ``__bool__()``, all its\n instances are considered true.\n',
+ 'customization': '\nBasic customization\n*******************\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. ``__new__()`` is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of ``__new__()`` should be the new object instance (usually\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.last_traceback``. Circular references which are garbage are\n detected when the option cycle detector is enabled (it\'s on by\n default), but can only be cleaned up if there are no Python-\n level ``__del__()`` methods involved. Refer to the documentation\n for the ``gc`` module for more information about how\n ``__del__()`` methods are handled by the cycle detector,\n particularly the description of the ``garbage`` value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted. For this reason, ``__del__()`` methods should do\n the absolute minimum needed to maintain external invariants.\n Starting with version 1.5, Python guarantees that globals whose\n name begins with a single underscore are deleted from their\n module before other globals are deleted; if no other references\n to such globals exist, this may help in assuring that imported\n modules are still available at the time when the ``__del__()``\n method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function to compute the\n "official" string representation of an object. If at all possible,\n this should look like a valid Python expression that could be used\n to recreate an object with the same value (given an appropriate\n environment). If this is not possible, a string of the form\n ``<...some useful description...>`` should be returned. The return\n value must be a string object. If a class defines ``__repr__()``\n but not ``__str__()``, then ``__repr__()`` is also used when an\n "informal" string representation of instances of that class is\n required.\n\n This is typically used for debugging, so it is important that the\n representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n Called by the ``str()`` built-in function and by the ``print()``\n function to compute the "informal" string representation of an\n object. This differs from ``__repr__()`` in that it does not have\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__format__(self, format_spec)\n\n Called by the ``format()`` built-in function (and by extension, the\n ``format()`` method of class ``str``) to produce a "formatted"\n string representation of an object. The ``format_spec`` argument is\n a string that contains a description of the formatting options\n desired. The interpretation of the ``format_spec`` argument is up\n to the type implementing ``__format__()``, however most classes\n will either delegate formatting to one of the built-in types, or\n use a similar formatting option syntax.\n\n See *Format Specification Mini-Language* for a description of the\n standard formatting syntax.\n\n The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n These are the so-called "rich comparison" methods. The\n correspondence between operator symbols and method names is as\n follows: ``xy`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\nobject.__hash__(self)\n\n Called for the key object for dictionary operations, and by the\n built-in function ``hash()``. Should return an integer usable as a\n hash value for dictionary operations. The only required property\n is that objects which compare equal have the same hash value; it is\n advised to somehow mix together (e.g., using exclusive or) the hash\n values for the components of the object that also play a part in\n comparison of objects.\n\n If a class does not define an ``__eq__()`` method it should not\n define a ``__hash__()`` operation either; if it defines\n ``__eq__()`` but not ``__hash__()``, its instances will not be\n usable as dictionary keys. If a class defines mutable objects and\n implements an ``__eq__()`` method, it should not implement\n ``__hash__()``, since the dictionary implementation requires that a\n key\'s hash value is immutable (if the object\'s hash value changes,\n it will be in the wrong hash bucket).\n\n User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__eq__()`` such that the hash value\n returned is no longer appropriate (e.g. by switching to a value-\n based concept of equality instead of the default identity based\n equality) can explicitly flag themselves as being unhashable by\n setting ``__hash__ = None`` in the class definition. Doing so means\n that not only will instances of the class raise an appropriate\n ``TypeError`` when a program attempts to retrieve their hash value,\n but they will also be correctly identified as unhashable when\n checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n which define their own ``__hash__()`` to explicitly raise\n ``TypeError``).\n\n If a class that overrrides ``__eq__()`` needs to retain the\n implementation of ``__hash__()`` from a parent class, the\n interpreter must be told this explicitly by setting ``__hash__ =\n .__hash__``. Otherwise the inheritance of\n ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n explicitly set to ``None``.\n\nobject.__bool__(self)\n\n Called to implement truth value testing, and the built-in operation\n ``bool()``; should return ``False`` or ``True``. When this method\n is not defined, ``__len__()`` is called, if it is defined (see\n below) and ``True`` is returned when the length is not zero. If a\n class defines neither ``__len__()`` nor ``__bool__()``, all its\n instances are considered true.\n',
'debugger': '\n``pdb`` --- The Python Debugger\n*******************************\n\nThe module ``pdb`` defines an interactive source code debugger for\nPython programs. It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame. It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible --- it is actually defined as the class\n``Pdb``. This is currently undocumented but easily understood by\nreading the source. The extension interface uses the modules ``bdb``\n(undocumented) and ``cmd``.\n\nThe debugger\'s prompt is ``(Pdb)``. Typical usage to run a program\nunder control of the debugger is:\n\n >>> import pdb\n >>> import mymodule\n >>> pdb.run(\'mymodule.test()\')\n > (0)?()\n (Pdb) continue\n > (1)?()\n (Pdb) continue\n NameError: \'spam\'\n > (1)?()\n (Pdb)\n\n``pdb.py`` can also be invoked as a script to debug other scripts.\nFor example:\n\n python -m pdb myscript.py\n\nWhen invoked as a script, pdb will automatically enter post-mortem\ndebugging if the program being debugged exits abnormally. After post-\nmortem debugging (or after normal exit of the program), pdb will\nrestart the program. Automatic restarting preserves pdb\'s state (such\nas breakpoints) and in most cases is more useful than quitting the\ndebugger upon program\'s exit.\n\nTypical usage to inspect a crashed program is:\n\n >>> import pdb\n >>> import mymodule\n >>> mymodule.test()\n Traceback (most recent call last):\n File "", line 1, in ?\n File "./mymodule.py", line 4, in test\n test2()\n File "./mymodule.py", line 3, in test2\n print(spam)\n NameError: spam\n >>> pdb.pm()\n > ./mymodule.py(3)test2()\n -> print(spam)\n (Pdb)\n\nThe module defines the following functions; each enters the debugger\nin a slightly different way:\n\npdb.run(statement[, globals[, locals]])\n\n Execute the *statement* (given as a string) under debugger control.\n The debugger prompt appears before any code is executed; you can\n set breakpoints and type ``continue``, or you can step through the\n statement using ``step`` or ``next`` (all these commands are\n explained below). The optional *globals* and *locals* arguments\n specify the environment in which the code is executed; by default\n the dictionary of the module ``__main__`` is used. (See the\n explanation of the built-in ``exec()`` or ``eval()`` functions.)\n\npdb.runeval(expression[, globals[, locals]])\n\n Evaluate the *expression* (given as a string) under debugger\n control. When ``runeval()`` returns, it returns the value of the\n expression. Otherwise this function is similar to ``run()``.\n\npdb.runcall(function[, argument, ...])\n\n Call the *function* (a function or method object, not a string)\n with the given arguments. When ``runcall()`` returns, it returns\n whatever the function call returned. The debugger prompt appears\n as soon as the function is entered.\n\npdb.set_trace()\n\n Enter the debugger at the calling stack frame. This is useful to\n hard-code a breakpoint at a given point in a program, even if the\n code is not otherwise being debugged (e.g. when an assertion\n fails).\n\npdb.post_mortem([traceback])\n\n Enter post-mortem debugging of the given *traceback* object. If no\n *traceback* is given, it uses the one of the exception that is\n currently being handled (an exception must be being handled if the\n default is to be used).\n\npdb.pm()\n\n Enter post-mortem debugging of the traceback found in\n ``sys.last_traceback``.\n',
'del': '\nThe ``del`` statement\n*********************\n\n del_stmt ::= "del" target_list\n\nDeletion is recursively defined very similar to the way assignment is\ndefined. Rather that spelling it out in full details, here are some\nhints.\n\nDeletion of a target list recursively deletes each target, from left\nto right.\n\nDeletion of a name removes the binding of that name from the local or\nglobal namespace, depending on whether the name occurs in a ``global``\nstatement in the same code block. If the name is unbound, a\n``NameError`` exception will be raised.\n\nIt is illegal to delete a name from the local namespace if it occurs\nas a free variable in a nested block.\n\nDeletion of attribute references, subscriptions and slicings is passed\nto the primary object involved; deletion of a slicing is in general\nequivalent to assignment of an empty slice of the right type (but even\nthis is determined by the sliced object).\n',
'dict': '\nDictionary displays\n*******************\n\nA dictionary display is a possibly empty series of key/datum pairs\nenclosed in curly braces:\n\n dict_display ::= "{" [key_datum_list | dict_comprehension] "}"\n key_datum_list ::= key_datum ("," key_datum)* [","]\n key_datum ::= expression ":" expression\n dict_comprehension ::= expression ":" expression comp_for\n\nA dictionary display yields a new dictionary object.\n\nIf a comma-separated sequence of key/datum pairs is given, they are\nevaluated from left to right to define the entries of the dictionary:\neach key object is used as a key into the dictionary to store the\ncorresponding datum. This means that you can specify the same key\nmultiple times in the key/datum list, and the final dictionary\'s value\nfor that key will be the last one given.\n\nA dict comprehension, in contrast to list and set comprehensions,\nneeds two expressions separated with a colon followed by the usual\n"for" and "if" clauses. When the comprehension is run, the resulting\nkey and value elements are inserted in the new dictionary in the order\nthey are produced.\n\nRestrictions on the types of the key values are listed earlier in\nsection *The standard type hierarchy*. (To summarize, the key type\nshould be *hashable*, which excludes all mutable objects.) Clashes\nbetween duplicate keys are not detected; the last datum (textually\nrightmost in the display) stored for a given key value prevails.\n',
@@ -41,7 +41,7 @@
'identifiers': '\nIdentifiers and keywords\n************************\n\nIdentifiers (also referred to as *names*) are described by the\nfollowing lexical definitions.\n\nThe syntax of identifiers in Python is based on the Unicode standard\nannex UAX-31, with elaboration and changes as defined below; see also\n**PEP 3131** for further details.\n\nWithin the ASCII range (U+0001..U+007F), the valid characters for\nidentifiers are the same as in Python 2.x: the uppercase and lowercase\nletters ``A`` through ``Z``, the underscore ``_`` and, except for the\nfirst character, the digits ``0`` through ``9``.\n\nPython 3.0 introduces additional characters from outside the ASCII\nrange (see **PEP 3131**). For these characters, the classification\nuses the version of the Unicode Character Database as included in the\n``unicodedata`` module.\n\nIdentifiers are unlimited in length. Case is significant.\n\n identifier ::= id_start id_continue*\n id_start ::= \n id_continue ::= \n\nThe Unicode category codes mentioned above stand for:\n\n* *Lu* - uppercase letters\n\n* *Ll* - lowercase letters\n\n* *Lt* - titlecase letters\n\n* *Lm* - modifier letters\n\n* *Lo* - other letters\n\n* *Nl* - letter numbers\n\n* *Mn* - nonspacing marks\n\n* *Mc* - spacing combining marks\n\n* *Nd* - decimal numbers\n\n* *Pc* - connector punctuations\n\nAll identifiers are converted into the normal form NFC while parsing;\ncomparison of identifiers is based on NFC.\n\nA non-normative HTML file listing all valid identifier characters for\nUnicode 4.1 can be found at http://www.dcl.hpi.uni-\npotsdam.de/home/loewis/table-3131.html.\n\n\nKeywords\n========\n\nThe following identifiers are used as reserved words, or *keywords* of\nthe language, and cannot be used as ordinary identifiers. They must\nbe spelled exactly as written here:\n\n False class finally is return\n None continue for lambda try\n True def from nonlocal while\n and del global not with\n as elif if or yield\n assert else import pass\n break except in raise\n\n\nReserved classes of identifiers\n===============================\n\nCertain classes of identifiers (besides keywords) have special\nmeanings. These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n Not imported by ``from module import *``. The special identifier\n ``_`` is used in the interactive interpreter to store the result of\n the last evaluation; it is stored in the ``builtins`` module. When\n not in interactive mode, ``_`` has no special meaning and is not\n defined. See section *The import statement*.\n\n Note: The name ``_`` is often used in conjunction with\n internationalization; refer to the documentation for the\n ``gettext`` module for more information on this convention.\n\n``__*__``\n System-defined names. These names are defined by the interpreter\n and its implementation (including the standard library);\n applications should not expect to define additional names using\n this convention. The set of names of this class defined by Python\n may be extended in future versions. See section *Special method\n names*.\n\n``__*``\n Class-private names. Names in this category, when used within the\n context of a class definition, are re-written to use a mangled form\n to help avoid name clashes between "private" attributes of base and\n derived classes. See section *Identifiers (Names)*.\n',
'if': '\nThe ``if`` statement\n********************\n\nThe ``if`` statement is used for conditional execution:\n\n if_stmt ::= "if" expression ":" suite\n ( "elif" expression ":" suite )*\n ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n',
'imaginary': '\nImaginary literals\n******************\n\nImaginary literals are described by the following lexical definitions:\n\n imagnumber ::= (floatnumber | intpart) ("j" | "J")\n\nAn imaginary literal yields a complex number with a real part of 0.0.\nComplex numbers are represented as a pair of floating point numbers\nand have the same restrictions on their range. To create a complex\nnumber with a nonzero real part, add a floating point number to it,\ne.g., ``(3+4j)``. Some examples of imaginary literals:\n\n 3.14j 10.j 10j .001j 1e100j 3.14e-10j\n',
- 'import': '\nThe ``import`` statement\n************************\n\n import_stmt ::= "import" module ["as" name] ( "," module ["as" name] )*\n | "from" relative_module "import" identifier ["as" name]\n ( "," identifier ["as" name] )*\n | "from" relative_module "import" "(" identifier ["as" name]\n ( "," identifier ["as" name] )* [","] ")"\n | "from" module "import" "*"\n module ::= (identifier ".")* identifier\n relative_module ::= "."* module | "."+\n name ::= identifier\n\nImport statements are executed in two steps: (1) find a module, and\ninitialize it if necessary; (2) define a name or names in the local\nnamespace (of the scope where the ``import`` statement occurs). The\nfirst form (without ``from``) repeats these steps for each identifier\nin the list. The form with ``from`` performs step (1) once, and then\nperforms step (2) repeatedly.\n\nIn this context, to "initialize" a built-in or extension module means\nto call an initialization function that the module must provide for\nthe purpose (in the reference implementation, the function\'s name is\nobtained by prepending string "init" to the module\'s name); to\n"initialize" a Python-coded module means to execute the module\'s body.\n\nThe system maintains a table of modules that have been or are being\ninitialized, indexed by module name. This table is accessible as\n``sys.modules``. When a module name is found in this table, step (1)\nis finished. If not, a search for a module definition is started.\nWhen a module is found, it is loaded. Details of the module searching\nand loading process are implementation and platform specific. It\ngenerally involves searching for a "built-in" module with the given\nname and then searching a list of locations given as ``sys.path``.\n\nIf a built-in module is found, its built-in initialization code is\nexecuted and step (1) is finished. If no matching file is found,\n``ImportError`` is raised. If a file is found, it is parsed, yielding\nan executable code block. If a syntax error occurs, ``SyntaxError``\nis raised. Otherwise, an empty module of the given name is created\nand inserted in the module table, and then the code block is executed\nin the context of this module. Exceptions during this execution\nterminate step (1).\n\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\n\nThe first form of ``import`` statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any. If the module name is followed by ``as``,\nthe name following ``as`` is used as the local name for the module.\n\nThe ``from`` form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in\nstep (1), and binds the name in the local namespace to the object thus\nfound. As with the first form of ``import``, an alternate local name\ncan be supplied by specifying "``as`` localname". If a name is not\nfound, ``ImportError`` is raised. If the list of identifiers is\nreplaced by a star (``\'*\'``), all public names defined in the module\nare bound in the local namespace of the ``import`` statement..\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named ``__all__``; if defined, it\nmust be a sequence of strings which are names defined or imported by\nthat module. The names given in ``__all__`` are all considered public\nand are required to exist. If ``__all__`` is not defined, the set of\npublic names includes all names found in the module\'s namespace which\ndo not begin with an underscore character (``\'_\'``). ``__all__``\nshould contain the entire public API. It is intended to avoid\naccidentally exporting items that are not part of the API (such as\nlibrary modules which were imported and used within the module).\n\nThe ``from`` form with ``*`` may only occur in a module scope. If the\nwild card form of import --- ``import *`` --- is used in a function\nand the function contains or is a nested block with free variables,\nthe compiler will raise a ``SyntaxError``.\n\n**Hierarchical module names:** when the module names contains one or\nmore dots, the module search path is carried out differently. The\nsequence of identifiers up to the last dot is used to find a\n"package"; the final identifier is then searched inside the package.\nA package is generally a subdirectory of a directory on ``sys.path``\nthat has a file ``__init__.py``.\n\nThe built-in function ``__import__()`` is provided to support\napplications that determine which modules need to be loaded\ndynamically; refer to *Built-in Functions* for additional information.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python. The future\nstatement is intended to ease migration to future versions of Python\nthat introduce incompatible changes to the language. It allows use of\nthe new features on a per-module basis before the release in which the\nfeature becomes standard.\n\n future_statement ::= "from" "__future__" "import" feature ["as" name]\n ("," feature ["as" name])*\n | "from" "__future__" "import" "(" feature ["as" name]\n ("," feature ["as" name])* [","] ")"\n feature ::= identifier\n name ::= identifier\n\nA future statement must appear near the top of the module. The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 3.0 are ``absolute_import``,\n``division``, ``generators``, ``nested_scopes`` and\n``with_statement``. They are all redundant because they are always\nenabled, and only kept for backwards compatibility.\n\nA future statement is recognized and treated specially at compile\ntime: Changes to the semantics of core constructs are often\nimplemented by generating different code. It may even be the case\nthat a new feature introduces new incompatible syntax (such as a new\nreserved word), in which case the compiler may need to parse the\nmodule differently. Such decisions cannot be pushed off until\nruntime.\n\nFor any given release, the compiler knows which feature names have\nbeen defined, and raises a compile-time error if a future statement\ncontains a feature not known to it.\n\nThe direct runtime semantics are the same as for any import statement:\nthere is a standard module ``__future__``, described later, and it\nwill be imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by calls to the builtin functions ``exec()`` and\n``compile()`` that occur in a module ``M`` containing a future\nstatement will, by default, use the new syntax or semantics associated\nwith the future statement. This can be controlled by optional\narguments to ``compile()`` --- see the documentation of that function\nfor details.\n\nA future statement typed at an interactive interpreter prompt will\ntake effect for the rest of the interpreter session. If an\ninterpreter is started with the *-i* option, is passed a script name\nto execute, and the script includes a future statement, it will be in\neffect in the interactive session started after the script is\nexecuted.\n',
+ 'import': '\nThe ``import`` statement\n************************\n\n import_stmt ::= "import" module ["as" name] ( "," module ["as" name] )*\n | "from" relative_module "import" identifier ["as" name]\n ( "," identifier ["as" name] )*\n | "from" relative_module "import" "(" identifier ["as" name]\n ( "," identifier ["as" name] )* [","] ")"\n | "from" module "import" "*"\n module ::= (identifier ".")* identifier\n relative_module ::= "."* module | "."+\n name ::= identifier\n\nImport statements are executed in two steps: (1) find a module, and\ninitialize it if necessary; (2) define a name or names in the local\nnamespace (of the scope where the ``import`` statement occurs). The\nfirst form (without ``from``) repeats these steps for each identifier\nin the list. The form with ``from`` performs step (1) once, and then\nperforms step (2) repeatedly.\n\nIn this context, to "initialize" a built-in or extension module means\nto call an initialization function that the module must provide for\nthe purpose (in the reference implementation, the function\'s name is\nobtained by prepending string "init" to the module\'s name); to\n"initialize" a Python-coded module means to execute the module\'s body.\n\nThe system maintains a table of modules that have been or are being\ninitialized, indexed by module name. This table is accessible as\n``sys.modules``. When a module name is found in this table, step (1)\nis finished. If not, a search for a module definition is started.\nWhen a module is found, it is loaded. Details of the module searching\nand loading process are implementation and platform specific. It\ngenerally involves searching for a "built-in" module with the given\nname and then searching a list of locations given as ``sys.path``.\n\nIf a built-in module is found, its built-in initialization code is\nexecuted and step (1) is finished. If no matching file is found,\n``ImportError`` is raised. If a file is found, it is parsed, yielding\nan executable code block. If a syntax error occurs, ``SyntaxError``\nis raised. Otherwise, an empty module of the given name is created\nand inserted in the module table, and then the code block is executed\nin the context of this module. Exceptions during this execution\nterminate step (1).\n\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\n\nThe first form of ``import`` statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any. If the module name is followed by ``as``,\nthe name following ``as`` is used as the local name for the module.\n\nThe ``from`` form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in\nstep (1), and binds the name in the local namespace to the object thus\nfound. As with the first form of ``import``, an alternate local name\ncan be supplied by specifying "``as`` localname". If a name is not\nfound, ``ImportError`` is raised. If the list of identifiers is\nreplaced by a star (``\'*\'``), all public names defined in the module\nare bound in the local namespace of the ``import`` statement..\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named ``__all__``; if defined, it\nmust be a sequence of strings which are names defined or imported by\nthat module. The names given in ``__all__`` are all considered public\nand are required to exist. If ``__all__`` is not defined, the set of\npublic names includes all names found in the module\'s namespace which\ndo not begin with an underscore character (``\'_\'``). ``__all__``\nshould contain the entire public API. It is intended to avoid\naccidentally exporting items that are not part of the API (such as\nlibrary modules which were imported and used within the module).\n\nThe ``from`` form with ``*`` may only occur in a module scope. If the\nwild card form of import --- ``import *`` --- is used in a function\nand the function contains or is a nested block with free variables,\nthe compiler will raise a ``SyntaxError``.\n\n**Hierarchical module names:** when the module names contains one or\nmore dots, the module search path is carried out differently. The\nsequence of identifiers up to the last dot is used to find a\n"package"; the final identifier is then searched inside the package.\nA package is generally a subdirectory of a directory on ``sys.path``\nthat has a file ``__init__.py``.\n\nThe built-in function ``__import__()`` is provided to support\napplications that determine which modules need to be loaded\ndynamically; refer to *Built-in Functions* for additional information.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python. The future\nstatement is intended to ease migration to future versions of Python\nthat introduce incompatible changes to the language. It allows use of\nthe new features on a per-module basis before the release in which the\nfeature becomes standard.\n\n future_statement ::= "from" "__future__" "import" feature ["as" name]\n ("," feature ["as" name])*\n | "from" "__future__" "import" "(" feature ["as" name]\n ("," feature ["as" name])* [","] ")"\n feature ::= identifier\n name ::= identifier\n\nA future statement must appear near the top of the module. The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 3.0 are ``absolute_import``,\n``division``, ``generators``, ``unicode_literals``,\n``print_function``, ``nested_scopes`` and ``with_statement``. They\nare all redundant because they are always enabled, and only kept for\nbackwards compatibility.\n\nA future statement is recognized and treated specially at compile\ntime: Changes to the semantics of core constructs are often\nimplemented by generating different code. It may even be the case\nthat a new feature introduces new incompatible syntax (such as a new\nreserved word), in which case the compiler may need to parse the\nmodule differently. Such decisions cannot be pushed off until\nruntime.\n\nFor any given release, the compiler knows which feature names have\nbeen defined, and raises a compile-time error if a future statement\ncontains a feature not known to it.\n\nThe direct runtime semantics are the same as for any import statement:\nthere is a standard module ``__future__``, described later, and it\nwill be imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by calls to the builtin functions ``exec()`` and\n``compile()`` that occur in a module ``M`` containing a future\nstatement will, by default, use the new syntax or semantics associated\nwith the future statement. This can be controlled by optional\narguments to ``compile()`` --- see the documentation of that function\nfor details.\n\nA future statement typed at an interactive interpreter prompt will\ntake effect for the rest of the interpreter session. If an\ninterpreter is started with the *-i* option, is passed a script name\nto execute, and the script includes a future statement, it will be in\neffect in the interactive session started after the script is\nexecuted.\n',
'in': '\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation. Also unlike C, expressions like ``a < b < c`` have the\ninterpretation that is conventional in mathematics:\n\n comparison ::= or_expr ( comp_operator or_expr )*\n comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: ``True`` or ``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects. The objects need not have the same type.\nIf both are numbers, they are converted to a common type. Otherwise,\nthe ``==`` and ``!=`` operators *always* consider objects of different\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\noperators raise a ``TypeError`` when comparing objects of different\ntypes that do not implement these operators for the given pair of\ntypes. You can control comparison behavior of objects of non-builtin\ntypes by defining rich comparison methods like ``__gt__()``, described\nin section *Basic customization*.\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* Bytes objects are compared lexicographically using the numeric\n values of their elements.\n\n* Strings are compared lexicographically using the numeric equivalents\n (the result of the built-in function ``ord()``) of their characters.\n [3] String and bytes object can\'t be compared!\n\n* Tuples and lists are compared lexicographically using comparison of\n corresponding elements. This means that to compare equal, each\n element must compare equal and the two sequences must be of the same\n type and have the same length.\n\n If not equal, the sequences are ordered the same as their first\n differing elements. For example, ``cmp([1,2,x], [1,2,y])`` returns\n the same as ``cmp(x,y)``. If the corresponding element does not\n exist, the shorter sequence is ordered first (for example, ``[1,2] <\n [1,2,3]``).\n\n* Mappings (dictionaries) compare equal if and only if their sorted\n ``(key, value)`` lists compare equal. [4] Outcomes other than\n equality are resolved consistently, but are not otherwise defined.\n [5]\n\n* Most other objects of builtin types compare unequal unless they are\n the same object; the choice whether one object is considered smaller\n or larger than another one is made arbitrarily but consistently\n within one execution of a program.\n\nThe operators ``in`` and ``not in`` test for membership. ``x in s``\nevaluates to true if *x* is a member of *s*, and false otherwise. ``x\nnot in s`` returns the negation of ``x in s``. All built-in sequences\nand set types support this as well as dictionary, for which ``in``\ntests whether a the dictionary has a given key.\n\nFor the list and tuple types, ``x in y`` is true if and only if there\nexists an index *i* such that ``x == y[i]`` is true.\n\nFor the string and bytes types, ``x in y`` is true if and only if *x*\nis a substring of *y*. An equivalent test is ``y.find(x) != -1``.\nEmpty strings are always considered to be a substring of any other\nstring, so ``"" in "abc"`` will return ``True``.\n\nFor user-defined classes which define the ``__contains__()`` method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` and do\ndefine ``__getitem__()``, ``x in y`` is true if and only if there is a\nnon-negative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception. (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object. ``x is\nnot y`` yields the inverse truth value. [6]\n',
'integers': '\nInteger literals\n****************\n\nInteger literals are described by the following lexical definitions:\n\n integer ::= decimalinteger | octinteger | hexinteger | bininteger\n decimalinteger ::= nonzerodigit digit* | "0"+\n nonzerodigit ::= "1"..."9"\n digit ::= "0"..."9"\n octinteger ::= "0" ("o" | "O") octdigit+\n hexinteger ::= "0" ("x" | "X") hexdigit+\n bininteger ::= "0" ("b" | "B") bindigit+\n octdigit ::= "0"..."7"\n hexdigit ::= digit | "a"..."f" | "A"..."F"\n bindigit ::= "0" | "1"\n\nThere is no limit for the length of integer literals apart from what\ncan be stored in available memory.\n\nNote that leading zeros in a non-zero decimal number are not allowed.\nThis is for disambiguation with C-style octal literals, which Python\nused before version 3.0.\n\nSome examples of integer literals:\n\n 7 2147483647 0o177 0b100110111\n 3 79228162514264337593543950336 0o377 0x100000000\n 79228162514264337593543950336 0xdeadbeef\n',
'lambda': '\nExpression lists\n****************\n\n expression_list ::= expression ( "," expression )* [","]\n\nAn expression list containing at least one comma yields a tuple. The\nlength of the tuple is the number of expressions in the list. The\nexpressions are evaluated from left to right.\n\nThe trailing comma is required only to create a single tuple (a.k.a. a\n*singleton*); it is optional in all other cases. A single expression\nwithout a trailing comma doesn\'t create a tuple, but rather yields the\nvalue of that expression. (To create an empty tuple, use an empty pair\nof parentheses: ``()``.)\n',
@@ -59,7 +59,7 @@
'shifting': '\nShifting operations\n*******************\n\nThe shifting operations have lower priority than the arithmetic\noperations:\n\n shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr\n\nThese operators accept integers as arguments. They shift the first\nargument to the left or right by the number of bits given by the\nsecond argument.\n\nA right shift by *n* bits is defined as division by ``pow(2,n)``. A\nleft shift by *n* bits is defined as multiplication with ``pow(2,n)``.\n',
'slicings': '\nSlicings\n********\n\nA slicing selects a range of items in a sequence object (e.g., a\nstring, tuple or list). Slicings may be used as expressions or as\ntargets in assignment or ``del`` statements. The syntax for a\nslicing:\n\n slicing ::= primary "[" slice_list "]"\n slice_list ::= slice_item ("," slice_item)* [","]\n slice_item ::= expression | proper_slice\n proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]\n lower_bound ::= expression\n upper_bound ::= expression\n stride ::= expression\n\nThere is ambiguity in the formal syntax here: anything that looks like\nan expression list also looks like a slice list, so any subscription\ncan be interpreted as a slicing. Rather than further complicating the\nsyntax, this is disambiguated by defining that in this case the\ninterpretation as a subscription takes priority over the\ninterpretation as a slicing (this is the case if the slice list\ncontains no proper slice).\n\nThe semantics for a slicing are as follows. The primary must evaluate\nto a mapping object, and it is indexed (using the same\n``__getitem__()`` method as normal subscription) with a key that is\nconstructed from the slice list, as follows. If the slice list\ncontains at least one comma, the key is a tuple containing the\nconversion of the slice items; otherwise, the conversion of the lone\nslice item is the key. The conversion of a slice item that is an\nexpression is that expression. The conversion of a proper slice is a\nslice object (see section *The standard type hierarchy*) whose\n``start``, ``stop`` and ``step`` attributes are the values of the\nexpressions given as lower bound, upper bound and stride,\nrespectively, substituting ``None`` for missing expressions.\n',
'specialattrs': "\nSpecial Attributes\n******************\n\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant. Some of these are not reported\nby the ``dir()`` built-in function.\n\nobject.__dict__\n\n A dictionary or other mapping object used to store an object's\n (writable) attributes.\n\ninstance.__class__\n\n The class to which a class instance belongs.\n\nclass.__bases__\n\n The tuple of base classes of a class object. If there are no base\n classes, this will be an empty tuple.\n\nclass.__name__\n\n The name of the class or type.\n\n-[ Footnotes ]-\n\n[1] Additional information on these special methods may be found in\n the Python Reference Manual (*Basic customization*).\n\n[2] As a consequence, the list ``[1, 2]`` is considered equal to\n ``[1.0, 2.0]``, and similarly for tuples.\n\n[3] They must have since the parser can't tell the type of the\n operands.\n\n[4] To format only a tuple you should therefore provide a singleton\n tuple whose only element is the tuple to be formatted.\n\n[5] These numbers are fairly arbitrary. They are intended to avoid\n printing endless strings of meaningless digits without hampering\n correct use and without having to know the exact precision of\n floating point values on a particular machine.\n\n[6] The advantage of leaving the newline on is that returning an empty\n string is then an unambiguous EOF indication. It is also possible\n (in cases where it might matter, for example, if you want to make\n an exact copy of a file while scanning its lines) to tell whether\n the last line of a file ended in a newline or not (yes this\n happens!).\n",
- 'specialnames': '\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators. For instance, if a class defines\na method named ``__getitem__()``, and ``x`` is an instance of this\nclass, then ``x[i]`` is roughly equivalent to ``type(x).__getitem__(x,\ni)``. Except where mentioned, attempts to execute an operation raise\nan exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled. For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense. (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. ``__new__()`` is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of ``__new__()`` should be the new object instance (usually\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.last_traceback``. Circular references which are garbage are\n detected when the option cycle detector is enabled (it\'s on by\n default), but can only be cleaned up if there are no Python-\n level ``__del__()`` methods involved. Refer to the documentation\n for the ``gc`` module for more information about how\n ``__del__()`` methods are handled by the cycle detector,\n particularly the description of the ``garbage`` value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted. For this reason, ``__del__()`` methods should do\n the absolute minimum needed to maintain external invariants.\n Starting with version 1.5, Python guarantees that globals whose\n name begins with a single underscore are deleted from their\n module before other globals are deleted; if no other references\n to such globals exist, this may help in assuring that imported\n modules are still available at the time when the ``__del__()``\n method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function and by string\n conversions (reverse quotes) to compute the "official" string\n representation of an object. If at all possible, this should look\n like a valid Python expression that could be used to recreate an\n object with the same value (given an appropriate environment). If\n this is not possible, a string of the form ``<...some useful\n description...>`` should be returned. The return value must be a\n string object. If a class defines ``__repr__()`` but not\n ``__str__()``, then ``__repr__()`` is also used when an "informal"\n string representation of instances of that class is required.\n\n This is typically used for debugging, so it is important that the\n representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n Called by the ``str()`` built-in function and by the ``print()``\n function to compute the "informal" string representation of an\n object. This differs from ``__repr__()`` in that it does not have\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__format__(self, format_spec)\n\n Called by the ``format()`` built-in function (and by extension, the\n ``format()`` method of class ``str``) to produce a "formatted"\n string representation of an object. The ``format_spec`` argument is\n a string that contains a description of the formatting options\n desired. The interpretation of the ``format_spec`` argument is up\n to the type implementing ``__format__()``, however most classes\n will either delegate formatting to one of the built-in types, or\n use a similar formatting option syntax.\n\n See *Format Specification Mini-Language* for a description of the\n standard formatting syntax.\n\n The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n These are the so-called "rich comparison" methods. The\n correspondence between operator symbols and method names is as\n follows: ``xy`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\nobject.__hash__(self)\n\n Called for the key object for dictionary operations, and by the\n built-in function ``hash()``. Should return an integer usable as a\n hash value for dictionary operations. The only required property\n is that objects which compare equal have the same hash value; it is\n advised to somehow mix together (e.g., using exclusive or) the hash\n values for the components of the object that also play a part in\n comparison of objects.\n\n If a class does not define an ``__eq__()`` method it should not\n define a ``__hash__()`` operation either; if it defines\n ``__eq__()`` but not ``__hash__()``, its instances will not be\n usable as dictionary keys. If a class defines mutable objects and\n implements an ``__eq__()`` method, it should not implement\n ``__hash__()``, since the dictionary implementation requires that a\n key\'s hash value is immutable (if the object\'s hash value changes,\n it will be in the wrong hash bucket).\n\n User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__eq__()`` such that the hash value\n returned is no longer appropriate (e.g. by switching to a value-\n based concept of equality instead of the default identity based\n equality) can explicitly flag themselves as being unhashable by\n setting ``__hash__ = None`` in the class definition. Doing so means\n that not only will instances of the class raise an appropriate\n ``TypeError`` when a program attempts to retrieve their hash value,\n but they will also be correctly identified as unhashable when\n checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n which define their own ``__hash__()`` to explicitly raise\n ``TypeError``).\n\n If a class that overrrides ``__eq__()`` needs to retain the\n implementation of ``__hash__()`` from a parent class, the\n interpreter must be told this explicitly by setting ``__hash__ =\n .__hash__``. Otherwise the inheritance of\n ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n explicitly set to ``None``.\n\nobject.__bool__(self)\n\n Called to implement truth value testing, and the built-in operation\n ``bool()``; should return ``False`` or ``True``. When this method\n is not defined, ``__len__()`` is called, if it is defined (see\n below) and ``True`` is returned when the length is not zero. If a\n class defines neither ``__len__()`` nor ``__bool__()``, all its\n instances are considered true.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control over attribute access.\n\nobject.__getattribute__(self, name)\n\n Called unconditionally to implement attribute accesses for\n instances of the class. If the class also defines\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n builtin functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\n\n Called when an attribute assignment is attempted. This is called\n instead of the normal mechanism (i.e. store the value in the\n instance dictionary). *name* is the attribute name, *value* is the\n value to be assigned to it.\n\n If ``__setattr__()`` wants to assign to an instance attribute, it\n should call the base class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\nobject.__dir__(self)\n\n Called when ``dir()`` is called on the object. A list must be\n returned.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another class, known as the *owner* class. In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or ``None`` when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to an object instance, ``a.x`` is transformed into the\n call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n If binding to a class, ``A.x`` is transformed into the call:\n ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n If ``a`` is an instance of ``super``, then the binding ``super(B,\n obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. Normally, data\ndescriptors define both ``__get__()`` and ``__set__()``, while non-\ndata descriptors have just the ``__get__()`` method. Data descriptors\nalways override a redefinition in an instance dictionary. In\ncontrast, non-data descriptors can be overridden by instances. [2]\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of classes have a dictionary for attribute\nstorage. This wastes space for objects having very few instance\nvariables. The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable. Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__slots__\n\n This class variable can be assigned a string, iterable, or sequence\n of strings with variable names used by instances. If defined in a\n class, *__slots__* reserves space for the declared variables and\n prevents the automatic creation of *__dict__* and *__weakref__* for\n each instance.\n\n\nNotes on using *__slots__*\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n attribute of that class will always be accessible, so a *__slots__*\n definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n variables not listed in the *__slots__* definition. Attempts to\n assign to an unlisted variable name raises ``AttributeError``. If\n dynamic assignment of new variables is desired, then add\n ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n descriptors (*Implementing Descriptors*) for each variable name. As\n a result, class attributes cannot be used to set default values for\n instance variables defined by *__slots__*; otherwise, the class\n attribute would overwrite the descriptor assignment.\n\n* If a class defines a slot also defined in a base class, the instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* The action of a *__slots__* declaration is limited to the class\n where it is defined. As a result, subclasses will have a *__dict__*\n unless they also define *__slots__*.\n\n* *__slots__* do not work for classes derived from "variable-length"\n built-in types such as ``int``, ``str`` and ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, classes are constructed using ``type()``. A class\ndefinition is read into a separate namespace and the value of class\nname is bound to the result of ``type(name, bases, dict)``.\n\nWhen the class definition is read, if *__metaclass__* is defined then\nthe callable assigned to it will be called instead of ``type()``. This\nallows classes or functions to be written which monitor or alter the\nclass creation process:\n\n* Modifying the class dictionary prior to the class being created.\n\n* Returning an instance of another class -- essentially performing the\n role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties. This example adds a new\nelement to the class dictionary before creating the class:\n\n class metacls(type):\n def __new__(mcs, name, bases, dict):\n dict[\'foo\'] = \'metacls was here\'\n return type.__new__(mcs, name, bases, dict)\n\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\n__metaclass__\n\n This variable can be any callable accepting arguments for ``name``,\n ``bases``, and ``dict``. Upon class creation, the callable is used\n instead of the built-in ``type()``.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If ``dict[\'__metaclass__\']`` exists, it is used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n used (this looks for a *__class__* attribute first and if not found,\n uses its type).\n\n* Otherwise, if a global variable named __metaclass__ exists, it is\n used.\n\n* Otherwise, the default metaclass (``type``) is used.\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n Called when the instance is "called" as a function; if this method\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n ``x.__call__(arg1, arg2, ...)``.\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well. The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items. It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\nand ``update()`` behaving similar to those for Python\'s standard\ndictionary objects. The ``collections`` module provides a\n``MutableMapping`` abstract base class to help create those methods\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\nlike Python standard list objects. Finally, sequence types should\nimplement addition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\ndescribed below; they should not define other numerical operators. It\nis recommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should search the mapping\'s keys; for\nsequences, it should search through the values. It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``keys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n Called to implement the built-in function ``len()``. Should return\n the length of the object, an integer ``>=`` 0. Also, an object\n that doesn\'t define a ``__bool__()`` method and whose ``__len__()``\n method returns zero is considered to be false in a Boolean context.\n\nNote: Slicing is done exclusively with the following three methods. A\n call like\n\n a[1:2] = b\n\n is translated to\n\n a[slice(1, 2, None)] = b\n\n and so forth. Missing slice items are always filled in with\n ``None``.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of ``self[key]``. For sequence\n types, the accepted keys should be integers and slice objects.\n Note that the special interpretation of negative indexes (if the\n class wishes to emulate a sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an inappropriate type,\n ``TypeError`` may be raised; if of a value outside the set of\n indexes for the sequence (after any special interpretation of\n negative values), ``IndexError`` should be raised. For mapping\n types, if *key* is missing (not in the container), ``KeyError``\n should be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\n illegal indexes to allow proper detection of the end of the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to implement assignment to ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support changes to the values for keys, or if new keys\n can be added, or for sequences if elements can be replaced. The\n same exceptions should be raised for improper *key* values as for\n the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to implement deletion of ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support removal of keys, or for sequences if elements\n can be removed from the sequence. The same exceptions should be\n raised for improper *key* values as for the ``__getitem__()``\n method.\n\nobject.__iter__(self)\n\n This method is called when an iterator is required for a container.\n This method should return a new iterator object that can iterate\n over all the objects in the container. For mappings, it should\n iterate over the keys of the container, and should also be made\n available as the method ``keys()``.\n\n Iterator objects also need to implement this method; they are\n required to return themselves. For more information on iterator\n objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n Called (if present) by the ``reversed()`` builtin to implement\n reverse iteration. It should return a new iterator object that\n iterates over all the objects in the container in reverse order.\n\n If the ``__reversed__()`` method is not provided, the\n ``reversed()`` builtin will fall back to using the sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects should\n normally only provide ``__reversed__()`` if they do not support the\n sequence protocol and an efficient implementation of reverse\n iteration is possible.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence. However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n Called to implement membership test operators. Should return true\n if *item* is in *self*, false otherwise. For mapping objects, this\n should consider the keys of the mapping rather than the values or\n the key-item pairs.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n ``|``). For instance, to evaluate the expression ``x + y``, where\n *x* is an instance of a class that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n should not be related to ``__truediv__()``. Note that\n ``__pow__()`` should be defined to accept an optional third\n argument if the ternary version of the built-in ``pow()`` function\n is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n ``|``) with reflected (swapped) operands. These functions are only\n called if the left operand does not support the corresponding\n operation and the operands are of different types. [3] For\n instance, to evaluate the expression ``x - y``, where *y* is an\n instance of a class that has an ``__rsub__()`` method,\n ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n *NotImplemented*.\n\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\n (the coercion rules would become too complicated).\n\n Note: If the right operand\'s type is a subclass of the left operand\'s\n type and that subclass provides the reflected method for the\n operation, this method will be called before the left operand\'s\n non-reflected method. This behavior allows subclasses to\n override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n These methods are called to implement the augmented arithmetic\n operations (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``). These methods\n should attempt to do the operation in-place (modifying *self*) and\n return the result (which could be, but does not have to be,\n *self*). If a specific method is not defined, the augmented\n operation falls back to the normal methods. For instance, to\n evaluate the expression ``x += y``, where *x* is an instance of a\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations (``-``, ``+``,\n ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``float()`` and ``round()``. Should return a value of\n the appropriate type.\n\nobject.__index__(self)\n\n Called to implement ``operator.index()``. Also called whenever\n Python needs an integer object (such as in slicing, or in the\n built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n an integer.\n\n\nWith Statement Context Managers\n===============================\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code. Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The ``with``\n statement will bind this method\'s return value to the target(s)\n specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be ``None``.\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that ``__exit__()`` methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n\n\nSpecial method lookup\n=====================\n\nFor custom classes, implicit invocations of special methods are only\nguaranteed to work correctly if defined on an object\'s type, not in\nthe object\'s instance dictionary. That behaviour is the reason why\nthe following code raises an exception:\n\n >>> class C(object):\n ... pass\n ...\n >>> c = C()\n >>> c.__len__ = lambda: 5\n >>> len(c)\n Traceback (most recent call last):\n File "", line 1, in \n TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as ``__hash__()`` and ``__repr__()`` that are implemented\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n >>> 1 .__hash__() == hash(1)\n True\n >>> int.__hash__() == hash(int)\n Traceback (most recent call last):\n File "", line 1, in \n TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n >>> type(1).__hash__(1) == hash(1)\n True\n >>> type(int).__hash__(int) == hash(int)\n True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup may also bypass the\n``__getattribute__()`` method even of the object\'s metaclass:\n\n >>> class Meta(type):\n ... def __getattribute__(*args):\n ... print "Metaclass getattribute invoked"\n ... return type.__getattribute__(*args)\n ...\n >>> class C(object):\n ... __metaclass__ = Meta\n ... def __len__(self):\n ... return 10\n ... def __getattribute__(*args):\n ... print "Class getattribute invoked"\n ... return object.__getattribute__(*args)\n ...\n >>> c = C()\n >>> c.__len__() # Explicit lookup via instance\n Class getattribute invoked\n 10\n >>> type(c).__len__(c) # Explicit lookup via type\n Metaclass getattribute invoked\n 10\n >>> len(c) # Implicit lookup\n 10\n\nBypassing the ``__getattribute__()`` machinery in this fashion\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n certain controlled conditions. It generally isn\'t a good idea\n though, since it can lead to some very strange behaviour if it is\n handled incorrectly.\n\n[2] A descriptor can define any combination of ``__get__()``,\n ``__set__()`` and ``__delete__()``. If it does not define\n ``__get__()``, then accessing the attribute even on an instance\n will return the descriptor object itself. If the descriptor\n defines ``__set__()`` and/or ``__delete__()``, it is a data\n descriptor; if it defines neither, it is a non-data descriptor.\n\n[3] For operands of the same type, it is assumed that if the non-\n reflected method (such as ``__add__()``) fails the operation is\n not supported, which is why the reflected method is not called.\n',
+ 'specialnames': '\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators. For instance, if a class defines\na method named ``__getitem__()``, and ``x`` is an instance of this\nclass, then ``x[i]`` is roughly equivalent to ``type(x).__getitem__(x,\ni)``. Except where mentioned, attempts to execute an operation raise\nan exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled. For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense. (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. ``__new__()`` is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of ``__new__()`` should be the new object instance (usually\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.last_traceback``. Circular references which are garbage are\n detected when the option cycle detector is enabled (it\'s on by\n default), but can only be cleaned up if there are no Python-\n level ``__del__()`` methods involved. Refer to the documentation\n for the ``gc`` module for more information about how\n ``__del__()`` methods are handled by the cycle detector,\n particularly the description of the ``garbage`` value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted. For this reason, ``__del__()`` methods should do\n the absolute minimum needed to maintain external invariants.\n Starting with version 1.5, Python guarantees that globals whose\n name begins with a single underscore are deleted from their\n module before other globals are deleted; if no other references\n to such globals exist, this may help in assuring that imported\n modules are still available at the time when the ``__del__()``\n method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function to compute the\n "official" string representation of an object. If at all possible,\n this should look like a valid Python expression that could be used\n to recreate an object with the same value (given an appropriate\n environment). If this is not possible, a string of the form\n ``<...some useful description...>`` should be returned. The return\n value must be a string object. If a class defines ``__repr__()``\n but not ``__str__()``, then ``__repr__()`` is also used when an\n "informal" string representation of instances of that class is\n required.\n\n This is typically used for debugging, so it is important that the\n representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n Called by the ``str()`` built-in function and by the ``print()``\n function to compute the "informal" string representation of an\n object. This differs from ``__repr__()`` in that it does not have\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__format__(self, format_spec)\n\n Called by the ``format()`` built-in function (and by extension, the\n ``format()`` method of class ``str``) to produce a "formatted"\n string representation of an object. The ``format_spec`` argument is\n a string that contains a description of the formatting options\n desired. The interpretation of the ``format_spec`` argument is up\n to the type implementing ``__format__()``, however most classes\n will either delegate formatting to one of the built-in types, or\n use a similar formatting option syntax.\n\n See *Format Specification Mini-Language* for a description of the\n standard formatting syntax.\n\n The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n These are the so-called "rich comparison" methods. The\n correspondence between operator symbols and method names is as\n follows: ``xy`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\nobject.__hash__(self)\n\n Called for the key object for dictionary operations, and by the\n built-in function ``hash()``. Should return an integer usable as a\n hash value for dictionary operations. The only required property\n is that objects which compare equal have the same hash value; it is\n advised to somehow mix together (e.g., using exclusive or) the hash\n values for the components of the object that also play a part in\n comparison of objects.\n\n If a class does not define an ``__eq__()`` method it should not\n define a ``__hash__()`` operation either; if it defines\n ``__eq__()`` but not ``__hash__()``, its instances will not be\n usable as dictionary keys. If a class defines mutable objects and\n implements an ``__eq__()`` method, it should not implement\n ``__hash__()``, since the dictionary implementation requires that a\n key\'s hash value is immutable (if the object\'s hash value changes,\n it will be in the wrong hash bucket).\n\n User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__eq__()`` such that the hash value\n returned is no longer appropriate (e.g. by switching to a value-\n based concept of equality instead of the default identity based\n equality) can explicitly flag themselves as being unhashable by\n setting ``__hash__ = None`` in the class definition. Doing so means\n that not only will instances of the class raise an appropriate\n ``TypeError`` when a program attempts to retrieve their hash value,\n but they will also be correctly identified as unhashable when\n checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n which define their own ``__hash__()`` to explicitly raise\n ``TypeError``).\n\n If a class that overrrides ``__eq__()`` needs to retain the\n implementation of ``__hash__()`` from a parent class, the\n interpreter must be told this explicitly by setting ``__hash__ =\n .__hash__``. Otherwise the inheritance of\n ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n explicitly set to ``None``.\n\nobject.__bool__(self)\n\n Called to implement truth value testing, and the built-in operation\n ``bool()``; should return ``False`` or ``True``. When this method\n is not defined, ``__len__()`` is called, if it is defined (see\n below) and ``True`` is returned when the length is not zero. If a\n class defines neither ``__len__()`` nor ``__bool__()``, all its\n instances are considered true.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control over attribute access.\n\nobject.__getattribute__(self, name)\n\n Called unconditionally to implement attribute accesses for\n instances of the class. If the class also defines\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n builtin functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\n\n Called when an attribute assignment is attempted. This is called\n instead of the normal mechanism (i.e. store the value in the\n instance dictionary). *name* is the attribute name, *value* is the\n value to be assigned to it.\n\n If ``__setattr__()`` wants to assign to an instance attribute, it\n should call the base class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\nobject.__dir__(self)\n\n Called when ``dir()`` is called on the object. A list must be\n returned.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another class, known as the *owner* class. In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or ``None`` when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to an object instance, ``a.x`` is transformed into the\n call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n If binding to a class, ``A.x`` is transformed into the call:\n ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n If ``a`` is an instance of ``super``, then the binding ``super(B,\n obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. Normally, data\ndescriptors define both ``__get__()`` and ``__set__()``, while non-\ndata descriptors have just the ``__get__()`` method. Data descriptors\nalways override a redefinition in an instance dictionary. In\ncontrast, non-data descriptors can be overridden by instances. [2]\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of classes have a dictionary for attribute\nstorage. This wastes space for objects having very few instance\nvariables. The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable. Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__slots__\n\n This class variable can be assigned a string, iterable, or sequence\n of strings with variable names used by instances. If defined in a\n class, *__slots__* reserves space for the declared variables and\n prevents the automatic creation of *__dict__* and *__weakref__* for\n each instance.\n\n\nNotes on using *__slots__*\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n attribute of that class will always be accessible, so a *__slots__*\n definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n variables not listed in the *__slots__* definition. Attempts to\n assign to an unlisted variable name raises ``AttributeError``. If\n dynamic assignment of new variables is desired, then add\n ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n descriptors (*Implementing Descriptors*) for each variable name. As\n a result, class attributes cannot be used to set default values for\n instance variables defined by *__slots__*; otherwise, the class\n attribute would overwrite the descriptor assignment.\n\n* If a class defines a slot also defined in a base class, the instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* The action of a *__slots__* declaration is limited to the class\n where it is defined. As a result, subclasses will have a *__dict__*\n unless they also define *__slots__*.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as ``int``, ``str`` and\n ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, classes are constructed using ``type()``. A class\ndefinition is read into a separate namespace and the value of class\nname is bound to the result of ``type(name, bases, dict)``.\n\nWhen the class definition is read, if a callable ``metaclass`` keyword\nargument is passed after the bases in the class definition, the\ncallable given will be called instead of ``type()``. If other keyword\narguments are passed, they will also be passed to the metaclass. This\nallows classes or functions to be written which monitor or alter the\nclass creation process:\n\n* Modifying the class dictionary prior to the class being created.\n\n* Returning an instance of another class -- essentially performing the\n role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties. This example adds a new\nelement to the class dictionary before creating the class:\n\n class metacls(type):\n def __new__(mcs, name, bases, dict):\n dict[\'foo\'] = \'metacls was here\'\n return type.__new__(mcs, name, bases, dict)\n\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\nIf the metaclass has a ``__prepare__()`` attribute (usually\nimplemented as a class or static method), it is called before the\nclass body is evaluated with the name of the class and a tuple of its\nbases for arguments. It should return an object that supports the\nmapping interface that will be used to store the namespace of the\nclass. The default is a plain dictionary. This could be used, for\nexample, to keep track of the order that class attributes are declared\nin by returning an ordered dictionary.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If the ``metaclass`` keyword argument is based with the bases, it is\n used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n used.\n\n* Otherwise, the default metaclass (``type``) is used.\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n Called when the instance is "called" as a function; if this method\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n ``x.__call__(arg1, arg2, ...)``.\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well. The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items. It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\nand ``update()`` behaving similar to those for Python\'s standard\ndictionary objects. The ``collections`` module provides a\n``MutableMapping`` abstract base class to help create those methods\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\nlike Python standard list objects. Finally, sequence types should\nimplement addition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\ndescribed below; they should not define other numerical operators. It\nis recommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should search the mapping\'s keys; for\nsequences, it should search through the values. It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``keys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n Called to implement the built-in function ``len()``. Should return\n the length of the object, an integer ``>=`` 0. Also, an object\n that doesn\'t define a ``__bool__()`` method and whose ``__len__()``\n method returns zero is considered to be false in a Boolean context.\n\nNote: Slicing is done exclusively with the following three methods. A\n call like\n\n a[1:2] = b\n\n is translated to\n\n a[slice(1, 2, None)] = b\n\n and so forth. Missing slice items are always filled in with\n ``None``.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of ``self[key]``. For sequence\n types, the accepted keys should be integers and slice objects.\n Note that the special interpretation of negative indexes (if the\n class wishes to emulate a sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an inappropriate type,\n ``TypeError`` may be raised; if of a value outside the set of\n indexes for the sequence (after any special interpretation of\n negative values), ``IndexError`` should be raised. For mapping\n types, if *key* is missing (not in the container), ``KeyError``\n should be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\n illegal indexes to allow proper detection of the end of the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to implement assignment to ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support changes to the values for keys, or if new keys\n can be added, or for sequences if elements can be replaced. The\n same exceptions should be raised for improper *key* values as for\n the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to implement deletion of ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support removal of keys, or for sequences if elements\n can be removed from the sequence. The same exceptions should be\n raised for improper *key* values as for the ``__getitem__()``\n method.\n\nobject.__iter__(self)\n\n This method is called when an iterator is required for a container.\n This method should return a new iterator object that can iterate\n over all the objects in the container. For mappings, it should\n iterate over the keys of the container, and should also be made\n available as the method ``keys()``.\n\n Iterator objects also need to implement this method; they are\n required to return themselves. For more information on iterator\n objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n Called (if present) by the ``reversed()`` builtin to implement\n reverse iteration. It should return a new iterator object that\n iterates over all the objects in the container in reverse order.\n\n If the ``__reversed__()`` method is not provided, the\n ``reversed()`` builtin will fall back to using the sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects should\n normally only provide ``__reversed__()`` if they do not support the\n sequence protocol and an efficient implementation of reverse\n iteration is possible.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence. However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n Called to implement membership test operators. Should return true\n if *item* is in *self*, false otherwise. For mapping objects, this\n should consider the keys of the mapping rather than the values or\n the key-item pairs.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n ``|``). For instance, to evaluate the expression ``x + y``, where\n *x* is an instance of a class that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n should not be related to ``__truediv__()``. Note that\n ``__pow__()`` should be defined to accept an optional third\n argument if the ternary version of the built-in ``pow()`` function\n is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n ``|``) with reflected (swapped) operands. These functions are only\n called if the left operand does not support the corresponding\n operation and the operands are of different types. [3] For\n instance, to evaluate the expression ``x - y``, where *y* is an\n instance of a class that has an ``__rsub__()`` method,\n ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n *NotImplemented*.\n\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\n (the coercion rules would become too complicated).\n\n Note: If the right operand\'s type is a subclass of the left operand\'s\n type and that subclass provides the reflected method for the\n operation, this method will be called before the left operand\'s\n non-reflected method. This behavior allows subclasses to\n override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n These methods are called to implement the augmented arithmetic\n operations (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``). These methods\n should attempt to do the operation in-place (modifying *self*) and\n return the result (which could be, but does not have to be,\n *self*). If a specific method is not defined, the augmented\n operation falls back to the normal methods. For instance, to\n evaluate the expression ``x += y``, where *x* is an instance of a\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations (``-``, ``+``,\n ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``float()`` and ``round()``. Should return a value of\n the appropriate type.\n\nobject.__index__(self)\n\n Called to implement ``operator.index()``. Also called whenever\n Python needs an integer object (such as in slicing, or in the\n built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n an integer.\n\n\nWith Statement Context Managers\n===============================\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code. Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The ``with``\n statement will bind this method\'s return value to the target(s)\n specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be ``None``.\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that ``__exit__()`` methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n\n\nSpecial method lookup\n=====================\n\nFor custom classes, implicit invocations of special methods are only\nguaranteed to work correctly if defined on an object\'s type, not in\nthe object\'s instance dictionary. That behaviour is the reason why\nthe following code raises an exception:\n\n >>> class C(object):\n ... pass\n ...\n >>> c = C()\n >>> c.__len__ = lambda: 5\n >>> len(c)\n Traceback (most recent call last):\n File "", line 1, in \n TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as ``__hash__()`` and ``__repr__()`` that are implemented\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n >>> 1 .__hash__() == hash(1)\n True\n >>> int.__hash__() == hash(int)\n Traceback (most recent call last):\n File "", line 1, in \n TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n >>> type(1).__hash__(1) == hash(1)\n True\n >>> type(int).__hash__(int) == hash(int)\n True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup may also bypass the\n``__getattribute__()`` method even of the object\'s metaclass:\n\n >>> class Meta(type):\n ... def __getattribute__(*args):\n ... print("Metaclass getattribute invoked")\n ... return type.__getattribute__(*args)\n ...\n >>> class C(object, metaclass=Meta):\n ... def __len__(self):\n ... return 10\n ... def __getattribute__(*args):\n ... print("Class getattribute invoked")\n ... return object.__getattribute__(*args)\n ...\n >>> c = C()\n >>> c.__len__() # Explicit lookup via instance\n Class getattribute invoked\n 10\n >>> type(c).__len__(c) # Explicit lookup via type\n Metaclass getattribute invoked\n 10\n >>> len(c) # Implicit lookup\n 10\n\nBypassing the ``__getattribute__()`` machinery in this fashion\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n certain controlled conditions. It generally isn\'t a good idea\n though, since it can lead to some very strange behaviour if it is\n handled incorrectly.\n\n[2] A descriptor can define any combination of ``__get__()``,\n ``__set__()`` and ``__delete__()``. If it does not define\n ``__get__()``, then accessing the attribute even on an instance\n will return the descriptor object itself. If the descriptor\n defines ``__set__()`` and/or ``__delete__()``, it is a data\n descriptor; if it defines neither, it is a non-data descriptor.\n\n[3] For operands of the same type, it is assumed that if the non-\n reflected method (such as ``__add__()``) fails the operation is\n not supported, which is why the reflected method is not called.\n',
'string-methods': '\nString Methods\n**************\n\nString objects support the methods listed below. Note that none of\nthese methods take keyword arguments.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, bytes, bytearray, list,\ntuple, range* section. To output formatted strings, see the *String\nFormatting* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with only its first character\n capitalized.\n\nstr.center(width[, fillchar])\n\n Return centered in a string of length *width*. Padding is done\n using the specified *fillchar* (default is a space).\n\nstr.count(sub[, start[, end]])\n\n Return the number of occurrences of substring *sub* in the range\n [*start*, *end*]. Optional arguments *start* and *end* are\n interpreted as in slice notation.\n\nstr.encode([encoding[, errors]])\n\n Return an encoded version of the string. Default encoding is the\n current default string encoding. *errors* may be given to set a\n different error handling scheme. The default for *errors* is\n ``\'strict\'``, meaning that encoding errors raise a\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\nstr.endswith(suffix[, start[, end]])\n\n Return ``True`` if the string ends with the specified *suffix*,\n otherwise return ``False``. *suffix* can also be a tuple of\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n position.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string where all tab characters are replaced\n by one or more spaces, depending on the current column and the\n given tab size. The column number is reset to zero after each\n newline occurring in the string. If *tabsize* is not given, a tab\n size of ``8`` characters is assumed. This doesn\'t understand other\n non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the range [*start*, *end*].\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\nstr.format(format_string, *args, **kwargs)\n\n Perform a string formatting operation. The *format_string*\n argument can contain literal text or replacement fields delimited\n by braces ``{}``. Each replacement field contains either the\n numeric index of a positional argument, or the name of a keyword\n argument. Returns a copy of *format_string* where each replacement\n field is replaced with the string value of the corresponding\n argument.\n\n >>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description of the various\n formatting options that can be specified in format strings.\n\nstr.index(sub[, start[, end]])\n\n Like ``find()``, but raise ``ValueError`` when the substring is not\n found.\n\nstr.isalnum()\n\n Return true if all characters in the string are alphanumeric and\n there is at least one character, false otherwise.\n\nstr.isalpha()\n\n Return true if all characters in the string are alphabetic and\n there is at least one character, false otherwise.\n\nstr.isdecimal()\n\n Return true if all characters in the string are decimal characters\n and there is at least one character, false otherwise. Decimal\n characters include digit characters, and all characters that that\n can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-\n INDIC DIGIT ZERO.\n\nstr.isdigit()\n\n Return true if all characters in the string are digits and there is\n at least one character, false otherwise.\n\nstr.isidentifier()\n\n Return true if the string is a valid identifier according to the\n language definition, section *Identifiers and keywords*.\n\nstr.islower()\n\n Return true if all cased characters in the string are lowercase and\n there is at least one cased character, false otherwise.\n\nstr.isnumeric()\n\n Return true if all characters in the string are numeric characters,\n and there is at least one character, false otherwise. Numeric\n characters include digit characters, and all characters that have\n the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n ONE FIFTH.\n\nstr.isprintable()\n\n Return true if all characters in the string are printable or the\n string is empty, false otherwise. Nonprintable characters are\n those characters defined in the Unicode character database as\n "Other" or "Separator", excepting the ASCII space (0x20) which is\n considered printable. (Note that printable characters in this\n context are those which should not be escaped when ``repr()`` is\n invoked on a string. It has no bearing on the handling of strings\n written to ``sys.stdout`` or ``sys.stderr``.)\n\nstr.isspace()\n\n Return true if there are only whitespace characters in the string\n and there is at least one character, false otherwise.\n\nstr.istitle()\n\n Return true if the string is a titlecased string and there is at\n least one character, for example uppercase characters may only\n follow uncased characters and lowercase characters only cased ones.\n Return false otherwise.\n\nstr.isupper()\n\n Return true if all cased characters in the string are uppercase and\n there is at least one cased character, false otherwise.\n\nstr.join(seq)\n\n Return a string which is the concatenation of the strings in the\n sequence *seq*. A ``TypeError`` will be raised if there are any\n non-string values in *seq*, including ``bytes`` objects. The\n separator between elements is the string providing this method.\n\nstr.ljust(width[, fillchar])\n\n Return the string left justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\nstr.lower()\n\n Return a copy of the string converted to lowercase.\n\nstr.lstrip([chars])\n\n Return a copy of the string with leading characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a prefix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.lstrip()\n \'spacious \'\n >>> \'www.example.com\'.lstrip(\'cmowz.\')\n \'example.com\'\n\nstr.maketrans(x[, y[, z]])\n\n This static method returns a translation table usable for\n ``str.translate()``.\n\n If there is only one argument, it must be a dictionary mapping\n Unicode ordinals (integers) or characters (strings of length 1) to\n Unicode ordinals, strings (of arbitrary lengths) or None.\n Character keys will then be converted to ordinals.\n\n If there are two arguments, they must be strings of equal length,\n and in the resulting dictionary, each character in x will be mapped\n to the character at the same position in y. If there is a third\n argument, it must be a string, whose characters will be mapped to\n None in the result.\n\nstr.partition(sep)\n\n Split the string at the first occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing the string itself, followed by\n two empty strings.\n\nstr.replace(old, new[, count])\n\n Return a copy of the string with all occurrences of substring *old*\n replaced by *new*. If the optional argument *count* is given, only\n the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n Return the highest index in the string where substring *sub* is\n found, such that *sub* is contained within s[start,end]. Optional\n arguments *start* and *end* are interpreted as in slice notation.\n Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\nstr.rpartition(sep)\n\n Split the string at the last occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing two empty strings, followed by\n the string itself.\n\nstr.rsplit([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n are done, the *rightmost* ones. If *sep* is not specified or\n ``None``, any whitespace string is a separator. Except for\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is described in detail below.\n\nstr.rstrip([chars])\n\n Return a copy of the string with trailing characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a suffix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.rstrip()\n \' spacious\'\n >>> \'mississippi\'.rstrip(\'ipz\')\n \'mississ\'\n\nstr.split([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit*\n splits are done (thus, the list will have at most ``maxsplit+1``\n elements). If *maxsplit* is not specified, then there is no limit\n on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\nstr.strip([chars])\n\n Return a copy of the string with the leading and trailing\n characters removed. The *chars* argument is a string specifying the\n set of characters to be removed. If omitted or ``None``, the\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\nstr.swapcase()\n\n Return a copy of the string with uppercase characters converted to\n lowercase and vice versa.\n\nstr.title()\n\n Return a titlecased version of the string: words start with\n uppercase characters, all remaining cased characters are lowercase.\n\nstr.translate(map)\n\n Return a copy of the *s* where all characters have been mapped\n through the *map* which must be a dictionary of Unicode\n ordinals(integers) to Unicode ordinals, strings or ``None``.\n Unmapped characters are left untouched. Characters mapped to\n ``None`` are deleted.\n\n A *map* for ``translate()`` is usually best created by\n ``str.maketrans()``.\n\n You can use the ``maketrans()`` helper function in the ``string``\n module to create a translation table. For string objects, set the\n *table* argument to ``None`` for translations that only delete\n characters:\n\n Note: An even more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see\n ``encodings.cp1251`` for an example).\n\nstr.upper()\n\n Return a copy of the string converted to uppercase.\n\nstr.zfill(width)\n\n Return the numeric string left filled with zeros in a string of\n length *width*. A sign prefix is handled correctly. The original\n string is returned if *width* is less than ``len(s)``.\n',
'strings': '\nString and Bytes literals\n*************************\n\nString literals are described by the following lexical definitions:\n\n stringliteral ::= [stringprefix](shortstring | longstring)\n stringprefix ::= "r" | "R"\n shortstring ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n longstring ::= "\'\'\'" longstringitem* "\'\'\'" | \'"""\' longstringitem* \'"""\'\n shortstringitem ::= shortstringchar | stringescapeseq\n longstringitem ::= longstringchar | stringescapeseq\n shortstringchar ::= \n longstringchar ::= \n stringescapeseq ::= "\\" \n\n bytesliteral ::= bytesprefix(shortbytes | longbytes)\n bytesprefix ::= "b" | "B"\n shortbytes ::= "\'" shortbytesitem* "\'" | \'"\' shortbytesitem* \'"\'\n longbytes ::= "\'\'\'" longbytesitem* "\'\'\'" | \'"""\' longbytesitem* \'"""\'\n shortbytesitem ::= shortbyteschar | bytesescapeseq\n longbytesitem ::= longbyteschar | bytesescapeseq\n shortbyteschar ::= \n longbyteschar ::= \n bytesescapeseq ::= "\\" \n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the **stringprefix** or\n**bytesprefix** and the rest of the literal. The source character set\nis defined by the encoding declaration; it is UTF-8 if no encoding\ndeclaration is given in the source file; see section *Encoding\ndeclarations*.\n\nIn plain English: Both types of literals can be enclosed in matching\nsingle quotes (``\'``) or double quotes (``"``). They can also be\nenclosed in matching groups of three single or double quotes (these\nare generally referred to as *triple-quoted strings*). The backslash\n(``\\``) character is used to escape characters that otherwise have a\nspecial meaning, such as newline, backslash itself, or the quote\ncharacter.\n\nString literals may optionally be prefixed with a letter ``\'r\'`` or\n``\'R\'``; such strings are called *raw strings* and treat backslashes\nas literal characters. As a result, ``\'\\U\'`` and ``\'\\u\'`` escapes in\nraw strings are not treated specially.\n\nBytes literals are always prefixed with ``\'b\'`` or ``\'B\'``; they\nproduce an instance of the ``bytes`` type instead of the ``str`` type.\nThey may only contain ASCII characters; bytes with a numeric value of\n128 or greater must be expressed with escapes.\n\nIn triple-quoted strings, unescaped newlines and quotes are allowed\n(and are retained), except that three unescaped quotes in a row\nterminate the string. (A "quote" is the character used to open the\nstring, i.e. either ``\'`` or ``"``.)\n\nUnless an ``\'r\'`` or ``\'R\'`` prefix is present, escape sequences in\nstrings are interpreted according to rules similar to those used by\nStandard C. The recognized escape sequences are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence | Meaning | Notes |\n+===================+===================================+=========+\n| ``\\newline`` | Backslash and newline ignored | |\n+-------------------+-----------------------------------+---------+\n| ``\\\\`` | Backslash (``\\``) | |\n+-------------------+-----------------------------------+---------+\n| ``\\\'`` | Single quote (``\'``) | |\n+-------------------+-----------------------------------+---------+\n| ``\\"`` | Double quote (``"``) | |\n+-------------------+-----------------------------------+---------+\n| ``\\a`` | ASCII Bell (BEL) | |\n+-------------------+-----------------------------------+---------+\n| ``\\b`` | ASCII Backspace (BS) | |\n+-------------------+-----------------------------------+---------+\n| ``\\f`` | ASCII Formfeed (FF) | |\n+-------------------+-----------------------------------+---------+\n| ``\\n`` | ASCII Linefeed (LF) | |\n+-------------------+-----------------------------------+---------+\n| ``\\r`` | ASCII Carriage Return (CR) | |\n+-------------------+-----------------------------------+---------+\n| ``\\t`` | ASCII Horizontal Tab (TAB) | |\n+-------------------+-----------------------------------+---------+\n| ``\\v`` | ASCII Vertical Tab (VT) | |\n+-------------------+-----------------------------------+---------+\n| ``\\ooo`` | Character with octal value *ooo* | (1,3) |\n+-------------------+-----------------------------------+---------+\n| ``\\xhh`` | Character with hex value *hh* | (2,3) |\n+-------------------+-----------------------------------+---------+\n\nEscape sequences only recognized in string literals are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence | Meaning | Notes |\n+===================+===================================+=========+\n| ``\\N{name}`` | Character named *name* in the | |\n| | Unicode database | |\n+-------------------+-----------------------------------+---------+\n| ``\\uxxxx`` | Character with 16-bit hex value | (4) |\n| | *xxxx* | |\n+-------------------+-----------------------------------+---------+\n| ``\\Uxxxxxxxx`` | Character with 32-bit hex value | (5) |\n| | *xxxxxxxx* | |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. As in Standard C, up to three octal digits are accepted.\n\n2. Unlike in Standard C, at most two hex digits are accepted.\n\n3. In a bytes literal, hexadecimal and octal escapes denote the byte\n with the given value. In a string literal, these escapes denote a\n Unicode character with the given value.\n\n4. Individual code units which form parts of a surrogate pair can be\n encoded using this escape sequence. Unlike in Standard C, exactly\n two hex digits are required.\n\n5. Any Unicode character can be encoded this way, but characters\n outside the Basic Multilingual Plane (BMP) will be encoded using a\n surrogate pair if Python is compiled to use 16-bit code units (the\n default). Individual code units which form parts of a surrogate\n pair can be encoded using this escape sequence.\n\nUnlike Standard C, all unrecognized escape sequences are left in the\nstring unchanged, i.e., *the backslash is left in the string*. (This\nbehavior is useful when debugging: if an escape sequence is mistyped,\nthe resulting output is more easily recognized as broken.) It is also\nimportant to note that the escape sequences only recognized in string\nliterals fall into the category of unrecognized escapes for bytes\nliterals.\n\nEven in a raw string, string quotes can be escaped with a backslash,\nbut the backslash remains in the string; for example, ``r"\\""`` is a\nvalid string literal consisting of two characters: a backslash and a\ndouble quote; ``r"\\"`` is not a valid string literal (even a raw\nstring cannot end in an odd number of backslashes). Specifically, *a\nraw string cannot end in a single backslash* (since the backslash\nwould escape the following quote character). Note also that a single\nbackslash followed by a newline is interpreted as those two characters\nas part of the string, *not* as a line continuation.\n',
'subscriptions': '\nSubscriptions\n*************\n\nA subscription selects an item of a sequence (string, tuple or list)\nor mapping (dictionary) object:\n\n subscription ::= primary "[" expression_list "]"\n\nThe primary must evaluate to an object that supports subscription,\ne.g. a list or dictionary. User-defined objects can support\nsubscription by defining a ``__getitem__()`` method.\n\nFor built-in objects, there are two types of objects that support\nsubscription:\n\nIf the primary is a mapping, the expression list must evaluate to an\nobject whose value is one of the keys of the mapping, and the\nsubscription selects the value in the mapping that corresponds to that\nkey. (The expression list is a tuple except if it has exactly one\nitem.)\n\nIf the primary is a sequence, the expression (list) must evaluate to\nan integer. If this value is negative, the length of the sequence is\nadded to it (so that, e.g., ``x[-1]`` selects the last item of ``x``.)\nThe resulting value must be a nonnegative integer less than the number\nof items in the sequence, and the subscription selects the item whose\nindex is that value (counting from zero).\n\nA string\'s items are characters. A character is not a separate data\ntype but a string of exactly one character.\n',
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Thu Nov 6 04:29:32 2008
@@ -4,13 +4,10 @@
(editors: check NEWS.help for information about editing NEWS using ReST.)
-What's New in Python 3.0 beta 5
-===============================
-
-[Note: due to the number of unresolved issues we're going back to beta
- releases for a while.]
+What's New in Python 3.0 release candidate 2
+============================================
-*Release date: XX-XXX-2008*
+*Release date: 05-Nov-2008*
Core and Builtins
-----------------
Modified: python/branches/py3k/Misc/RPM/python-3.0.spec
==============================================================================
--- python/branches/py3k/Misc/RPM/python-3.0.spec (original)
+++ python/branches/py3k/Misc/RPM/python-3.0.spec Thu Nov 6 04:29:32 2008
@@ -34,7 +34,7 @@
%define name python
#--start constants--
-%define version 3.0rc1
+%define version 3.0rc2
%define libver 3.0
#--end constants--
%define release 1pydotorg
Modified: python/branches/py3k/README
==============================================================================
--- python/branches/py3k/README (original)
+++ python/branches/py3k/README Thu Nov 6 04:29:32 2008
@@ -1,4 +1,4 @@
-This is Python version 3.0 release candidate 1
+This is Python version 3.0 release candidate 2
==============================================
For notes specific to this release, see RELNOTES in this directory.
From nnorwitz at gmail.com Thu Nov 6 14:43:37 2008
From: nnorwitz at gmail.com (Neal Norwitz)
Date: Thu, 6 Nov 2008 08:43:37 -0500
Subject: [Python-3000-checkins] Python Regression Test Failures doc (1)
Message-ID: <20081106134337.GA5412@python.psfb.org>
svn update tools/sphinx
U tools/sphinx/__init__.py
U tools/sphinx/htmlwriter.py
U tools/sphinx/config.py
U tools/sphinx/latexwriter.py
U tools/sphinx/directives/desc.py
U tools/sphinx/directives/other.py
U tools/sphinx/texinputs/sphinx.sty
U tools/sphinx/textwriter.py
U tools/sphinx/builder.py
U tools/sphinx/util/texescape.py
U tools/sphinx/util/compat.py
Updated to revision 67119.
svn update tools/docutils
At revision 67119.
svn update tools/jinja
At revision 67119.
svn update tools/pygments
At revision 67119.
mkdir -p build/html build/doctrees
python2.5 tools/sphinx-build.py -b html -d build/doctrees -D latex_paper_size= . build/html
Sphinx v0.5, building html
loading pickled environment... done
building [html]: targets for 0 source files that are out of date
updating environment: [config changed] 393 added, 0 changed, 0 removed
reading sources... about bugs c-api/abstract c-api/allocation c-api/arg c-api/bool c-api/buffer c-api/bytearray c-api/bytes c-api/cell c-api/cobject c-api/complex c-api/concrete c-api/conversion c-api/datetime c-api/descriptor c-api/dict c-api/exceptions c-api/file c-api/float c-api/function c-api/gcsupport c-api/gen c-api/import c-api/index c-api/init c-api/intro c-api/iter c-api/iterator c-api/list c-api/long c-api/mapping c-api/marshal c-api/memory c-api/method c-api/module c-api/none c-api/number c-api/objbuffer c-api/object c-api/objimpl c-api/refcounting c-api/reflection c-api/sequence c-api/set c-api/slice c-api/structures c-api/sys c-api/tuple c-api/type c-api/typeobj c-api/unicode c-api/utilities c-api/veryhigh c-api/weakref contents copyright distutils/apiref distutils/builtdist distutils/commandref distutils/configfile distutils/examples distutils/extending distutils/index distutils/introduction distutils/packageindex distutils/setupscript distutils/sourcedist distutils/uploading documenting/fromlatex documenting/index documenting/intro documenting/markup documenting/rest documenting/sphinx documenting/style extending/building extending/embedding extending/extending extending/index extending/newtypes extending/windows glossary howto/advocacy howto/cporting howto/curses howto/doanddont howto/functional howto/index howto/regex howto/sockets howto/unicode howto/urllib2 howto/webservers install/index library/2to3 library/__future__ library/__main__ library/_dummy_thread library/_thread library/abc library/aifc library/allos library/archiving library/array library/ast library/asynchat library/asyncore library/atexit library/audioop library/base64 library/bdb library/binascii library/binhex library/bisect library/builtins library/bz2 library/calendar library/cgi library/cgitb library/chunk library/cmath library/cmd library/code library/codecs library/codeop library/collections library/colorsys library/compileall library/configparser library/constants library/contextlib library/copy library/copyreg library/crypt library/crypto library/csv library/ctypes library/curses library/curses.ascii library/curses.panel library/custominterp library/datatypes library/datetime library/dbm library/debug library/decimal library/development library/difflib library/dis library/distutils library/doctest library/dummy_threading library/email library/email-examples library/email.charset library/email.encoders library/email.errors library/email.generator library/email.header library/email.iterators library/email.message library/email.mime library/email.parser library/email.util library/errno library/exceptions library/fcntl library/filecmp library/fileformats library/fileinput library/filesys library/fnmatch library/formatter library/fpectl library/fractions library/frameworks library/ftplib library/functions library/functools library/gc library/getopt library/getpass library/gettext library/glob library/grp library/gzip library/hashlib library/heapq library/hmac library/html.entities library/html.parser library/http.client library/http.cookiejar library/http.cookies library/http.server library/i18n library/idle library/imaplib library/imghdr library/imp library/index library/inspect library/internet library/intro library/io library/ipc library/itertools library/json library/keyword library/language library/linecache library/locale library/logging library/macpath library/mailbox library/mailcap library/markup library/marshal library/math library/mimetypes library/misc library/mm library/mmap library/modulefinder library/modules library/msilib library/msvcrt library/multiprocessing library/netdata library/netrc library/nis library/nntplib library/numbers library/numeric library/objects library/operator library/optparse library/os library/os.path library/ossaudiodev library/othergui library/parser library/pdb library/persistence library/pickle library/pickletools library/pipes library/pkgutil library/platform library/plistlib library/poplib library/posix library/pprint library/profile library/pty library/pwd library/py_compile library/pyclbr library/pydoc library/pyexpat library/python library/queue library/quopri library/random library/re library/readline library/reprlib library/resource library/rlcompleter library/runpy library/sched library/select library/shelve library/shlex library/shutil library/signal library/site library/smtpd library/smtplib library/sndhdr library/socket library/socketserver library/someos library/spwd library/sqlite3 library/ssl library/stat library/stdtypes library/string library/stringprep library/strings library/struct library/subprocess library/sunau library/symbol library/symtable library/sys library/syslog library/tabnanny library/tarfile library/telnetlib library/tempfile library/termios library/test library/textwrap library/threading library/time library/timeit library/tk library/tkinter library/tkinter.scrolledtext library/tkinter.tix library/token library/tokenize library/trace library/traceback library/tty library/turtle library/types library/undoc library/unicodedata library/unittest library/unix library/urllib.error library/urllib.parse library/urllib.request library/urllib.robotparser library/uu library/uuid library/warnings library/wave library/weakref library/webbrowser library/windows library/winreg library/winsound library/wsgiref library/xdrlib library/xml.dom library/xml.dom.minidom library/xml.dom.pulldom library/xml.etree.elementtree library/xml.sax library/xml.sax.handler library/xml.sax.reader library/xml.sax.utils library/xmlrpc.client library/xmlrpc.server library/zipfile library/zipimport library/zlib license reference/compound_stmts reference/datamodel reference/executionmodel reference/expressions reference/grammar reference/index reference/introduction reference/lexical_analysis reference/simple_stmts reference/toplevel_components tutorial/appetite tutorial/classes tutorial/controlflow tutorial/datastructures tutorial/errors tutorial/floatingpoint tutorial/index tutorial/inputoutput tutorial/interactive tutorial/interpreter tutorial/introduction tutorial/modules tutorial/stdlib tutorial/stdlib2 tutorial/whatnow using/cmdline Exception occurred:
File "/home/neal/python/py3k/Doc/tools/docutils/nodes.py", line 90, in setup_child
child.parent = self
AttributeError: 'list' object has no attribute 'parent'
The full traceback has been saved in /tmp/sphinx-err-DFSQlx.log, if you want to report the issue to the author.
Please also report this if it was a user error, so that a better error message can be provided next time.
Send reports to sphinx-dev at googlegroups.com. Thanks!
make: *** [build] Error 1
From python-3000-checkins at python.org Thu Nov 6 18:30:03 2008
From: python-3000-checkins at python.org (martin.v.loewis)
Date: Thu, 6 Nov 2008 18:30:03 +0100 (CET)
Subject: [Python-3000-checkins] r67122 - in python/branches/py3k: Misc/NEWS
PCbuild/pyd.vsprops PCbuild/pyd_d.vsprops
Message-ID: <20081106173003.F29241E4012@bag.python.org>
Author: martin.v.loewis
Date: Thu Nov 6 18:30:03 2008
New Revision: 67122
Log:
Merged revisions 67120 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67120 | martin.v.loewis | 2008-11-06 17:43:00 +0100 (Do, 06 Nov 2008) | 2 lines
Issue #4120: Exclude manifest from extension modules in VS2008.
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Misc/NEWS
python/branches/py3k/PCbuild/pyd.vsprops
python/branches/py3k/PCbuild/pyd_d.vsprops
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Thu Nov 6 18:30:03 2008
@@ -103,6 +103,8 @@
Build
-----
+- Issue #4120: Exclude manifest from extension modules in VS2008.
+
- Issue #4091: Install pythonxy.dll in system32 again.
- Issue #4018: Disable "for me" installations on Vista.
Modified: python/branches/py3k/PCbuild/pyd.vsprops
==============================================================================
--- python/branches/py3k/PCbuild/pyd.vsprops (original)
+++ python/branches/py3k/PCbuild/pyd.vsprops Thu Nov 6 18:30:03 2008
@@ -1,4 +1,4 @@
-
+
+
+
Author: martin.v.loewis
Date: Thu Nov 6 20:46:56 2008
New Revision: 67127
Log:
Merged revisions 67125 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67125 | martin.v.loewis | 2008-11-06 20:46:03 +0100 (Do, 06 Nov 2008) | 2 lines
Stop including fake manifest file in DLLs directory.
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Tools/msi/msi.py
Modified: python/branches/py3k/Tools/msi/msi.py
==============================================================================
--- python/branches/py3k/Tools/msi/msi.py (original)
+++ python/branches/py3k/Tools/msi/msi.py Thu Nov 6 20:46:56 2008
@@ -941,10 +941,12 @@
root.add_file(manifest[0], **manifest[1])
root.add_file(crtdll[0], **crtdll[1])
# Copy the manifest
- manifest_dlls = manifest[0]+".root"
- open(manifest_dlls, "w").write(open(manifest[1]['src']).read().replace("msvcr","../msvcr"))
- DLLs.start_component("msvcr90_dlls", feature=private_crt)
- DLLs.add_file(manifest[0], src=os.path.abspath(manifest_dlls))
+ # Actually, don't do that anymore - no DLL in DLLs should have a manifest
+ # dependency on msvcr90.dll anymore, so this should not be necessary
+ #manifest_dlls = manifest[0]+".root"
+ #open(manifest_dlls, "w").write(open(manifest[1]['src']).read().replace("msvcr","../msvcr"))
+ #DLLs.start_component("msvcr90_dlls", feature=private_crt)
+ #DLLs.add_file(manifest[0], src=os.path.abspath(manifest_dlls))
# Now start the main component for the DLLs directory;
# no regular files have been added to the directory yet.
From python-3000-checkins at python.org Fri Nov 7 02:38:26 2008
From: python-3000-checkins at python.org (barry.warsaw)
Date: Fri, 7 Nov 2008 02:38:26 +0100 (CET)
Subject: [Python-3000-checkins] r67132 -
python/branches/py3k/Lib/pydoc_topics.py
Message-ID: <20081107013826.E797D1E4002@bag.python.org>
Author: barry.warsaw
Date: Fri Nov 7 02:38:26 2008
New Revision: 67132
Log:
update
Modified:
python/branches/py3k/Lib/pydoc_topics.py
Modified: python/branches/py3k/Lib/pydoc_topics.py
==============================================================================
--- python/branches/py3k/Lib/pydoc_topics.py (original)
+++ python/branches/py3k/Lib/pydoc_topics.py Fri Nov 7 02:38:26 2008
@@ -1,4 +1,4 @@
-# Autogenerated by Sphinx on Wed Nov 5 22:25:20 2008
+# Autogenerated by Sphinx on Thu Nov 6 20:34:10 2008
topics = {'assert': '\nThe ``assert`` statement\n************************\n\nAssert statements are a convenient way to insert debugging assertions\ninto a program:\n\n assert_stmt ::= "assert" expression ["," expression]\n\nThe simple form, ``assert expression``, is equivalent to\n\n if __debug__:\n if not expression: raise AssertionError\n\nThe extended form, ``assert expression1, expression2``, is equivalent\nto\n\n if __debug__:\n if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that ``__debug__`` and ``AssertionError``\nrefer to the built-in variables with those names. In the current\nimplementation, the built-in variable ``__debug__`` is ``True`` under\nnormal circumstances, ``False`` when optimization is requested\n(command line option -O). The current code generator emits no code\nfor an assert statement when optimization is requested at compile\ntime. Note that it is unnecessary to include the source code for the\nexpression that failed in the error message; it will be displayed as\npart of the stack trace.\n\nAssignments to ``__debug__`` are illegal. The value for the built-in\nvariable is determined when the interpreter starts.\n',
'assignment': '\nAssignment statements\n*********************\n\nAssignment statements are used to (re)bind names to values and to\nmodify attributes or items of mutable objects:\n\n assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)\n target_list ::= target ("," target)* [","]\n target ::= identifier\n | "(" target_list ")"\n | "[" target_list "]"\n | attributeref\n | subscription\n | slicing\n | "*" target\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn assignment statement evaluates the expression list (remember that\nthis can be a single expression or a comma-separated list, the latter\nyielding a tuple) and assigns the single resulting object to each of\nthe target lists, from left to right.\n\nAssignment is defined recursively depending on the form of the target\n(list). When a target is part of a mutable object (an attribute\nreference, subscription or slicing), the mutable object must\nultimately perform the assignment and decide about its validity, and\nmay raise an exception if the assignment is unacceptable. The rules\nobserved by various types and the exceptions raised are given with the\ndefinition of the object types (see section *The standard type\nhierarchy*).\n\nAssignment of an object to a target list, optionally enclosed in\nparentheses or square brackets, is recursively defined as follows.\n\n* If the target list is a single target: The object is assigned to\n that target.\n\n* If the target list is a comma-separated list of targets:\n\n * If the target list contains one target prefixed with an asterisk,\n called a "starred" target: The object must be a sequence with at\n least as many items as there are targets in the target list, minus\n one. The first items of the sequence are assigned, from left to\n right, to the targets before the starred target. The final items\n of the sequence are assigned to the targets after the starred\n target. A list of the remaining items in the sequence is then\n assigned to the starred target (the list can be empty).\n\n * Else: The object must be a sequence with the same number of items\n as there are targets in the target list, and the items are\n assigned, from left to right, to the corresponding targets.\n\nAssignment of an object to a single target is recursively defined as\nfollows.\n\n* If the target is an identifier (name):\n\n * If the name does not occur in a ``global`` or ``nonlocal``\n statement in the current code block: the name is bound to the\n object in the current local namespace.\n\n * Otherwise: the name is bound to the object in the global namespace\n or the outer namespace determined by ``nonlocal``, respectively.\n\n The name is rebound if it was already bound. This may cause the\n reference count for the object previously bound to the name to reach\n zero, causing the object to be deallocated and its destructor (if it\n has one) to be called.\n\n The name is rebound if it was already bound. This may cause the\n reference count for the object previously bound to the name to reach\n zero, causing the object to be deallocated and its destructor (if it\n has one) to be called.\n\n* If the target is a target list enclosed in parentheses or in square\n brackets: The object must be a sequence with the same number of\n items as there are targets in the target list, and its items are\n assigned, from left to right, to the corresponding targets.\n\n* If the target is an attribute reference: The primary expression in\n the reference is evaluated. It should yield an object with\n assignable attributes; if this is not the case, ``TypeError`` is\n raised. That object is then asked to assign the assigned object to\n the given attribute; if it cannot perform the assignment, it raises\n an exception (usually but not necessarily ``AttributeError``).\n\n* If the target is a subscription: The primary expression in the\n reference is evaluated. It should yield either a mutable sequence\n object (such as a list) or a mapping object (such as a dictionary).\n Next, the subscript expression is evaluated.\n\n If the primary is a mutable sequence object (such as a list), the\n subscript must yield an integer. If it is negative, the sequence\'s\n length is added to it. The resulting value must be a nonnegative\n integer less than the sequence\'s length, and the sequence is asked\n to assign the assigned object to its item with that index. If the\n index is out of range, ``IndexError`` is raised (assignment to a\n subscripted sequence cannot add new items to a list).\n\n If the primary is a mapping object (such as a dictionary), the\n subscript must have a type compatible with the mapping\'s key type,\n and the mapping is then asked to create a key/datum pair which maps\n the subscript to the assigned object. This can either replace an\n existing key/value pair with the same key value, or insert a new\n key/value pair (if no key with the same value existed).\n\n For user-defined objects, the ``__setitem__()`` method is called\n with appropriate arguments.\n\n* If the target is a slicing: The primary expression in the reference\n is evaluated. It should yield a mutable sequence object (such as a\n list). The assigned object should be a sequence object of the same\n type. Next, the lower and upper bound expressions are evaluated,\n insofar they are present; defaults are zero and the sequence\'s\n length. The bounds should evaluate to integers. If either bound is\n negative, the sequence\'s length is added to it. The resulting\n bounds are clipped to lie between zero and the sequence\'s length,\n inclusive. Finally, the sequence object is asked to replace the\n slice with the items of the assigned sequence. The length of the\n slice may be different from the length of the assigned sequence,\n thus changing the length of the target sequence, if the object\n allows it.\n\n(In the current implementation, the syntax for targets is taken to be\nthe same as for expressions, and invalid syntax is rejected during the\ncode generation phase, causing less detailed error messages.)\n\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are \'safe\' (for\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\ncollection of assigned-to variables are not safe! For instance, the\nfollowing program prints ``[0, 2]``:\n\n x = [0, 1]\n i = 0\n i, x[i] = 1, 2\n print(x)\n\nSee also:\n\n **PEP 3132** - Extended Iterable Unpacking\n The specification for the ``*target`` feature.\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n augmented_assignment_stmt ::= target augop (expression_list | yield_expression)\n augop ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the initial value is\nretrieved with a ``getattr()`` and the result is assigned with a\n``setattr()``. Notice that the two methods do not necessarily refer\nto the same variable. When ``getattr()`` refers to a class variable,\n``setattr()`` still writes to an instance variable. For example:\n\n class A:\n x = 3 # class variable\n a = A()\n a.x += 1 # writes a.x as 4 leaving A.x as 3\n',
'atom-identifiers': '\nIdentifiers (Names)\n*******************\n\nAn identifier occurring as an atom is a name. See section\n*Identifiers and keywords* for lexical definition and section *Naming\nand binding* for documentation of naming and binding.\n\nWhen the name is bound to an object, evaluation of the atom yields\nthat object. When a name is not bound, an attempt to evaluate it\nraises a ``NameError`` exception.\n\n**Private name mangling:** When an identifier that textually occurs in\na class definition begins with two or more underscore characters and\ndoes not end in two or more underscores, it is considered a *private\nname* of that class. Private names are transformed to a longer form\nbefore code is generated for them. The transformation inserts the\nclass name in front of the name, with leading underscores removed, and\na single underscore inserted in front of the class name. For example,\nthe identifier ``__spam`` occurring in a class named ``Ham`` will be\ntransformed to ``_Ham__spam``. This transformation is independent of\nthe syntactical context in which the identifier is used. If the\ntransformed name is extremely long (longer than 255 characters),\nimplementation defined truncation may happen. If the class name\nconsists only of underscores, no transformation is done.\n',
From nnorwitz at gmail.com Fri Nov 7 02:43:38 2008
From: nnorwitz at gmail.com (Neal Norwitz)
Date: Thu, 6 Nov 2008 20:43:38 -0500
Subject: [Python-3000-checkins] Python Regression Test Failures doc (1)
Message-ID: <20081107014338.GA19139@python.psfb.org>
svn update tools/sphinx
At revision 67133.
svn update tools/docutils
At revision 67133.
svn update tools/jinja
At revision 67133.
svn update tools/pygments
At revision 67133.
mkdir -p build/html build/doctrees
python2.5 tools/sphinx-build.py -b html -d build/doctrees -D latex_paper_size= . build/html
Sphinx v0.5, building html
loading pickled environment... done
building [html]: targets for 0 source files that are out of date
updating environment: [config changed] 393 added, 0 changed, 0 removed
reading sources... about bugs c-api/abstract c-api/allocation c-api/arg c-api/bool c-api/buffer c-api/bytearray c-api/bytes c-api/cell c-api/cobject c-api/complex c-api/concrete c-api/conversion c-api/datetime c-api/descriptor c-api/dict c-api/exceptions c-api/file c-api/float c-api/function c-api/gcsupport c-api/gen c-api/import c-api/index c-api/init c-api/intro c-api/iter c-api/iterator c-api/list c-api/long c-api/mapping c-api/marshal c-api/memory c-api/method c-api/module c-api/none c-api/number c-api/objbuffer c-api/object c-api/objimpl c-api/refcounting c-api/reflection c-api/sequence c-api/set c-api/slice c-api/structures c-api/sys c-api/tuple c-api/type c-api/typeobj c-api/unicode c-api/utilities c-api/veryhigh c-api/weakref contents copyright distutils/apiref distutils/builtdist distutils/commandref distutils/configfile distutils/examples distutils/extending distutils/index distutils/introduction distutils/packageindex distutils/setupscript distutils/sourcedist distutils/uploading documenting/fromlatex documenting/index documenting/intro documenting/markup documenting/rest documenting/sphinx documenting/style extending/building extending/embedding extending/extending extending/index extending/newtypes extending/windows glossary howto/advocacy howto/cporting howto/curses howto/doanddont howto/functional howto/index howto/regex howto/sockets howto/unicode howto/urllib2 howto/webservers install/index library/2to3 library/__future__ library/__main__ library/_dummy_thread library/_thread library/abc library/aifc library/allos library/archiving library/array library/ast library/asynchat library/asyncore library/atexit library/audioop library/base64 library/bdb library/binascii library/binhex library/bisect library/builtins library/bz2 library/calendar library/cgi library/cgitb library/chunk library/cmath library/cmd library/code library/codecs library/codeop library/collections library/colorsys library/compileall library/configparser library/constants library/contextlib library/copy library/copyreg library/crypt library/crypto library/csv library/ctypes library/curses library/curses.ascii library/curses.panel library/custominterp library/datatypes library/datetime library/dbm library/debug library/decimal library/development library/difflib library/dis library/distutils library/doctest library/dummy_threading library/email library/email-examples library/email.charset library/email.encoders library/email.errors library/email.generator library/email.header library/email.iterators library/email.message library/email.mime library/email.parser library/email.util library/errno library/exceptions library/fcntl library/filecmp library/fileformats library/fileinput library/filesys library/fnmatch library/formatter library/fpectl library/fractions library/frameworks library/ftplib library/functions library/functools library/gc library/getopt library/getpass library/gettext library/glob library/grp library/gzip library/hashlib library/heapq library/hmac library/html.entities library/html.parser library/http.client library/http.cookiejar library/http.cookies library/http.server library/i18n library/idle library/imaplib library/imghdr library/imp library/index library/inspect library/internet library/intro library/io library/ipc library/itertools library/json library/keyword library/language library/linecache library/locale library/logging library/macpath library/mailbox library/mailcap library/markup library/marshal library/math library/mimetypes library/misc library/mm library/mmap library/modulefinder library/modules library/msilib library/msvcrt library/multiprocessing library/netdata library/netrc library/nis library/nntplib library/numbers library/numeric library/objects library/operator library/optparse library/os library/os.path library/ossaudiodev library/othergui library/parser library/pdb library/persistence library/pickle library/pickletools library/pipes library/pkgutil library/platform library/plistlib library/poplib library/posix library/pprint library/profile library/pty library/pwd library/py_compile library/pyclbr library/pydoc library/pyexpat library/python library/queue library/quopri library/random library/re library/readline library/reprlib library/resource library/rlcompleter library/runpy library/sched library/select library/shelve library/shlex library/shutil library/signal library/site library/smtpd library/smtplib library/sndhdr library/socket library/socketserver library/someos library/spwd library/sqlite3 library/ssl library/stat library/stdtypes library/string library/stringprep library/strings library/struct library/subprocess library/sunau library/symbol library/symtable library/sys library/syslog library/tabnanny library/tarfile library/telnetlib library/tempfile library/termios library/test library/textwrap library/threading library/time library/timeit library/tk library/tkinter library/tkinter.scrolledtext library/tkinter.tix library/token library/tokenize library/trace library/traceback library/tty library/turtle library/types library/undoc library/unicodedata library/unittest library/unix library/urllib.error library/urllib.parse library/urllib.request library/urllib.robotparser library/uu library/uuid library/warnings library/wave library/weakref library/webbrowser library/windows library/winreg library/winsound library/wsgiref library/xdrlib library/xml.dom library/xml.dom.minidom library/xml.dom.pulldom library/xml.etree.elementtree library/xml.sax library/xml.sax.handler library/xml.sax.reader library/xml.sax.utils library/xmlrpc.client library/xmlrpc.server library/zipfile library/zipimport library/zlib license reference/compound_stmts reference/datamodel reference/executionmodel reference/expressions reference/grammar reference/index reference/introduction reference/lexical_analysis reference/simple_stmts reference/toplevel_components tutorial/appetite tutorial/classes tutorial/controlflow tutorial/datastructures tutorial/errors tutorial/floatingpoint tutorial/index tutorial/inputoutput tutorial/interactive tutorial/interpreter tutorial/introduction tutorial/modules tutorial/stdlib tutorial/stdlib2 tutorial/whatnow using/cmdline Exception occurred:
File "/home/neal/python/py3k/Doc/tools/docutils/nodes.py", line 90, in setup_child
child.parent = self
AttributeError: 'list' object has no attribute 'parent'
The full traceback has been saved in /tmp/sphinx-err-TxU4cI.log, if you want to report the issue to the author.
Please also report this if it was a user error, so that a better error message can be provided next time.
Send reports to sphinx-dev at googlegroups.com. Thanks!
make: *** [build] Error 1
From python-3000-checkins at python.org Fri Nov 7 04:06:24 2008
From: python-3000-checkins at python.org (barry.warsaw)
Date: Fri, 7 Nov 2008 04:06:24 +0100 (CET)
Subject: [Python-3000-checkins] r67136 -
python/branches/py3k/Doc/using/cmdline.rst
Message-ID: <20081107030624.90D0D1E4002@bag.python.org>
Author: barry.warsaw
Date: Fri Nov 7 04:06:24 2008
New Revision: 67136
Log:
A totally crappy workaround for issue 4266, but this allows me to build the
release.
Modified:
python/branches/py3k/Doc/using/cmdline.rst
Modified: python/branches/py3k/Doc/using/cmdline.rst
==============================================================================
--- python/branches/py3k/Doc/using/cmdline.rst (original)
+++ python/branches/py3k/Doc/using/cmdline.rst Fri Nov 7 04:06:24 2008
@@ -135,9 +135,6 @@
an empty string (``""``) and the current directory will be added to the
start of :data:`sys.path`.
- .. seealso::
- :ref:`tut-invoking`
-
Generic options
~~~~~~~~~~~~~~~
From python-3000-checkins at python.org Fri Nov 7 04:46:33 2008
From: python-3000-checkins at python.org (barry.warsaw)
Date: Fri, 7 Nov 2008 04:46:33 +0100 (CET)
Subject: [Python-3000-checkins] r67139 - in python/branches/py3k:
Include/patchlevel.h Misc/NEWS
Message-ID: <20081107034633.896DC1E4002@bag.python.org>
Author: barry.warsaw
Date: Fri Nov 7 04:46:33 2008
New Revision: 67139
Log:
post release cleanup
Modified:
python/branches/py3k/Include/patchlevel.h
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Include/patchlevel.h
==============================================================================
--- python/branches/py3k/Include/patchlevel.h (original)
+++ python/branches/py3k/Include/patchlevel.h Fri Nov 7 04:46:33 2008
@@ -23,7 +23,7 @@
#define PY_RELEASE_SERIAL 2
/* Version as a string */
-#define PY_VERSION "3.0rc2"
+#define PY_VERSION "3.0rc2+"
/*--end constants--*/
/* Subversion Revision number of this file (not of the repository) */
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Fri Nov 7 04:46:33 2008
@@ -4,6 +4,18 @@
(editors: check NEWS.help for information about editing NEWS using ReST.)
+What's New in Python {XXX PUT NEXT VERSION HERE XXX}?
+================================
+
+*Release date: XX-XXX-2008*
+
+Core and Builtins
+-----------------
+
+Library
+-------
+
+
What's New in Python 3.0 release candidate 2
============================================
From python-3000-checkins at python.org Fri Nov 7 04:51:43 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Fri, 7 Nov 2008 04:51:43 +0100 (CET)
Subject: [Python-3000-checkins] r67141 - python/branches/py3k/Misc/NEWS
Message-ID: <20081107035143.518E81E4002@bag.python.org>
Author: benjamin.peterson
Date: Fri Nov 7 04:51:42 2008
New Revision: 67141
Log:
name the release
Modified:
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Fri Nov 7 04:51:42 2008
@@ -4,11 +4,12 @@
(editors: check NEWS.help for information about editing NEWS using ReST.)
-What's New in Python {XXX PUT NEXT VERSION HERE XXX}?
-================================
+What's New in Python 3.0 release candiate 3?
+============================================
*Release date: XX-XXX-2008*
+
Core and Builtins
-----------------
From python-3000-checkins at python.org Fri Nov 7 10:39:56 2008
From: python-3000-checkins at python.org (georg.brandl)
Date: Fri, 7 Nov 2008 10:39:56 +0100 (CET)
Subject: [Python-3000-checkins] r67148 - in python/branches/py3k:
Doc/library/email.parser.rst Doc/library/sqlite3.rst
Doc/library/threading.rst Doc/tutorial/controlflow.rst
Doc/using/cmdline.rst
Message-ID: <20081107093956.D00381E4002@bag.python.org>
Author: georg.brandl
Date: Fri Nov 7 10:39:56 2008
New Revision: 67148
Log:
Merged revisions 67117-67119,67123-67124,67143 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67117 | georg.brandl | 2008-11-06 11:17:58 +0100 (Thu, 06 Nov 2008) | 2 lines
#4268: Use correct module for two toplevel functions.
........
r67118 | georg.brandl | 2008-11-06 11:19:11 +0100 (Thu, 06 Nov 2008) | 2 lines
#4267: small fixes in sqlite3 docs.
........
r67119 | georg.brandl | 2008-11-06 11:20:49 +0100 (Thu, 06 Nov 2008) | 2 lines
#4245: move Thread section to the top.
........
r67123 | georg.brandl | 2008-11-06 19:49:15 +0100 (Thu, 06 Nov 2008) | 2 lines
#4247: add "pass" examples to tutorial.
........
r67124 | andrew.kuchling | 2008-11-06 20:23:02 +0100 (Thu, 06 Nov 2008) | 1 line
Fix grammar error; reword two paragraphs
........
r67143 | georg.brandl | 2008-11-07 09:27:39 +0100 (Fri, 07 Nov 2008) | 2 lines
Fix syntax.
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Doc/library/email.parser.rst
python/branches/py3k/Doc/library/sqlite3.rst
python/branches/py3k/Doc/library/threading.rst
python/branches/py3k/Doc/tutorial/controlflow.rst
python/branches/py3k/Doc/using/cmdline.rst
Modified: python/branches/py3k/Doc/library/email.parser.rst
==============================================================================
--- python/branches/py3k/Doc/library/email.parser.rst (original)
+++ python/branches/py3k/Doc/library/email.parser.rst Fri Nov 7 10:39:56 2008
@@ -145,6 +145,7 @@
a common task, two functions are provided as a convenience. They are available
in the top-level :mod:`email` package namespace.
+.. currentmodule:: email
.. function:: message_from_string(s[, _class[, strict]])
Modified: python/branches/py3k/Doc/library/sqlite3.rst
==============================================================================
--- python/branches/py3k/Doc/library/sqlite3.rst (original)
+++ python/branches/py3k/Doc/library/sqlite3.rst Fri Nov 7 10:39:56 2008
@@ -62,10 +62,10 @@
c.execute('select * from stocks where symbol=?', t)
# Larger example
- for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
+ for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
- ):
+ ]:
c.execute('insert into stocks values (?,?,?,?,?)', t)
To retrieve data after executing a SELECT statement, you can either treat the
@@ -421,10 +421,9 @@
import sqlite3, os
con = sqlite3.connect('existing_db.db')
- full_dump = os.linesep.join(con.iterdump())
- f = open('dump.sql', 'w')
- f.writelines(full_dump)
- f.close()
+ with open('dump.sql', 'w') as f:
+ for line in con.iterdump():
+ f.write('%s\n' % line)
.. _sqlite3-cursor-objects:
@@ -800,8 +799,8 @@
If you want **autocommit mode**, then set :attr:`isolation_level` to None.
Otherwise leave it at its default, which will result in a plain "BEGIN"
-statement, or set it to one of SQLite's supported isolation levels: DEFERRED,
-IMMEDIATE or EXCLUSIVE.
+statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
+"IMMEDIATE" or "EXCLUSIVE".
Modified: python/branches/py3k/Doc/library/threading.rst
==============================================================================
--- python/branches/py3k/Doc/library/threading.rst (original)
+++ python/branches/py3k/Doc/library/threading.rst Fri Nov 7 10:39:56 2008
@@ -168,6 +168,163 @@
All of the methods described below are executed atomically.
+.. _thread-objects:
+
+Thread Objects
+--------------
+
+This class represents an activity that is run in a separate thread of control.
+There are two ways to specify the activity: by passing a callable object to the
+constructor, or by overriding the :meth:`run` method in a subclass. No other
+methods (except for the constructor) should be overridden in a subclass. In
+other words, *only* override the :meth:`__init__` and :meth:`run` methods of
+this class.
+
+Once a thread object is created, its activity must be started by calling the
+thread's :meth:`start` method. This invokes the :meth:`run` method in a
+separate thread of control.
+
+Once the thread's activity is started, the thread is considered 'alive'. It
+stops being alive when its :meth:`run` method terminates -- either normally, or
+by raising an unhandled exception. The :meth:`is_alive` method tests whether the
+thread is alive.
+
+Other threads can call a thread's :meth:`join` method. This blocks the calling
+thread until the thread whose :meth:`join` method is called is terminated.
+
+A thread has a name. The name can be passed to the constructor, and read or
+changed through the :attr:`name` attribute.
+
+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.
+
+There is a "main thread" object; this corresponds to the initial thread of
+control in the Python program. It is not a daemon thread.
+
+There is the possibility that "dummy thread objects" are created. These are
+thread objects corresponding to "alien threads", which are threads of control
+started outside the threading module, such as directly from C code. Dummy
+thread objects have limited functionality; they are always considered alive and
+daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
+impossible to detect the termination of alien threads.
+
+
+.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
+
+ This constructor should always be called with keyword arguments. Arguments are:
+
+ *group* should be ``None``; reserved for future extension when a
+ :class:`ThreadGroup` class is implemented.
+
+ *target* is the callable object to be invoked by the :meth:`run` method.
+ Defaults to ``None``, meaning nothing is called.
+
+ *name* is the thread name. By default, a unique name is constructed of the form
+ "Thread-*N*" where *N* is a small decimal number.
+
+ *args* is the argument tuple for the target invocation. Defaults to ``()``.
+
+ *kwargs* is a dictionary of keyword arguments for the target invocation.
+ Defaults to ``{}``.
+
+ If the subclass overrides the constructor, it must make sure to invoke the base
+ class constructor (``Thread.__init__()``) before doing anything else to the
+ thread.
+
+
+.. method:: Thread.start()
+
+ Start the thread's activity.
+
+ It must be called at most once per thread object. It arranges for the object's
+ :meth:`run` method to be invoked in a separate thread of control.
+
+ This method will raise a :exc:`RuntimeException` if called more than once on the
+ same thread object.
+
+
+.. method:: Thread.run()
+
+ Method representing the thread's activity.
+
+ You may override this method in a subclass. The standard :meth:`run` method
+ invokes the callable object passed to the object's constructor as the *target*
+ argument, if any, with sequential and keyword arguments taken from the *args*
+ and *kwargs* arguments, respectively.
+
+
+.. method:: Thread.join([timeout])
+
+ Wait until the thread terminates. This blocks the calling thread until the
+ thread whose :meth:`join` method is called terminates -- either normally or
+ through an unhandled exception -- or until the optional timeout occurs.
+
+ When the *timeout* argument is present and not ``None``, it should be a floating
+ point number specifying a timeout for the operation in seconds (or fractions
+ thereof). As :meth:`join` always returns ``None``, you must call :meth:`is_alive`
+ after :meth:`join` to decide whether a timeout happened -- if the thread is
+ still alive, the :meth:`join` call timed out.
+
+ When the *timeout* argument is not present or ``None``, the operation will block
+ until the thread terminates.
+
+ A thread can be :meth:`join`\ ed many times.
+
+ :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
+ the current thread as that would cause a deadlock. It is also an error to
+ :meth:`join` a thread before it has been started and attempts to do so
+ raises the same exception.
+
+
+.. method:: Thread.getName()
+ Thread.setName()
+
+ Old API for :attr:`~Thread.name`.
+
+
+.. attribute:: Thread.name
+
+ A string used for identification purposes only. It has no semantics.
+ Multiple threads may be given the same name. The initial name is set by the
+ constructor.
+
+
+.. attribute:: Thread.ident
+
+ The 'thread identifier' of this thread or ``None`` if the thread has not been
+ started. This is a nonzero integer. See the :func:`thread.get_ident()`
+ function. Thread identifiers may be recycled when a thread exits and another
+ thread is created. The identifier is available even after the thread has
+ exited.
+
+
+.. method:: Thread.is_alive()
+
+ Return whether the thread is alive.
+
+ Roughly, a thread is alive from the moment the :meth:`start` method returns
+ until its :meth:`run` method terminates. The module function :func:`enumerate`
+ returns a list of all alive threads.
+
+
+.. method:: Thread.isDaemon()
+ Thread.setDaemon()
+
+ Old API for :attr:`~Thread.daemon`.
+
+
+.. attribute:: Thread.daemon
+
+ The thread's daemon flag. This must be set before :meth:`start` is called,
+ otherwise :exc:`RuntimeError` is raised.
+
+ The initial value is inherited from the creating thread.
+
+ The entire Python program exits when no alive non-daemon threads are left.
+
+
.. _lock-objects:
Lock Objects
@@ -525,163 +682,6 @@
thereof).
-.. _thread-objects:
-
-Thread Objects
---------------
-
-This class represents an activity that is run in a separate thread of control.
-There are two ways to specify the activity: by passing a callable object to the
-constructor, or by overriding the :meth:`run` method in a subclass. No other
-methods (except for the constructor) should be overridden in a subclass. In
-other words, *only* override the :meth:`__init__` and :meth:`run` methods of
-this class.
-
-Once a thread object is created, its activity must be started by calling the
-thread's :meth:`start` method. This invokes the :meth:`run` method in a
-separate thread of control.
-
-Once the thread's activity is started, the thread is considered 'alive'. It
-stops being alive when its :meth:`run` method terminates -- either normally, or
-by raising an unhandled exception. The :meth:`is_alive` method tests whether the
-thread is alive.
-
-Other threads can call a thread's :meth:`join` method. This blocks the calling
-thread until the thread whose :meth:`join` method is called is terminated.
-
-A thread has a name. The name can be passed to the constructor, and read or
-changed through the :attr:`name` attribute.
-
-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.
-
-There is a "main thread" object; this corresponds to the initial thread of
-control in the Python program. It is not a daemon thread.
-
-There is the possibility that "dummy thread objects" are created. These are
-thread objects corresponding to "alien threads", which are threads of control
-started outside the threading module, such as directly from C code. Dummy
-thread objects have limited functionality; they are always considered alive and
-daemonic, and cannot be :meth:`join`\ ed. They are never deleted, since it is
-impossible to detect the termination of alien threads.
-
-
-.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
-
- This constructor should always be called with keyword arguments. Arguments are:
-
- *group* should be ``None``; reserved for future extension when a
- :class:`ThreadGroup` class is implemented.
-
- *target* is the callable object to be invoked by the :meth:`run` method.
- Defaults to ``None``, meaning nothing is called.
-
- *name* is the thread name. By default, a unique name is constructed of the form
- "Thread-*N*" where *N* is a small decimal number.
-
- *args* is the argument tuple for the target invocation. Defaults to ``()``.
-
- *kwargs* is a dictionary of keyword arguments for the target invocation.
- Defaults to ``{}``.
-
- If the subclass overrides the constructor, it must make sure to invoke the base
- class constructor (``Thread.__init__()``) before doing anything else to the
- thread.
-
-
-.. method:: Thread.start()
-
- Start the thread's activity.
-
- It must be called at most once per thread object. It arranges for the object's
- :meth:`run` method to be invoked in a separate thread of control.
-
- This method will raise a :exc:`RuntimeException` if called more than once on the
- same thread object.
-
-
-.. method:: Thread.run()
-
- Method representing the thread's activity.
-
- You may override this method in a subclass. The standard :meth:`run` method
- invokes the callable object passed to the object's constructor as the *target*
- argument, if any, with sequential and keyword arguments taken from the *args*
- and *kwargs* arguments, respectively.
-
-
-.. method:: Thread.join([timeout])
-
- Wait until the thread terminates. This blocks the calling thread until the
- thread whose :meth:`join` method is called terminates -- either normally or
- through an unhandled exception -- or until the optional timeout occurs.
-
- When the *timeout* argument is present and not ``None``, it should be a floating
- point number specifying a timeout for the operation in seconds (or fractions
- thereof). As :meth:`join` always returns ``None``, you must call :meth:`is_alive`
- after :meth:`join` to decide whether a timeout happened -- if the thread is
- still alive, the :meth:`join` call timed out.
-
- When the *timeout* argument is not present or ``None``, the operation will block
- until the thread terminates.
-
- A thread can be :meth:`join`\ ed many times.
-
- :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
- the current thread as that would cause a deadlock. It is also an error to
- :meth:`join` a thread before it has been started and attempts to do so
- raises the same exception.
-
-
-.. method:: Thread.getName()
- Thread.setName()
-
- Old API for :attr:`~Thread.name`.
-
-
-.. attribute:: Thread.name
-
- A string used for identification purposes only. It has no semantics.
- Multiple threads may be given the same name. The initial name is set by the
- constructor.
-
-
-.. attribute:: Thread.ident
-
- The 'thread identifier' of this thread or ``None`` if the thread has not been
- started. This is a nonzero integer. See the :func:`thread.get_ident()`
- function. Thread identifiers may be recycled when a thread exits and another
- thread is created. The identifier is available even after the thread has
- exited.
-
-
-.. method:: Thread.is_alive()
-
- Return whether the thread is alive.
-
- Roughly, a thread is alive from the moment the :meth:`start` method returns
- until its :meth:`run` method terminates. The module function :func:`enumerate`
- returns a list of all alive threads.
-
-
-.. method:: Thread.isDaemon()
- Thread.setDaemon()
-
- Old API for :attr:`~Thread.daemon`.
-
-
-.. attribute:: Thread.daemon
-
- The thread's daemon flag. This must be set before :meth:`start` is called,
- otherwise :exc:`RuntimeError` is raised.
-
- The initial value is inherited from the creating thread.
-
- The entire Python program exits when no alive non-daemon threads are left.
-
-
.. _timer-objects:
Timer Objects
Modified: python/branches/py3k/Doc/tutorial/controlflow.rst
==============================================================================
--- python/branches/py3k/Doc/tutorial/controlflow.rst (original)
+++ python/branches/py3k/Doc/tutorial/controlflow.rst Fri Nov 7 10:39:56 2008
@@ -196,6 +196,41 @@
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
+This is commonly used for creating minimal classes such as exceptions, or
+for ignoring unwanted exceptions::
+
+ >>> class ParserError(Exception):
+ ... 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::
+
+ >>> 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')
+ ...
+
+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:
Modified: python/branches/py3k/Doc/using/cmdline.rst
==============================================================================
--- python/branches/py3k/Doc/using/cmdline.rst (original)
+++ python/branches/py3k/Doc/using/cmdline.rst Fri Nov 7 10:39:56 2008
@@ -135,6 +135,8 @@
an empty string (``""``) and the current directory will be added to the
start of :data:`sys.path`.
+.. seealso:: :ref:`tut-invoking`
+
Generic options
~~~~~~~~~~~~~~~
From python-3000-checkins at python.org Fri Nov 7 19:54:51 2008
From: python-3000-checkins at python.org (martin.v.loewis)
Date: Fri, 7 Nov 2008 19:54:51 +0100 (CET)
Subject: [Python-3000-checkins] r67151 - in python/branches/py3k: Misc/NEWS
Tools/msi/msi.py
Message-ID: <20081107185451.7A7271E401E@bag.python.org>
Author: martin.v.loewis
Date: Fri Nov 7 19:54:51 2008
New Revision: 67151
Log:
Merged revisions 67149 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67149 | martin.v.loewis | 2008-11-07 19:51:50 +0100 (Fr, 07 Nov 2008) | 1 line
Issue #1656675: Register a drop handler for .py* files on Windows.
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Misc/NEWS
python/branches/py3k/Tools/msi/msi.py
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Fri Nov 7 19:54:51 2008
@@ -16,6 +16,11 @@
Library
-------
+Build
+-----
+
+- Issue #1656675: Register a drop handler for .py* files on Windows.
+
What's New in Python 3.0 release candidate 2
============================================
Modified: python/branches/py3k/Tools/msi/msi.py
==============================================================================
--- python/branches/py3k/Tools/msi/msi.py (original)
+++ python/branches/py3k/Tools/msi/msi.py Fri Nov 7 19:54:51 2008
@@ -1183,6 +1183,7 @@
ewi = "Edit with IDLE"
pat2 = r"Software\Classes\%sPython.%sFile\DefaultIcon"
pat3 = r"Software\Classes\%sPython.%sFile"
+ pat4 = r"Software\Classes\%sPython.%sFile\shellex\DropHandler"
tcl_verbs = []
if have_tcl:
tcl_verbs=[
@@ -1230,6 +1231,13 @@
"Python File (no console)", "REGISTRY.def"),
("pyc.txt", -1, pat3 % (testprefix, "Compiled"), "",
"Compiled Python File", "REGISTRY.def"),
+ # Drop Handler
+ ("py.drop", -1, pat4 % (testprefix, ""), "",
+ "{60254CA5-953B-11CF-8C96-00AA00B8708C}", "REGISTRY.def"),
+ ("pyw.drop", -1, pat4 % (testprefix, "NoCon"), "",
+ "{60254CA5-953B-11CF-8C96-00AA00B8708C}", "REGISTRY.def"),
+ ("pyc.drop", -1, pat4 % (testprefix, "Compiled"), "",
+ "{60254CA5-953B-11CF-8C96-00AA00B8708C}", "REGISTRY.def"),
])
# Registry keys
From python-3000-checkins at python.org Sat Nov 8 16:15:58 2008
From: python-3000-checkins at python.org (georg.brandl)
Date: Sat, 8 Nov 2008 16:15:58 +0100 (CET)
Subject: [Python-3000-checkins] r67160 - in python/branches/py3k:
Lib/distutils/command/install.py Misc/NEWS
Message-ID: <20081108151558.4626A1E4002@bag.python.org>
Author: georg.brandl
Date: Sat Nov 8 16:15:57 2008
New Revision: 67160
Log:
#4283: fix left-over iteritems() in distutils.
Modified:
python/branches/py3k/Lib/distutils/command/install.py
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Lib/distutils/command/install.py
==============================================================================
--- python/branches/py3k/Lib/distutils/command/install.py (original)
+++ python/branches/py3k/Lib/distutils/command/install.py Sat Nov 8 16:15:57 2008
@@ -546,7 +546,7 @@
if not self.user:
return
home = convert_path(os.path.expanduser("~"))
- for name, path in self.config_vars.iteritems():
+ for name, path in self.config_vars.items():
if path.startswith(home) and not os.path.isdir(path):
self.debug_print("os.makedirs('%s', 0o700)" % path)
os.makedirs(path, 0o700)
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Sat Nov 8 16:15:57 2008
@@ -16,6 +16,8 @@
Library
-------
+- Issue #4283: fix a left-over "iteritems" call in distutils.
+
Build
-----
From python-3000-checkins at python.org Sat Nov 8 17:54:05 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Sat, 8 Nov 2008 17:54:05 +0100 (CET)
Subject: [Python-3000-checkins] r67161 -
python/branches/py3k/Doc/library/functions.rst
Message-ID: <20081108165405.A9F5A1E4002@bag.python.org>
Author: benjamin.peterson
Date: Sat Nov 8 17:54:05 2008
New Revision: 67161
Log:
compile can also produce AST
Modified:
python/branches/py3k/Doc/library/functions.rst
Modified: python/branches/py3k/Doc/library/functions.rst
==============================================================================
--- python/branches/py3k/Doc/library/functions.rst (original)
+++ python/branches/py3k/Doc/library/functions.rst Sat Nov 8 17:54:05 2008
@@ -199,11 +199,11 @@
.. function:: compile(source, filename, mode[, flags[, dont_inherit]])
- Compile the *source* into a code object. Code objects can be
+ Compile the *source* into a code object or AST object. Code objects can be
executed by a call to :func:`exec` 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.
+ :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.
The *filename* argument should give the file from
which the code was read; pass some recognizable value if it wasn't
From python-3000-checkins at python.org Sat Nov 8 18:05:00 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Sat, 8 Nov 2008 18:05:00 +0100 (CET)
Subject: [Python-3000-checkins] r67164 - in python/branches/py3k:
Doc/library/ast.rst Doc/library/functions.rst
Message-ID: <20081108170500.A112F1E4002@bag.python.org>
Author: benjamin.peterson
Date: Sat Nov 8 18:05:00 2008
New Revision: 67164
Log:
Merged revisions 67162 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67162 | benjamin.peterson | 2008-11-08 10:55:33 -0600 (Sat, 08 Nov 2008) | 1 line
a few compile() and ast doc improvements
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Doc/library/ast.rst
python/branches/py3k/Doc/library/functions.rst
Modified: python/branches/py3k/Doc/library/ast.rst
==============================================================================
--- python/branches/py3k/Doc/library/ast.rst (original)
+++ python/branches/py3k/Doc/library/ast.rst Sat Nov 8 18:05:00 2008
@@ -15,13 +15,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
------------
@@ -113,7 +112,7 @@
.. 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)
Modified: python/branches/py3k/Doc/library/functions.rst
==============================================================================
--- python/branches/py3k/Doc/library/functions.rst (original)
+++ python/branches/py3k/Doc/library/functions.rst Sat Nov 8 18:05:00 2008
@@ -199,21 +199,20 @@
.. function:: compile(source, filename, mode[, flags[, dont_inherit]])
- Compile the *source* into a code object or AST object. Code objects can be
- executed by a call to :func:`exec` 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.
-
- 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). The *mode*
- argument specifies what kind of code must be compiled; it can be
- ``'exec'`` if *source* consists of a sequence of statements,
- ``'eval'`` if it consists of a single expression, or ``'single'``
- if it consists of a single interactive statement (in the latter
- case, expression statements that evaluate to something else than
- ``None`` will be printed).
+ 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 work with AST objects.
+
+ 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).
+
+ The *mode* argument specifies what kind of code must be compiled; it can be
+ ``'exec'`` if *source* consists of a sequence of statements, ``'eval'`` if it
+ consists of a single expression, or ``'single'`` if it consists of a single
+ 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* control which future
statements (see :pep:`236`) affect the compilation of *source*. If neither
@@ -233,6 +232,14 @@
This function raises :exc:`SyntaxError` if the compiled source is invalid,
and :exc:`TypeError` if the source contains null bytes.
+ .. 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'``.
+
.. function:: complex([real[, imag]])
From python-3000-checkins at python.org Sat Nov 8 18:06:19 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Sat, 8 Nov 2008 18:06:19 +0100 (CET)
Subject: [Python-3000-checkins] r67165 - python/branches/py3k
Message-ID: <20081108170619.080CF1E4002@bag.python.org>
Author: benjamin.peterson
Date: Sat Nov 8 18:06:18 2008
New Revision: 67165
Log:
Blocked revisions 67163 via svnmerge
........
r67163 | benjamin.peterson | 2008-11-08 11:04:18 -0600 (Sat, 08 Nov 2008) | 1 line
move context clue to versionchanged tag
........
Modified:
python/branches/py3k/ (props changed)
From python-3000-checkins at python.org Sat Nov 8 18:08:32 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Sat, 8 Nov 2008 18:08:32 +0100 (CET)
Subject: [Python-3000-checkins] r67167 - python/branches/py3k
Message-ID: <20081108170832.99F7A1E4002@bag.python.org>
Author: benjamin.peterson
Date: Sat Nov 8 18:08:32 2008
New Revision: 67167
Log:
Blocked revisions 67166 via svnmerge
........
r67166 | benjamin.peterson | 2008-11-08 11:07:06 -0600 (Sat, 08 Nov 2008) | 1 line
clarify what was added
........
Modified:
python/branches/py3k/ (props changed)
From python-3000-checkins at python.org Sat Nov 8 18:24:34 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Sat, 8 Nov 2008 18:24:34 +0100 (CET)
Subject: [Python-3000-checkins] r67168 - in python/branches/py3k:
Demo/sockets/udpecho.py Demo/sockets/unixclient.py
Doc/library/socketserver.rst Misc/ACKS Misc/NEWS
Message-ID: <20081108172434.80F2F1E4002@bag.python.org>
Author: benjamin.peterson
Date: Sat Nov 8 18:24:34 2008
New Revision: 67168
Log:
fix the socketserver demo code for py3k
#4275 Thanks to Don MacMillen
Modified:
python/branches/py3k/Demo/sockets/udpecho.py
python/branches/py3k/Demo/sockets/unixclient.py
python/branches/py3k/Doc/library/socketserver.rst
python/branches/py3k/Misc/ACKS
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Demo/sockets/udpecho.py
==============================================================================
--- python/branches/py3k/Demo/sockets/udpecho.py (original)
+++ python/branches/py3k/Demo/sockets/udpecho.py Sat Nov 8 18:24:34 2008
@@ -56,7 +56,8 @@
line = sys.stdin.readline()
if not line:
break
- s.sendto(line, addr)
+ print('addr = ', addr)
+ s.sendto(bytes(line, 'ascii'), addr)
data, fromaddr = s.recvfrom(BUFSIZE)
print('client received %r from %r' % (data, fromaddr))
Modified: python/branches/py3k/Demo/sockets/unixclient.py
==============================================================================
--- python/branches/py3k/Demo/sockets/unixclient.py (original)
+++ python/branches/py3k/Demo/sockets/unixclient.py Sat Nov 8 18:24:34 2008
@@ -6,7 +6,7 @@
FILE = 'unix-socket'
s = socket(AF_UNIX, SOCK_STREAM)
s.connect(FILE)
-s.send('Hello, world')
+s.send(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))
Modified: python/branches/py3k/Doc/library/socketserver.rst
==============================================================================
--- python/branches/py3k/Doc/library/socketserver.rst (original)
+++ python/branches/py3k/Doc/library/socketserver.rst Sat Nov 8 18:24:34 2008
@@ -336,8 +336,8 @@
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
- print "%s wrote:" % self.client_address[0]
- print self.data
+ print("%s wrote:" % self.client_address[0])
+ print(self.data)
# just send back the same data, but upper-cased
self.request.send(self.data.upper())
@@ -360,8 +360,8 @@
# self.rfile is a file-like object created by the handler;
# we can now use e.g. readline() instead of raw recv() calls
self.data = self.rfile.readline().strip()
- print "%s wrote:" % self.client_address[0]
- print self.data
+ print("%s wrote:" % self.client_address[0])
+ print(self.data)
# Likewise, self.wfile is a file-like object used to write back
# to the client
self.wfile.write(self.data.upper())
@@ -385,14 +385,14 @@
# Connect to server and send data
sock.connect((HOST, PORT))
- sock.send(data + "\n")
+ sock.send(bytes(data + "\n","utf8"))
# Receive data from the server and shut down
received = sock.recv(1024)
sock.close()
- print "Sent: %s" % data
- print "Received: %s" % received
+ print("Sent: %s" % data)
+ print("Received: %s" % received)
The output of the example should look something like this:
@@ -401,18 +401,18 @@
$ python TCPServer.py
127.0.0.1 wrote:
- hello world with TCP
+ b'hello world with TCP'
127.0.0.1 wrote:
- python is nice
+ b'python is nice'
Client::
$ python TCPClient.py hello world with TCP
Sent: hello world with TCP
- Received: HELLO WORLD WITH TCP
+ Received: b'HELLO WORLD WITH TCP'
$ python TCPClient.py python is nice
Sent: python is nice
- Received: PYTHON IS NICE
+ Received: b'PYTHON IS NICE'
:class:`socketserver.UDPServer` Example
@@ -433,13 +433,13 @@
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
- print "%s wrote:" % self.client_address[0]
- print data
+ print("%s wrote:" % self.client_address[0])
+ print(data)
socket.sendto(data.upper(), self.client_address)
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::
@@ -447,7 +447,7 @@
import socket
import sys
- HOST, PORT = "localhost"
+ HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
# SOCK_DGRAM is the socket type to use for UDP sockets
@@ -455,11 +455,11 @@
# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
- sock.sendto(data + "\n", (HOST, PORT))
+ sock.sendto(bytes(data + "\n","utf8"), (HOST, PORT))
received = sock.recv(1024)
- print "Sent: %s" % data
- print "Received: %s" % received
+ print("Sent: %s" % data)
+ print("Received: %s" % received)
The output of the example should look exactly like for the TCP server example.
@@ -481,7 +481,7 @@
def handle(self):
data = self.request.recv(1024)
cur_thread = threading.current_thread()
- response = "%s: %s" % (cur_thread.get_name(), data)
+ response = bytes("%s: %s" % (cur_thread.getName(), data),'ascii')
self.request.send(response)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
@@ -492,7 +492,7 @@
sock.connect((ip, port))
sock.send(message)
response = sock.recv(1024)
- print "Received: %s" % response
+ print("Received: %s" % response)
sock.close()
if __name__ == "__main__":
@@ -506,23 +506,24 @@
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
- server_thread.set_daemon(True)
+ server_thread.setDaemon(True)
server_thread.start()
- print "Server loop running in thread:", t.get_name()
+ print("Server loop running in thread:", server_thread.getName())
- client(ip, port, "Hello World 1")
- client(ip, port, "Hello World 2")
- client(ip, port, "Hello World 3")
+ client(ip, port, b"Hello World 1")
+ client(ip, port, b"Hello World 2")
+ client(ip, port, b"Hello World 3")
server.shutdown()
+
The output of the example should look something like this::
$ python ThreadedTCPServer.py
Server loop running in thread: Thread-1
- Received: Thread-2: Hello World 1
- Received: Thread-3: Hello World 2
- Received: Thread-4: Hello World 3
+ Received: b"Thread-2: b'Hello World 1'"
+ Received: b"Thread-3: b'Hello World 2'"
+ Received: b"Thread-4: b'Hello World 3'"
The :class:`ForkingMixIn` class is used in the same way, except that the server
Modified: python/branches/py3k/Misc/ACKS
==============================================================================
--- python/branches/py3k/Misc/ACKS (original)
+++ python/branches/py3k/Misc/ACKS Sat Nov 8 18:24:34 2008
@@ -435,6 +435,7 @@
Andrew I MacIntyre
Tim MacKenzie
Nick Maclaren
+Don MacMillen
Steve Majewski
Grzegorz Makarewicz
Ken Manheimer
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Sat Nov 8 18:24:34 2008
@@ -23,6 +23,11 @@
- Issue #1656675: Register a drop handler for .py* files on Windows.
+Tools/Demos
+-----------
+
+- Demos of the socketserver module now work with Python 3.
+
What's New in Python 3.0 release candidate 2
============================================
From python-3000-checkins at python.org Sat Nov 8 20:56:21 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Sat, 8 Nov 2008 20:56:21 +0100 (CET)
Subject: [Python-3000-checkins] r67172 - in python/branches/py3k:
Python/ast.c Python/compile.c
Message-ID: <20081108195621.E08EC1E400C@bag.python.org>
Author: benjamin.peterson
Date: Sat Nov 8 20:56:21 2008
New Revision: 67172
Log:
Merged revisions 67171 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67171 | benjamin.peterson | 2008-11-08 12:38:54 -0600 (Sat, 08 Nov 2008) | 4 lines
check for assignment to __debug__ during AST generation
Also, give assignment to None a better error message
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Python/ast.c
python/branches/py3k/Python/compile.c
Modified: python/branches/py3k/Python/ast.c
==============================================================================
--- python/branches/py3k/Python/ast.c (original)
+++ python/branches/py3k/Python/ast.c Sat Nov 8 20:56:21 2008
@@ -354,6 +354,7 @@
"None",
"True",
"False",
+ "__debug__",
NULL,
};
Modified: python/branches/py3k/Python/compile.c
==============================================================================
--- python/branches/py3k/Python/compile.c (original)
+++ python/branches/py3k/Python/compile.c Sat Nov 8 20:56:21 2008
@@ -2498,12 +2498,6 @@
PyObject *mangled;
/* XXX AugStore isn't used anywhere! */
- /* First check for assignment to __debug__. Param? */
- if ((ctx == Store || ctx == AugStore || ctx == Del)
- && !PyUnicode_CompareWithASCIIString(name, "__debug__")) {
- return compiler_error(c, "can not assign to __debug__");
- }
-
mangled = _Py_Mangle(c->u->u_private, name);
if (!mangled)
return 0;
From python-3000-checkins at python.org Sun Nov 9 02:43:03 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Sun, 9 Nov 2008 02:43:03 +0100 (CET)
Subject: [Python-3000-checkins] r67174 -
python/branches/py3k/Doc/library/string.rst
Message-ID: <20081109014303.4A5071E4002@bag.python.org>
Author: benjamin.peterson
Date: Sun Nov 9 02:43:02 2008
New Revision: 67174
Log:
update string formatting grammar
Modified:
python/branches/py3k/Doc/library/string.rst
Modified: python/branches/py3k/Doc/library/string.rst
==============================================================================
--- python/branches/py3k/Doc/library/string.rst (original)
+++ python/branches/py3k/Doc/library/string.rst Sun Nov 9 02:43:02 2008
@@ -199,7 +199,7 @@
field_name: (`identifier` | `integer`) ("." `attribute_name` | "[" element_index "]")*
attribute_name: `identifier`
element_index: `integer`
- conversion: "r" | "s"
+ conversion: "r" | "s" | "a"
format_spec:
In less formal terms, the replacement field starts with a *field_name*, which
From python-3000-checkins at python.org Mon Nov 10 23:21:33 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Mon, 10 Nov 2008 23:21:33 +0100 (CET)
Subject: [Python-3000-checkins] r67182 - in python/branches/py3k:
Lib/lib2to3 Lib/lib2to3/fixes/fix_import.py
Lib/lib2to3/fixes/fix_imports.py
Lib/lib2to3/fixes/fix_metaclass.py Lib/lib2to3/refactor.py
Lib/lib2to3/tests/test_fixers.py
Message-ID: <20081110222133.D54711E4002@bag.python.org>
Author: benjamin.peterson
Date: Mon Nov 10 23:21:33 2008
New Revision: 67182
Log:
Merged revisions 67180 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
................
r67180 | benjamin.peterson | 2008-11-10 16:11:12 -0600 (Mon, 10 Nov 2008) | 29 lines
Merged revisions 66985,67170,67173,67177-67179 via svnmerge from
svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3
........
r66985 | benjamin.peterson | 2008-10-20 16:43:46 -0500 (Mon, 20 Oct 2008) | 1 line
no need to use nested try, except, finally
........
r67170 | benjamin.peterson | 2008-11-08 12:28:31 -0600 (Sat, 08 Nov 2008) | 1 line
fix #4271: fix_imports didn't recognize imports with parenthesis (ie from x import (a, b))
........
r67173 | benjamin.peterson | 2008-11-08 17:42:08 -0600 (Sat, 08 Nov 2008) | 1 line
consolidate test
........
r67177 | benjamin.peterson | 2008-11-09 21:52:52 -0600 (Sun, 09 Nov 2008) | 1 line
let the metclass fixer handle complex assignments in the class body gracefully
........
r67178 | benjamin.peterson | 2008-11-10 15:26:43 -0600 (Mon, 10 Nov 2008) | 1 line
the metaclass fixers shouldn't die when bases are not a simple name
........
r67179 | benjamin.peterson | 2008-11-10 15:29:58 -0600 (Mon, 10 Nov 2008) | 1 line
allow the fix_import pattern to catch from imports with parenthesis
........
................
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Lib/lib2to3/ (props changed)
python/branches/py3k/Lib/lib2to3/fixes/fix_import.py
python/branches/py3k/Lib/lib2to3/fixes/fix_imports.py
python/branches/py3k/Lib/lib2to3/fixes/fix_metaclass.py
python/branches/py3k/Lib/lib2to3/refactor.py
python/branches/py3k/Lib/lib2to3/tests/test_fixers.py
Modified: python/branches/py3k/Lib/lib2to3/fixes/fix_import.py
==============================================================================
--- python/branches/py3k/Lib/lib2to3/fixes/fix_import.py (original)
+++ python/branches/py3k/Lib/lib2to3/fixes/fix_import.py Mon Nov 10 23:21:33 2008
@@ -18,7 +18,7 @@
class FixImport(fixer_base.BaseFix):
PATTERN = """
- import_from< type='from' imp=any 'import' any >
+ import_from< type='from' imp=any 'import' ['('] any [')'] >
|
import_name< type='import' imp=any >
"""
Modified: python/branches/py3k/Lib/lib2to3/fixes/fix_imports.py
==============================================================================
--- python/branches/py3k/Lib/lib2to3/fixes/fix_imports.py (original)
+++ python/branches/py3k/Lib/lib2to3/fixes/fix_imports.py Mon Nov 10 23:21:33 2008
@@ -66,9 +66,9 @@
yield """import_name< 'import' ((%s)
| dotted_as_names< any* (%s) any* >) >
""" % (mod_list, mod_list)
- yield """import_from< 'from' (%s) 'import'
+ yield """import_from< 'from' (%s) 'import' ['(']
( any | import_as_name< any 'as' any > |
- import_as_names< any* >) >
+ import_as_names< any* >) [')'] >
""" % mod_name_list
yield """import_name< 'import'
dotted_as_name< (%s) 'as' any > >
Modified: python/branches/py3k/Lib/lib2to3/fixes/fix_metaclass.py
==============================================================================
--- python/branches/py3k/Lib/lib2to3/fixes/fix_metaclass.py (original)
+++ python/branches/py3k/Lib/lib2to3/fixes/fix_metaclass.py Mon Nov 10 23:21:33 2008
@@ -35,8 +35,9 @@
elif node.type == syms.simple_stmt and node.children:
expr_node = 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__':
+ left_side = expr_node.children[0]
+ if isinstance(left_side, Leaf) and \
+ left_side.value == '__metaclass__':
return True
return False
@@ -165,12 +166,10 @@
if node.children[3].type == syms.arglist:
arglist = node.children[3]
# Node(classdef, ['class', 'name', '(', 'Parent', ')', ':', suite])
- elif isinstance(node.children[3], Leaf):
+ else:
parent = node.children[3].clone()
arglist = Node(syms.arglist, [parent])
node.set_child(3, arglist)
- else:
- raise ValueError("Unexpected class inheritance arglist")
elif len(node.children) == 6:
# Node(classdef, ['class', 'name', '(', ')', ':', suite])
# 0 1 2 3 4 5
Modified: python/branches/py3k/Lib/lib2to3/refactor.py
==============================================================================
--- python/branches/py3k/Lib/lib2to3/refactor.py (original)
+++ python/branches/py3k/Lib/lib2to3/refactor.py Mon Nov 10 23:21:33 2008
@@ -363,10 +363,9 @@
self.log_error("Can't create %s: %s", filename, err)
return
try:
- try:
- f.write(new_text)
- except os.error as err:
- self.log_error("Can't write %s: %s", filename, err)
+ f.write(new_text)
+ except os.error as err:
+ self.log_error("Can't write %s: %s", filename, err)
finally:
f.close()
self.log_debug("Wrote changes to %s", filename)
Modified: python/branches/py3k/Lib/lib2to3/tests/test_fixers.py
==============================================================================
--- python/branches/py3k/Lib/lib2to3/tests/test_fixers.py (original)
+++ python/branches/py3k/Lib/lib2to3/tests/test_fixers.py Mon Nov 10 23:21:33 2008
@@ -1450,6 +1450,10 @@
a = "from %s import foo, bar" % new
self.check(b, a)
+ b = "from %s import (yes, no)" % old
+ a = "from %s import (yes, no)" % new
+ self.check(b, a)
+
def test_import_module_as(self):
for old, new in self.modules.items():
b = "import %s as foo_bar" % old
@@ -3345,6 +3349,10 @@
a = "from .foo import bar"
self.check_both(b, a)
+ b = "from foo import (bar, baz)"
+ a = "from .foo import (bar, baz)"
+ self.check_both(b, a)
+
def test_dotted_from(self):
b = "from green.eggs import ham"
a = "from .green.eggs import ham"
@@ -3624,6 +3632,12 @@
"""
self.unchanged(s)
+ s = """
+ class X:
+ a[23] = 74
+ """
+ self.unchanged(s)
+
def test_comments(self):
b = """
class X:
@@ -3732,6 +3746,26 @@
a = """class m(a, arg=23, metaclass=Meta): pass"""
self.check(b, a)
+ b = """
+ class X(expression(2 + 4)):
+ __metaclass__ = Meta
+ """
+ a = """
+ class X(expression(2 + 4), metaclass=Meta):
+ pass
+ """
+ self.check(b, a)
+
+ b = """
+ class X(expression(2 + 4), x**4):
+ __metaclass__ = Meta
+ """
+ a = """
+ class X(expression(2 + 4), x**4, metaclass=Meta):
+ pass
+ """
+ self.check(b, a)
+
class Test_getcwdu(FixerTestCase):
From python-3000-checkins at python.org Tue Nov 11 13:53:39 2008
From: python-3000-checkins at python.org (christian.heimes)
Date: Tue, 11 Nov 2008 13:53:39 +0100 (CET)
Subject: [Python-3000-checkins] r67185 -
python/branches/py3k/Modules/_testcapimodule.c
Message-ID: <20081111125339.924081E4002@bag.python.org>
Author: christian.heimes
Date: Tue Nov 11 13:53:39 2008
New Revision: 67185
Log:
Fixed a compiler warning
Modified:
python/branches/py3k/Modules/_testcapimodule.c
Modified: python/branches/py3k/Modules/_testcapimodule.c
==============================================================================
--- python/branches/py3k/Modules/_testcapimodule.c (original)
+++ python/branches/py3k/Modules/_testcapimodule.c Tue Nov 11 13:53:39 2008
@@ -517,10 +517,12 @@
PyObject *tuple, *obj;
Py_UNICODE *value;
Py_ssize_t len;
+ int x;
/* 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);
+ x = x;
tuple = PyTuple_New(1);
if (tuple == NULL)
From python-3000-checkins at python.org Tue Nov 11 21:05:07 2008
From: python-3000-checkins at python.org (amaury.forgeotdarc)
Date: Tue, 11 Nov 2008 21:05:07 +0100 (CET)
Subject: [Python-3000-checkins] r67187 - in python/branches/py3k:
Lib/test/pickletester.py Misc/NEWS Modules/_pickle.c
Message-ID: <20081111200507.694561E4036@bag.python.org>
Author: amaury.forgeotdarc
Date: Tue Nov 11 21:05:06 2008
New Revision: 67187
Log:
#4298: pickle.load() can segfault on invalid or truncated input.
Patch and test by Hirokazu Yamamoto.
Modified:
python/branches/py3k/Lib/test/pickletester.py
python/branches/py3k/Misc/NEWS
python/branches/py3k/Modules/_pickle.c
Modified: python/branches/py3k/Lib/test/pickletester.py
==============================================================================
--- python/branches/py3k/Lib/test/pickletester.py (original)
+++ python/branches/py3k/Lib/test/pickletester.py Tue Nov 11 21:05:06 2008
@@ -1032,6 +1032,11 @@
self.assertRaises(pickle.PicklingError, BadPickler().dump, 0)
self.assertRaises(pickle.UnpicklingError, BadUnpickler().load)
+ def test_bad_input(self):
+ # Test issue4298
+ s = bytes([0x58, 0, 0, 0, 0x54])
+ self.assertRaises(EOFError, pickle.loads, s)
+
class AbstractPersistentPicklerTests(unittest.TestCase):
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Tue Nov 11 21:05:06 2008
@@ -16,7 +16,9 @@
Library
-------
-- Issue #4283: fix a left-over "iteritems" call in distutils.
+- Issue #4298: Fix a segfault when pickle.loads is passed a ill-formed input.
+
+- Issue #4283: Fix a left-over "iteritems" call in distutils.
Build
-----
Modified: python/branches/py3k/Modules/_pickle.c
==============================================================================
--- python/branches/py3k/Modules/_pickle.c (original)
+++ python/branches/py3k/Modules/_pickle.c Tue Nov 11 21:05:06 2008
@@ -489,6 +489,11 @@
return -1;
}
+ if (PyBytes_GET_SIZE(data) != n) {
+ PyErr_SetNone(PyExc_EOFError);
+ return -1;
+ }
+
Py_XDECREF(self->last_string);
self->last_string = data;
From python-3000-checkins at python.org Tue Nov 11 22:43:43 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Tue, 11 Nov 2008 22:43:43 +0100 (CET)
Subject: [Python-3000-checkins] r67188 -
python/branches/py3k/Doc/library/functions.rst
Message-ID: <20081111214343.2E73D1E4002@bag.python.org>
Author: benjamin.peterson
Date: Tue Nov 11 22:43:42 2008
New Revision: 67188
Log:
exec won't take file objects anymore
Modified:
python/branches/py3k/Doc/library/functions.rst
Modified: python/branches/py3k/Doc/library/functions.rst
==============================================================================
--- python/branches/py3k/Doc/library/functions.rst (original)
+++ python/branches/py3k/Doc/library/functions.rst Tue Nov 11 22:43:42 2008
@@ -391,16 +391,15 @@
.. function:: exec(object[, globals[, locals]])
- This function supports dynamic execution of Python code. *object* must be either
- a string, an open file object, or a code object. If it is a string, the string
- is parsed as a suite of Python statements which is then executed (unless a
- syntax error occurs). If it is an open file, the file is parsed until EOF and
- executed. If it is a code object, it is simply executed. In all cases, the
+ This function supports dynamic execution of Python code. *object* must be
+ either a string or a code object. If it is a string, the string is parsed as
+ a suite of Python statements which is then executed (unless a syntax error
+ occurs). If it is a code object, it is simply executed. In all cases, the
code that's executed is expected to be valid as file input (see the section
- "File input" in the Reference Manual). Be aware that the :keyword:`return` and
- :keyword:`yield` statements may not be used outside of function definitions even
- within the context of code passed to the :func:`exec` function. The return value
- is ``None``.
+ "File input" in the Reference Manual). Be aware that the :keyword:`return`
+ and :keyword:`yield` statements may not be used outside of function
+ definitions even within the context of code passed to the :func:`exec`
+ function. The return value is ``None``.
In all cases, if the optional parts are omitted, the code is executed in the
current scope. If only *globals* is provided, it must be a dictionary, which
From python-3000-checkins at python.org Wed Nov 12 00:05:00 2008
From: python-3000-checkins at python.org (amaury.forgeotdarc)
Date: Wed, 12 Nov 2008 00:05:00 +0100 (CET)
Subject: [Python-3000-checkins] r67190 - in python/branches/py3k:
Lib/test/test_cmd_line.py Misc/NEWS Modules/main.c Python/import.c
Message-ID: <20081111230500.026CF1E4002@bag.python.org>
Author: amaury.forgeotdarc
Date: Wed Nov 12 00:04:59 2008
New Revision: 67190
Log:
#3705: Command-line arguments were not correctly decoded when the
terminal does not use UTF8.
Now the code propagates the unicode string as far as possible, and avoids
the conversion to char* which implicitely uses utf-8.
Reviewed by Benjamin.
Modified:
python/branches/py3k/Lib/test/test_cmd_line.py
python/branches/py3k/Misc/NEWS
python/branches/py3k/Modules/main.c
python/branches/py3k/Python/import.c
Modified: python/branches/py3k/Lib/test/test_cmd_line.py
==============================================================================
--- python/branches/py3k/Lib/test/test_cmd_line.py (original)
+++ python/branches/py3k/Lib/test/test_cmd_line.py Wed Nov 12 00:04:59 2008
@@ -135,6 +135,12 @@
self.exit_code('-c', 'pass'),
0)
+ # Test handling of non-ascii data
+ command = "assert(ord('\xe9') == 0xe9)"
+ self.assertEqual(
+ self.exit_code('-c', command),
+ 0)
+
def test_main():
test.support.run_unittest(CmdLineTest)
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Nov 12 00:04:59 2008
@@ -13,6 +13,9 @@
Core and Builtins
-----------------
+- Issue #3705: Command-line arguments were not correctly decoded when the
+ terminal does not use UTF8.
+
Library
-------
Modified: python/branches/py3k/Modules/main.c
==============================================================================
--- python/branches/py3k/Modules/main.c (original)
+++ python/branches/py3k/Modules/main.c Wed Nov 12 00:04:59 2008
@@ -287,7 +287,7 @@
{
int c;
int sts;
- char *command = NULL;
+ wchar_t *command = NULL;
wchar_t *filename = NULL;
wchar_t *module = NULL;
FILE *fp = stdin;
@@ -299,7 +299,6 @@
int version = 0;
int saw_unbuffered_flag = 0;
PyCompilerFlags cf;
- char *oldloc;
cf.cf_flags = 0;
@@ -310,30 +309,19 @@
while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
if (c == 'c') {
- size_t r1, r2;
- oldloc = setlocale(LC_ALL, NULL);
- setlocale(LC_ALL, "");
- r1 = wcslen(_PyOS_optarg);
- r2 = wcstombs(NULL, _PyOS_optarg, r1);
- if (r2 == (size_t) -1)
- Py_FatalError(
- "cannot convert character encoding of -c argument");
- if (r2 > r1)
- r1 = r2;
- r1 += 2;
+ size_t len;
/* -c is the last option; following arguments
that look like options are left for the
command to interpret. */
- command = (char *)malloc(r1);
+
+ len = wcslen(_PyOS_optarg) + 1 + 1;
+ command = (wchar_t *)malloc(sizeof(wchar_t) * len);
if (command == NULL)
Py_FatalError(
"not enough memory to copy -c argument");
- r2 = wcstombs(command, _PyOS_optarg, r1);
- if (r2 > r1-1)
- Py_FatalError(
- "not enough memory to copy -c argument");
- strcat(command, "\n");
- setlocale(LC_ALL, oldloc);
+ wcscpy(command, _PyOS_optarg);
+ command[len - 2] = '\n';
+ command[len - 1] = 0;
break;
}
@@ -543,8 +531,18 @@
}
if (command) {
- sts = PyRun_SimpleStringFlags(command, &cf) != 0;
+ PyObject *commandObj = PyUnicode_FromWideChar(
+ command, wcslen(command));
free(command);
+ if (commandObj != NULL) {
+ sts = PyRun_SimpleStringFlags(
+ _PyUnicode_AsString(commandObj), &cf) != 0;
+ }
+ else {
+ PyErr_Print();
+ sts = 1;
+ }
+ Py_DECREF(commandObj);
} else if (module) {
sts = RunModule(module, 1);
}
Modified: python/branches/py3k/Python/import.c
==============================================================================
--- python/branches/py3k/Python/import.c (original)
+++ python/branches/py3k/Python/import.c Wed Nov 12 00:04:59 2008
@@ -2793,6 +2793,7 @@
{
extern int fclose(FILE *);
PyObject *fob, *ret;
+ PyObject *pathobj;
struct filedescr *fdp;
char pathname[MAXPATHLEN+1];
FILE *fp = NULL;
@@ -2836,9 +2837,9 @@
fob = Py_None;
Py_INCREF(fob);
}
- ret = Py_BuildValue("Os(ssi)",
- fob, pathname, fdp->suffix, fdp->mode, fdp->type);
- Py_DECREF(fob);
+ pathobj = PyUnicode_DecodeFSDefault(pathname);
+ ret = Py_BuildValue("NN(ssi)",
+ fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
PyMem_FREE(found_encoding);
return ret;
@@ -2849,7 +2850,9 @@
{
char *name;
PyObject *path = NULL;
- if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
+ if (!PyArg_ParseTuple(args, "es|O:find_module",
+ Py_FileSystemDefaultEncoding, &name,
+ &path))
return NULL;
return call_find_module(name, path);
}
From python-3000-checkins at python.org Wed Nov 12 01:13:46 2008
From: python-3000-checkins at python.org (amaury.forgeotdarc)
Date: Wed, 12 Nov 2008 01:13:46 +0100 (CET)
Subject: [Python-3000-checkins] r67192 -
python/branches/py3k/Lib/test/test_cmd_line.py
Message-ID: <20081112001346.0B07C1E4002@bag.python.org>
Author: amaury.forgeotdarc
Date: Wed Nov 12 01:13:45 2008
New Revision: 67192
Log:
Temporarily print some information in test_cmd_line,
to understand why the test fails on some platforms.
Modified:
python/branches/py3k/Lib/test/test_cmd_line.py
Modified: python/branches/py3k/Lib/test/test_cmd_line.py
==============================================================================
--- python/branches/py3k/Lib/test/test_cmd_line.py (original)
+++ python/branches/py3k/Lib/test/test_cmd_line.py Wed Nov 12 01:13:45 2008
@@ -136,6 +136,8 @@
0)
# Test handling of non-ascii data
+ if test.support.verbose:
+ print("FileSystemEncoding:", sys.getfilesystemencoding())
command = "assert(ord('\xe9') == 0xe9)"
self.assertEqual(
self.exit_code('-c', command),
From python-3000-checkins at python.org Wed Nov 12 01:59:11 2008
From: python-3000-checkins at python.org (amaury.forgeotdarc)
Date: Wed, 12 Nov 2008 01:59:11 +0100 (CET)
Subject: [Python-3000-checkins] r67193 -
python/branches/py3k/Lib/test/test_cmd_line.py
Message-ID: <20081112005911.BD1C51E4002@bag.python.org>
Author: amaury.forgeotdarc
Date: Wed Nov 12 01:59:11 2008
New Revision: 67193
Log:
Enable this test only when subprocess supports non-ascii arguments.
(it is about parsing the python command line arguments, not about subprocess)
Modified:
python/branches/py3k/Lib/test/test_cmd_line.py
Modified: python/branches/py3k/Lib/test/test_cmd_line.py
==============================================================================
--- python/branches/py3k/Lib/test/test_cmd_line.py (original)
+++ python/branches/py3k/Lib/test/test_cmd_line.py Wed Nov 12 01:59:11 2008
@@ -136,12 +136,11 @@
0)
# Test handling of non-ascii data
- if test.support.verbose:
- print("FileSystemEncoding:", sys.getfilesystemencoding())
- command = "assert(ord('\xe9') == 0xe9)"
- self.assertEqual(
- self.exit_code('-c', command),
- 0)
+ if sys.getfilesystemencoding() != 'ascii':
+ command = "assert(ord('\xe9') == 0xe9)"
+ self.assertEqual(
+ self.exit_code('-c', command),
+ 0)
def test_main():
From python-3000-checkins at python.org Wed Nov 12 02:57:36 2008
From: python-3000-checkins at python.org (amaury.forgeotdarc)
Date: Wed, 12 Nov 2008 02:57:36 +0100 (CET)
Subject: [Python-3000-checkins] r67194 -
python/branches/py3k/Lib/test/test_zipfile64.py
Message-ID: <20081112015736.618B71E4002@bag.python.org>
Author: amaury.forgeotdarc
Date: Wed Nov 12 02:57:36 2008
New Revision: 67194
Log:
#2971: test_zipfile64 fails.
This test is always skipped, but it is not a reason not to adapt it to py3k.
I had to reduce most of the big figures to actually run the test.
Modified:
python/branches/py3k/Lib/test/test_zipfile64.py
Modified: python/branches/py3k/Lib/test/test_zipfile64.py
==============================================================================
--- python/branches/py3k/Lib/test/test_zipfile64.py (original)
+++ python/branches/py3k/Lib/test/test_zipfile64.py Wed Nov 12 02:57:36 2008
@@ -35,7 +35,7 @@
def setUp(self):
# Create test data.
line_gen = ("Test of zipfile line %d." % i for i in range(1000000))
- self.data = '\n'.join(line_gen)
+ self.data = '\n'.join(line_gen).encode('ascii')
# And write it to a file.
fp = open(TESTFN, "wb")
@@ -100,21 +100,22 @@
# and that the resulting archive can be read properly by ZipFile
zipf = zipfile.ZipFile(TESTFN, mode="w")
zipf.debug = 100
- numfiles = (1 << 16) * 3/2
- for i in xrange(numfiles):
+ numfiles = (1 << 16) * 3//2
+ for i in range(numfiles):
zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
self.assertEqual(len(zipf.namelist()), numfiles)
zipf.close()
zipf2 = zipfile.ZipFile(TESTFN, mode="r")
self.assertEqual(len(zipf2.namelist()), numfiles)
- for i in xrange(numfiles):
- self.assertEqual(zipf2.read("foo%08d" % i), "%d" % (i**3 % 57))
+ for i in range(numfiles):
+ content = zipf2.read("foo%08d" % i).decode('ascii')
+ self.assertEqual(content, "%d" % (i**3 % 57))
zipf.close()
def tearDown(self):
- test_support.unlink(TESTFN)
- test_support.unlink(TESTFN2)
+ support.unlink(TESTFN)
+ support.unlink(TESTFN2)
def test_main():
run_unittest(TestsWithSourceFile, OtherTests)
From python-3000-checkins at python.org Wed Nov 12 10:04:04 2008
From: python-3000-checkins at python.org (christian.heimes)
Date: Wed, 12 Nov 2008 10:04:04 +0100 (CET)
Subject: [Python-3000-checkins] r67201 -
python/branches/py3k/Modules/_testcapimodule.c
Message-ID: <20081112090404.8C42C1E4002@bag.python.org>
Author: christian.heimes
Date: Wed Nov 12 10:04:04 2008
New Revision: 67201
Log:
Style fix, use tab instead of space
Modified:
python/branches/py3k/Modules/_testcapimodule.c
Modified: python/branches/py3k/Modules/_testcapimodule.c
==============================================================================
--- python/branches/py3k/Modules/_testcapimodule.c (original)
+++ python/branches/py3k/Modules/_testcapimodule.c Wed Nov 12 10:04:04 2008
@@ -521,8 +521,8 @@
/* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
/* Just use the macro and check that it compiles */
- x = Py_UNICODE_ISSPACE(25);
- x = x;
+ x = Py_UNICODE_ISSPACE(25);
+ x = x;
tuple = PyTuple_New(1);
if (tuple == NULL)
From python-3000-checkins at python.org Wed Nov 12 22:26:46 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Wed, 12 Nov 2008 22:26:46 +0100 (CET)
Subject: [Python-3000-checkins] r67202 -
python/branches/py3k/Doc/library/inspect.rst
Message-ID: <20081112212646.DD7F11E4002@bag.python.org>
Author: benjamin.peterson
Date: Wed Nov 12 22:26:46 2008
New Revision: 67202
Log:
getfullargspec() has other virtues, too
Modified:
python/branches/py3k/Doc/library/inspect.rst
Modified: python/branches/py3k/Doc/library/inspect.rst
==============================================================================
--- python/branches/py3k/Doc/library/inspect.rst (original)
+++ python/branches/py3k/Doc/library/inspect.rst Wed Nov 12 22:26:46 2008
@@ -394,7 +394,7 @@
.. deprecated:: 3.0
Use :func:`getfullargspec` instead, which provides information about
- keyword-only arguments.
+ keyword-only arguments and annotations.
.. function:: getfullargspec(func)
From python-3000-checkins at python.org Wed Nov 12 22:39:02 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Wed, 12 Nov 2008 22:39:02 +0100 (CET)
Subject: [Python-3000-checkins] r67203 - in python/branches/py3k:
Lib/inspect.py Misc/ACKS Misc/NEWS
Message-ID: <20081112213902.0F1061E4002@bag.python.org>
Author: benjamin.peterson
Date: Wed Nov 12 22:39:01 2008
New Revision: 67203
Log:
change the named tuple returned by inspect.getfullargspec to have a 'kwonlydefaults' (as claimed by the docs) attribute instead of 'kwdefaults'
Fixes #4307
Reviewed by Christian
Modified:
python/branches/py3k/Lib/inspect.py
python/branches/py3k/Misc/ACKS
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Lib/inspect.py
==============================================================================
--- python/branches/py3k/Lib/inspect.py (original)
+++ python/branches/py3k/Lib/inspect.py Wed Nov 12 22:39:01 2008
@@ -791,7 +791,7 @@
return ArgSpec(args, varargs, varkw, defaults)
FullArgSpec = namedtuple('FullArgSpec',
- 'args, varargs, varkw, defaults, kwonlyargs, kwdefaults, annotations')
+ 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
def getfullargspec(func):
"""Get the names and default values of a function's arguments.
Modified: python/branches/py3k/Misc/ACKS
==============================================================================
--- python/branches/py3k/Misc/ACKS (original)
+++ python/branches/py3k/Misc/ACKS Wed Nov 12 22:39:01 2008
@@ -230,6 +230,7 @@
Peter Funk
Geoff Furnish
Ulisses Furquim
+Hagen F?rstenau
Achim Gaedke
Lele Gaifax
Santiago Gala
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Nov 12 22:39:01 2008
@@ -19,6 +19,9 @@
Library
-------
+- Issue #4307: The named tuple that ``inspect.getfullargspec()`` returns now
+ uses ``kwonlydefaults`` instead of ``kwdefaults``.
+
- Issue #4298: Fix a segfault when pickle.loads is passed a ill-formed input.
- Issue #4283: Fix a left-over "iteritems" call in distutils.
From python-3000-checkins at python.org Thu Nov 13 00:23:37 2008
From: python-3000-checkins at python.org (mark.dickinson)
Date: Thu, 13 Nov 2008 00:23:37 +0100 (CET)
Subject: [Python-3000-checkins] r67204 - in python/branches/py3k:
Lib/test/test_contains.py Lib/test/test_float.py Misc/NEWS
Objects/object.c
Message-ID: <20081112232337.599B01E4002@bag.python.org>
Author: mark.dickinson
Date: Thu Nov 13 00:23:36 2008
New Revision: 67204
Log:
Issue #4296: Fix PyObject_RichCompareBool so that "x in [x]" evaluates to
True, even when x doesn't compare equal to itself. This was a regression
from 2.6.
Reviewed by R. Hettinger and C. Heimes.
Modified:
python/branches/py3k/Lib/test/test_contains.py
python/branches/py3k/Lib/test/test_float.py
python/branches/py3k/Misc/NEWS
python/branches/py3k/Objects/object.c
Modified: python/branches/py3k/Lib/test/test_contains.py
==============================================================================
--- python/branches/py3k/Lib/test/test_contains.py (original)
+++ python/branches/py3k/Lib/test/test_contains.py Thu Nov 13 00:23:36 2008
@@ -1,3 +1,4 @@
+from collections import deque
from test.support import run_unittest
import unittest
@@ -6,7 +7,7 @@
def __init__(self, el):
self.el = el
-class set(base_set):
+class myset(base_set):
def __contains__(self, el):
return self.el == el
@@ -17,7 +18,7 @@
class TestContains(unittest.TestCase):
def test_common_tests(self):
a = base_set(1)
- b = set(1)
+ b = myset(1)
c = seq(1)
self.assert_(1 in b)
self.assert_(0 not in b)
@@ -80,6 +81,25 @@
except TypeError:
pass
+ def test_nonreflexive(self):
+ # containment and equality tests involving elements that are
+ # not necessarily equal to themselves
+
+ class MyNonReflexive(object):
+ def __eq__(self, other):
+ return False
+ def __hash__(self):
+ return 28
+
+ values = float('nan'), 1, None, 'abc', MyNonReflexive()
+ constructors = list, tuple, dict.fromkeys, set, frozenset, deque
+ for constructor in constructors:
+ container = constructor(values)
+ for elem in container:
+ self.assert_(elem in container)
+ self.assert_(container == constructor(values))
+ self.assert_(container == container)
+
def test_main():
run_unittest(TestContains)
Modified: python/branches/py3k/Lib/test/test_float.py
==============================================================================
--- python/branches/py3k/Lib/test/test_float.py (original)
+++ python/branches/py3k/Lib/test/test_float.py Thu Nov 13 00:23:36 2008
@@ -117,6 +117,33 @@
self.assertRaises(OverflowError, float('-inf').as_integer_ratio)
self.assertRaises(ValueError, float('nan').as_integer_ratio)
+ def test_float_containment(self):
+ floats = (INF, -INF, 0.0, 1.0, NAN)
+ for f in floats:
+ self.assert_(f in [f], "'%r' not in []" % f)
+ self.assert_(f in (f,), "'%r' not in ()" % f)
+ self.assert_(f in {f}, "'%r' not in set()" % f)
+ self.assert_(f in {f: None}, "'%r' not in {}" % f)
+ self.assertEqual([f].count(f), 1, "[].count('%r') != 1" % f)
+ self.assert_(f in floats, "'%r' not in container" % f)
+
+ for f in floats:
+ # nonidentical containers, same type, same contents
+ self.assert_([f] == [f], "[%r] != [%r]" % (f, f))
+ self.assert_((f,) == (f,), "(%r,) != (%r,)" % (f, f))
+ self.assert_({f} == {f}, "{%r} != {%r}" % (f, f))
+ self.assert_({f : None} == {f: None}, "{%r : None} != "
+ "{%r : None}" % (f, f))
+
+ # identical containers
+ l, t, s, d = [f], (f,), {f}, {f: None}
+ self.assert_(l == l, "[%r] not equal to itself" % f)
+ self.assert_(t == t, "(%r,) not equal to itself" % f)
+ self.assert_(s == s, "{%r} not equal to itself" % f)
+ self.assert_(d == d, "{%r : None} not equal to itself" % f)
+
+
+
class FormatFunctionsTestCase(unittest.TestCase):
def setUp(self):
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Thu Nov 13 00:23:36 2008
@@ -13,6 +13,10 @@
Core and Builtins
-----------------
+- Issue #4296: Fix PyObject_RichCompareBool so that "x in [x]" evaluates to
+ True, even when x doesn't compare equal to itself. This was a regression
+ from 2.6.
+
- Issue #3705: Command-line arguments were not correctly decoded when the
terminal does not use UTF8.
Modified: python/branches/py3k/Objects/object.c
==============================================================================
--- python/branches/py3k/Objects/object.c (original)
+++ python/branches/py3k/Objects/object.c Thu Nov 13 00:23:36 2008
@@ -687,6 +687,15 @@
PyObject *res;
int ok;
+ /* Quick result when objects are the same.
+ Guarantees that identity implies equality. */
+ if (v == w) {
+ if (op == Py_EQ)
+ return 1;
+ else if (op == Py_NE)
+ return 0;
+ }
+
res = PyObject_RichCompare(v, w, op);
if (res == NULL)
return -1;
From python-3000-checkins at python.org Sun Nov 16 12:44:56 2008
From: python-3000-checkins at python.org (raymond.hettinger)
Date: Sun, 16 Nov 2008 12:44:56 +0100 (CET)
Subject: [Python-3000-checkins] r67232 - in python/branches/py3k:
Lib/test/test_set.py Misc/NEWS Objects/setobject.c
Message-ID: <20081116114456.18F2C1E4002@bag.python.org>
Author: raymond.hettinger
Date: Sun Nov 16 12:44:54 2008
New Revision: 67232
Log:
Issue #1721812: Binary operations and copy operations on set/frozenset
subclasses need to return the base type, not the subclass itself.
Modified:
python/branches/py3k/Lib/test/test_set.py
python/branches/py3k/Misc/NEWS
python/branches/py3k/Objects/setobject.c
Modified: python/branches/py3k/Lib/test/test_set.py
==============================================================================
--- python/branches/py3k/Lib/test/test_set.py (original)
+++ python/branches/py3k/Lib/test/test_set.py Sun Nov 16 12:44:54 2008
@@ -71,7 +71,7 @@
for c in self.letters:
self.assertEqual(c in u, c in self.d or c in self.otherword)
self.assertEqual(self.s, self.thetype(self.word))
- self.assertEqual(type(u), self.thetype)
+ self.assertEqual(type(u), self.basetype)
self.assertRaises(PassThru, self.s.union, check_pass_thru())
self.assertRaises(TypeError, self.s.union, [[]])
for C in set, frozenset, dict.fromkeys, str, list, tuple:
@@ -97,7 +97,7 @@
for c in self.letters:
self.assertEqual(c in i, c in self.d and c in self.otherword)
self.assertEqual(self.s, self.thetype(self.word))
- self.assertEqual(type(i), self.thetype)
+ self.assertEqual(type(i), self.basetype)
self.assertRaises(PassThru, self.s.intersection, check_pass_thru())
for C in set, frozenset, dict.fromkeys, str, list, tuple:
self.assertEqual(self.thetype('abcba').intersection(C('cdc')), set('cc'))
@@ -142,7 +142,7 @@
for c in self.letters:
self.assertEqual(c in i, c in self.d and c not in self.otherword)
self.assertEqual(self.s, self.thetype(self.word))
- self.assertEqual(type(i), self.thetype)
+ self.assertEqual(type(i), self.basetype)
self.assertRaises(PassThru, self.s.difference, check_pass_thru())
self.assertRaises(TypeError, self.s.difference, [[]])
for C in set, frozenset, dict.fromkeys, str, list, tuple:
@@ -169,7 +169,7 @@
for c in self.letters:
self.assertEqual(c in i, (c in self.d) ^ (c in self.otherword))
self.assertEqual(self.s, self.thetype(self.word))
- self.assertEqual(type(i), self.thetype)
+ self.assertEqual(type(i), self.basetype)
self.assertRaises(PassThru, self.s.symmetric_difference, check_pass_thru())
self.assertRaises(TypeError, self.s.symmetric_difference, [[]])
for C in set, frozenset, dict.fromkeys, str, list, tuple:
@@ -325,6 +325,7 @@
class TestSet(TestJointOps):
thetype = set
+ basetype = set
def test_init(self):
s = self.thetype()
@@ -357,6 +358,7 @@
dup = self.s.copy()
self.assertEqual(self.s, dup)
self.assertNotEqual(id(self.s), id(dup))
+ self.assertEqual(type(dup), self.basetype)
def test_add(self):
self.s.add('Q')
@@ -595,6 +597,7 @@
class TestSetSubclass(TestSet):
thetype = SetSubclass
+ basetype = set
class SetSubclassWithKeywordArgs(set):
def __init__(self, iterable=[], newarg=None):
@@ -608,6 +611,7 @@
class TestFrozenSet(TestJointOps):
thetype = frozenset
+ basetype = frozenset
def test_init(self):
s = self.thetype(self.word)
@@ -673,6 +677,7 @@
class TestFrozenSetSubclass(TestFrozenSet):
thetype = FrozenSetSubclass
+ basetype = frozenset
def test_constructor_identity(self):
s = self.thetype(range(3))
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Sun Nov 16 12:44:54 2008
@@ -13,6 +13,11 @@
Core and Builtins
-----------------
+- Issue #1721812: Binary set operations and copy() returned the input type
+ instead of the appropriate base type. This was incorrect because set
+ subclasses would be created without their __init__() method being called.
+ The corrected behavior brings sets into line with lists and dicts.
+
- Issue #4296: Fix PyObject_RichCompareBool so that "x in [x]" evaluates to
True, even when x doesn't compare equal to itself. This was a regression
from 2.6.
Modified: python/branches/py3k/Objects/setobject.c
==============================================================================
--- python/branches/py3k/Objects/setobject.c (original)
+++ python/branches/py3k/Objects/setobject.c Sun Nov 16 12:44:54 2008
@@ -1017,6 +1017,18 @@
return (PyObject *)so;
}
+static PyObject *
+make_new_set_basetype(PyTypeObject *type, PyObject *iterable)
+{
+ if (type != &PySet_Type && type != &PyFrozenSet_Type) {
+ if (PyType_IsSubtype(type, &PySet_Type))
+ type = &PySet_Type;
+ else
+ type = &PyFrozenSet_Type;
+ }
+ return make_new_set(type, iterable);
+}
+
/* The empty frozenset is a singleton */
static PyObject *emptyfrozenset = NULL;
@@ -1129,7 +1141,7 @@
static PyObject *
set_copy(PySetObject *so)
{
- return make_new_set(Py_TYPE(so), (PyObject *)so);
+ return make_new_set_basetype(Py_TYPE(so), (PyObject *)so);
}
static PyObject *
@@ -1225,7 +1237,7 @@
if ((PyObject *)so == other)
return set_copy(so);
- result = (PySetObject *)make_new_set(Py_TYPE(so), NULL);
+ result = (PySetObject *)make_new_set_basetype(Py_TYPE(so), NULL);
if (result == NULL)
return NULL;
@@ -1520,7 +1532,7 @@
return NULL;
}
- result = make_new_set(Py_TYPE(so), NULL);
+ result = make_new_set_basetype(Py_TYPE(so), NULL);
if (result == NULL)
return NULL;
@@ -1641,7 +1653,7 @@
Py_INCREF(other);
otherset = (PySetObject *)other;
} else {
- otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
+ otherset = (PySetObject *)make_new_set_basetype(Py_TYPE(so), other);
if (otherset == NULL)
return NULL;
}
@@ -1672,7 +1684,7 @@
PyObject *rv;
PySetObject *otherset;
- otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
+ otherset = (PySetObject *)make_new_set_basetype(Py_TYPE(so), other);
if (otherset == NULL)
return NULL;
rv = set_symmetric_difference_update(otherset, (PyObject *)so);
From python-3000-checkins at python.org Sun Nov 16 19:33:54 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Sun, 16 Nov 2008 19:33:54 +0100 (CET)
Subject: [Python-3000-checkins] r67237 - in python/branches/py3k:
Doc/conf.py Doc/documenting/index.rst
Doc/documenting/markup.rst Doc/documenting/rest.rst
Doc/documenting/sphinx.rst Doc/documenting/style.rst
Doc/library/http.client.rst Doc/library/locale.rst
Doc/library/multiprocessing.rst Lib/http/client.py
Lib/string.py Modules/posixmodule.c configure configure.in
Message-ID: <20081116183354.53C1D1E4002@bag.python.org>
Author: benjamin.peterson
Date: Sun Nov 16 19:33:53 2008
New Revision: 67237
Log:
Merged revisions 67154,67157-67159,67175-67176,67189,67224-67227,67234 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67154 | hirokazu.yamamoto | 2008-11-07 21:46:17 -0600 (Fri, 07 Nov 2008) | 1 line
Issue #4071: ntpath.abspath returned an empty string for long unicode path.
........
r67157 | georg.brandl | 2008-11-08 05:47:44 -0600 (Sat, 08 Nov 2008) | 2 lines
Don't use "HOWTO" as the title for all howto .tex files.
........
r67158 | georg.brandl | 2008-11-08 05:48:20 -0600 (Sat, 08 Nov 2008) | 2 lines
Update "Documenting" a bit. Concentrate on Python-specifics.
........
r67159 | georg.brandl | 2008-11-08 06:52:25 -0600 (Sat, 08 Nov 2008) | 2 lines
Fix warning.
........
r67175 | benjamin.peterson | 2008-11-08 19:44:32 -0600 (Sat, 08 Nov 2008) | 1 line
update link
........
r67176 | benjamin.peterson | 2008-11-08 19:52:32 -0600 (Sat, 08 Nov 2008) | 1 line
fix comment
........
r67189 | benjamin.peterson | 2008-11-11 15:56:06 -0600 (Tue, 11 Nov 2008) | 1 line
use correct name
........
r67224 | georg.brandl | 2008-11-15 02:10:04 -0600 (Sat, 15 Nov 2008) | 2 lines
#4324: fix getlocale() argument.
........
r67225 | brett.cannon | 2008-11-15 16:33:25 -0600 (Sat, 15 Nov 2008) | 1 line
Clarify the docs for the 'strict' argument to httplib.HTTPConnection.
........
r67226 | brett.cannon | 2008-11-15 16:40:44 -0600 (Sat, 15 Nov 2008) | 4 lines
The docs for httplib.HTTPConnection.putheader() have claimed for quite a while
that their could be an arbitrary number of values passed in. Turns out the code
did not match that. The code now matches the docs.
........
r67227 | georg.brandl | 2008-11-16 02:00:17 -0600 (Sun, 16 Nov 2008) | 2 lines
#4316: fix configure.in markup problem.
........
r67234 | benjamin.peterson | 2008-11-16 11:54:55 -0600 (Sun, 16 Nov 2008) | 1 line
run autoconf
........
Removed:
python/branches/py3k/Doc/documenting/sphinx.rst
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Doc/conf.py
python/branches/py3k/Doc/documenting/index.rst
python/branches/py3k/Doc/documenting/markup.rst
python/branches/py3k/Doc/documenting/rest.rst
python/branches/py3k/Doc/documenting/style.rst
python/branches/py3k/Doc/library/http.client.rst
python/branches/py3k/Doc/library/locale.rst
python/branches/py3k/Doc/library/multiprocessing.rst
python/branches/py3k/Lib/http/client.py
python/branches/py3k/Lib/string.py
python/branches/py3k/Modules/posixmodule.c
python/branches/py3k/configure
python/branches/py3k/configure.in
Modified: python/branches/py3k/Doc/conf.py
==============================================================================
--- python/branches/py3k/Doc/conf.py (original)
+++ python/branches/py3k/Doc/conf.py Sun Nov 16 19:33:53 2008
@@ -131,7 +131,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')
Modified: python/branches/py3k/Doc/documenting/index.rst
==============================================================================
--- python/branches/py3k/Doc/documenting/index.rst (original)
+++ python/branches/py3k/Doc/documenting/index.rst Sun Nov 16 19:33:53 2008
@@ -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.
-
Modified: python/branches/py3k/Doc/documenting/markup.rst
==============================================================================
--- python/branches/py3k/Doc/documenting/markup.rst (original)
+++ python/branches/py3k/Doc/documenting/markup.rst Sun Nov 16 19:33:53 2008
@@ -8,24 +8,11 @@
Documentation for "standard" reST constructs is not included here, though
they are used in the Python documentation.
-File-wide metadata
-------------------
-
-reST has the concept of "field lists"; these are a sequence of fields marked up
-like this::
-
- :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:
+.. note::
-``nocomments``
- If set, the web application won't display a comment form for a page generated
- from this source file.
+ This is just an overview of Sphinx' extended markup capabilities; full
+ coverage can be found in `its own documentation
+ `_.
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``
@@ -799,7 +785,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|
Modified: python/branches/py3k/Doc/documenting/rest.rst
==============================================================================
--- python/branches/py3k/Doc/documenting/rest.rst (original)
+++ python/branches/py3k/Doc/documenting/rest.rst Sun Nov 16 19:33:53 2008
@@ -67,12 +67,6 @@
#. 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::
@@ -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?
Deleted: python/branches/py3k/Doc/documenting/sphinx.rst
==============================================================================
--- python/branches/py3k/Doc/documenting/sphinx.rst Sun Nov 16 19:33:53 2008
+++ (empty file)
@@ -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
Modified: python/branches/py3k/Doc/documenting/style.rst
==============================================================================
--- python/branches/py3k/Doc/documenting/style.rst (original)
+++ python/branches/py3k/Doc/documenting/style.rst Sun Nov 16 19:33:53 2008
@@ -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
Modified: python/branches/py3k/Doc/library/http.client.rst
==============================================================================
--- python/branches/py3k/Doc/library/http.client.rst (original)
+++ python/branches/py3k/Doc/library/http.client.rst Sun Nov 16 19:33:53 2008
@@ -29,7 +29,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
Modified: python/branches/py3k/Doc/library/locale.rst
==============================================================================
--- python/branches/py3k/Doc/library/locale.rst (original)
+++ python/branches/py3k/Doc/library/locale.rst Sun Nov 16 19:33:53 2008
@@ -472,7 +472,7 @@
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.setlocale(locale.LC_ALL, '') # use user's preferred locale
Modified: python/branches/py3k/Doc/library/multiprocessing.rst
==============================================================================
--- python/branches/py3k/Doc/library/multiprocessing.rst (original)
+++ python/branches/py3k/Doc/library/multiprocessing.rst Sun Nov 16 19:33:53 2008
@@ -1780,7 +1780,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
Modified: python/branches/py3k/Lib/http/client.py
==============================================================================
--- python/branches/py3k/Lib/http/client.py (original)
+++ python/branches/py3k/Lib/http/client.py Sun Nov 16 19:33:53 2008
@@ -812,7 +812,7 @@
# For HTTP/1.0, the server will assume "not chunked"
pass
- def putheader(self, header, value):
+ def putheader(self, header, *values):
"""Send a request header line to the server.
For example: h.putheader('Accept', 'text/html')
@@ -822,8 +822,11 @@
if hasattr(header, 'encode'):
header = header.encode('ascii')
- if hasattr(value, 'encode'):
- value = value.encode('ascii')
+ values = list(values)
+ for i, one_value in enumerate(values):
+ if hasattr(one_value, 'encode'):
+ values[i] = one_value.encode('ascii')
+ value = b'\r\n\t'.join(values)
header = header + b': ' + value
self._output(header)
Modified: python/branches/py3k/Lib/string.py
==============================================================================
--- python/branches/py3k/Lib/string.py (original)
+++ python/branches/py3k/Lib/string.py Sun Nov 16 19:33:53 2008
@@ -189,9 +189,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
Modified: python/branches/py3k/Modules/posixmodule.c
==============================================================================
--- python/branches/py3k/Modules/posixmodule.c (original)
+++ python/branches/py3k/Modules/posixmodule.c Sun Nov 16 19:33:53 2008
@@ -2395,13 +2395,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. */
Modified: python/branches/py3k/configure
==============================================================================
--- python/branches/py3k/configure (original)
+++ python/branches/py3k/configure Sun Nov 16 19:33:53 2008
@@ -1,5 +1,5 @@
#! /bin/sh
-# From configure.in Revision: 66297 .
+# From configure.in Revision: 67100 .
# Guess values for system-dependent variables and create Makefiles.
# Generated by GNU Autoconf 2.61 for python 3.0.
#
@@ -2083,7 +2083,7 @@
# Defining _XOPEN_SOURCE on NetBSD version prior to the introduction of
# _NETBSD_SOURCE disables certain features (eg. setgroups). Reported by
# Marc Recht
- NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6A-S)
+ NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6[A-S])
define_xopen_source=no;;
# On Solaris 2.6, sys/wait.h is inconsistent in the usage
# of union __?sigval. Reported by Stuart Bishop.
Modified: python/branches/py3k/configure.in
==============================================================================
--- python/branches/py3k/configure.in (original)
+++ python/branches/py3k/configure.in Sun Nov 16 19:33:53 2008
@@ -260,7 +260,7 @@
# Defining _XOPEN_SOURCE on NetBSD version prior to the introduction of
# _NETBSD_SOURCE disables certain features (eg. setgroups). Reported by
# Marc Recht
- NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6[A-S])
+ NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6@<:@A-S@:>@)
define_xopen_source=no;;
# On Solaris 2.6, sys/wait.h is inconsistent in the usage
# of union __?sigval. Reported by Stuart Bishop.
From python-3000-checkins at python.org Mon Nov 17 17:04:11 2008
From: python-3000-checkins at python.org (martin.v.loewis)
Date: Mon, 17 Nov 2008 17:04:11 +0100 (CET)
Subject: [Python-3000-checkins] r67241 -
python/branches/py3k/Doc/distutils/setupscript.rst
Message-ID: <20081117160411.52C421E4010@bag.python.org>
Author: martin.v.loewis
Date: Mon Nov 17 17:04:09 2008
New Revision: 67241
Log:
Issue #4312: Remove claim that distutils parameters must not be Unicode. The opposite is true.
Modified:
python/branches/py3k/Doc/distutils/setupscript.rst
Modified: python/branches/py3k/Doc/distutils/setupscript.rst
==============================================================================
--- python/branches/py3k/Doc/distutils/setupscript.rst (original)
+++ python/branches/py3k/Doc/distutils/setupscript.rst Mon Nov 17 17:04:09 2008
@@ -588,8 +588,6 @@
'list of strings'
See below.
-None of the string values may be Unicode.
-
Encoding the version information is an art in itself. Python packages generally
adhere to the version format *major.minor[.patch][sub]*. The major number is 0
for initial, experimental releases of software. It is incremented for releases
From python-3000-checkins at python.org Mon Nov 17 17:22:12 2008
From: python-3000-checkins at python.org (martin.v.loewis)
Date: Mon, 17 Nov 2008 17:22:12 +0100 (CET)
Subject: [Python-3000-checkins] r67242 - in python/branches/py3k: Misc/NEWS
Python/pystate.c
Message-ID: <20081117162212.214F51E4010@bag.python.org>
Author: martin.v.loewis
Date: Mon Nov 17 17:22:11 2008
New Revision: 67242
Log:
Issue #3327: Don't overallocate in the modules_by_index list.
Modified:
python/branches/py3k/Misc/NEWS
python/branches/py3k/Python/pystate.c
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Mon Nov 17 17:22:11 2008
@@ -13,6 +13,8 @@
Core and Builtins
-----------------
+- Issue #3327: Don't overallocate in the modules_by_index list.
+
- Issue #1721812: Binary set operations and copy() returned the input type
instead of the appropriate base type. This was incorrect because set
subclasses would be created without their __init__() method being called.
Modified: python/branches/py3k/Python/pystate.c
==============================================================================
--- python/branches/py3k/Python/pystate.c (original)
+++ python/branches/py3k/Python/pystate.c Mon Nov 17 17:22:11 2008
@@ -234,7 +234,7 @@
if (!def)
return -1;
if (!state->modules_by_index) {
- state->modules_by_index = PyList_New(20);
+ state->modules_by_index = PyList_New(0);
if (!state->modules_by_index)
return -1;
}
From python-3000-checkins at python.org Mon Nov 17 22:47:41 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Mon, 17 Nov 2008 22:47:41 +0100 (CET)
Subject: [Python-3000-checkins] r67244 -
python/branches/py3k/Doc/library/stdtypes.rst
Message-ID: <20081117214741.B6C4B1E4010@bag.python.org>
Author: benjamin.peterson
Date: Mon Nov 17 22:47:41 2008
New Revision: 67244
Log:
rephrase dict view docs
Modified:
python/branches/py3k/Doc/library/stdtypes.rst
Modified: python/branches/py3k/Doc/library/stdtypes.rst
==============================================================================
--- python/branches/py3k/Doc/library/stdtypes.rst (original)
+++ python/branches/py3k/Doc/library/stdtypes.rst Mon Nov 17 22:47:41 2008
@@ -1881,8 +1881,7 @@
The objects returned by :meth:`dict.keys`, :meth:`dict.values` and
:meth:`dict.items` are *view objects*. They provide a dynamic view on the
dictionary's entries, which means that when the dictionary changes, the view
-reflects these changes. The keys and items views have a set-like character
-since their entries
+reflects these changes.
Dictionary views can be iterated over to yield their respective data, and
support membership tests:
@@ -1910,8 +1909,11 @@
items (in the latter case, *x* should be a ``(key, value)`` tuple).
-The keys and items views also provide set-like operations ("other" here refers
-to another dictionary view or a set):
+Keys views are set-like since their entries are unique and hashable. If all
+values are hashable, so that (key, value) pairs are unique and hashable, then
+the items view is also set-like. (Values views are not treated as set-like
+since the entries are generally not unique.) Then these set operations are
+available ("other" refers either to another view or a set):
.. describe:: dictview & other
@@ -1931,11 +1933,6 @@
Return the symmetric difference (all elements either in *dictview* or
*other*, but not in both) of the dictview and the other object as a new set.
-.. warning::
-
- Since a dictionary's values are not required to be hashable, any of these
- four operations will fail if an involved dictionary contains such a value.
-
An example of dictionary view usage::
From python-3000-checkins at python.org Mon Nov 17 23:45:50 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Mon, 17 Nov 2008 23:45:50 +0100 (CET)
Subject: [Python-3000-checkins] r67248 - in python/branches/py3k:
Lib/test/test_descr.py Objects/typeobject.c
Message-ID: <20081117224550.916DD1E400C@bag.python.org>
Author: benjamin.peterson
Date: Mon Nov 17 23:45:50 2008
New Revision: 67248
Log:
Merged revisions 67246 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67246 | benjamin.peterson | 2008-11-17 16:39:09 -0600 (Mon, 17 Nov 2008) | 5 lines
when __getattr__ is a descriptor, call it correctly; fixes #4230
patch from Ziga Seilnacht
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Lib/test/test_descr.py
python/branches/py3k/Objects/typeobject.c
Modified: python/branches/py3k/Lib/test/test_descr.py
==============================================================================
--- python/branches/py3k/Lib/test/test_descr.py (original)
+++ python/branches/py3k/Lib/test/test_descr.py Mon Nov 17 23:45:50 2008
@@ -4001,6 +4001,46 @@
c[1:2] = 3
self.assertEqual(c.value, 3)
+ def test_getattr_hooks(self):
+ # issue 4230
+
+ class Descriptor(object):
+ counter = 0
+ def __get__(self, obj, objtype=None):
+ def getter(name):
+ self.counter += 1
+ raise AttributeError(name)
+ return getter
+
+ descr = Descriptor()
+ class A(object):
+ __getattribute__ = descr
+ class B(object):
+ __getattr__ = descr
+ class C(object):
+ __getattribute__ = descr
+ __getattr__ = descr
+
+ self.assertRaises(AttributeError, getattr, A(), "attr")
+ self.assertEquals(descr.counter, 1)
+ self.assertRaises(AttributeError, getattr, B(), "attr")
+ self.assertEquals(descr.counter, 2)
+ self.assertRaises(AttributeError, getattr, C(), "attr")
+ self.assertEquals(descr.counter, 4)
+
+ import gc
+ class EvilGetattribute(object):
+ # This used to segfault
+ def __getattr__(self, name):
+ raise AttributeError(name)
+ def __getattribute__(self, name):
+ del EvilGetattribute.__getattr__
+ for i in range(5):
+ gc.collect()
+ raise AttributeError(name)
+
+ self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
+
class DictProxyTests(unittest.TestCase):
def setUp(self):
Modified: python/branches/py3k/Objects/typeobject.c
==============================================================================
--- python/branches/py3k/Objects/typeobject.c (original)
+++ python/branches/py3k/Objects/typeobject.c Mon Nov 17 23:45:50 2008
@@ -4960,6 +4960,24 @@
}
static PyObject *
+call_attribute(PyObject *self, PyObject *attr, PyObject *name)
+{
+ PyObject *res, *descr = NULL;
+ descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
+
+ if (f != NULL) {
+ descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
+ if (descr == NULL)
+ return NULL;
+ else
+ attr = descr;
+ }
+ res = PyObject_CallFunctionObjArgs(attr, name, NULL);
+ Py_XDECREF(descr);
+ return res;
+}
+
+static PyObject *
slot_tp_getattr_hook(PyObject *self, PyObject *name)
{
PyTypeObject *tp = Py_TYPE(self);
@@ -4978,24 +4996,39 @@
if (getattribute_str == NULL)
return NULL;
}
+ /* speed hack: we could use lookup_maybe, but that would resolve the
+ method fully for each attribute lookup for classes with
+ __getattr__, even when the attribute is present. So we use
+ _PyType_Lookup and create the method only when needed, with
+ call_attribute. */
getattr = _PyType_Lookup(tp, getattr_str);
if (getattr == NULL) {
/* No __getattr__ hook: use a simpler dispatcher */
tp->tp_getattro = slot_tp_getattro;
return slot_tp_getattro(self, name);
}
+ Py_INCREF(getattr);
+ /* speed hack: we could use lookup_maybe, but that would resolve the
+ method fully for each attribute lookup for classes with
+ __getattr__, even when self has the default __getattribute__
+ method. So we use _PyType_Lookup and create the method only when
+ needed, with call_attribute. */
getattribute = _PyType_Lookup(tp, getattribute_str);
if (getattribute == NULL ||
(Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
((PyWrapperDescrObject *)getattribute)->d_wrapped ==
(void *)PyObject_GenericGetAttr))
res = PyObject_GenericGetAttr(self, name);
- else
- res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
+ else {
+ Py_INCREF(getattribute);
+ res = call_attribute(self, getattribute, name);
+ Py_DECREF(getattribute);
+ }
if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear();
- res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
+ res = call_attribute(self, getattr, name);
}
+ Py_DECREF(getattr);
return res;
}
From python-3000-checkins at python.org Mon Nov 17 23:55:16 2008
From: python-3000-checkins at python.org (raymond.hettinger)
Date: Mon, 17 Nov 2008 23:55:16 +0100 (CET)
Subject: [Python-3000-checkins] r67249 -
python/branches/py3k/Doc/reference/expressions.rst
Message-ID: <20081117225516.86D721E400C@bag.python.org>
Author: raymond.hettinger
Date: Mon Nov 17 23:55:16 2008
New Revision: 67249
Log:
Issue 4090 and 4087: Further documentation of comparisons.
Modified:
python/branches/py3k/Doc/reference/expressions.rst
Modified: python/branches/py3k/Doc/reference/expressions.rst
==============================================================================
--- python/branches/py3k/Doc/reference/expressions.rst (original)
+++ python/branches/py3k/Doc/reference/expressions.rst Mon Nov 17 23:55:16 2008
@@ -1003,6 +1003,12 @@
* Numbers are compared arithmetically.
+* The values :const:`float('NaN')` and :const:`Decimal('NaN')` are special.
+ The are identical to themselves, ``x is x`` but are not equal to themselves,
+ ``x != x``. Additionally, comparing any value to a not-a-number value
+ will return ``False``. For example, both ``3 < float('NaN')`` and
+ ``float('NaN') < 3`` will return ``False``.
+
* Bytes objects are compared lexicographically using the numeric values of their
elements.
@@ -1024,19 +1030,36 @@
value)`` lists compare equal. [#]_ Outcomes other than equality are resolved
consistently, but are not otherwise defined. [#]_
+* Sets and frozensets define comparison operators to mean subset and superset
+ tests. Those relations do not define total orderings (the two sets ``{1,2}``
+ and {2,3} are not equal, nor subsets of one another, nor supersets of one
+ another). Accordingly, sets are not appropriate arguments for functions
+ which depend on total ordering. For example, :func:`min`, :func:`max`, and
+ :func:`sorted` produce undefined results given a list of sets as inputs.
+
* Most other objects of builtin types compare unequal unless they are the same
object; the choice whether one object is considered smaller or larger than
another one is made arbitrarily but consistently within one execution of a
program.
+Comparison of objects of the differing types depends on whether either
+of the types provide explicit support for the comparison. Most numberic types
+can be compared with one another, but comparisons of :class:`float` and
+:class:`Decimal` are not supported to avoid the inevitable confusion arising
+from representation issues such as ``float('1.1')`` being inexactly represented
+and therefore not exactly equal to ``Decimal('1.1')`` which is. When
+cross-type comparison is not supported, the comparison method returns
+``NotImplemented``. This can create the illusion of non-transitivity between
+supported cross-type comparisons and unsupported comparisons. For example,
+``Decimal(2) == 2`` and `2 == float(2)`` but ``Decimal(2) != float(2)``.
+
The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
in s`` returns the negation of ``x in s``. All built-in sequences and set types
support this as well as dictionary, for which :keyword:`in` tests whether a the
-dictionary has a given key.
-
-For the list and tuple types, ``x in y`` is true if and only if there exists an
-index *i* such that ``x == y[i]`` is true.
+dictionary has a given key. For container types such as list, tuple, set,
+frozenset, dict, or collections.deque, the expression ``x in y`` equivalent to
+``any(x is e or x == e for val e in y)``.
For the string and bytes types, ``x in y`` is true if and only if *x* is a
substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
From python-3000-checkins at python.org Tue Nov 18 01:07:10 2008
From: python-3000-checkins at python.org (raymond.hettinger)
Date: Tue, 18 Nov 2008 01:07:10 +0100 (CET)
Subject: [Python-3000-checkins] r67253 -
python/branches/py3k/Python/peephole.c
Message-ID: <20081118000710.8E52E1E4002@bag.python.org>
Author: raymond.hettinger
Date: Tue Nov 18 01:07:10 2008
New Revision: 67253
Log:
Issue 2260: Small peephole optimization -- eliminate unnecessary POP_TOP /JUMP_FORWARD 1 pairs.
Modified:
python/branches/py3k/Python/peephole.c
Modified: python/branches/py3k/Python/peephole.c
==============================================================================
--- python/branches/py3k/Python/peephole.c (original)
+++ python/branches/py3k/Python/peephole.c Tue Nov 18 01:07:10 2008
@@ -430,6 +430,16 @@
cumlc = 0;
break;
+ /* Replace POP_TOP JUMP_FORWARD 1 POP_TOP
+ with NOP NOP NOP NOP POP_TOP. */
+ case POP_TOP:
+ if (UNCONDITIONAL_JUMP(codestr[i+1]) &&
+ GETJUMPTGT(codestr, i+1) == i+5 &&
+ codestr[i+4] == POP_TOP &&
+ ISBASICBLOCK(blocks,i,4))
+ memset(codestr+i, NOP, 4);
+ break;
+
/* Try to fold tuples of constants (includes a case for lists
which are only used for "in" and "not in" tests).
Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
From musiccomposition at gmail.com Tue Nov 18 01:10:31 2008
From: musiccomposition at gmail.com (Benjamin Peterson)
Date: Mon, 17 Nov 2008 18:10:31 -0600
Subject: [Python-3000-checkins] r67253 -
python/branches/py3k/Python/peephole.c
In-Reply-To: <20081118000710.8E52E1E4002@bag.python.org>
References: <20081118000710.8E52E1E4002@bag.python.org>
Message-ID: <1afaf6160811171610q190e962dw5815b7776f339a2@mail.gmail.com>
On Mon, Nov 17, 2008 at 6:07 PM, raymond. hettinger
wrote:
> Author: raymond.hettinger
> Date: Tue Nov 18 01:07:10 2008
> New Revision: 67253
>
> Log:
> Issue 2260: Small peephole optimization -- eliminate unnecessary POP_TOP /JUMP_FORWARD 1 pairs.
1. Shouldn't this be applied in the trunk?
2. Shouldn't this have tests?
3. Isn't past the second RC too late for any optimizations?
--
Cheers,
Benjamin Peterson
"There's nothing quite as beautiful as an oboe... except a chicken
stuck in a vacuum cleaner."
From python-3000-checkins at python.org Tue Nov 18 05:33:04 2008
From: python-3000-checkins at python.org (hirokazu.yamamoto)
Date: Tue, 18 Nov 2008 05:33:04 +0100 (CET)
Subject: [Python-3000-checkins] r67256 -
python/branches/py3k/Modules/_tkinter.c
Message-ID: <20081118043304.445D81E4002@bag.python.org>
Author: hirokazu.yamamoto
Date: Tue Nov 18 05:33:04 2008
New Revision: 67256
Log:
Issue #4313: Fixed segfault on IDLE exit. Reverted r57540 and reopened Issue #1028.
Modified:
python/branches/py3k/Modules/_tkinter.c
Modified: python/branches/py3k/Modules/_tkinter.c
==============================================================================
--- python/branches/py3k/Modules/_tkinter.c (original)
+++ python/branches/py3k/Modules/_tkinter.c Tue Nov 18 05:33:04 2008
@@ -1906,7 +1906,7 @@
PythonCmd(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[])
{
PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
- PyObject *self, *func, *arg, *res, *s;
+ PyObject *self, *func, *arg, *res;
int i, rv;
Tcl_Obj *obj_res;
@@ -1923,13 +1923,7 @@
return PythonCmd_Error(interp);
for (i = 0; i < (argc - 1); i++) {
- if (11 == (i + 1)) { /* the %A arg is the unicode char */
- char *a = argv[i + 1];
- s = PyUnicode_FromUnicode((Py_UNICODE *) a, strlen(a));
- }
- else {
- s = PyUnicode_FromString(argv[i + 1]);
- }
+ PyObject *s = PyUnicode_FromString(argv[i + 1]);
if (!s || PyTuple_SetItem(arg, i, s)) {
Py_DECREF(arg);
return PythonCmd_Error(interp);
From python-3000-checkins at python.org Tue Nov 18 23:37:15 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Tue, 18 Nov 2008 23:37:15 +0100 (CET)
Subject: [Python-3000-checkins] r67269 - in python/branches/py3k:
Makefile.pre.in Misc/NEWS
Message-ID: <20081118223715.7F7191E4002@bag.python.org>
Author: benjamin.peterson
Date: Tue Nov 18 23:37:15 2008
New Revision: 67269
Log:
fix the Makefile so it doesn't pollute sys.path
#4349 reviewed by Christian
Modified:
python/branches/py3k/Makefile.pre.in
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Makefile.pre.in
==============================================================================
--- python/branches/py3k/Makefile.pre.in (original)
+++ python/branches/py3k/Makefile.pre.in Tue Nov 18 23:37:15 2008
@@ -801,7 +801,6 @@
# Install the library
PLATDIR= plat-$(MACHDEP)
EXTRAPLATDIR= @EXTRAPLATDIR@
-EXTRAMACHDEPPATH=@EXTRAMACHDEPPATH@
MACHDEPS= $(PLATDIR) $(EXTRAPLATDIR)
XMLLIBSUBDIRS= xml xml/dom xml/etree xml/parsers xml/sax
LIBSUBDIRS= tkinter site-packages test test/output test/data \
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Tue Nov 18 23:37:15 2008
@@ -13,6 +13,9 @@
Core and Builtins
-----------------
+- Issue #4349: sys.path included a non-existent platform directory because of a
+ faulty Makefile.
+
- Issue #3327: Don't overallocate in the modules_by_index list.
- Issue #1721812: Binary set operations and copy() returned the input type
From python-3000-checkins at python.org Tue Nov 18 23:56:20 2008
From: python-3000-checkins at python.org (amaury.forgeotdarc)
Date: Tue, 18 Nov 2008 23:56:20 +0100 (CET)
Subject: [Python-3000-checkins] r67271 - python/branches/py3k
Message-ID: <20081118225620.0CA441E4002@bag.python.org>
Author: amaury.forgeotdarc
Date: Tue Nov 18 23:56:19 2008
New Revision: 67271
Log:
Blocked revisions 67266 via svnmerge
........
r67266 | amaury.forgeotdarc | 2008-11-18 23:19:37 +0100 (Tue, 18 Nov 2008) | 4 lines
#4317: Fix an Array Bounds Read in imageop.rgb2rgb8.
Will backport to 2.4.
........
Modified:
python/branches/py3k/ (props changed)
From python-3000-checkins at python.org Wed Nov 19 10:14:31 2008
From: python-3000-checkins at python.org (martin.v.loewis)
Date: Wed, 19 Nov 2008 10:14:31 +0100 (CET)
Subject: [Python-3000-checkins] r67281 - in python/branches/py3k:
Lib/turtle.py Misc/NEWS
Message-ID: <20081119091431.2448A1E4002@bag.python.org>
Author: martin.v.loewis
Date: Wed Nov 19 10:14:30 2008
New Revision: 67281
Log:
Merged revisions 67279 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67279 | martin.v.loewis | 2008-11-19 10:09:41 +0100 (Mi, 19 Nov 2008) | 2 lines
Issue #4116: Resolve member name conflict in ScrolledCanvas.__init__
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Lib/turtle.py
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Lib/turtle.py
==============================================================================
--- python/branches/py3k/Lib/turtle.py (original)
+++ python/branches/py3k/Lib/turtle.py Wed Nov 19 10:14:30 2008
@@ -357,7 +357,7 @@
def __init__(self, master, width=500, height=350,
canvwidth=600, canvheight=500):
TK.Frame.__init__(self, master, width=width, height=height)
- self._root = self.winfo_toplevel()
+ self._rootwindow = self.winfo_toplevel()
self.width, self.height = width, height
self.canvwidth, self.canvheight = canvwidth, canvheight
self.bg = "white"
@@ -377,7 +377,7 @@
self.hscroll.grid(padx=1, in_ = self, pady=1, row=1,
column=0, rowspan=1, columnspan=1, sticky='news')
self.reset()
- self._root.bind('', self.onResize)
+ self._rootwindow.bind('', self.onResize)
def reset(self, canvwidth=None, canvheight=None, bg = None):
"""Ajust canvas and scrollbars according to given canvas size."""
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Nov 19 10:14:30 2008
@@ -33,6 +33,8 @@
Library
-------
+- Issue #4116: Resolve member name conflict in ScrolledCanvas.__init__.
+
- Issue #4307: The named tuple that ``inspect.getfullargspec()`` returns now
uses ``kwonlydefaults`` instead of ``kwdefaults``.
From python-3000-checkins at python.org Wed Nov 19 14:55:07 2008
From: python-3000-checkins at python.org (martin.v.loewis)
Date: Wed, 19 Nov 2008 14:55:07 +0100 (CET)
Subject: [Python-3000-checkins] r67285 - in python/branches/py3k: Misc/NEWS
Tools/msi/msi.py
Message-ID: <20081119135507.5BDFB1E4002@bag.python.org>
Author: martin.v.loewis
Date: Wed Nov 19 14:55:07 2008
New Revision: 67285
Log:
Merged revisions 67283 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67283 | martin.v.loewis | 2008-11-19 14:51:44 +0100 (Mi, 19 Nov 2008) | 1 line
Issue #4289: Remove Cancel button from AdvancedDlg.
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Misc/NEWS
python/branches/py3k/Tools/msi/msi.py
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Wed Nov 19 14:55:07 2008
@@ -45,6 +45,8 @@
Build
-----
+- Issue #4289: Remove Cancel button from AdvancedDlg.
+
- Issue #1656675: Register a drop handler for .py* files on Windows.
Tools/Demos
Modified: python/branches/py3k/Tools/msi/msi.py
==============================================================================
--- python/branches/py3k/Tools/msi/msi.py (original)
+++ python/branches/py3k/Tools/msi/msi.py Wed Nov 19 14:55:07 2008
@@ -717,18 +717,15 @@
#####################################################################
# Advanced Dialog.
advanced = PyDialog(db, "AdvancedDlg", x, y, w, h, modal, title,
- "CompilePyc", "Next", "Cancel")
+ "CompilePyc", "Ok", "Ok")
advanced.title("Advanced Options for [ProductName]")
# A radio group with two options: allusers, justme
advanced.checkbox("CompilePyc", 135, 60, 230, 50, 3,
- "COMPILEALL", "Compile .py files to byte code after installation", "Next")
+ "COMPILEALL", "Compile .py files to byte code after installation", "Ok")
- c = advanced.next("Finish", "Cancel")
+ c = advanced.cancel("Ok", "CompilePyc", name="Ok") # Button just has location of cancel button.
c.event("EndDialog", "Return")
- c = advanced.cancel("Cancel", "CompilePyc")
- c.event("SpawnDialog", "CancelDlg")
-
#####################################################################
# Existing Directory dialog
dlg = Dialog(db, "ExistingDirectoryDlg", 50, 30, 200, 80, modal, title,
From python-3000-checkins at python.org Wed Nov 19 19:22:42 2008
From: python-3000-checkins at python.org (josiah.carlson)
Date: Wed, 19 Nov 2008 19:22:42 +0100 (CET)
Subject: [Python-3000-checkins] r67286 - python/branches/py3k/Lib/asyncore.py
Message-ID: <20081119182242.4A49E1E4002@bag.python.org>
Author: josiah.carlson
Date: Wed Nov 19 19:22:41 2008
New Revision: 67286
Log:
This fixes issue 4332 for Py3k.
Modified:
python/branches/py3k/Lib/asyncore.py
Modified: python/branches/py3k/Lib/asyncore.py
==============================================================================
--- python/branches/py3k/Lib/asyncore.py (original)
+++ python/branches/py3k/Lib/asyncore.py Wed Nov 19 19:22:41 2008
@@ -614,6 +614,6 @@
fcntl.fcntl(fd, fcntl.F_SETFL, flags)
def set_file(self, fd):
- self._fileno = fd
self.socket = file_wrapper(fd)
+ self._fileno = self.socket.fileno()
self.add_channel()
From lists at cheimes.de Wed Nov 19 19:32:52 2008
From: lists at cheimes.de (Christian Heimes)
Date: Wed, 19 Nov 2008 19:32:52 +0100
Subject: [Python-3000-checkins] r67286 -
python/branches/py3k/Lib/asyncore.py
In-Reply-To: <20081119182242.4A49E1E4002@bag.python.org>
References: <20081119182242.4A49E1E4002@bag.python.org>
Message-ID: <49245BD4.5010508@cheimes.de>
josiah.carlson wrote:
> Author: josiah.carlson
> Date: Wed Nov 19 19:22:41 2008
> New Revision: 67286
>
> Log:
> This fixes issue 4332 for Py3k.
Please update Misc/NEWS, too!
From python-3000-checkins at python.org Wed Nov 19 22:38:49 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Wed, 19 Nov 2008 22:38:49 +0100 (CET)
Subject: [Python-3000-checkins] r67290 - python/branches/py3k
Message-ID: <20081119213849.005481E4002@bag.python.org>
Author: benjamin.peterson
Date: Wed Nov 19 22:38:48 2008
New Revision: 67290
Log:
Blocked revisions 67287 via svnmerge
........
r67287 | josiah.carlson | 2008-11-19 12:26:12 -0600 (Wed, 19 Nov 2008) | 2 lines
Fix for issue 4332 in trunk.
........
Modified:
python/branches/py3k/ (props changed)
From python-3000-checkins at python.org Wed Nov 19 23:05:52 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Wed, 19 Nov 2008 23:05:52 +0100 (CET)
Subject: [Python-3000-checkins] r67292 - in python/branches/py3k:
Lib/test/test_bytes.py Objects/bytearrayobject.c
Message-ID: <20081119220552.EACA11E4002@bag.python.org>
Author: benjamin.peterson
Date: Wed Nov 19 23:05:52 2008
New Revision: 67292
Log:
Merged revisions 67291 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67291 | benjamin.peterson | 2008-11-19 15:49:09 -0600 (Wed, 19 Nov 2008) | 5 lines
make sure that bytearray methods return a new bytearray even if there is no change
Fixes #4348
Reviewed by Brett
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Lib/test/test_bytes.py
python/branches/py3k/Objects/bytearrayobject.c
Modified: python/branches/py3k/Lib/test/test_bytes.py
==============================================================================
--- python/branches/py3k/Lib/test/test_bytes.py (original)
+++ python/branches/py3k/Lib/test/test_bytes.py Wed Nov 19 23:05:52 2008
@@ -738,6 +738,16 @@
b.insert(0, Indexable(ord('A')))
self.assertEqual(b, b'A')
+ def test_copied(self):
+ # 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))
+
+ t = bytearray([i for i in range(256)])
+ x = bytearray(b'')
+ self.assertFalse(x is x.translate(t))
+
def test_partition_bytearray_doesnt_share_nullstring(self):
a, b, c = bytearray(b"x").partition(b"y")
self.assertEqual(b, b"")
Modified: python/branches/py3k/Objects/bytearrayobject.c
==============================================================================
--- python/branches/py3k/Objects/bytearrayobject.c (original)
+++ python/branches/py3k/Objects/bytearrayobject.c Wed Nov 19 23:05:52 2008
@@ -1351,7 +1351,7 @@
{
register char *input, *output;
register const char *table;
- register Py_ssize_t i, c, changed = 0;
+ register Py_ssize_t i, c;
PyObject *input_obj = (PyObject*)self;
const char *output_start;
Py_ssize_t inlen;
@@ -1397,14 +1397,8 @@
/* If no deletions are required, use faster code */
for (i = inlen; --i >= 0; ) {
c = Py_CHARMASK(*input++);
- if (Py_CHARMASK((*output++ = table[c])) != c)
- changed = 1;
+ *output++ = table[c];
}
- if (changed || !PyByteArray_CheckExact(input_obj))
- goto done;
- Py_DECREF(result);
- Py_INCREF(input_obj);
- result = input_obj;
goto done;
}
@@ -1419,13 +1413,6 @@
if (trans_table[c] != -1)
if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
continue;
- changed = 1;
- }
- if (!changed && PyByteArray_CheckExact(input_obj)) {
- Py_DECREF(result);
- Py_INCREF(input_obj);
- result = input_obj;
- goto done;
}
/* Fix the size of the resulting string */
if (inlen > 0)
@@ -1454,8 +1441,7 @@
!memcmp(target+offset+1, pattern+1, length-2) )
-/* Bytes ops must return a string. */
-/* If the object is subclass of bytes, create a copy */
+/* Bytes ops must return a string, create a copy */
Py_LOCAL(PyByteArrayObject *)
return_self(PyByteArrayObject *self)
{
From python-3000-checkins at python.org Wed Nov 19 23:38:29 2008
From: python-3000-checkins at python.org (benjamin.peterson)
Date: Wed, 19 Nov 2008 23:38:29 +0100 (CET)
Subject: [Python-3000-checkins] r67294 - in python/branches/py3k:
Doc/conf.py Doc/reference/datamodel.rst
Doc/tools/sphinxext/download.html Lib/doctest.py
Message-ID: <20081119223829.AC9B31E4002@bag.python.org>
Author: benjamin.peterson
Date: Wed Nov 19 23:38:29 2008
New Revision: 67294
Log:
Merged revisions 67243,67245,67277-67278,67289 via svnmerge from
svn+ssh://pythondev at svn.python.org/python/trunk
........
r67243 | benjamin.peterson | 2008-11-17 15:39:05 -0600 (Mon, 17 Nov 2008) | 1 line
a few fixes on the download page
........
r67245 | benjamin.peterson | 2008-11-17 16:05:19 -0600 (Mon, 17 Nov 2008) | 1 line
improve __hash__ docs
........
r67277 | skip.montanaro | 2008-11-18 21:35:41 -0600 (Tue, 18 Nov 2008) | 1 line
patch from issue 1108
........
r67278 | georg.brandl | 2008-11-19 01:59:09 -0600 (Wed, 19 Nov 2008) | 2 lines
Try to fix problems with verbatim.
........
r67289 | brett.cannon | 2008-11-19 14:29:39 -0600 (Wed, 19 Nov 2008) | 2 lines
Ignore .pyc and .pyo files.
........
Modified:
python/branches/py3k/ (props changed)
python/branches/py3k/Doc/conf.py
python/branches/py3k/Doc/reference/datamodel.rst
python/branches/py3k/Doc/tools/sphinxext/download.html
python/branches/py3k/Lib/doctest.py
Modified: python/branches/py3k/Doc/conf.py
==============================================================================
--- python/branches/py3k/Doc/conf.py (original)
+++ python/branches/py3k/Doc/conf.py Wed Nov 19 23:38:29 2008
@@ -141,6 +141,8 @@
\strong{Python Software Foundation}\\
Email: \email{docs at python.org}
}
+\let\Verbatim=\OriginalVerbatim
+\let\endVerbatim=\endOriginalVerbatim
'''
# Documents to append as an appendix to all manuals.
Modified: python/branches/py3k/Doc/reference/datamodel.rst
==============================================================================
--- python/branches/py3k/Doc/reference/datamodel.rst (original)
+++ python/branches/py3k/Doc/reference/datamodel.rst Wed Nov 19 23:38:29 2008
@@ -1202,20 +1202,22 @@
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 an :meth:`__eq__` method it should not define a
:meth:`__hash__` operation either; if it defines :meth:`__eq__` but not
- :meth:`__hash__`, its instances will not be usable as dictionary keys. If a
- class defines mutable objects and implements an :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).
+ :meth:`__hash__`, its instances will not be usable as items in hashable
+ collections. If a class defines mutable objects and implements an
+ :meth:`__eq__` method, it should not implement :meth:`__hash__`, since the
+ implementation of hashable collections requires that a key'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:`__eq__` and :meth:`__hash__` methods
by default; with them, all objects compare unequal (except with themselves)
Modified: python/branches/py3k/Doc/tools/sphinxext/download.html
==============================================================================
--- python/branches/py3k/Doc/tools/sphinxext/download.html (original)
+++ python/branches/py3k/Doc/tools/sphinxext/download.html Wed Nov 19 23:38:29 2008
@@ -14,7 +14,7 @@
To download an archive containing all the documents for this version of
Python in one of various formats, follow one of links in this table. The numbers
-in the table are the size of the download files in Kilobytes.
+in the table are the size of the download files in megabytes.