Merged revisions 68133-68134,68141-68142,68145-68146,68148-68149,68159-68162,68166,68171-68174,68179,68195-68196,68210,68214-68215,68217-68222 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/trunk

........
  r68133 | antoine.pitrou | 2009-01-01 16:38:03 +0100 (Thu, 01 Jan 2009) | 1 line

  fill in actual issue number in tests
........
  r68134 | hirokazu.yamamoto | 2009-01-01 16:45:39 +0100 (Thu, 01 Jan 2009) | 2 lines

  Issue #4797: IOError.filename was not set when _fileio.FileIO failed to open
  file with `str' filename on Windows.
........
  r68141 | benjamin.peterson | 2009-01-01 17:43:12 +0100 (Thu, 01 Jan 2009) | 1 line

  fix highlighting
........
  r68142 | benjamin.peterson | 2009-01-01 18:29:49 +0100 (Thu, 01 Jan 2009) | 2 lines

  welcome to 2009, Python!
........
  r68145 | amaury.forgeotdarc | 2009-01-02 01:03:54 +0100 (Fri, 02 Jan 2009) | 5 lines

  #4801 _collections module fails to build on cygwin.

  _PyObject_GC_TRACK is the macro version of PyObject_GC_Track,
  and according to documentation it should not be used for extension modules.
........
  r68146 | ronald.oussoren | 2009-01-02 11:44:46 +0100 (Fri, 02 Jan 2009) | 2 lines

  Fix for issue4472: "configure --enable-shared doesn't work on OSX"
........
  r68148 | ronald.oussoren | 2009-01-02 11:48:31 +0100 (Fri, 02 Jan 2009) | 2 lines

  Forgot to add a NEWS item in my previous checkin
........
  r68149 | ronald.oussoren | 2009-01-02 11:50:48 +0100 (Fri, 02 Jan 2009) | 2 lines

  Fix for issue4780
........
  r68159 | ronald.oussoren | 2009-01-02 15:48:17 +0100 (Fri, 02 Jan 2009) | 2 lines

  Fix for issue 1627952
........
  r68160 | ronald.oussoren | 2009-01-02 15:52:09 +0100 (Fri, 02 Jan 2009) | 2 lines

  Fix for issue r1737832
........
  r68161 | ronald.oussoren | 2009-01-02 16:00:05 +0100 (Fri, 02 Jan 2009) | 3 lines

  Fix for issue 1149804
........
  r68162 | ronald.oussoren | 2009-01-02 16:06:00 +0100 (Fri, 02 Jan 2009) | 3 lines

  Fix for issue 4472 is incompatible with Cygwin, this patch
  should fix that.
........
  r68166 | benjamin.peterson | 2009-01-02 19:26:23 +0100 (Fri, 02 Jan 2009) | 1 line

  document PyMemberDef
........
  r68171 | georg.brandl | 2009-01-02 21:25:14 +0100 (Fri, 02 Jan 2009) | 3 lines

  #4811: fix markup glitches (mostly remains of the conversion),
  found by Gabriel Genellina.
........
  r68172 | martin.v.loewis | 2009-01-02 21:32:55 +0100 (Fri, 02 Jan 2009) | 2 lines

  Issue #4075: Use OutputDebugStringW in Py_FatalError.
........
  r68173 | martin.v.loewis | 2009-01-02 21:40:14 +0100 (Fri, 02 Jan 2009) | 2 lines

  Issue #4051: Prevent conflict of UNICODE macros in cPickle.
........
  r68174 | benjamin.peterson | 2009-01-02 21:47:27 +0100 (Fri, 02 Jan 2009) | 1 line

  fix compilation on non-Windows platforms
........
  r68179 | raymond.hettinger | 2009-01-02 22:26:45 +0100 (Fri, 02 Jan 2009) | 1 line

  Issue #4615.  Document how to use itertools for de-duping.
........
  r68195 | georg.brandl | 2009-01-03 14:45:15 +0100 (Sat, 03 Jan 2009) | 2 lines

  Remove useless string literal.
........
  r68196 | georg.brandl | 2009-01-03 15:29:53 +0100 (Sat, 03 Jan 2009) | 2 lines

  Fix indentation.
........
  r68210 | georg.brandl | 2009-01-03 20:10:12 +0100 (Sat, 03 Jan 2009) | 2 lines

  Set eol-style correctly for mp_distributing.py.
........
  r68214 | georg.brandl | 2009-01-03 20:44:48 +0100 (Sat, 03 Jan 2009) | 2 lines

  Make indentation consistent.
........
  r68215 | georg.brandl | 2009-01-03 21:15:14 +0100 (Sat, 03 Jan 2009) | 2 lines

  Fix role name.
........
  r68217 | georg.brandl | 2009-01-03 21:30:15 +0100 (Sat, 03 Jan 2009) | 2 lines

  Add rstlint, a little tool to find subtle markup problems and inconsistencies in the Doc sources.
........
  r68218 | georg.brandl | 2009-01-03 21:38:59 +0100 (Sat, 03 Jan 2009) | 2 lines

  Recognize usage of the default role.
........
  r68219 | georg.brandl | 2009-01-03 21:47:01 +0100 (Sat, 03 Jan 2009) | 2 lines

  Fix uses of the default role.
........
  r68220 | georg.brandl | 2009-01-03 21:55:06 +0100 (Sat, 03 Jan 2009) | 2 lines

  Remove trailing whitespace.
........
  r68221 | georg.brandl | 2009-01-03 22:04:55 +0100 (Sat, 03 Jan 2009) | 2 lines

  Remove tabs from the documentation.
........
  r68222 | georg.brandl | 2009-01-03 22:11:58 +0100 (Sat, 03 Jan 2009) | 2 lines

  Disable the line length checker by default.
........
This commit is contained in:
Georg Brandl 2009-01-03 21:55:17 +00:00
parent 9b520efa8f
commit 734373cc4d
186 changed files with 1803 additions and 1459 deletions

View file

@ -60,6 +60,7 @@ docs@python.org), and we'll be glad to correct the problem.
* Peter Funk
* Lele Gaifax
* Matthew Gallagher
* Gabriel Genellina
* Ben Gertzfield
* Nadim Ghaznavi
* Jonathan Giddy

View file

@ -14,7 +14,7 @@ DISTVERSION = $(shell $(PYTHON) tools/sphinxext/patchlevel.py)
ALLSPHINXOPTS = -b $(BUILDER) -d build/doctrees -D latex_paper_size=$(PAPER) \
$(SPHINXOPTS) . build/$(BUILDER) $(SOURCES)
.PHONY: help checkout update build html htmlhelp clean coverage dist
.PHONY: help checkout update build html htmlhelp clean coverage dist check
help:
@echo "Please use \`make <target>' where <target> is one of"
@ -141,3 +141,5 @@ dist:
cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-letter.zip
cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-letter.tar.bz2
check:
$(PYTHON) tools/rstlint.py -i tools

View file

@ -46,12 +46,12 @@ variable(s) whose address should be passed.
:ctype:`Py_ssize_t` rather than an int.
``s*`` (string, Unicode, or any buffer compatible object) [Py_buffer \*]
Similar to ``s#``, this code fills a Py_buffer structure provided by the caller.
The buffer gets locked, so that the caller can subsequently use the buffer even
inside a ``Py_BEGIN_ALLOW_THREADS`` block; the caller is responsible for calling
``PyBuffer_Release`` with the structure after it has processed the data.
Similar to ``s#``, this code fills a Py_buffer structure provided by the caller.
The buffer gets locked, so that the caller can subsequently use the buffer even
inside a ``Py_BEGIN_ALLOW_THREADS`` block; the caller is responsible for calling
``PyBuffer_Release`` with the structure after it has processed the data.
.. versionadded:: 2.6
.. versionadded:: 2.6
``z`` (string or ``None``) [const char \*]
Like ``s``, but the Python object may also be ``None``, in which case the C
@ -63,7 +63,7 @@ variable(s) whose address should be passed.
``z*`` (string or ``None`` or any buffer compatible object) [Py_buffer*]
This is to ``s*`` as ``z`` is to ``s``.
.. versionadded:: 2.6
.. versionadded:: 2.6
``u`` (Unicode object) [Py_UNICODE \*]
Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of
@ -261,6 +261,7 @@ variable(s) whose address should be passed.
``w*`` (read-write byte-oriented buffer) [Py_buffer \*]
This is to ``w`` what ``s*`` is to ``s``.
.. versionadded:: 2.6
``(items)`` (tuple) [*matching-items*]

View file

@ -63,8 +63,8 @@ change in future releases of Python.
Return the file object associated with *p* as a :ctype:`FILE\*`.
If the caller will ever use the returned :ctype:`FILE\*` object while
the GIL is released it must also call the `PyFile_IncUseCount` and
`PyFile_DecUseCount` functions described below as appropriate.
the GIL is released it must also call the :cfunc:`PyFile_IncUseCount` and
:cfunc:`PyFile_DecUseCount` functions described below as appropriate.
.. cfunction:: void PyFile_IncUseCount(PyFileObject \*p)
@ -72,13 +72,13 @@ change in future releases of Python.
Increments the PyFileObject's internal use count to indicate
that the underlying :ctype:`FILE\*` is being used.
This prevents Python from calling f_close() on it from another thread.
Callers of this must call `PyFile_DecUseCount` when they are
Callers of this must call :cfunc:`PyFile_DecUseCount` when they are
finished with the :ctype:`FILE\*`. Otherwise the file object will
never be closed by Python.
The GIL must be held while calling this function.
The suggested use is to call this after `PyFile_AsFile` just before
The suggested use is to call this after :cfunc:`PyFile_AsFile` just before
you release the GIL.
.. versionadded:: 2.6
@ -88,7 +88,7 @@ change in future releases of Python.
Decrements the PyFileObject's internal unlocked_count member to
indicate that the caller is done with its own use of the :ctype:`FILE\*`.
This may only be called to undo a prior call to `PyFile_IncUseCount`.
This may only be called to undo a prior call to :cfunc:`PyFile_IncUseCount`.
The GIL must be held while calling this function.

View file

@ -205,6 +205,69 @@ definition with the same method name.
.. versionadded:: 2.4
.. ctype:: PyMemberDef
Structure which describes an attribute of a type which corresponds to a C
struct member. It's fields are:
+------------------+-------------+-------------------------------+
| Field | C Type | Meaning |
+==================+=============+===============================+
| :attr:`name` | char \* | name of the member |
+------------------+-------------+-------------------------------+
| :attr:`type` | int | the type of the member in the |
| | | C struct |
+------------------+-------------+-------------------------------+
| :attr:`offset` | Py_ssize_t | the offset in bytes that the |
| | | member is located on the |
| | | type's object struct |
+------------------+-------------+-------------------------------+
| :attr:`flags` | int | flag bits indicating if the |
| | | field should be read-only or |
| | | writable |
+------------------+-------------+-------------------------------+
| :attr:`doc` | char \* | points to the contents of the |
| | | docstring |
+------------------+-------------+-------------------------------+
:attr:`type` can be one of many ``T_`` macros corresponding to various C
types. When the member is accessed in Python, it will be converted to the
equivalent Python type.
=============== ==================
Macro name C type
=============== ==================
T_SHORT short
T_INT int
T_LONG long
T_FLOAT float
T_DOUBLE double
T_STRING char \*
T_OBJECT PyObject \*
T_OBJECT_EX PyObject \*
T_CHAR char
T_BYTE char
T_UNBYTE unsigned char
T_UINT unsigned int
T_USHORT unsigned short
T_ULONG unsigned long
T_BOOL char
T_LONGLONG long long
T_ULONGLONG unsigned long long
T_PYSSIZET Py_ssize_t
=============== ==================
:cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX` differ in that
:cmacro:`T_OBJECT` returns ``None`` if the member is *NULL* and
:cmacro:`T_OBJECT_EX` raises an :exc:`AttributeError`.
:attr:`flags` can be 0 for write and read access or :cmacro:`READONLY` for
read-only access. Using :cmacro:`T_STRING` for :attr:`type` implies
:cmacro:`READONLY`. Only :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX` can be
deleted. (They are set to *NULL*).
.. cfunction:: PyObject* Py_FindMethod(PyMethodDef table[], PyObject *ob, char *name)
Return a bound method object for an extension type implemented in C. This can

View file

@ -188,9 +188,10 @@ the full reference.
| | for C/C++ header files (in | |
| | Unix form for portability) | |
+------------------------+--------------------------------+---------------------------+
| *define_macros* | list of macros to define; each | (string,string) tuple or |
| | macro is defined using a | (name,``None``) |
| | 2-tuple, where 'value' is | |
| *define_macros* | list of macros to define; each | (string, string) tuple or |
| | macro is defined using a | (name, ``None``) |
| | 2-tuple ``(name, value)``, | |
| | where *value* is | |
| | either the string to define it | |
| | to or ``None`` to define it | |
| | without a particular value | |

View file

@ -35,9 +35,9 @@ uploaded file using GPG (GNU Privacy Guard). The :program:`gpg` program must
be available for execution on the system :envvar:`PATH`. You can also specify
which key to use for signing using the :option:`--identity=*name*` option.
Other :command:`upload` options include :option:`--repository=*url*`
or :option:`--repository=*section*` where `url` is the url of the server
and `section` the name of the section in :file:`$HOME/.pypirc`, and
Other :command:`upload` options include :option:`--repository=<url>` or
:option:`--repository=<section>` where *url* is the url of the server and
*section* the name of the section in :file:`$HOME/.pypirc`, and
:option:`--show-response` (which displays the full response text from the PyPI
server for help in debugging upload problems).

View file

@ -599,7 +599,7 @@ units as well as normal text:
Example::
.. versionadded:: 2.5
The `spam` parameter.
The *spam* parameter.
Note that there must be no blank line between the directive head and the
explanation; this is to make these blocks visually continuous in the markup.
@ -760,7 +760,7 @@ the definition of the symbol. There is this directive:
Blank lines are not allowed within ``productionlist`` directive arguments.
The definition can contain token names which are marked as interpreted text
(e.g. ``sum ::= `integer` "+" `integer```) -- this generates cross-references
(e.g. ``unaryneg ::= "-" `integer```) -- this generates cross-references
to the productions of these tokens.
Note that no further reST parsing is done in the production, so that you

View file

@ -840,8 +840,8 @@ As you can see, the source code closely resembles the :class:`Noddy` examples in
previous sections. We will break down the main differences between them. ::
typedef struct {
PyListObject list;
int state;
PyListObject list;
int state;
} Shoddy;
The primary difference for derived type objects is that the base type's object
@ -854,10 +854,10 @@ be safely cast to both *PyListObject\** and *Shoddy\**. ::
static int
Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds)
{
if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
return -1;
self->state = 0;
return 0;
if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
return -1;
self->state = 0;
return 0;
}
In the :attr:`__init__` method for our type, we can see how to call through to
@ -876,18 +876,18 @@ the module's :cfunc:`init` function. ::
PyMODINIT_FUNC
initshoddy(void)
{
PyObject *m;
PyObject *m;
ShoddyType.tp_base = &PyList_Type;
if (PyType_Ready(&ShoddyType) < 0)
return;
ShoddyType.tp_base = &PyList_Type;
if (PyType_Ready(&ShoddyType) < 0)
return;
m = Py_InitModule3("shoddy", NULL, "Shoddy module");
if (m == NULL)
return;
m = Py_InitModule3("shoddy", NULL, "Shoddy module");
if (m == NULL)
return;
Py_INCREF(&ShoddyType);
PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
Py_INCREF(&ShoddyType);
PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
}
Before calling :cfunc:`PyType_Ready`, the type structure must have the
@ -1167,7 +1167,7 @@ structure::
typedef struct PyMethodDef {
char *ml_name; /* method name */
PyCFunction ml_meth; /* implementation function */
int ml_flags; /* flags */
int ml_flags; /* flags */
char *ml_doc; /* docstring */
} PyMethodDef;

View file

@ -297,7 +297,7 @@ So, to display a reverse-video status line on the top line of the screen, you
could code::
stdscr.addstr(0, 0, "Current mode: Typing mode",
curses.A_REVERSE)
curses.A_REVERSE)
stdscr.refresh()
The curses library also supports color on those terminals that provide it, The

View file

@ -585,7 +585,7 @@ And here's an example of changing the counter:
9
>>> print it.next()
Traceback (most recent call last):
File ``t.py'', line 15, in ?
File "t.py", line 15, in ?
print it.next()
StopIteration

View file

@ -611,7 +611,7 @@ of each one.
is to read? ::
charref = re.compile(r"""
&[#] # Start of a numeric entity reference
&[#] # Start of a numeric entity reference
(
0[0-7]+ # Octal form
| [0-9]+ # Decimal form
@ -917,7 +917,7 @@ module::
InternalDate = re.compile(r'INTERNALDATE "'
r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
r'(?P<year>[0-9][0-9][0-9][0-9])'
r'(?P<year>[0-9][0-9][0-9][0-9])'
r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
r'"')

View file

@ -190,33 +190,33 @@ length message::
'''
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
if sock is None:
self.sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def connect(self, host, port):
self.sock.connect((host, port))
self.sock.connect((host, port))
def mysend(self, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError, \
"socket connection broken"
totalsent = totalsent + sent
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError, \
"socket connection broken"
totalsent = totalsent + sent
def myreceive(self):
msg = ''
while len(msg) < MSGLEN:
chunk = self.sock.recv(MSGLEN-len(msg))
if chunk == '':
raise RuntimeError, \
"socket connection broken"
msg = msg + chunk
return msg
msg = ''
while len(msg) < MSGLEN:
chunk = self.sock.recv(MSGLEN-len(msg))
if chunk == '':
raise RuntimeError, \
"socket connection broken"
msg = msg + chunk
return msg
The sending code here is usable for almost any messaging scheme - in Python you
send strings, and you can use ``len()`` to determine its length (even if it has

View file

@ -30,8 +30,8 @@ For a while people just wrote programs that didn't display accents. I remember
looking at Apple ][ BASIC programs, published in French-language publications in
the mid-1980s, that had lines like these::
PRINT "FICHIER EST COMPLETE."
PRINT "CARACTERE NON ACCEPTE."
PRINT "FICHIER EST COMPLETE."
PRINT "CARACTERE NON ACCEPTE."
Those messages should contain accents, and they just look wrong to someone who
can read French.
@ -89,11 +89,11 @@ standard, a code point is written using the notation U+12ca to mean the
character with value 0x12ca (4810 decimal). The Unicode standard contains a lot
of tables listing characters and their corresponding code points::
0061 'a'; LATIN SMALL LETTER A
0062 'b'; LATIN SMALL LETTER B
0063 'c'; LATIN SMALL LETTER C
...
007B '{'; LEFT CURLY BRACKET
0061 'a'; LATIN SMALL LETTER A
0062 'b'; LATIN SMALL LETTER B
0063 'c'; LATIN SMALL LETTER C
...
007B '{'; LEFT CURLY BRACKET
Strictly, these definitions imply that it's meaningless to say 'this is
character U+12ca'. U+12ca is a code point, which represents some particular
@ -597,19 +597,19 @@ encoding and a list of Unicode strings will be returned, while passing an 8-bit
path will return the 8-bit versions of the filenames. For example, assuming the
default filesystem encoding is UTF-8, running the following program::
fn = u'filename\u4500abc'
f = open(fn, 'w')
f.close()
fn = u'filename\u4500abc'
f = open(fn, 'w')
f.close()
import os
print os.listdir('.')
print os.listdir(u'.')
import os
print os.listdir('.')
print os.listdir(u'.')
will produce the following output::
amk:~$ python t.py
['.svn', 'filename\xe4\x94\x80abc', ...]
[u'.svn', u'filename\u4500abc', ...]
amk:~$ python t.py
['.svn', 'filename\xe4\x94\x80abc', ...]
[u'.svn', u'filename\u4500abc', ...]
The first list contains UTF-8-encoded filenames, and the second list contains
the Unicode versions.
@ -703,26 +703,26 @@ Version 1.02: posted August 16 2005. Corrects factual errors.
- [ ] Unicode introduction
- [ ] ASCII
- [ ] Terms
- [ ] Character
- [ ] Code point
- [ ] Encodings
- [ ] Common encodings: ASCII, Latin-1, UTF-8
- [ ] Character
- [ ] Code point
- [ ] Encodings
- [ ] Common encodings: ASCII, Latin-1, UTF-8
- [ ] Unicode Python type
- [ ] Writing unicode literals
- [ ] Obscurity: -U switch
- [ ] Built-ins
- [ ] unichr()
- [ ] ord()
- [ ] unicode() constructor
- [ ] Unicode type
- [ ] encode(), decode() methods
- [ ] Writing unicode literals
- [ ] Obscurity: -U switch
- [ ] Built-ins
- [ ] unichr()
- [ ] ord()
- [ ] unicode() constructor
- [ ] Unicode type
- [ ] encode(), decode() methods
- [ ] Unicodedata module for character properties
- [ ] I/O
- [ ] Reading/writing Unicode data into files
- [ ] Byte-order marks
- [ ] Unicode filenames
- [ ] Reading/writing Unicode data into files
- [ ] Byte-order marks
- [ ] Unicode filenames
- [ ] Writing Unicode programs
- [ ] Do everything in Unicode
- [ ] Declaring source code encodings (PEP 263)
- [ ] Do everything in Unicode
- [ ] Declaring source code encodings (PEP 263)
- [ ] Other issues
- [ ] Building Python (UCS2, UCS4)
- [ ] Building Python (UCS2, UCS4)

View file

@ -470,7 +470,7 @@ than the URL you pass to .add_password() will also match. ::
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

View file

@ -587,7 +587,7 @@ value of ``sys.path``. ::
$ python
Python 2.2 (#11, Oct 3 2002, 13:31:27)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
Type ``help'', ``copyright'', ``credits'' or ``license'' for more information.
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2',

View file

@ -43,15 +43,15 @@ This module provides the following class:
Register *subclass* as a "virtual subclass" of this ABC. For
example::
from abc import ABCMeta
from abc import ABCMeta
class MyABC:
__metaclass__ = ABCMeta
class MyABC:
__metaclass__ = ABCMeta
MyABC.register(tuple)
MyABC.register(tuple)
assert issubclass(tuple, MyABC)
assert isinstance((), MyABC)
assert issubclass(tuple, MyABC)
assert isinstance((), MyABC)
You can also override this method in an abstract base class:

View file

@ -191,7 +191,7 @@ and classes for traversing abstract syntax trees:
A node visitor base class that walks the abstract syntax tree and calls a
visitor function for every node found. This function may return a value
which is forwarded by the `visit` method.
which is forwarded by the :meth:`visit` method.
This class is meant to be subclassed, with the subclass adding visitor
methods.
@ -220,11 +220,11 @@ and classes for traversing abstract syntax trees:
A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
allows modification of nodes.
The `NodeTransformer` will walk the AST and use the return value of the
visitor methods to replace or remove the old node. If the return value of
the visitor method is ``None``, the node will be removed from its location,
otherwise it is replaced with the return value. The return value may be the
original node in which case no replacement takes place.
The :class:`NodeTransformer` will walk the AST and use the return value of
the visitor methods to replace or remove the old node. If the return value
of the visitor method is ``None``, the node will be removed from its
location, otherwise it is replaced with the return value. The return value
may be the original node in which case no replacement takes place.
Here is an example transformer that rewrites all occurrences of name lookups
(``foo``) to ``data['foo']``::

View file

@ -53,7 +53,7 @@ ABC Inherits Abstract Methods Mixin
:class:`Hashable` ``__hash__``
:class:`Iterable` ``__iter__``
:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
:class:`Sized` ``__len__``
:class:`Sized` ``__len__``
:class:`Callable` ``__call__``
:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``.
@ -80,7 +80,7 @@ ABC Inherits Abstract Methods Mixin
:class:`MutableMapping` :class:`Mapping` ``__getitem__`` Inherited Mapping methods and
``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``,
``__delitem__``, and ``setdefault``
``__iter__``, and
``__iter__``, and
``__len__``
:class:`MappingView` :class:`Sized` ``__len__``
@ -96,7 +96,7 @@ particular functionality, for example::
size = None
if isinstance(myvar, collections.Sized):
size = len(myvar)
size = len(myvar)
Several of the ABCs are also useful as mixins that make it easier to develop
classes supporting container APIs. For example, to write a class supporting

View file

@ -11,9 +11,9 @@
.. note::
The :mod:`ConfigParser` module has been renamed to `configparser` in Python
3.0. The :term:`2to3` tool will automatically adapt imports when converting
your sources to 3.0.
The :mod:`ConfigParser` module has been renamed to :mod:`configparser` in
Python 3.0. The :term:`2to3` tool will automatically adapt imports when
converting your sources to 3.0.
.. index::
pair: .ini; file

View file

@ -733,7 +733,7 @@ accessed using the following methods:
The :class:`Cookie` class also defines the following method:
.. method:: Cookie.is_expired([now=:const:`None`])
.. method:: Cookie.is_expired([now=None])
True if cookie has passed the time at which the server requested it should
expire. If *now* is given (in seconds since the epoch), return whether the

View file

@ -1378,24 +1378,22 @@ it.
The *mode* parameter can be used to specify how the library is loaded. For
details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
The *use_errno* parameter, when set to True, enables a ctypes
mechanism that allows to access the system `errno` error number in a
safe way. `ctypes` maintains a thread-local copy of the systems
`errno` variable; if you call foreign functions created with
`use_errno=True` then the `errno` value before the function call is
swapped with the ctypes private copy, the same happens immediately
after the function call.
The *use_errno* parameter, when set to True, enables a ctypes mechanism that
allows to access the system :data:`errno` error number in a safe way.
:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
variable; if you call foreign functions created with ``use_errno=True`` then the
:data:`errno` value before the function call is swapped with the ctypes private
copy, the same happens immediately after the function call.
The function `ctypes.get_errno()` returns the value of the ctypes
private copy, and the function `ctypes.set_errno(value)` changes the
ctypes private copy to `value` and returns the former value.
The function :func:`ctypes.get_errno` returns the value of the ctypes private
copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
to a new value and returns the former value.
The *use_last_error* parameter, when set to True, enables the same
mechanism for the Windows error code which is managed by the
:func:`GetLastError` and :func:`SetLastError` Windows API functions;
`ctypes.get_last_error()` and `ctypes.set_last_error(value)` are used
to request and change the ctypes private copy of the windows error
code.
The *use_last_error* parameter, when set to True, enables the same mechanism for
the Windows error code which is managed by the :func:`GetLastError` and
:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
:func:`ctypes.set_last_error` are used to request and change the ctypes private
copy of the windows error code.
.. versionadded:: 2.6
The ``use_last_error`` and ``use_errno`` optional parameters
@ -1602,22 +1600,23 @@ type and the argument types of the function.
.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
The returned function prototype creates functions that use the standard C
calling convention. The function will release the GIL during the call.
If `use_errno` is set to True, the ctypes private copy of the system `errno`
variable is exchanged with the real `errno` value bafore and after the call;
`use_last_error` does the same for the Windows error code.
calling convention. The function will release the GIL during the call. If
*use_errno* is set to True, the ctypes private copy of the system
:data:`errno` variable is exchanged with the real :data:`errno` value bafore
and after the call; *use_last_error* does the same for the Windows error
code.
.. versionchanged:: 2.6
The optional `use_errno` and `use_last_error` parameters were
added.
The optional *use_errno* and *use_last_error* parameters were added.
.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Windows only: The returned function prototype creates functions that use the
``stdcall`` calling convention, except on Windows CE where :func:`WINFUNCTYPE`
is the same as :func:`CFUNCTYPE`. The function will release the GIL during the
call. `use_errno` and `use_last_error` have the same meaning as above.
``stdcall`` calling convention, except on Windows CE where
:func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
release the GIL during the call. *use_errno* and *use_last_error* have the
same meaning as above.
.. function:: PYFUNCTYPE(restype, *argtypes)
@ -1864,10 +1863,10 @@ Utility functions
.. function:: find_library(name)
:module: ctypes.util
Try to find a library and return a pathname. `name` is the library name without
any prefix like `lib`, suffix like ``.so``, ``.dylib`` or version number (this
is the form used for the posix linker option :option:`-l`). If no library can
be found, returns ``None``.
Try to find a library and return a pathname. *name* is the library name
without any prefix like ``lib```, suffix like ``.so``, ``.dylib`` or version
number (this is the form used for the posix linker option :option:`-l`). If
no library can be found, returns ``None``.
The exact functionality is system dependent.
@ -1905,14 +1904,14 @@ Utility functions
.. function:: get_errno()
Returns the current value of the ctypes-private copy of the system
`errno` variable in the calling thread.
:data:`errno` variable in the calling thread.
.. versionadded:: 2.6
.. function:: get_last_error()
Windows only: returns the current value of the ctypes-private copy of the system
`LastError` variable in the calling thread.
:data:`LastError` variable in the calling thread.
.. versionadded:: 2.6
@ -1969,17 +1968,16 @@ Utility functions
.. function:: set_errno(value)
Set the current value of the ctypes-private copy of the system
`errno` variable in the calling thread to `value` and return the
previous value.
Set the current value of the ctypes-private copy of the system :data:`errno`
variable in the calling thread to *value* and return the previous value.
.. versionadded:: 2.6
.. function:: set_last_error(value)
Windows only: set the current value of the ctypes-private copy of
the system `LastError` variable in the calling thread to `value`
and return the previous value.
Windows only: set the current value of the ctypes-private copy of the system
:data:`LastError` variable in the calling thread to *value* and return the
previous value.
.. versionadded:: 2.6

