mirror of https://github.com/python/cpython
Merged revisions 68221 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r68221 | georg.brandl | 2009-01-03 22:04:55 +0100 (Sat, 03 Jan 2009) | 2 lines Remove tabs from the documentation. ........
This commit is contained in:
parent
48310cd3f2
commit
a1c6a1cea5
|
@ -823,8 +823,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. ::
|
previous sections. We will break down the main differences between them. ::
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
PyListObject list;
|
PyListObject list;
|
||||||
int state;
|
int state;
|
||||||
} Shoddy;
|
} Shoddy;
|
||||||
|
|
||||||
The primary difference for derived type objects is that the base type's object
|
The primary difference for derived type objects is that the base type's object
|
||||||
|
@ -837,10 +837,10 @@ be safely cast to both *PyListObject\** and *Shoddy\**. ::
|
||||||
static int
|
static int
|
||||||
Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds)
|
Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds)
|
||||||
{
|
{
|
||||||
if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
|
if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
|
||||||
return -1;
|
return -1;
|
||||||
self->state = 0;
|
self->state = 0;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
In the :attr:`__init__` method for our type, we can see how to call through to
|
In the :attr:`__init__` method for our type, we can see how to call through to
|
||||||
|
@ -859,18 +859,18 @@ the module's :cfunc:`init` function. ::
|
||||||
PyMODINIT_FUNC
|
PyMODINIT_FUNC
|
||||||
PyInit_shoddy(void)
|
PyInit_shoddy(void)
|
||||||
{
|
{
|
||||||
PyObject *m;
|
PyObject *m;
|
||||||
|
|
||||||
ShoddyType.tp_base = &PyList_Type;
|
ShoddyType.tp_base = &PyList_Type;
|
||||||
if (PyType_Ready(&ShoddyType) < 0)
|
if (PyType_Ready(&ShoddyType) < 0)
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
m = PyModule_Create(&shoddymodule);
|
m = PyModule_Create(&shoddymodule);
|
||||||
if (m == NULL)
|
if (m == NULL)
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
Py_INCREF(&ShoddyType);
|
Py_INCREF(&ShoddyType);
|
||||||
PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
|
PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
|
||||||
}
|
}
|
||||||
|
|
||||||
Before calling :cfunc:`PyType_Ready`, the type structure must have the
|
Before calling :cfunc:`PyType_Ready`, the type structure must have the
|
||||||
|
@ -1113,7 +1113,7 @@ structure::
|
||||||
typedef struct PyMethodDef {
|
typedef struct PyMethodDef {
|
||||||
char *ml_name; /* method name */
|
char *ml_name; /* method name */
|
||||||
PyCFunction ml_meth; /* implementation function */
|
PyCFunction ml_meth; /* implementation function */
|
||||||
int ml_flags; /* flags */
|
int ml_flags; /* flags */
|
||||||
char *ml_doc; /* docstring */
|
char *ml_doc; /* docstring */
|
||||||
} PyMethodDef;
|
} PyMethodDef;
|
||||||
|
|
||||||
|
|
|
@ -297,7 +297,7 @@ So, to display a reverse-video status line on the top line of the screen, you
|
||||||
could code::
|
could code::
|
||||||
|
|
||||||
stdscr.addstr(0, 0, "Current mode: Typing mode",
|
stdscr.addstr(0, 0, "Current mode: Typing mode",
|
||||||
curses.A_REVERSE)
|
curses.A_REVERSE)
|
||||||
stdscr.refresh()
|
stdscr.refresh()
|
||||||
|
|
||||||
The curses library also supports color on those terminals that provide it, The
|
The curses library also supports color on those terminals that provide it, The
|
||||||
|
|
|
@ -917,7 +917,7 @@ module::
|
||||||
|
|
||||||
InternalDate = re.compile(r'INTERNALDATE "'
|
InternalDate = re.compile(r'INTERNALDATE "'
|
||||||
r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
|
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<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' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
|
||||||
r'"')
|
r'"')
|
||||||
|
|
|
@ -189,30 +189,30 @@ length message::
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, sock=None):
|
def __init__(self, sock=None):
|
||||||
if sock is None:
|
if sock is None:
|
||||||
self.sock = socket.socket(
|
self.sock = socket.socket(
|
||||||
socket.AF_INET, socket.SOCK_STREAM)
|
socket.AF_INET, socket.SOCK_STREAM)
|
||||||
else:
|
else:
|
||||||
self.sock = sock
|
self.sock = sock
|
||||||
|
|
||||||
def connect(self, host, port):
|
def connect(self, host, port):
|
||||||
self.sock.connect((host, port))
|
self.sock.connect((host, port))
|
||||||
|
|
||||||
def mysend(self, msg):
|
def mysend(self, msg):
|
||||||
totalsent = 0
|
totalsent = 0
|
||||||
while totalsent < MSGLEN:
|
while totalsent < MSGLEN:
|
||||||
sent = self.sock.send(msg[totalsent:])
|
sent = self.sock.send(msg[totalsent:])
|
||||||
if sent == 0:
|
if sent == 0:
|
||||||
raise RuntimeError("socket connection broken")
|
raise RuntimeError("socket connection broken")
|
||||||
totalsent = totalsent + sent
|
totalsent = totalsent + sent
|
||||||
|
|
||||||
def myreceive(self):
|
def myreceive(self):
|
||||||
msg = ''
|
msg = ''
|
||||||
while len(msg) < MSGLEN:
|
while len(msg) < MSGLEN:
|
||||||
chunk = self.sock.recv(MSGLEN-len(msg))
|
chunk = self.sock.recv(MSGLEN-len(msg))
|
||||||
if chunk == '':
|
if chunk == '':
|
||||||
raise RuntimeError("socket connection broken")
|
raise RuntimeError("socket connection broken")
|
||||||
msg = msg + chunk
|
msg = msg + chunk
|
||||||
return msg
|
return msg
|
||||||
|
|
||||||
The sending code here is usable for almost any messaging scheme - in Python you
|
The sending code here is usable for almost any messaging scheme - in Python you
|
||||||
|
|
|
@ -32,8 +32,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
|
looking at Apple ][ BASIC programs, published in French-language publications in
|
||||||
the mid-1980s, that had lines like these::
|
the mid-1980s, that had lines like these::
|
||||||
|
|
||||||
PRINT "FICHIER EST COMPLETE."
|
PRINT "FICHIER EST COMPLETE."
|
||||||
PRINT "CARACTERE NON ACCEPTE."
|
PRINT "CARACTERE NON ACCEPTE."
|
||||||
|
|
||||||
Those messages should contain accents, and they just look wrong to someone who
|
Those messages should contain accents, and they just look wrong to someone who
|
||||||
can read French.
|
can read French.
|
||||||
|
@ -91,11 +91,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
|
character with value 0x12ca (4810 decimal). The Unicode standard contains a lot
|
||||||
of tables listing characters and their corresponding code points::
|
of tables listing characters and their corresponding code points::
|
||||||
|
|
||||||
0061 'a'; LATIN SMALL LETTER A
|
0061 'a'; LATIN SMALL LETTER A
|
||||||
0062 'b'; LATIN SMALL LETTER B
|
0062 'b'; LATIN SMALL LETTER B
|
||||||
0063 'c'; LATIN SMALL LETTER C
|
0063 'c'; LATIN SMALL LETTER C
|
||||||
...
|
...
|
||||||
007B '{'; LEFT CURLY BRACKET
|
007B '{'; LEFT CURLY BRACKET
|
||||||
|
|
||||||
Strictly, these definitions imply that it's meaningless to say 'this is
|
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
|
character U+12ca'. U+12ca is a code point, which represents some particular
|
||||||
|
@ -527,19 +527,19 @@ path will return the byte string versions of the filenames. For example,
|
||||||
assuming the default filesystem encoding is UTF-8, running the following
|
assuming the default filesystem encoding is UTF-8, running the following
|
||||||
program::
|
program::
|
||||||
|
|
||||||
fn = 'filename\u4500abc'
|
fn = 'filename\u4500abc'
|
||||||
f = open(fn, 'w')
|
f = open(fn, 'w')
|
||||||
f.close()
|
f.close()
|
||||||
|
|
||||||
import os
|
import os
|
||||||
print(os.listdir(b'.'))
|
print(os.listdir(b'.'))
|
||||||
print(os.listdir('.'))
|
print(os.listdir('.'))
|
||||||
|
|
||||||
will produce the following output::
|
will produce the following output::
|
||||||
|
|
||||||
amk:~$ python t.py
|
amk:~$ python t.py
|
||||||
[b'.svn', b'filename\xe4\x94\x80abc', ...]
|
[b'.svn', b'filename\xe4\x94\x80abc', ...]
|
||||||
['.svn', 'filename\u4500abc', ...]
|
['.svn', 'filename\u4500abc', ...]
|
||||||
|
|
||||||
The first list contains UTF-8-encoded filenames, and the second list contains
|
The first list contains UTF-8-encoded filenames, and the second list contains
|
||||||
the Unicode versions.
|
the Unicode versions.
|
||||||
|
@ -636,26 +636,26 @@ Version 1.1: Feb-Nov 2008. Updates the document with respect to Python 3 change
|
||||||
- [ ] Unicode introduction
|
- [ ] Unicode introduction
|
||||||
- [ ] ASCII
|
- [ ] ASCII
|
||||||
- [ ] Terms
|
- [ ] Terms
|
||||||
- [ ] Character
|
- [ ] Character
|
||||||
- [ ] Code point
|
- [ ] Code point
|
||||||
- [ ] Encodings
|
- [ ] Encodings
|
||||||
- [ ] Common encodings: ASCII, Latin-1, UTF-8
|
- [ ] Common encodings: ASCII, Latin-1, UTF-8
|
||||||
- [ ] Unicode Python type
|
- [ ] Unicode Python type
|
||||||
- [ ] Writing unicode literals
|
- [ ] Writing unicode literals
|
||||||
- [ ] Obscurity: -U switch
|
- [ ] Obscurity: -U switch
|
||||||
- [ ] Built-ins
|
- [ ] Built-ins
|
||||||
- [ ] unichr()
|
- [ ] unichr()
|
||||||
- [ ] ord()
|
- [ ] ord()
|
||||||
- [ ] unicode() constructor
|
- [ ] unicode() constructor
|
||||||
- [ ] Unicode type
|
- [ ] Unicode type
|
||||||
- [ ] encode(), decode() methods
|
- [ ] encode(), decode() methods
|
||||||
- [ ] Unicodedata module for character properties
|
- [ ] Unicodedata module for character properties
|
||||||
- [ ] I/O
|
- [ ] I/O
|
||||||
- [ ] Reading/writing Unicode data into files
|
- [ ] Reading/writing Unicode data into files
|
||||||
- [ ] Byte-order marks
|
- [ ] Byte-order marks
|
||||||
- [ ] Unicode filenames
|
- [ ] Unicode filenames
|
||||||
- [ ] Writing Unicode programs
|
- [ ] Writing Unicode programs
|
||||||
- [ ] Do everything in Unicode
|
- [ ] Do everything in Unicode
|
||||||
- [ ] Declaring source code encodings (PEP 263)
|
- [ ] Declaring source code encodings (PEP 263)
|
||||||
- [ ] Other issues
|
- [ ] Other issues
|
||||||
- [ ] Building Python (UCS2, UCS4)
|
- [ ] Building Python (UCS2, UCS4)
|
||||||
|
|
|
@ -42,15 +42,15 @@ This module provides the following class:
|
||||||
Register *subclass* as a "virtual subclass" of this ABC. For
|
Register *subclass* as a "virtual subclass" of this ABC. For
|
||||||
example::
|
example::
|
||||||
|
|
||||||
from abc import ABCMeta
|
from abc import ABCMeta
|
||||||
|
|
||||||
class MyABC(metaclass=ABCMeta):
|
class MyABC(metaclass=ABCMeta):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
MyABC.register(tuple)
|
MyABC.register(tuple)
|
||||||
|
|
||||||
assert issubclass(tuple, MyABC)
|
assert issubclass(tuple, MyABC)
|
||||||
assert isinstance((), MyABC)
|
assert isinstance((), MyABC)
|
||||||
|
|
||||||
You can also override this method in an abstract base class:
|
You can also override this method in an abstract base class:
|
||||||
|
|
||||||
|
|
|
@ -41,7 +41,7 @@ ABC Inherits Abstract Methods Mixin
|
||||||
:class:`Hashable` ``__hash__``
|
:class:`Hashable` ``__hash__``
|
||||||
:class:`Iterable` ``__iter__``
|
:class:`Iterable` ``__iter__``
|
||||||
:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
|
:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
|
||||||
:class:`Sized` ``__len__``
|
:class:`Sized` ``__len__``
|
||||||
:class:`Callable` ``__call__``
|
:class:`Callable` ``__call__``
|
||||||
|
|
||||||
:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``.
|
:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``.
|
||||||
|
@ -68,7 +68,7 @@ ABC Inherits Abstract Methods Mixin
|
||||||
:class:`MutableMapping` :class:`Mapping` ``__getitem__`` Inherited Mapping methods and
|
:class:`MutableMapping` :class:`Mapping` ``__getitem__`` Inherited Mapping methods and
|
||||||
``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``,
|
``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``,
|
||||||
``__delitem__``, and ``setdefault``
|
``__delitem__``, and ``setdefault``
|
||||||
``__iter__``, and
|
``__iter__``, and
|
||||||
``__len__``
|
``__len__``
|
||||||
|
|
||||||
:class:`MappingView` :class:`Sized` ``__len__``
|
:class:`MappingView` :class:`Sized` ``__len__``
|
||||||
|
@ -84,7 +84,7 @@ particular functionality, for example::
|
||||||
|
|
||||||
size = None
|
size = None
|
||||||
if isinstance(myvar, collections.Sized):
|
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
|
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
|
classes supporting container APIs. For example, to write a class supporting
|
||||||
|
|
|
@ -551,10 +551,9 @@ translation until later. A classic example is::
|
||||||
|
|
||||||
animals = ['mollusk',
|
animals = ['mollusk',
|
||||||
'albatross',
|
'albatross',
|
||||||
'rat',
|
'rat',
|
||||||
'penguin',
|
'penguin',
|
||||||
'python',
|
'python', ]
|
||||||
]
|
|
||||||
# ...
|
# ...
|
||||||
for a in animals:
|
for a in animals:
|
||||||
print(a)
|
print(a)
|
||||||
|
@ -569,10 +568,9 @@ Here is one way you can handle this situation::
|
||||||
|
|
||||||
animals = [_('mollusk'),
|
animals = [_('mollusk'),
|
||||||
_('albatross'),
|
_('albatross'),
|
||||||
_('rat'),
|
_('rat'),
|
||||||
_('penguin'),
|
_('penguin'),
|
||||||
_('python'),
|
_('python'), ]
|
||||||
]
|
|
||||||
|
|
||||||
del _
|
del _
|
||||||
|
|
||||||
|
@ -595,10 +593,9 @@ Another way to handle this is with the following example::
|
||||||
|
|
||||||
animals = [N_('mollusk'),
|
animals = [N_('mollusk'),
|
||||||
N_('albatross'),
|
N_('albatross'),
|
||||||
N_('rat'),
|
N_('rat'),
|
||||||
N_('penguin'),
|
N_('penguin'),
|
||||||
N_('python'),
|
N_('python'), ]
|
||||||
]
|
|
||||||
|
|
||||||
# ...
|
# ...
|
||||||
for a in animals:
|
for a in animals:
|
||||||
|
|
|
@ -35,7 +35,7 @@ Windows.
|
||||||
>>> from multiprocessing import Pool
|
>>> from multiprocessing import Pool
|
||||||
>>> p = Pool(5)
|
>>> p = Pool(5)
|
||||||
>>> def f(x):
|
>>> def f(x):
|
||||||
... return x*x
|
... return x*x
|
||||||
...
|
...
|
||||||
>>> p.map(f, [1,2,3])
|
>>> p.map(f, [1,2,3])
|
||||||
Process PoolWorker-1:
|
Process PoolWorker-1:
|
||||||
|
|
|
@ -543,8 +543,8 @@ Continuing with the parser defined above, adding an
|
||||||
:class:`OptionGroup` to a parser is easy::
|
:class:`OptionGroup` to a parser is easy::
|
||||||
|
|
||||||
group = OptionGroup(parser, "Dangerous Options",
|
group = OptionGroup(parser, "Dangerous Options",
|
||||||
"Caution: use these options at your own risk. "
|
"Caution: use these options at your own risk. "
|
||||||
"It is believed that some of them bite.")
|
"It is believed that some of them bite.")
|
||||||
group.add_option("-g", action="store_true", help="Group option.")
|
group.add_option("-g", action="store_true", help="Group option.")
|
||||||
parser.add_option_group(group)
|
parser.add_option_group(group)
|
||||||
|
|
||||||
|
@ -558,12 +558,12 @@ This would result in the following help output::
|
||||||
-q, --quiet be vewwy quiet (I'm hunting wabbits)
|
-q, --quiet be vewwy quiet (I'm hunting wabbits)
|
||||||
-fFILE, --file=FILE write output to FILE
|
-fFILE, --file=FILE write output to FILE
|
||||||
-mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
|
-mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
|
||||||
[default], 'expert'
|
[default], 'expert'
|
||||||
|
|
||||||
Dangerous Options:
|
Dangerous Options:
|
||||||
Caution: use of these options is at your own risk. It is believed that
|
Caution: use of these options is at your own risk. It is believed that
|
||||||
some of them bite.
|
some of them bite.
|
||||||
-g Group option.
|
-g Group option.
|
||||||
|
|
||||||
.. _optparse-printing-version-string:
|
.. _optparse-printing-version-string:
|
||||||
|
|
||||||
|
|
|
@ -58,7 +58,7 @@ Example::
|
||||||
... print(time.time())
|
... print(time.time())
|
||||||
... Timer(5, print_time, ()).start()
|
... Timer(5, print_time, ()).start()
|
||||||
... Timer(10, 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(time.time())
|
||||||
...
|
...
|
||||||
>>> print_some_times()
|
>>> print_some_times()
|
||||||
|
|
|
@ -797,17 +797,17 @@ sends traffic to the first one connected successfully. ::
|
||||||
socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
|
socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
|
||||||
af, socktype, proto, canonname, sa = res
|
af, socktype, proto, canonname, sa = res
|
||||||
try:
|
try:
|
||||||
s = socket.socket(af, socktype, proto)
|
s = socket.socket(af, socktype, proto)
|
||||||
except socket.error as msg:
|
except socket.error as msg:
|
||||||
s = None
|
s = None
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
s.bind(sa)
|
s.bind(sa)
|
||||||
s.listen(1)
|
s.listen(1)
|
||||||
except socket.error as msg:
|
except socket.error as msg:
|
||||||
s.close()
|
s.close()
|
||||||
s = None
|
s = None
|
||||||
continue
|
continue
|
||||||
break
|
break
|
||||||
if s is None:
|
if s is None:
|
||||||
print('could not open socket')
|
print('could not open socket')
|
||||||
|
@ -832,16 +832,16 @@ sends traffic to the first one connected successfully. ::
|
||||||
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
|
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
|
||||||
af, socktype, proto, canonname, sa = res
|
af, socktype, proto, canonname, sa = res
|
||||||
try:
|
try:
|
||||||
s = socket.socket(af, socktype, proto)
|
s = socket.socket(af, socktype, proto)
|
||||||
except socket.error as msg:
|
except socket.error as msg:
|
||||||
s = None
|
s = None
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
s.connect(sa)
|
s.connect(sa)
|
||||||
except socket.error as msg:
|
except socket.error as msg:
|
||||||
s.close()
|
s.close()
|
||||||
s = None
|
s = None
|
||||||
continue
|
continue
|
||||||
break
|
break
|
||||||
if s is None:
|
if s is None:
|
||||||
print('could not open socket')
|
print('could not open socket')
|
||||||
|
|
|
@ -195,7 +195,7 @@ Using the :keyword:`if` clause we can filter the stream::
|
||||||
|
|
||||||
Tuples can often be created without their parentheses, but not here::
|
Tuples can often be created without their parentheses, but not here::
|
||||||
|
|
||||||
>>> [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 ?
|
File "<stdin>", line 1, in ?
|
||||||
[x, x**2 for x in vec]
|
[x, x**2 for x in vec]
|
||||||
^
|
^
|
||||||
|
|
|
@ -62,7 +62,7 @@ formatting numbers with group separators::
|
||||||
>>> locale.format("%d", x, grouping=True)
|
>>> locale.format("%d", x, grouping=True)
|
||||||
'1,234,567'
|
'1,234,567'
|
||||||
>>> locale.format("%s%.*f", (conv['currency_symbol'],
|
>>> locale.format("%s%.*f", (conv['currency_symbol'],
|
||||||
... conv['frac_digits'], x), grouping=True)
|
... conv['frac_digits'], x), grouping=True)
|
||||||
'$1,234,567.80'
|
'$1,234,567.80'
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -281,7 +281,7 @@ write the following to do it::
|
||||||
# containing the substring S.
|
# containing the substring S.
|
||||||
sublist = filter( lambda s, substring=S:
|
sublist = filter( lambda s, substring=S:
|
||||||
string.find(s, substring) != -1,
|
string.find(s, substring) != -1,
|
||||||
L)
|
L)
|
||||||
|
|
||||||
Because of Python's scoping rules, a default argument is used so that the
|
Because of Python's scoping rules, a default argument is used so that the
|
||||||
anonymous function created by the :keyword:`lambda` statement knows what
|
anonymous function created by the :keyword:`lambda` statement knows what
|
||||||
|
@ -293,7 +293,7 @@ List comprehensions have the form::
|
||||||
|
|
||||||
[ expression for expr in sequence1
|
[ expression for expr in sequence1
|
||||||
for expr2 in sequence2 ...
|
for expr2 in sequence2 ...
|
||||||
for exprN in sequenceN
|
for exprN in sequenceN
|
||||||
if condition ]
|
if condition ]
|
||||||
|
|
||||||
The :keyword:`for`...\ :keyword:`in` clauses contain the sequences to be
|
The :keyword:`for`...\ :keyword:`in` clauses contain the sequences to be
|
||||||
|
@ -368,7 +368,7 @@ instance with an incremented value.
|
||||||
def __init__(self, value):
|
def __init__(self, value):
|
||||||
self.value = value
|
self.value = value
|
||||||
def __iadd__(self, increment):
|
def __iadd__(self, increment):
|
||||||
return Number( self.value + increment)
|
return Number( self.value + increment)
|
||||||
|
|
||||||
n = Number(5)
|
n = Number(5)
|
||||||
n += 3
|
n += 3
|
||||||
|
@ -852,13 +852,12 @@ the PyXML package::
|
||||||
from distutils.core import setup, Extension
|
from distutils.core import setup, Extension
|
||||||
|
|
||||||
expat_extension = Extension('xml.parsers.pyexpat',
|
expat_extension = Extension('xml.parsers.pyexpat',
|
||||||
define_macros = [('XML_NS', None)],
|
define_macros = [('XML_NS', None)],
|
||||||
include_dirs = [ 'extensions/expat/xmltok',
|
include_dirs = [ 'extensions/expat/xmltok',
|
||||||
'extensions/expat/xmlparse' ],
|
'extensions/expat/xmlparse' ],
|
||||||
sources = [ 'extensions/pyexpat.c',
|
sources = [ 'extensions/pyexpat.c',
|
||||||
'extensions/expat/xmltok/xmltok.c',
|
'extensions/expat/xmltok/xmltok.c',
|
||||||
'extensions/expat/xmltok/xmlrole.c',
|
'extensions/expat/xmltok/xmlrole.c', ]
|
||||||
]
|
|
||||||
)
|
)
|
||||||
setup (name = "PyXML", version = "0.5.4",
|
setup (name = "PyXML", version = "0.5.4",
|
||||||
ext_modules =[ expat_extension ] )
|
ext_modules =[ expat_extension ] )
|
||||||
|
|
|
@ -295,7 +295,7 @@ will be used in methods to call a method in the superclass; for example,
|
||||||
|
|
||||||
class D (B,C):
|
class D (B,C):
|
||||||
def save (self):
|
def save (self):
|
||||||
# Call superclass .save()
|
# Call superclass .save()
|
||||||
super(D, self).save()
|
super(D, self).save()
|
||||||
# Save D's private information here
|
# Save D's private information here
|
||||||
...
|
...
|
||||||
|
|
|
@ -396,10 +396,10 @@ single class called :class:`Popen` whose constructor supports a number of
|
||||||
different keyword arguments. ::
|
different keyword arguments. ::
|
||||||
|
|
||||||
class Popen(args, bufsize=0, executable=None,
|
class Popen(args, bufsize=0, executable=None,
|
||||||
stdin=None, stdout=None, stderr=None,
|
stdin=None, stdout=None, stderr=None,
|
||||||
preexec_fn=None, close_fds=False, shell=False,
|
preexec_fn=None, close_fds=False, shell=False,
|
||||||
cwd=None, env=None, universal_newlines=False,
|
cwd=None, env=None, universal_newlines=False,
|
||||||
startupinfo=None, creationflags=0):
|
startupinfo=None, creationflags=0):
|
||||||
|
|
||||||
*args* is commonly a sequence of strings that will be the arguments to the
|
*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*
|
program executed as the subprocess. (If the *shell* argument is true, *args*
|
||||||
|
|
|
@ -590,30 +590,30 @@ multiple of 4.
|
||||||
|
|
||||||
|
|
||||||
def factorial(queue, N):
|
def factorial(queue, N):
|
||||||
"Compute a factorial."
|
"Compute a factorial."
|
||||||
# If N is a multiple of 4, this function will take much longer.
|
# If N is a multiple of 4, this function will take much longer.
|
||||||
if (N % 4) == 0:
|
if (N % 4) == 0:
|
||||||
time.sleep(.05 * N/4)
|
time.sleep(.05 * N/4)
|
||||||
|
|
||||||
# Calculate the result
|
# Calculate the result
|
||||||
fact = 1L
|
fact = 1L
|
||||||
for i in range(1, N+1):
|
for i in range(1, N+1):
|
||||||
fact = fact * i
|
fact = fact * i
|
||||||
|
|
||||||
# Put the result on the queue
|
# Put the result on the queue
|
||||||
queue.put(fact)
|
queue.put(fact)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
queue = Queue()
|
queue = Queue()
|
||||||
|
|
||||||
N = 5
|
N = 5
|
||||||
|
|
||||||
p = Process(target=factorial, args=(queue, N))
|
p = Process(target=factorial, args=(queue, N))
|
||||||
p.start()
|
p.start()
|
||||||
p.join()
|
p.join()
|
||||||
|
|
||||||
result = queue.get()
|
result = queue.get()
|
||||||
print 'Factorial', N, '=', result
|
print 'Factorial', N, '=', result
|
||||||
|
|
||||||
A :class:`Queue` is used to communicate the input parameter *N* and
|
A :class:`Queue` is used to communicate the input parameter *N* and
|
||||||
the result. The :class:`Queue` object is stored in a global variable.
|
the result. The :class:`Queue` object is stored in a global variable.
|
||||||
|
@ -634,12 +634,12 @@ across 5 worker processes and retrieve a list of results::
|
||||||
from multiprocessing import Pool
|
from multiprocessing import Pool
|
||||||
|
|
||||||
def factorial(N, dictionary):
|
def factorial(N, dictionary):
|
||||||
"Compute a factorial."
|
"Compute a factorial."
|
||||||
...
|
...
|
||||||
p = Pool(5)
|
p = Pool(5)
|
||||||
result = p.map(factorial, range(1, 1000, 10))
|
result = p.map(factorial, range(1, 1000, 10))
|
||||||
for v in result:
|
for v in result:
|
||||||
print v
|
print v
|
||||||
|
|
||||||
This produces the following output::
|
This produces the following output::
|
||||||
|
|
||||||
|
@ -1889,9 +1889,9 @@ changes, or look through the Subversion logs for all the details.
|
||||||
('id', 'name', 'type', 'size')
|
('id', 'name', 'type', 'size')
|
||||||
|
|
||||||
>>> var = var_type(1, 'frequency', 'int', 4)
|
>>> var = var_type(1, 'frequency', 'int', 4)
|
||||||
>>> print var[0], var.id # Equivalent
|
>>> print var[0], var.id # Equivalent
|
||||||
1 1
|
1 1
|
||||||
>>> print var[2], var.type # Equivalent
|
>>> print var[2], var.type # Equivalent
|
||||||
int int
|
int int
|
||||||
>>> var._asdict()
|
>>> var._asdict()
|
||||||
{'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
|
{'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
|
||||||
|
@ -2050,8 +2050,8 @@ changes, or look through the Subversion logs for all the details.
|
||||||
|
|
||||||
>>> list(itertools.product([1,2,3], [4,5,6]))
|
>>> list(itertools.product([1,2,3], [4,5,6]))
|
||||||
[(1, 4), (1, 5), (1, 6),
|
[(1, 4), (1, 5), (1, 6),
|
||||||
(2, 4), (2, 5), (2, 6),
|
(2, 4), (2, 5), (2, 6),
|
||||||
(3, 4), (3, 5), (3, 6)]
|
(3, 4), (3, 5), (3, 6)]
|
||||||
|
|
||||||
The optional *repeat* keyword argument is used for taking the
|
The optional *repeat* keyword argument is used for taking the
|
||||||
product of an iterable or a set of iterables with themselves,
|
product of an iterable or a set of iterables with themselves,
|
||||||
|
|
Loading…
Reference in New Issue