View file

@ -1168,7 +1168,7 @@ In addition to the three supplied contexts, new contexts can be created with the
.. method:: logical_and(x, y)
Applies the logical operation `and` between each operand's digits.
Applies the logical operation *and* between each operand's digits.
.. method:: logical_invert(x)
@ -1178,12 +1178,12 @@ In addition to the three supplied contexts, new contexts can be created with the
.. method:: logical_or(x, y)
Applies the logical operation `or` between each operand's digits.
Applies the logical operation *or* between each operand's digits.
.. method:: logical_xor(x, y)
Applies the logical operation `xor` between each operand's digits.
Applies the logical operation *xor* between each operand's digits.
.. method:: max(x, y)
@ -1294,8 +1294,8 @@ In addition to the three supplied contexts, new contexts can be created with the
.. method:: remainder_near(x, y)
Returns `x - y * n`, where *n* is the integer nearest the exact value
of `x / y` (if the result is `0` then its sign will be the sign of *x*).
Returns ``x - y * n``, where *n* is the integer nearest the exact value
of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
.. method:: rotate(x, y)

View file

@ -57,14 +57,14 @@ Here are the classes:
.. currentmodule:: email.mime.multipart
.. class:: MIMEMultipart([subtype[, boundary[, _subparts[, _params]]]])
.. class:: MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]])
Module: :mod:`email.mime.multipart`
A subclass of :class:`MIMEBase`, this is an intermediate base class for MIME
messages that are :mimetype:`multipart`. Optional *_subtype* defaults to
:mimetype:`mixed`, but can be used to specify the subtype of the message. A
:mailheader:`Content-Type` header of :mimetype:`multipart/`*_subtype* will be
:mailheader:`Content-Type` header of :mimetype:`multipart/_subtype` will be
added to the message object. A :mailheader:`MIME-Version` header will also be
added.

View file

@ -101,11 +101,11 @@ another rational number, or from a string.
.. function:: gcd(a, b)
Return the greatest common divisor of the integers `a` and `b`. If
either `a` or `b` is nonzero, then the absolute value of `gcd(a,
b)` is the largest integer that divides both `a` and `b`. `gcd(a,b)`
has the same sign as `b` if `b` is nonzero; otherwise it takes the sign
of `a`. `gcd(0, 0)` returns `0`.
Return the greatest common divisor of the integers *a* and *b*. If either
*a* or *b* is nonzero, then the absolute value of ``gcd(a, b)`` is the
largest integer that divides both *a* and *b*. ``gcd(a,b)`` has the same
sign as *b* if *b* is nonzero; otherwise it takes the sign of *a*. ``gcd(0,
0)`` returns ``0``.
.. seealso::

View file

@ -648,10 +648,9 @@ translation until later. A classic example is::
animals = ['mollusk',
'albatross',
'rat',
'penguin',
'python',
]
'rat',
'penguin',
'python', ]
# ...
for a in animals:
print a
@ -666,10 +665,9 @@ Here is one way you can handle this situation::
animals = [_('mollusk'),
_('albatross'),
_('rat'),
_('penguin'),
_('python'),
]
_('rat'),
_('penguin'),
_('python'), ]
del _
@ -692,10 +690,9 @@ Another way to handle this is with the following example::
animals = [N_('mollusk'),
N_('albatross'),
N_('rat'),
N_('penguin'),
N_('python'),
]
N_('rat'),
N_('penguin'),
N_('python'), ]
# ...
for a in animals:

View file

@ -7,7 +7,7 @@
This module provides a simple interface to compress and decompress files just
like the GNU programs :program:`gzip` and :program:`gunzip` would.
The data compression is provided by the :mod:``zlib`` module.
The data compression is provided by the :mod:`zlib` module.
The :mod:`gzip` module provides the :class:`GzipFile` class which is modeled
after Python's File Object. The :class:`GzipFile` class reads and writes

View file

@ -547,7 +547,7 @@ can be combined.
.. doctest::
# Show a dictionary sorted and grouped by value
>>> # Show a dictionary sorted and grouped by value
>>> from operator import itemgetter
>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
>>> di = sorted(d.iteritems(), key=itemgetter(1))
@ -558,9 +558,9 @@ can be combined.
2 ['b', 'd', 'f']
3 ['g']
# Find runs of consecutive numbers using groupby. The key to the solution
# is differencing with a range so that consecutive numbers all appear in
# same group.
>>> # Find runs of consecutive numbers using groupby. The key to the solution
>>> # is differencing with a range so that consecutive numbers all appear in
>>> # same group.
>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
>>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
... print map(itemgetter(1), g)

View file

@ -152,7 +152,7 @@ Basic Usage
*default(obj)* is a function that should return a serializable version of
*obj* or raise :exc:`TypeError`. The default simply raises :exc:`TypeError`.
To use a custom :class:`JSONEncoder`` subclass (e.g. one that overrides the
To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
:meth:`default` method to serialize additional types), specify it with the
*cls* kwarg.

View file

@ -37,7 +37,7 @@ Windows.
>>> from multiprocessing import Pool
>>> p = Pool(5)
>>> def f(x):
... return x*x
... return x*x
...
>>> p.map(f, [1,2,3])
Process PoolWorker-1:
@ -109,12 +109,12 @@ processes:
def f(q):
q.put([42, None, 'hello'])
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()
Queues are thread and process safe.
@ -1138,18 +1138,18 @@ their parent process exits. The manager classes are defined in the
Returns a :class:`Server` object which represents the actual server under
the control of the Manager. The :class:`Server` object supports the
:meth:`serve_forever` method::
:meth:`serve_forever` method:
>>> from multiprocessing.managers import BaseManager
>>> m = BaseManager(address=('', 50000), authkey='abc'))
>>> server = m.get_server()
>>> s.serve_forever()
>>> from multiprocessing.managers import BaseManager
>>> m = BaseManager(address=('', 50000), authkey='abc'))
>>> server = m.get_server()
>>> s.serve_forever()
:class:`Server` additionally have an :attr:`address` attribute.
:class:`Server` additionally have an :attr:`address` attribute.
.. method:: connect()
Connect a local manager object to a remote manager process::
Connect a local manager object to a remote manager process:
>>> from multiprocessing.managers import BaseManager
>>> m = BaseManager(address='127.0.0.1', authkey='abc))
@ -1295,7 +1295,7 @@ Customized managers
>>>>>>>>>>>>>>>>>>>
To create one's own manager, one creates a subclass of :class:`BaseManager` and
use the :meth:`~BaseManager.resgister` classmethod to register new types or
use the :meth:`~BaseManager.register` classmethod to register new types or
callables with the manager class. For example::
from multiprocessing.managers import BaseManager
@ -1811,7 +1811,7 @@ Address Formats
* An ``'AF_PIPE'`` address is a string of the form
:samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named
pipe on a remote computer called ServerName* one should use an address of the
pipe on a remote computer called *ServerName* one should use an address of the
form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'`` instead.
Note that any string beginning with two backslashes is assumed by default to be

View file

@ -51,14 +51,14 @@ The numeric tower
:func:`round`, :func:`math.floor`, :func:`math.ceil`, :func:`divmod`, ``//``,
``%``, ``<``, ``<=``, ``>``, and ``>=``.
Real also provides defaults for :func:`complex`, :attr:`Complex.real`,
:attr:`Complex.imag`, and :meth:`Complex.conjugate`.
Real also provides defaults for :func:`complex`, :attr:`~Complex.real`,
:attr:`~Complex.imag`, and :meth:`~Complex.conjugate`.
.. class:: Rational
Subtypes :class:`Real` and adds
:attr:`Rational.numerator` and :attr:`Rational.denominator` properties, which
:attr:`~Rational.numerator` and :attr:`~Rational.denominator` properties, which
should be in lowest terms. With these, it provides a default for
:func:`float`.
@ -74,8 +74,8 @@ The numeric tower
.. class:: Integral
Subtypes :class:`Rational` and adds a conversion to :class:`int`.
Provides defaults for :func:`float`, :attr:`Rational.numerator`, and
:attr:`Rational.denominator`, and bit-string operations: ``<<``,
Provides defaults for :func:`float`, :attr:`~Rational.numerator`, and
:attr:`~Rational.denominator`, and bit-string operations: ``<<``,
``>>``, ``&``, ``^``, ``|``, ``~``.
@ -171,7 +171,7 @@ Complex``. I'll consider ``a + b``:
knowledge of ``A``, so it can handle those instances before
delegating to :class:`Complex`.
If ``A<:Complex`` and ``B<:Real`` without sharing any other knowledge,
If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge,
then the appropriate shared operation is the one involving the built
in :class:`complex`, and both :meth:`__radd__` s land there, so ``a+b
== b+a``.

View file

@ -548,8 +548,8 @@ Continuing with the parser defined above, adding an
:class:`OptionGroup` to a parser is easy::
group = OptionGroup(parser, "Dangerous Options",
"Caution: use these options at your own risk. "
"It is believed that some of them bite.")
"Caution: use these options at your own risk. "
"It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)
@ -563,12 +563,12 @@ This would result in the following help output::
-q, --quiet be vewwy quiet (I'm hunting wabbits)
-fFILE, --file=FILE write output to FILE
-mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
[default], 'expert'
[default], 'expert'
Dangerous Options:
Caution: use of these options is at your own risk. It is believed that
some of them bite.
-g Group option.
Caution: use of these options is at your own risk. It is believed that
some of them bite.
-g Group option.
.. _optparse-printing-version-string:

View file

@ -641,7 +641,7 @@ on the same line as the definition of the code block, as in ::
while the long form uses an indented block and allows nested definitions::
def make_power(exp):
"Make a function that raises an argument to the exponent `exp'."
"Make a function that raises an argument to the exponent `exp`."
def raiser(x, y=exp):
return x ** y
return raiser

View file

@ -125,15 +125,15 @@ The use of dynamic dispatching by :meth:`Repr.repr1` allows subclasses of
the handling of types already supported. This example shows how special support
for file objects could be added::
import repr
import repr as reprlib
import sys
class MyRepr(repr.Repr):
class MyRepr(reprlib.Repr):
def repr_file(self, obj, level):
if obj.name in ['<stdin>', '<stdout>', '<stderr>']:
return obj.name
else:
return `obj`
return repr(obj)
aRepr = MyRepr()
print aRepr.repr(sys.stdin) # prints '<stdin>'

View file

@ -58,7 +58,7 @@ Example::
... print time.time()
... Timer(5, print_time, ()).start()
... Timer(10, print_time, ()).start()
... time.sleep(11) # sleep while time-delay events execute
... time.sleep(11) # sleep while time-delay events execute
... print time.time()
...
>>> print_some_times()

View file

@ -207,7 +207,7 @@ An :class:`SMTP` instance has the following methods:
previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO``
first.
:exc:SMTPHeloError
:exc:`SMTPHeloError`
The server didn't reply properly to the ``HELO`` greeting.
.. versionadded:: 2.6

View file

@ -852,20 +852,21 @@ sends traffic to the first one connected successfully. ::
HOST = None # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
s = socket.socket(af, socktype, proto)
except socket.error, msg:
s = None
continue
s = None
continue
try:
s.bind(sa)
s.listen(1)
s.bind(sa)
s.listen(1)
except socket.error, msg:
s.close()
s = None
continue
s.close()
s = None
continue
break
if s is None:
print 'could not open socket'
@ -890,16 +891,16 @@ sends traffic to the first one connected successfully. ::
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
s = socket.socket(af, socktype, proto)
except socket.error, msg:
s = None
continue
s = None
continue
try:
s.connect(sa)
s.connect(sa)
except socket.error, msg:
s.close()
s = None
continue
s.close()
s = None
continue
break
if s is None:
print 'could not open socket'

View file

@ -7,9 +7,9 @@
.. note::
The :mod:`SocketServer` module has been renamed to `socketserver` in Python
3.0. The :term:`2to3` tool will automatically adapt imports when converting
your sources to 3.0.
The :mod:`SocketServer` module has been renamed to :mod:`socketserver` in
Python 3.0. The :term:`2to3` tool will automatically adapt imports when
converting your sources to 3.0.
The :mod:`SocketServer` module simplifies the task of writing network servers.

View file

@ -164,11 +164,11 @@ The module defines the following user-callable functions:
.. warning::
Use of this function may introduce a security hole in your program.
By the time you get around to doing anything with the file name it
returns, someone else may have beaten you to the punch.
:func:`mktemp` usage can be replaced easily with
:func:`NamedTemporaryFile`, passing it the `delete=False` parameter::
Use of this function may introduce a security hole in your program. By
the time you get around to doing anything with the file name it returns,
someone else may have beaten you to the punch. :func:`mktemp` usage can
be replaced easily with :func:`NamedTemporaryFile`, passing it the
``delete=False`` parameter::
>>> f = NamedTemporaryFile(delete=False)
>>> f

View file

@ -290,7 +290,7 @@ described in those functions, as well as provide an additional method:
.. versionadded:: 2.5
The following classes provide the implementations of the parse results::
The following classes provide the implementations of the parse results:
.. class:: BaseResult

View file

@ -560,8 +560,8 @@ transport. The following example shows how:
self.proxy = proxy
def make_connection(self, host):
self.realhost = host
h = httplib.HTTP(self.proxy)
return h
h = httplib.HTTP(self.proxy)
return h
def send_request(self, connection, handler, request_body):
connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
def send_host(self, connection, host):

View file

@ -124,7 +124,7 @@ Terms and conditions for accessing or otherwise using Python
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python |release| alone or in any derivative
version, provided, however, that PSF's License Agreement and PSF's notice of
copyright, i.e., "Copyright © 2001-2008 Python Software Foundation; All Rights
copyright, i.e., "Copyright © 2001-2009 Python Software Foundation; All Rights
Reserved" are retained in Python |release| alone or in any derivative version
prepared by Licensee.
@ -453,7 +453,7 @@ The source code for the :mod:`md5` module contains the following notice::
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
@ -464,12 +464,12 @@ The source code for the :mod:`md5` module contains the following notice::
that follows (in reverse chronological order):
2002-04-13 lpd Removed support for non-ANSI compilers; removed
references to Ghostscript; clarified derivation from RFC 1321;
now handles byte order either statically or dynamically.
references to Ghostscript; clarified derivation from RFC 1321;
now handles byte order either statically or dynamically.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
added conditionalization for C++ compilation from Martin
Purschke <purschke@bnl.gov>.
added conditionalization for C++ compilation from Martin
Purschke <purschke@bnl.gov>.
1999-05-03 lpd Original version.

230
Doc/tools/rstlint.py Executable file
View file

@ -0,0 +1,230 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Check for stylistic and formal issues in .rst and .py
# files included in the documentation.
#
# 01/2009, Georg Brandl
from __future__ import with_statement
import os
import re
import sys
import getopt
import subprocess
from os.path import join, splitext, abspath, exists
from collections import defaultdict
directives = [
# standard docutils ones
'admonition', 'attention', 'caution', 'class', 'compound', 'container',
'contents', 'csv-table', 'danger', 'date', 'default-role', 'epigraph',
'error', 'figure', 'footer', 'header', 'highlights', 'hint', 'image',
'important', 'include', 'line-block', 'list-table', 'meta', 'note',
'parsed-literal', 'pull-quote', 'raw', 'replace',
'restructuredtext-test-directive', 'role', 'rubric', 'sectnum', 'sidebar',
'table', 'target-notes', 'tip', 'title', 'topic', 'unicode', 'warning',
# Sphinx custom ones
'acks', 'attribute', 'autoattribute', 'autoclass', 'autodata',
'autoexception', 'autofunction', 'automethod', 'automodule', 'centered',
'cfunction', 'class', 'classmethod', 'cmacro', 'cmdoption', 'cmember',
'code-block', 'confval', 'cssclass', 'ctype', 'currentmodule', 'cvar',
'data', 'deprecated', 'describe', 'directive', 'doctest', 'envvar', 'event',
'exception', 'function', 'glossary', 'highlight', 'highlightlang', 'index',
'literalinclude', 'method', 'module', 'moduleauthor', 'productionlist',
'program', 'role', 'sectionauthor', 'seealso', 'sourcecode', 'staticmethod',
'tabularcolumns', 'testcode', 'testoutput', 'testsetup', 'toctree', 'todo',
'todolist', 'versionadded', 'versionchanged'
]
all_directives = '(' + '|'.join(directives) + ')'
seems_directive_re = re.compile(r'\.\. %s([^a-z:]|:(?!:))' % all_directives)
default_role_re = re.compile(r'(^| )`\w([^`]*?\w)?`($| )')
leaked_markup_re = re.compile(r'[a-z]::[^=]|:[a-z]+:|`|\.\.\s*\w+:')
checkers = {}
checker_props = {'severity': 1, 'falsepositives': False}
def checker(*suffixes, **kwds):
"""Decorator to register a function as a checker."""
def deco(func):
for suffix in suffixes:
checkers.setdefault(suffix, []).append(func)
for prop in checker_props:
setattr(func, prop, kwds.get(prop, checker_props[prop]))
return func
return deco
@checker('.py', severity=4)
def check_syntax(fn, lines):
"""Check Python examples for valid syntax."""
try:
code = ''.join(lines)
if '\r' in code:
if os.name != 'nt':
yield 0, '\\r in code file'
code = code.replace('\r', '')
compile(code, fn, 'exec')
except SyntaxError, err:
yield err.lineno, 'not compilable: %s' % err
@checker('.rst', severity=2)
def check_suspicious_constructs(fn, lines):
"""Check for suspicious reST constructs."""
inprod = False
for lno, line in enumerate(lines):
if seems_directive_re.match(line):
yield lno+1, 'comment seems to be intended as a directive'
if '.. productionlist::' in line:
inprod = True
elif not inprod and default_role_re.search(line):
yield lno+1, 'default role used'
elif inprod and not line.strip():
inprod = False
@checker('.py', '.rst')
def check_whitespace(fn, lines):
"""Check for whitespace and line length issues."""
for lno, line in enumerate(lines):
if '\r' in line:
yield lno+1, '\\r in line'
if '\t' in line:
yield lno+1, 'OMG TABS!!!1'
if line[:-1].rstrip(' \t') != line[:-1]:
yield lno+1, 'trailing whitespace'
@checker('.rst', severity=0)
def check_line_length(fn, lines):
"""Check for line length; this checker is not run by default."""
for lno, line in enumerate(lines):
if len(line) > 81:
# don't complain about tables, links and function signatures
if line.lstrip()[0] not in '+|' and \
'http://' not in line and \
not line.lstrip().startswith(('.. function',
'.. method',
'.. cfunction')):
yield lno+1, "line too long"
@checker('.html', severity=2, falsepositives=True)
def check_leaked_markup(fn, lines):
"""Check HTML files for leaked reST markup; this only works if
the HTML files have been built.
"""
for lno, line in enumerate(lines):
if leaked_markup_re.search(line):
yield lno+1, 'possibly leaked markup: %r' % line
def main(argv):
usage = '''\
Usage: %s [-v] [-f] [-s sev] [-i path]* [path]
Options: -v verbose (print all checked file names)
-f enable checkers that yield many false positives
-s sev only show problems with severity >= sev
-i path ignore subdir or file path
''' % argv[0]
try:
gopts, args = getopt.getopt(argv[1:], 'vfs:i:')
except getopt.GetoptError:
print usage
return 2
verbose = False
severity = 1
ignore = []
falsepos = False
for opt, val in gopts:
if opt == '-v':
verbose = True
elif opt == '-f':
falsepos = True
elif opt == '-s':
severity = int(val)
elif opt == '-i':
ignore.append(abspath(val))
if len(args) == 0:
path = '.'
elif len(args) == 1:
path = args[0]
else:
print usage
return 2
if not exists(path):
print 'Error: path %s does not exist' % path
return 2
count = defaultdict(int)
out = sys.stdout
for root, dirs, files in os.walk(path):
# ignore subdirs controlled by svn
if '.svn' in dirs:
dirs.remove('.svn')
# ignore subdirs in ignore list
if abspath(root) in ignore:
del dirs[:]
continue
for fn in files:
fn = join(root, fn)
if fn[:2] == './':
fn = fn[2:]
# ignore files in ignore list
if abspath(fn) in ignore:
continue
ext = splitext(fn)[1]
checkerlist = checkers.get(ext, None)
if not checkerlist:
continue
if verbose:
print 'Checking %s...' % fn
try:
with open(fn, 'r') as f:
lines = list(f)
except (IOError, OSError), err:
print '%s: cannot open: %s' % (fn, err)
count[4] += 1
continue
for checker in checkerlist:
if checker.falsepositives and not falsepos:
continue
csev = checker.severity
if csev >= severity:
for lno, msg in checker(fn, lines):
print >>out, '[%d] %s:%d: %s' % (csev, fn, lno, msg)
count[csev] += 1
if verbose:
print
if not count:
if severity > 1:
print 'No problems with severity >= %d found.' % severity
else:
print 'No problems found.'
else:
for severity in sorted(count):
number = count[severity]
print '%d problem%s with severity %d found.' % \
(number, number > 1 and 's' or '', severity)
return int(bool(count))
if __name__ == '__main__':
sys.exit(main(sys.argv))

View file

@ -251,7 +251,7 @@ would evaluate to a tuple, it must be parenthesized. ::
[]
>>> [[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
>>> [x, x**2 for x in vec] # error - parens required for tuples
>>> [x, x**2 for x in vec] # error - parens required for tuples
File "<stdin>", line 1, in ?
[x, x**2 for x in vec]
^

View file

@ -148,7 +148,7 @@ Positional and keyword arguments can be arbitrarily combined::
... other='Georg')
The story of Bill, Manfred, and Georg.
An optional ``':``` and format specifier can follow the field name. This also
An optional ``':'`` and format specifier can follow the field name. This also
greater control over how the value is formatted. The following example
truncates the Pi to three places after the decimal.

View file

@ -62,7 +62,7 @@ formatting numbers with group separators::
>>> locale.format("%d", x, grouping=True)
'1,234,567'
>>> locale.format("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
... conv['frac_digits'], x), grouping=True)
'$1,234,567.80'

View file

@ -404,7 +404,7 @@ These environment variables influence Python's behavior.
compiled form). Extension modules cannot be imported from zipfiles.
The default search path is installation dependent, but generally begins with
:file:`{prefix}/lib/python{version}`` (see :envvar:`PYTHONHOME` above). It
:file:`{prefix}/lib/python{version}` (see :envvar:`PYTHONHOME` above). It
is *always* appended to :envvar:`PYTHONPATH`.
An additional directory will be inserted in the search path in front of

View file

@ -281,7 +281,7 @@ write the following to do it::
# containing the substring S.
sublist = filter( lambda s, substring=S:
string.find(s, substring) != -1,
L)
L)
Because of Python's scoping rules, a default argument is used so that the
anonymous function created by the :keyword:`lambda` statement knows what
@ -293,7 +293,7 @@ List comprehensions have the form::
[ expression for expr in sequence1
for expr2 in sequence2 ...
for exprN in sequenceN
for exprN in sequenceN
if condition ]
The :keyword:`for`...\ :keyword:`in` clauses contain the sequences to be
@ -368,7 +368,7 @@ instance with an incremented value.
def __init__(self, value):
self.value = value
def __iadd__(self, increment):
return Number( self.value + increment)
return Number( self.value + increment)
n = Number(5)
n += 3
@ -852,13 +852,12 @@ the PyXML package::
from distutils.core import setup, Extension
expat_extension = Extension('xml.parsers.pyexpat',
define_macros = [('XML_NS', None)],
include_dirs = [ 'extensions/expat/xmltok',
'extensions/expat/xmlparse' ],
sources = [ 'extensions/pyexpat.c',
'extensions/expat/xmltok/xmltok.c',
'extensions/expat/xmltok/xmlrole.c',
]
define_macros = [('XML_NS', None)],
include_dirs = [ 'extensions/expat/xmltok',
'extensions/expat/xmlparse' ],
sources = [ 'extensions/pyexpat.c',
'extensions/expat/xmltok/xmltok.c',
'extensions/expat/xmltok/xmlrole.c', ]
)
setup (name = "PyXML", version = "0.5.4",
ext_modules =[ expat_extension ] )

View file

@ -295,7 +295,7 @@ will be used in methods to call a method in the superclass; for example,
class D (B,C):
def save (self):
# Call superclass .save()
# Call superclass .save()
super(D, self).save()
# Save D's private information here
...

View file

@ -396,10 +396,10 @@ single class called :class:`Popen` whose constructor supports a number of
different keyword arguments. ::
class Popen(args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0):
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0):
*args* is commonly a sequence of strings that will be the arguments to the
program executed as the subprocess. (If the *shell* argument is true, *args*
@ -1428,7 +1428,7 @@ Running the above function's tests with :const:`doctest.REPORT_UDIFF` specified,
you get the following output::
**********************************************************************
File ``t.py'', line 15, in g
File "t.py", line 15, in g
Failed example:
g(4)
Differences (unified diff with -expected +actual):

View file

@ -485,7 +485,7 @@ And here's an example of changing the counter::
9
>>> print it.next()
Traceback (most recent call last):
File ``t.py'', line 15, in ?
File "t.py", line 15, in ?
print it.next()
StopIteration

View file

@ -586,30 +586,30 @@ multiple of 4.
def factorial(queue, N):
"Compute a factorial."
# If N is a multiple of 4, this function will take much longer.
if (N % 4) == 0:
time.sleep(.05 * N/4)
"Compute a factorial."
# If N is a multiple of 4, this function will take much longer.
if (N % 4) == 0:
time.sleep(.05 * N/4)
# Calculate the result
fact = 1L
for i in range(1, N+1):
fact = fact * i
# Calculate the result
fact = 1L
for i in range(1, N+1):
fact = fact * i
# Put the result on the queue
queue.put(fact)
# Put the result on the queue
queue.put(fact)
if __name__ == '__main__':
queue = Queue()
queue = Queue()
N = 5
N = 5
p = Process(target=factorial, args=(queue, N))
p.start()
p.join()
p = Process(target=factorial, args=(queue, N))
p.start()
p.join()
result = queue.get()
print 'Factorial', N, '=', result
result = queue.get()
print 'Factorial', N, '=', result
A :class:`Queue` is used to communicate the input parameter *N* and
the result. The :class:`Queue` object is stored in a global variable.
@ -630,12 +630,12 @@ across 5 worker processes and retrieve a list of results::
from multiprocessing import Pool
def factorial(N, dictionary):
"Compute a factorial."
...
"Compute a factorial."
...
p = Pool(5)
result = p.map(factorial, range(1, 1000, 10))
for v in result:
print v
print v
This produces the following output::
@ -1885,9 +1885,9 @@ changes, or look through the Subversion logs for all the details.
('id', 'name', 'type', 'size')
>>> var = var_type(1, 'frequency', 'int', 4)
>>> print var[0], var.id # Equivalent
>>> print var[0], var.id # Equivalent
1 1
>>> print var[2], var.type # Equivalent
>>> print var[2], var.type # Equivalent
int int
>>> var._asdict()
{'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
@ -2046,8 +2046,8 @@ changes, or look through the Subversion logs for all the details.
>>> list(itertools.product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6),
(2, 4), (2, 5), (2, 6),
(3, 4), (3, 5), (3, 6)]
(2, 4), (2, 5), (2, 6),
(3, 4), (3, 5), (3, 6)]
The optional *repeat* keyword argument is used for taking the
product of an iterable or a set of iterables with themselves,

17
LICENSE
View file

@ -88,15 +88,14 @@ PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
otherwise using this software ("Python") in source or binary form and
its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python
alone or in any derivative version, provided, however, that PSF's
License Agreement and PSF's notice of copyright, i.e., "Copyright (c)
2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Python Software Foundation;
All Rights Reserved" are retained in Python alone or in any derivative
version prepared by Licensee.
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative version,
provided, however, that PSF's License Agreement and PSF's notice of copyright,
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Python
Software Foundation; All Rights Reserved" are retained in Python alone or in any
derivative version prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python or any part thereof, and wants to make

View file

@ -573,7 +573,7 @@ def GetArgv(optionlist=None, commandlist=None, addoldfile=1, addnewfile=1, addfo
del d
def _process_Nav_args(dftflags, **args):
import aepack
import Carbon.AppleEvents
import Carbon.AE
import Carbon.File
for k in args.keys():
@ -585,11 +585,14 @@ def _process_Nav_args(dftflags, **args):
if args.has_key('defaultLocation') and \
not isinstance(args['defaultLocation'], Carbon.AE.AEDesc):
defaultLocation = args['defaultLocation']
if isinstance(defaultLocation, (Carbon.File.FSSpec, Carbon.File.FSRef)):
args['defaultLocation'] = aepack.pack(defaultLocation)
if isinstance(defaultLocation, Carbon.File.FSSpec):
args['defaultLocation'] = Carbon.AE.AECreateDesc(
Carbon.AppleEvents.typeFSS, defaultLocation.data)
else:
defaultLocation = Carbon.File.FSRef(defaultLocation)
args['defaultLocation'] = aepack.pack(defaultLocation)
if not isinstance(defaultLocation, Carbon.File.FSRef):
defaultLocation = Carbon.File.FSRef(defaultLocation)
args['defaultLocation'] = Carbon.AE.AECreateDesc(
Carbon.AppleEvents.typeFSRef, defaultLocation.data)
if args.has_key('typeList') and not isinstance(args['typeList'], Carbon.Res.ResourceType):
typeList = args['typeList'][:]
# Workaround for OSX typeless files:

View file

@ -62,7 +62,14 @@ def mkdirs(dst):
if os.sep == ':' and not ':' in head:
head = head + ':'
mkdirs(head)
os.mkdir(dst, 0777)
try:
os.mkdir(dst, 0777)
except OSError, e:
# be happy if someone already created the path
if e.errno != errno.EEXIST:
raise
def touched(dst):
"""Tell the finder a file has changed. No-op on MacOSX."""

View file

@ -18,7 +18,7 @@ from Carbon import Qdoffs
from Carbon import QDOffscreen
from Carbon import Res
try:
import MediaDescr
from Carbon import MediaDescr
except ImportError:
def _audiodescr(data):
return None

View file

@ -420,7 +420,7 @@ class TestBasic(unittest.TestCase):
gc.collect()
def test_container_iterator(self):
# Bug # XXX: tp_traverse was not implemented for deque iterator objects
# Bug #3680: tp_traverse was not implemented for deque iterator objects
class C(object):
pass
for i in range(2):

View file

@ -556,7 +556,7 @@ class DictTest(unittest.TestCase):
d = {}
def test_container_iterator(self):
# Bug # XXX: tp_traverse was not implemented for dictiter objects
# Bug #3680: tp_traverse was not implemented for dictiter objects
class C(object):
pass
iterators = (dict.iteritems, dict.itervalues, dict.iterkeys)

View file

@ -324,7 +324,7 @@ class TestJointOps(unittest.TestCase):
self.assertEqual(d3, dict.fromkeys(d, 123))
def test_container_iterator(self):
# Bug # XXX: tp_traverse was not implemented for set iterator object
# Bug #3680: tp_traverse was not implemented for set iterator object
class C(object):
pass
obj = C()

View file

@ -773,8 +773,8 @@ altbininstall: $(BUILDPYTHON)
done
$(INSTALL_PROGRAM) $(BUILDPYTHON) $(DESTDIR)$(BINDIR)/python$(VERSION)$(EXE)
if test -f $(LDLIBRARY); then \
if test "$(SO)" = .dll; then \
$(INSTALL_SHARED) $(LDLIBRARY) $(DESTDIR)$(BINDIR); \
if test -n "$(DLLLIBRARY)" ; then \
$(INSTALL_SHARED) $(DLLLIBRARY) $(DESTDIR)$(BINDIR); \
else \
$(INSTALL_SHARED) $(LDLIBRARY) $(DESTDIR)$(LIBDIR)/$(INSTSONAME); \
if test $(LDLIBRARY) != $(INSTSONAME); then \
@ -909,7 +909,7 @@ $(srcdir)/Lib/$(PLATDIR):
export PYTHONPATH; PYTHONPATH="`pwd`/Lib"; \
export DYLD_FRAMEWORK_PATH; DYLD_FRAMEWORK_PATH="`pwd`"; \
export EXE; EXE="$(BUILDEXE)"; \
cd $(srcdir)/Lib/$(PLATDIR); ./regen
cd $(srcdir)/Lib/$(PLATDIR); $(RUNSHARED) ./regen
# Install the include files
INCLDIRSTOMAKE=$(INCLUDEDIR) $(CONFINCLUDEDIR) $(INCLUDEPY) $(CONFINCLUDEPY)

View file

@ -12,6 +12,11 @@ What's New in Python 2.6.2
Core and Builtins
-----------------
- Issue #4075: Use OutputDebugStringW in Py_FatalError.
- Issue #4797: IOError.filename was not set when _fileio.FileIO failed to open
file with `str' filename on Windows.
- Issue #3680: Reference cycles created through a dict, set or deque iterator
did not get collected.
@ -233,6 +238,14 @@ Library
- Issue #4730: Fixed the cPickle module to handle correctly astral characters
when protocol 0 is used.
- Issue #16278952: plat-mac/videoreader.py now correctly imports MediaDescr
- Issue #1737832 : plat-mac/EasyDialog.py no longer uses the broken aepack
module.
- Issue #1149804: macostools.mkdirs now even works when another process
creates one of the needed subdirectories.
Tools/Demos
-----------
@ -241,6 +254,8 @@ Tools/Demos
Build
-----
- Issue #4472: "configure --enable-shared" now works on OSX
- Issues #4728 and #4060: WORDS_BIGEDIAN is now correct in Universal builds.
- Issue #4389: Add icon to the uninstall entry in "add-and-remove-programs".
@ -273,6 +288,8 @@ C-API
Extension Modules
-----------------
- Issue #4051: Prevent conflict of UNICODE macros in cPickle.
- Issue #4228: Pack negative values the same way as 2.4 in struct's L format.
- Issue #1040026: Fix os.times result on systems where HZ is incorrect.

View file

@ -967,7 +967,7 @@ deque_iter(dequeobject *deque)
it->deque = deque;
it->state = deque->state;
it->counter = deque->len;
_PyObject_GC_TRACK(it);
PyObject_GC_Track(it);
return (PyObject *)it;
}
@ -1077,7 +1077,7 @@ deque_reviter(dequeobject *deque)
it->deque = deque;
it->state = deque->state;
it->counter = deque->len;
_PyObject_GC_TRACK(it);
PyObject_GC_Track(it);
return (PyObject *)it;
}

View file

@ -265,10 +265,11 @@ fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
Py_END_ALLOW_THREADS
if (self->fd < 0) {
#ifdef MS_WINDOWS
PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
#else
PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
if (widename != NULL)
PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
else
#endif
PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
goto error;
}
if(dircheck(self, name) < 0)

View file

@ -17,6 +17,14 @@ PyDoc_STRVAR(cPickle_module_documentation,
/* Bump this when new opcodes are added to the pickle protocol. */
#define HIGHEST_PROTOCOL 2
/*
* Note: The UNICODE macro controls the TCHAR meaning of the win32 API. Since
* all headers have already been included here, we can safely redefine it.
*/
#ifdef UNICODE
# undef UNICODE
#endif
/*
* Pickle opcodes. These must be kept in synch with pickle.py. Extensive
* docs are in pickletools.py.

View file

@ -167,7 +167,7 @@ class ASDLParser(spark.GenericParser, object):
return Product(fields)
def p_sum_0(self, (constructor,)):
" sum ::= constructor """
" sum ::= constructor "
return [constructor]
def p_sum_1(self, (constructor, _, sum)):

View file

@ -4,7 +4,7 @@
static char cprt[] =
"\
Copyright (c) 2001-2008 Python Software Foundation.\n\
Copyright (c) 2001-2009 Python Software Foundation.\n\
All Rights Reserved.\n\
\n\
Copyright (c) 2000 BeOpen.com.\n\

View file

@ -22,6 +22,10 @@
#include <signal.h>
#endif
#ifdef MS_WINDOWS
#include "malloc.h" /* for alloca */
#endif
#ifdef HAVE_LANGINFO_H
#include <locale.h>
#include <langinfo.h>
@ -1628,9 +1632,21 @@ Py_FatalError(const char *msg)
{
fprintf(stderr, "Fatal Python error: %s\n", msg);
#ifdef MS_WINDOWS
OutputDebugString("Fatal Python error: ");
OutputDebugString(msg);
OutputDebugString("\n");
{
size_t len = strlen(msg);
WCHAR* buffer;
size_t i;
/* Convert the message to wchar_t. This uses a simple one-to-one
conversion, assuming that the this error message actually uses ASCII
only. If this ceases to be true, we will have to convert. */
buffer = alloca( (len+1) * (sizeof *buffer));
for( i=0; i<=len; ++i)
buffer[i] = msg[i];
OutputDebugStringW(L"Fatal Python error: ");
OutputDebugStringW(buffer);
OutputDebugStringW(L"\n");
}
#ifdef _DEBUG
DebugBreak();
#endif

2
README
View file

@ -1,7 +1,7 @@
This is Python version 2.6.1
============================
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
Python Software Foundation.
All rights reserved.