Merged revisions 74210,74239,74252-74253,74256,74258-74261,74332-74333,74404,74411,74445,74465,74467,74488 via svnmerge from

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

........
  r74210 | georg.brandl | 2009-07-26 16:44:23 +0200 (So, 26 Jul 2009) | 1 line

  Move member descriptions inside the classes.
........
  r74239 | georg.brandl | 2009-07-28 20:55:32 +0200 (Di, 28 Jul 2009) | 1 line

  Clarify quote_plus() usage.
........
  r74252 | georg.brandl | 2009-07-29 18:06:31 +0200 (Mi, 29 Jul 2009) | 1 line

  #6593: fix link targets.
........
  r74253 | georg.brandl | 2009-07-29 18:09:17 +0200 (Mi, 29 Jul 2009) | 1 line

  #6591: add reference to ioctl in fcntl module for platforms other than Windows.
........
  r74256 | georg.brandl | 2009-07-29 18:32:30 +0200 (Mi, 29 Jul 2009) | 1 line

  #6336: Add nb_divide.
........
  r74258 | georg.brandl | 2009-07-29 18:57:05 +0200 (Mi, 29 Jul 2009) | 1 line

  Add a link to readline, and mention IPython and bpython.
........
  r74259 | georg.brandl | 2009-07-29 19:07:21 +0200 (Mi, 29 Jul 2009) | 1 line

  Fix some markup and small factual glitches found by M. Markert.
........
  r74260 | georg.brandl | 2009-07-29 19:15:20 +0200 (Mi, 29 Jul 2009) | 1 line

  Fix a few markup glitches.
........
  r74261 | georg.brandl | 2009-07-29 19:50:25 +0200 (Mi, 29 Jul 2009) | 1 line

  Rewrite the section about classes a bit; mostly tidbits, and a larger update to the section about "private" variables to reflect the Pythonic consensus better.
........
  r74332 | georg.brandl | 2009-08-06 19:23:21 +0200 (Do, 06 Aug 2009) | 1 line

  Fix punctuation and one copy-paste error.
........
  r74333 | georg.brandl | 2009-08-06 19:43:55 +0200 (Do, 06 Aug 2009) | 1 line

  #6658: fix two typos.
........
  r74404 | georg.brandl | 2009-08-13 14:05:52 +0200 (Do, 13 Aug 2009) | 1 line

  Use locale.format_string() for more than one specifier.
........
  r74411 | georg.brandl | 2009-08-13 14:57:25 +0200 (Do, 13 Aug 2009) | 2 lines

  Remove potentially confusing sentence in __mangling description.
........
  r74445 | vinay.sajip | 2009-08-14 13:33:54 +0200 (Fr, 14 Aug 2009) | 1 line

  Added versionchanged notices for optional 'delay' parameter to file handler classes.
........
  r74465 | vinay.sajip | 2009-08-16 01:23:12 +0200 (So, 16 Aug 2009) | 1 line

  Added section on logging to one file from multiple processes.
........
  r74467 | vinay.sajip | 2009-08-16 01:34:47 +0200 (So, 16 Aug 2009) | 1 line

  Refined section on logging to one file from multiple processes.
........
  r74488 | vinay.sajip | 2009-08-17 15:14:37 +0200 (Mo, 17 Aug 2009) | 1 line

  Further refined section on logging to one file from multiple processes.
........
This commit is contained in:
Georg Brandl 2009-10-27 14:41:50 +00:00
parent 4ae4f876a2
commit 46e9daa3ae
13 changed files with 326 additions and 285 deletions

View File

@ -147,7 +147,7 @@ Buffer related functions
kind of buffer the caller is prepared to deal with and therefore what
kind of buffer the exporter is allowed to return. The buffer interface
allows for complicated memory sharing possibilities, but some caller may
not be able to handle all the complexibity but may want to see if the
not be able to handle all the complexity but may want to see if the
exporter will let them take a simpler view to its memory.
Some exporters may not be able to share memory in every possible way and
@ -255,7 +255,7 @@ Buffer related functions
.. cfunction:: void PyBuffer_Release(PyObject *obj, Py_buffer *view)
Release the buffer *view* over *obj*. This shouldd be called when the buffer
Release the buffer *view* over *obj*. This should be called when the buffer
is no longer being used as it may free memory from it.

View File

@ -1160,6 +1160,7 @@ Number Object Structures
binaryfunc nb_add;
binaryfunc nb_subtract;
binaryfunc nb_multiply;
binaryfunc nb_divide;
binaryfunc nb_remainder;
binaryfunc nb_divmod;
ternaryfunc nb_power;

View File

@ -208,10 +208,10 @@ the built-in namespace as the function :func:`_`.
This installs the function :func:`_` in Python's builtins namespace, based on
*domain*, *localedir*, and *codeset* which are passed to the function
:func:`translation`. The *unicode* flag is passed to the resulting translation
object's :meth:`install` method.
object's :meth:`~NullTranslations.install` method.
For the *names* parameter, please see the description of the translation
object's :meth:`install` method.
object's :meth:`~NullTranslations.install` method.
As seen below, you usually mark the strings in your application that are
candidates for translation, by wrapping them in a call to the :func:`_`

View File

@ -1321,6 +1321,31 @@ When this script is run, the output should look something like this::
The :class:`LoggerAdapter` class was not present in previous versions.
.. _multiple-processes:
Logging to a single file from multiple processes
------------------------------------------------
Although logging is thread-safe, and logging to a single file from multiple
threads in a single process *is* supported, logging to a single file from
*multiple processes* is *not* supported, because there is no standard way to
serialize access to a single file across multiple processes in Python. If you
need to log to a single file from multiple processes, the best way of doing
this is to have all the processes log to a :class:`SocketHandler`, and have a
separate process which implements a socket server which reads from the socket
and logs to file. (If you prefer, you can dedicate one thread in one of the
existing processes to perform this function.) The following section documents
this approach in more detail and includes a working socket receiver which can
be used as a starting point for you to adapt in your own applications.
If you are using a recent version of Python which includes the
:mod:`multiprocessing` module, you can write your own handler which uses the
:class:`Lock` class from this module to serialize access to the file from
your processes. The existing :class:`FileHandler` and subclasses do not make
use of :mod:`multiprocessing` at present, though they may do so in the future.
Note that at present, the :mod:`multiprocessing` module does not provide
working lock functionality on all platforms (see
http://bugs.python.org/issue3770).
.. _network-logging:
@ -1613,6 +1638,8 @@ sends logging output to a disk file. It inherits the output functionality from
with that encoding. If *delay* is true, then file opening is deferred until the
first call to :meth:`emit`. By default, the file grows indefinitely.
.. versionchanged:: 2.6
*delay* was added.
.. method:: close()
@ -1661,6 +1688,9 @@ this value.
with that encoding. If *delay* is true, then file opening is deferred until the
first call to :meth:`emit`. By default, the file grows indefinitely.
.. versionchanged:: 2.6
*delay* was added.
.. method:: emit(record)
@ -1698,6 +1728,8 @@ module, supports rotation of disk log files.
:file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
:file:`app.log.2`, :file:`app.log.3` etc. respectively.
.. versionchanged:: 2.6
*delay* was added.
.. method:: doRollover()
@ -1757,6 +1789,11 @@ timed intervals.
one is deleted. The deletion logic uses the interval to determine which
files to delete, so changing the interval may leave old files lying around.
If *delay* is true, then file opening is deferred until the first call to
:meth:`emit`.
.. versionchanged:: 2.6
*delay* was added.
.. method:: doRollover()

View File

@ -307,7 +307,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
.. attribute:: kevent.filter
Name of the kernel filter
Name of the kernel filter.
+---------------------------+---------------------------------------------+
| Constant | Meaning |
@ -316,7 +316,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
| | there is data available to read |
+---------------------------+---------------------------------------------+
| :const:`KQ_FILTER_WRITE` | Takes a descriptor and returns whenever |
| | there is data available to read |
| | there is data available to write |
+---------------------------+---------------------------------------------+
| :const:`KQ_FILTER_AIO` | AIO requests |
+---------------------------+---------------------------------------------+
@ -336,7 +336,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
.. attribute:: kevent.flags
Filter action
Filter action.
+---------------------------+---------------------------------------------+
| Constant | Meaning |
@ -365,10 +365,9 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
.. attribute:: kevent.fflags
Filter specific flags
Filter specific flags.
:const:`KQ_FILTER_READ` and :const:`KQ_FILTER_WRITE` filter flags
:const:`KQ_FILTER_READ` and :const:`KQ_FILTER_WRITE` filter flags:
+----------------------------+--------------------------------------------+
| Constant | Meaning |
@ -376,8 +375,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
| :const:`KQ_NOTE_LOWAT` | low water mark of a socket buffer |
+----------------------------+--------------------------------------------+
:const:`KQ_FILTER_VNODE` filter flags
:const:`KQ_FILTER_VNODE` filter flags:
+----------------------------+--------------------------------------------+
| Constant | Meaning |
@ -397,8 +395,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
| :const:`KQ_NOTE_REVOKE` | access to the file was revoked |
+----------------------------+--------------------------------------------+
:const:`KQ_FILTER_PROC` filter flags
:const:`KQ_FILTER_PROC` filter flags:
+----------------------------+--------------------------------------------+
| Constant | Meaning |
@ -421,7 +418,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
| :const:`KQ_NOTE_TRACKERR` | unable to attach to a child |
+----------------------------+--------------------------------------------+
:const:`KQ_FILTER_NETDEV` filter flags [not available on Mac OS X]
:const:`KQ_FILTER_NETDEV` filter flags (not available on Mac OS X):
+----------------------------+--------------------------------------------+
| Constant | Meaning |
@ -436,9 +433,9 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
.. attribute:: kevent.data
Filter specific data
Filter specific data.
.. attribute:: kevent.udata
User defined value
User defined value.

View File

@ -604,6 +604,9 @@ correspond to Unix system calls applicable to sockets.
The :meth:`ioctl` method is a limited interface to the WSAIoctl system
interface. Please refer to the MSDN documentation for more information.
On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl`
functions may be used; they accept a socket object as their first argument.
.. versionadded:: 2.6

View File

@ -231,7 +231,8 @@ impossible to detect the termination of alien threads.
.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
This constructor should always be called with keyword arguments. Arguments are:
This constructor should always be called with keyword arguments. Arguments
are:
*group* should be ``None``; reserved for future extension when a
:class:`ThreadGroup` class is implemented.
@ -239,112 +240,104 @@ impossible to detect the termination of alien threads.
*target* is the callable object to be invoked by the :meth:`run` method.
Defaults to ``None``, meaning nothing is called.
*name* is the thread name. By default, a unique name is constructed of the form
"Thread-*N*" where *N* is a small decimal number.
*name* is the thread name. By default, a unique name is constructed of the
form "Thread-*N*" where *N* is a small decimal number.
*args* is the argument tuple for the target invocation. Defaults to ``()``.
*kwargs* is a dictionary of keyword arguments for the target invocation.
Defaults to ``{}``.
If the subclass overrides the constructor, it must make sure to invoke the base
class constructor (``Thread.__init__()``) before doing anything else to the
thread.
If the subclass overrides the constructor, it must make sure to invoke the
base class constructor (``Thread.__init__()``) before doing anything else to
the thread.
.. method:: start()
.. method:: Thread.start()
Start the thread's activity.
Start the thread's activity.
It must be called at most once per thread object. It arranges for the
object's :meth:`run` method to be invoked in a separate thread of control.
It must be called at most once per thread object. It arranges for the object's
:meth:`run` method to be invoked in a separate thread of control.
This method will raise a :exc:`RuntimeException` if called more than once
on the same thread object.
This method will raise a :exc:`RuntimeException` if called more than once on the
same thread object.
.. method:: run()
Method representing the thread's activity.
.. method:: Thread.run()
You may override this method in a subclass. The standard :meth:`run`
method invokes the callable object passed to the object's constructor as
the *target* argument, if any, with sequential and keyword arguments taken
from the *args* and *kwargs* arguments, respectively.
Method representing the thread's activity.
.. method:: join([timeout])
You may override this method in a subclass. The standard :meth:`run` method
invokes the callable object passed to the object's constructor as the *target*
argument, if any, with sequential and keyword arguments taken from the *args*
and *kwargs* arguments, respectively.
Wait until the thread terminates. This blocks the calling thread until the
thread whose :meth:`join` method is called terminates -- either normally
or through an unhandled exception -- or until the optional timeout occurs.
When the *timeout* argument is present and not ``None``, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). As :meth:`join` always returns ``None``, you must
call :meth:`isAlive` after :meth:`join` to decide whether a timeout
happened -- if the thread is still alive, the :meth:`join` call timed out.
.. method:: Thread.join([timeout])
When the *timeout* argument is not present or ``None``, the operation will
block until the thread terminates.
Wait until the thread terminates. This blocks the calling thread until the
thread whose :meth:`join` method is called terminates -- either normally or
through an unhandled exception -- or until the optional timeout occurs.
A thread can be :meth:`join`\ ed many times.
When the *timeout* argument is present and not ``None``, it should be a floating
point number specifying a timeout for the operation in seconds (or fractions
thereof). As :meth:`join` always returns ``None``, you must call :meth:`isAlive`
after :meth:`join` to decide whether a timeout happened -- if the thread is
still alive, the :meth:`join` call timed out.
:meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
the current thread as that would cause a deadlock. It is also an error to
:meth:`join` a thread before it has been started and attempts to do so
raises the same exception.
When the *timeout* argument is not present or ``None``, the operation will block
until the thread terminates.
.. method:: getName()
setName()
A thread can be :meth:`join`\ ed many times.
Old API for :attr:`~Thread.name`.
:meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
the current thread as that would cause a deadlock. It is also an error to
:meth:`join` a thread before it has been started and attempts to do so
raises the same exception.
.. attribute:: name
A string used for identification purposes only. It has no semantics.
Multiple threads may be given the same name. The initial name is set by
the constructor.
.. method:: Thread.getName()
Thread.setName()
.. attribute:: ident
Old API for :attr:`~Thread.name`.
The 'thread identifier' of this thread or ``None`` if the thread has not
been started. This is a nonzero integer. See the
:func:`thread.get_ident()` function. Thread identifiers may be recycled
when a thread exits and another thread is created. The identifier is
available even after the thread has exited.
.. versionadded:: 2.6
.. attribute:: Thread.name
.. method:: is_alive()
isAlive()
A string used for identification purposes only. It has no semantics.
Multiple threads may be given the same name. The initial name is set by the
constructor.
Return whether the thread is alive.
Roughly, a thread is alive from the moment the :meth:`start` method
returns until its :meth:`run` method terminates. The module function
:func:`enumerate` returns a list of all alive threads.
.. attribute:: Thread.ident
.. method:: isDaemon()
setDaemon()
The 'thread identifier' of this thread or ``None`` if the thread has not been
started. This is a nonzero integer. See the :func:`thread.get_ident()`
function. Thread identifiers may be recycled when a thread exits and another
thread is created. The identifier is available even after the thread has
exited.
Old API for :attr:`~Thread.daemon`.
.. versionadded:: 2.6
.. attribute:: daemon
A boolean value indicating whether this thread is a daemon thread (True)
or not (False). This must be set before :meth:`start` is called,
otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
from the creating thread; the main thread is not a daemon thread and
therefore all threads created in the main thread default to :attr:`daemon`
= ``False``.
.. method:: Thread.is_alive()
Thread.isAlive()
Return whether the thread is alive.
Roughly, a thread is alive from the moment the :meth:`start` method returns
until its :meth:`run` method terminates. The module function :func:`enumerate`
returns a list of all alive threads.
.. method:: Thread.isDaemon()
Thread.setDaemon()
Old API for :attr:`~Thread.daemon`.
.. attribute:: Thread.daemon
A boolean value indicating whether this thread is a daemon thread (True) or
not (False). This must be set before :meth:`start` is called, otherwise
:exc:`RuntimeError` is raised. Its initial value is inherited from the
creating thread; the main thread is not a daemon thread and therefore all
threads created in the main thread default to :attr:`daemon` = ``False``.
The entire Python program exits when no alive non-daemon threads are left.
The entire Python program exits when no alive non-daemon threads are left.
.. _lock-objects:
@ -515,70 +508,66 @@ needs to wake up one consumer thread.
.. class:: Condition([lock])
If the *lock* argument is given and not ``None``, it must be a :class:`Lock` or
:class:`RLock` object, and it is used as the underlying lock. Otherwise, a new
:class:`RLock` object is created and used as the underlying lock.
If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
a new :class:`RLock` object is created and used as the underlying lock.
.. method:: acquire(*args)
.. method:: Condition.acquire(*args)
Acquire the underlying lock. This method calls the corresponding method on
the underlying lock; the return value is whatever that method returns.
Acquire the underlying lock. This method calls the corresponding method on the
underlying lock; the return value is whatever that method returns.
.. method:: release()
Release the underlying lock. This method calls the corresponding method on
the underlying lock; there is no return value.
.. method:: Condition.release()
.. method:: wait([timeout])
Release the underlying lock. This method calls the corresponding method on the
underlying lock; there is no return value.
Wait until notified or until a timeout occurs. If the calling thread has not
acquired the lock when this method is called, a :exc:`RuntimeError` is raised.
This method releases the underlying lock, and then blocks until it is
awakened by a :meth:`notify` or :meth:`notifyAll` call for the same
condition variable in another thread, or until the optional timeout
occurs. Once awakened or timed out, it re-acquires the lock and returns.
.. method:: Condition.wait([timeout])
When the *timeout* argument is present and not ``None``, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).
Wait until notified or until a timeout occurs. If the calling thread has not
acquired the lock when this method is called, a :exc:`RuntimeError` is raised.
When the underlying lock is an :class:`RLock`, it is not released using
its :meth:`release` method, since this may not actually unlock the lock
when it was acquired multiple times recursively. Instead, an internal
interface of the :class:`RLock` class is used, which really unlocks it
even when it has been recursively acquired several times. Another internal
interface is then used to restore the recursion level when the lock is
reacquired.
This method releases the underlying lock, and then blocks until it is awakened
by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
another thread, or until the optional timeout occurs. Once awakened or timed
out, it re-acquires the lock and returns.
.. method:: notify()
When the *timeout* argument is present and not ``None``, it should be a floating
point number specifying a timeout for the operation in seconds (or fractions
thereof).
Wake up a thread waiting on this condition, if any. If the calling thread
has not acquired the lock when this method is called, a
:exc:`RuntimeError` is raised.
When the underlying lock is an :class:`RLock`, it is not released using its
:meth:`release` method, since this may not actually unlock the lock when it was
acquired multiple times recursively. Instead, an internal interface of the
:class:`RLock` class is used, which really unlocks it even when it has been
recursively acquired several times. Another internal interface is then used to
restore the recursion level when the lock is reacquired.
This method wakes up one of the threads waiting for the condition
variable, if any are waiting; it is a no-op if no threads are waiting.
The current implementation wakes up exactly one thread, if any are
waiting. However, it's not safe to rely on this behavior. A future,
optimized implementation may occasionally wake up more than one thread.
.. method:: Condition.notify()
Note: the awakened thread does not actually return from its :meth:`wait`
call until it can reacquire the lock. Since :meth:`notify` does not
release the lock, its caller should.
Wake up a thread waiting on this condition, if any. If the calling thread
has not acquired the lock when this method is called, a :exc:`RuntimeError`
is raised.
.. method:: notify_all()
notifyAll()
This method wakes up one of the threads waiting for the condition variable,
if any are waiting; it is a no-op if no threads are waiting.
The current implementation wakes up exactly one thread, if any are waiting.
However, it's not safe to rely on this behavior. A future, optimized
implementation may occasionally wake up more than one thread.
Note: the awakened thread does not actually return from its :meth:`wait` call
until it can reacquire the lock. Since :meth:`notify` does not release the
lock, its caller should.
.. method:: Condition.notify_all()
Condition.notifyAll()
Wake up all threads waiting on this condition. This method acts like
:meth:`notify`, but wakes up all waiting threads instead of one. If the calling
thread has not acquired the lock when this method is called, a
:exc:`RuntimeError` is raised.
Wake up all threads waiting on this condition. This method acts like
:meth:`notify`, but wakes up all waiting threads instead of one. If the
calling thread has not acquired the lock when this method is called, a
:exc:`RuntimeError` is raised.
.. _semaphore-objects:
@ -602,33 +591,31 @@ waiting until some other thread calls :meth:`release`.
defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
raised.
.. method:: acquire([blocking])
.. method:: Semaphore.acquire([blocking])
Acquire a semaphore.
Acquire a semaphore.
When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately. If it is zero
on entry, block, waiting until some other thread has called
:meth:`release` to make it larger than zero. This is done with proper
interlocking so that if multiple :meth:`acquire` calls are blocked,
:meth:`release` will wake exactly one of them up. The implementation may
pick one at random, so the order in which blocked threads are awakened
should not be relied on. There is no return value in this case.
When invoked without arguments: if the internal counter is larger than zero on
entry, decrement it by one and return immediately. If it is zero on entry,
block, waiting until some other thread has called :meth:`release` to make it
larger than zero. This is done with proper interlocking so that if multiple
:meth:`acquire` calls are blocked, :meth:`release` will wake exactly one of them
up. The implementation may pick one at random, so the order in which blocked
threads are awakened should not be relied on. There is no return value in this
case.
When invoked with *blocking* set to true, do the same thing as when called
without arguments, and return true.
When invoked with *blocking* set to true, do the same thing as when called
without arguments, and return true.
When invoked with *blocking* set to false, do not block. If a call
without an argument would block, return false immediately; otherwise, do
the same thing as when called without arguments, and return true.
When invoked with *blocking* set to false, do not block. If a call without an
argument would block, return false immediately; otherwise, do the same thing as
when called without arguments, and return true.
.. method:: release()
.. method:: Semaphore.release()
Release a semaphore, incrementing the internal counter by one. When it was zero
on entry and another thread is waiting for it to become larger than zero again,
wake up that thread.
Release a semaphore, incrementing the internal counter by one. When it
was zero on entry and another thread is waiting for it to become larger
than zero again, wake up that thread.
.. _semaphore-examples:
@ -675,36 +662,39 @@ An event object manages an internal flag that can be set to true with the
The internal flag is initially false.
.. method:: is_set()
isSet()
.. method:: Event.is_set()
Event.isSet()
Return true if and only if the internal flag is true.
Return true if and only if the internal flag is true.
.. method:: set()
Set the internal flag to true. All threads waiting for it to become true
are awakened. Threads that call :meth:`wait` once the flag is true will
not block at all.
.. method:: Event.set()
.. method:: clear()
Set the internal flag to true. All threads waiting for it to become true are
awakened. Threads that call :meth:`wait` once the flag is true will not block at
all.
Reset the internal flag to false. Subsequently, threads calling
:meth:`wait` will block until :meth:`.set` is called to set the internal
flag to true again.
.. method:: wait([timeout])
.. method:: Event.clear()
Block until the internal flag is true. If the internal flag is true on
entry, return immediately. Otherwise, block until another thread calls
:meth:`.set` to set the flag to true, or until the optional timeout
occurs.
Reset the internal flag to false. Subsequently, threads calling :meth:`wait`
will block until :meth:`.set` is called to set the internal flag to true
again.
When the timeout argument is present and not ``None``, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).
This method returns the internal flag on exit, so it will always return
``True`` except if a timeout is given and the operation times out.
.. method:: Event.wait([timeout])
Block until the internal flag is true. If the internal flag is true on
entry, return immediately. Otherwise, block until another thread calls
:meth:`.set` to set the flag to true, or until the optional timeout occurs.
When the timeout argument is present and not ``None``, it should be a floating
point number specifying a timeout for the operation in seconds (or fractions
thereof).
.. versionchanged:: 2.7
Previously, the method always returned ``None``.
.. _timer-objects:
@ -735,11 +725,10 @@ For example::
Create a timer that will run *function* with arguments *args* and keyword
arguments *kwargs*, after *interval* seconds have passed.
.. method:: cancel()
.. method:: Timer.cancel()
Stop the timer, and cancel the execution of the timer's action. This will only
work if the timer is still in its waiting stage.
Stop the timer, and cancel the execution of the timer's action. This will
only work if the timer is still in its waiting stage.
.. _with-locks:

View File

@ -215,8 +215,9 @@ Utility functions
.. function:: quote_plus(string[, safe])
Like :func:`quote`, but also replaces spaces by plus signs, as required for
quoting HTML form values. Plus signs in the original string are escaped unless
they are included in *safe*. It also does not have *safe* default to ``'/'``.
quoting HTML form values when building up a query string to go into a URL.
Plus signs in the original string are escaped unless they are included in
*safe*. It also does not have *safe* default to ``'/'``.
.. function:: unquote(string)

View File

@ -12,43 +12,40 @@ user not to "break into the definition." The most important features of classes
are retained with full power, however: the class inheritance mechanism allows
multiple base classes, a derived class can override any methods of its base
class or classes, and a method can call the method of a base class with the same
name. Objects can contain an arbitrary amount of private data.
name. Objects can contain an arbitrary amount of data.
In C++ terminology, all class members (including the data members) are *public*,
and all member functions are *virtual*. There are no special constructors or
destructors. As in Modula-3, there are no shorthands for referencing the
object's members from its methods: the method function is declared with an
explicit first argument representing the object, which is provided implicitly by
the call. As in Smalltalk, classes themselves are objects, albeit in the wider
sense of the word: in Python, all data types are objects. This provides
semantics for importing and renaming. Unlike C++ and Modula-3, built-in types
can be used as base classes for extension by the user. Also, like in C++ but
unlike in Modula-3, most built-in operators with special syntax (arithmetic
and all member functions are *virtual*. As in Modula-3, there are no shorthands
for referencing the object's members from its methods: the method function is
declared with an explicit first argument representing the object, which is
provided implicitly by the call. As in Smalltalk, classes themselves are
objects. This provides semantics for importing and renaming. Unlike C++ and
Modula-3, built-in types can be used as base classes for extension by the user.
Also, like in C++, most built-in operators with special syntax (arithmetic
operators, subscripting etc.) can be redefined for class instances.
.. _tut-terminology:
A Word About Terminology
========================
Lacking universally accepted terminology to talk about classes, I will make
occasional use of Smalltalk and C++ terms. (I would use Modula-3 terms, since
(Lacking universally accepted terminology to talk about classes, I will make
occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, since
its object-oriented semantics are closer to those of Python than C++, but I
expect that few readers have heard of it.)
.. _tut-object:
A Word About Names and Objects
==============================
Objects have individuality, and multiple names (in multiple scopes) can be bound
to the same object. This is known as aliasing in other languages. This is
usually not appreciated on a first glance at Python, and can be safely ignored
when dealing with immutable basic types (numbers, strings, tuples). However,
aliasing has an (intended!) effect on the semantics of Python code involving
mutable objects such as lists, dictionaries, and most types representing
entities outside the program (files, windows, etc.). This is usually used to
the benefit of the program, since aliases behave like pointers in some respects.
For example, passing an object is cheap since only a pointer is passed by the
implementation; and if a function modifies an object passed as an argument, the
caller will see the change --- this eliminates the need for two different
argument passing mechanisms as in Pascal.
aliasing has a possibly surprising effect on the semantics of Python code
involving mutable objects such as lists, dictionaries, and most other types.
This is usually used to the benefit of the program, since aliases behave like
pointers in some respects. For example, passing an object is cheap since only a
pointer is passed by the implementation; and if a function modifies an object
passed as an argument, the caller will see the change --- this eliminates the
need for two different argument passing mechanisms as in Pascal.
.. _tut-scopes:
@ -72,7 +69,7 @@ built-in exception names); the global names in a module; and the local names in
a function invocation. In a sense the set of attributes of an object also form
a namespace. The important thing to know about namespaces is that there is
absolutely no relation between names in different namespaces; for instance, two
different modules may both define a function "maximize" without confusion ---
different modules may both define a function ``maximize`` without confusion ---
users of the modules must prefix it with the module name.
By the way, I use the word *attribute* for any name following a dot --- for
@ -111,11 +108,13 @@ name attempts to find the name in the namespace.
Although scopes are determined statically, they are used dynamically. At any
time during execution, there are at least three nested scopes whose namespaces
are directly accessible: the innermost scope, which is searched first, contains
the local names; the namespaces of any enclosing functions, which are searched
starting with the nearest enclosing scope; the middle scope, searched next,
contains the current module's global names; and the outermost scope (searched
last) is the namespace containing built-in names.
are directly accessible:
* the innermost scope, which is searched first, contains the local names
* the scopes of any enclosing functions, which are searched starting with the
nearest enclosing scope, contains non-local, but also non-global names
* the next-to-last scope contains the current module's global names
* the outermost scope (searched last) is the namespace containing built-in names
If a name is declared global, then all references and assignments go directly to
the middle scope containing the module's global names. Otherwise, all variables
@ -136,15 +135,15 @@ language definition is evolving towards static name resolution, at "compile"
time, so don't rely on dynamic name resolution! (In fact, local variables are
already determined statically.)
A special quirk of Python is that -- if no :keyword:`global`
statement is in effect -- assignments to names always go
into the innermost scope. Assignments do not copy data --- they just bind names
to objects. The same is true for deletions: the statement ``del x`` removes the
binding of ``x`` from the namespace referenced by the local scope. In fact, all
operations that introduce new names use the local scope: in particular, import
statements and function definitions bind the module or function name in the
local scope. (The :keyword:`global` statement can be used to indicate that
particular variables live in the global scope.)
A special quirk of Python is that -- if no :keyword:`global` statement is in
effect -- assignments to names always go into the innermost scope. Assignments
do not copy data --- they just bind names to objects. The same is true for
deletions: the statement ``del x`` removes the binding of ``x`` from the
namespace referenced by the local scope. In fact, all operations that introduce
new names use the local scope: in particular, :keyword:`import` statements and
function definitions bind the module or function name in the local scope. (The
:keyword:`global` statement can be used to indicate that particular variables
live in the global scope.)
.. _tut-firstclasses:
@ -372,9 +371,9 @@ glancing through a method.
Often, the first argument of a method is called ``self``. This is nothing more
than a convention: the name ``self`` has absolutely no special meaning to
Python. (Note, however, that by not following the convention your code may be
Python. Note, however, that by not following the convention your code may be
less readable to other Python programmers, and it is also conceivable that a
*class browser* program might be written that relies upon such a convention.)
*class browser* program might be written that relies upon such a convention.
Any function object that is a class attribute defines a method for instances of
that class. It is not necessary that the function definition is textually
@ -410,13 +409,13 @@ argument::
Methods may reference global names in the same way as ordinary functions. The
global scope associated with a method is the module containing the class
definition. (The class itself is never used as a global scope!) While one
definition. (The class itself is never used as a global scope.) While one
rarely encounters a good reason for using global data in a method, there are
many legitimate uses of the global scope: for one thing, functions and modules
imported into the global scope can be used by methods, as well as functions and
classes defined in it. Usually, the class containing the method is itself
defined in this global scope, and in the next section we'll find some good
reasons why a method would want to reference its own class!
reasons why a method would want to reference its own class.
Each value is an object, and therefore has a *class* (also called its *type*).
It is stored as ``object.__class__``.
@ -467,12 +466,12 @@ An overriding method in a derived class may in fact want to extend rather than
simply replace the base class method of the same name. There is a simple way to
call the base class method directly: just call ``BaseClassName.methodname(self,
arguments)``. This is occasionally useful to clients as well. (Note that this
only works if the base class is defined or imported directly in the global
only works if the base class is accessible as ``BaseClassName`` in the global
scope.)
Python has two built-in functions that work with inheritance:
* Use :func:`isinstance` to check an object's type: ``isinstance(obj, int)``
* Use :func:`isinstance` to check an instance's type: ``isinstance(obj, int)``
will be ``True`` only if ``obj.__class__`` is :class:`int` or some class
derived from :class:`int`.
@ -537,26 +536,25 @@ http://www.python.org/download/releases/2.3/mro/.
Private Variables
=================
There is limited support for class-private identifiers. Any identifier of the
form ``__spam`` (at least two leading underscores, at most one trailing
underscore) is textually replaced with ``_classname__spam``, where ``classname``
is the current class name with leading underscore(s) stripped. This mangling is
done without regard to the syntactic position of the identifier, so it can be
used to define class-private instance and class variables, methods, variables
stored in globals, and even variables stored in instances. private to this class
on instances of *other* classes. Truncation may occur when the mangled name
would be longer than 255 characters. Outside classes, or when the class name
consists of only underscores, no mangling occurs.
"Private" instance variables that cannot be accessed except from inside an
object, don't exist in Python. However, there is a convention that is followed
by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should
be treated as a non-public part of the API (whether it is a function, a method
or a data member). It should be considered an implementation detail and subject
to change without notice.
Name mangling is intended to give classes an easy way to define "private"
instance variables and methods, without having to worry about instance variables
defined by derived classes, or mucking with instance variables by code outside
the class. Note that the mangling rules are designed mostly to avoid accidents;
it still is possible for a determined soul to access or modify a variable that
is considered private. This can even be useful in special circumstances, such
as in the debugger, and that's one reason why this loophole is not closed.
(Buglet: derivation of a class with the same name as the base class makes use of
private variables of the base class possible.)
Since there is a valid use-case for class-private members (namely to avoid name
clashes of names with names defined by subclasses), there is limited support for
such a mechanism, called :dfn:`name mangling`. Any identifier of the form
``__spam`` (at least two leading underscores, at most one trailing underscore)
is textually replaced with ``_classname__spam``, where ``classname`` is the
current class name with leading underscore(s) stripped. This mangling is done
without regard to the syntactic position of the identifier, as long as it
occurs within the definition of a class.
Note that the mangling rules are designed mostly to avoid accidents; it still is
possible to access or modify a variable that is considered private. This can
even be useful in special circumstances, such as in the debugger.
Notice that code passed to ``exec``, ``eval()`` or ``execfile()`` does not
consider the classname of the invoking class to be the current class; this is
@ -609,7 +607,7 @@ Exceptions Are Classes Too
User-defined exceptions are identified by classes as well. Using this mechanism
it is possible to create extensible hierarchies of exceptions.
There are two new valid (semantic) forms for the raise statement::
There are two new valid (semantic) forms for the :keyword:`raise` statement::
raise Class, instance
@ -620,10 +618,10 @@ class derived from it. The second form is a shorthand for::
raise instance.__class__, instance
A class in an except clause is compatible with an exception if it is the same
class or a base class thereof (but not the other way around --- an except clause
listing a derived class is not compatible with a base class). For example, the
following code will print B, C, D in that order::
A class in an :keyword:`except` clause is compatible with an exception if it is
the same class or a base class thereof (but not the other way around --- an
except clause listing a derived class is not compatible with a base class). For
example, the following code will print B, C, D in that order::
class B:
pass

View File

@ -127,16 +127,17 @@ Basic usage of the :meth:`str.format` method looks like this::
We are the knights who say "Ni!"
The brackets and characters within them (called format fields) are replaced with
the objects passed into the format method. The number in the brackets refers to
the position of the object passed into the format method. ::
the objects passed into the :meth:`~str.format` method. The number in the
brackets refers to the position of the object passed into the
:meth:`~str.format` method. ::
>>> print '{0} and {1}'.format('spam', 'eggs')
spam and eggs
>>> print '{1} and {0}'.format('spam', 'eggs')
eggs and spam
If keyword arguments are used in the format method, their values are referred to
by using the name of the argument. ::
If keyword arguments are used in the :meth:`~str.format` method, their values
are referred to by using the name of the argument. ::
>>> print 'This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible')
@ -157,7 +158,7 @@ truncates Pi to three places after the decimal.
The value of PI is approximately 3.142.
Passing an integer after the ``':'`` will cause that field to be a minimum
number of characters wide. This is useful for making tables pretty.::
number of characters wide. This is useful for making tables pretty. ::
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
@ -178,7 +179,7 @@ square brackets ``'[]'`` to access the keys ::
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
This could also be done by passing the table as keyword arguments with the '**'
notation.::
notation. ::
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)
@ -356,9 +357,9 @@ shorter than writing equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::
>>> f.closed
True
File objects have some additional methods, such as :meth:`isatty` and
:meth:`truncate` which are less frequently used; consult the Library Reference
for a complete guide to file objects.
File objects have some additional methods, such as :meth:`~file.isatty` and
:meth:`~file.truncate` which are less frequently used; consult the Library
Reference for a complete guide to file objects.
.. _tut-pickle:

View File

@ -6,8 +6,8 @@ Interactive Input Editing and History Substitution
Some versions of the Python interpreter support editing of the current input
line and history substitution, similar to facilities found in the Korn shell and
the GNU Bash shell. This is implemented using the *GNU Readline* library, which
supports Emacs-style and vi-style editing. This library has its own
the GNU Bash shell. This is implemented using the `GNU Readline`_ library,
which supports Emacs-style and vi-style editing. This library has its own
documentation which I won't duplicate here; however, the basics are easily
explained. The interactive editing and history described here are optionally
available in the Unix and Cygwin versions of the interpreter.
@ -148,8 +148,8 @@ interpreter. ::
.. _tut-commentary:
Commentary
==========
Alternatives to the Interactive Interpreter
===========================================
This facility is an enormous step forward compared to earlier versions of the
interpreter; however, some wishes are left: It would be nice if the proper
@ -158,6 +158,12 @@ token is required next). The completion mechanism might use the interpreter's
symbol table. A command to check (or even suggest) matching parentheses,
quotes, etc., would also be useful.
One alternative enhanced interactive interpreter that has been around for quite
some time is `IPython`_, which features tab completion, object exploration and
advanced history management. It can also be thoroughly customized and embedded
into other applications. Another similar enhanced interactive environment is
`bpython`_.
.. rubric:: Footnotes
@ -165,3 +171,7 @@ quotes, etc., would also be useful.
:envvar:`PYTHONSTARTUP` environment variable when you start an interactive
interpreter.
.. _GNU Readline: http://tiswww.case.edu/php/chet/readline/rltop.html
.. _IPython: http://ipython.scipy.org/
.. _bpython: http://www.bpython-interpreter.org/

View File

@ -446,14 +446,14 @@ one would hope that this somehow goes out to the filesystem, finds which
submodules are present in the package, and imports them all. Unfortunately,
this operation does not work very well on Windows platforms, where the
filesystem does not always have accurate information about the case of a
filename! On these platforms, there is no guaranteed way to know whether a file
filename. On these platforms, there is no guaranteed way to know whether a file
:file:`ECHO.PY` should be imported as a module :mod:`echo`, :mod:`Echo` or
:mod:`ECHO`. (For example, Windows 95 has the annoying practice of showing all
file names with a capitalized first letter.) The DOS 8+3 filename restriction
adds another interesting problem for long module names.
The only solution is for the package author to provide an explicit index of the
package. The import statement uses the following convention: if a package's
package. The :keyword:`import` statement uses the following convention: if a package's
:file:`__init__.py` code defines a list named ``__all__``, it is taken to be the
list of module names that should be imported when ``from package import *`` is
encountered. It is up to the package author to keep this list up-to-date when a
@ -474,16 +474,16 @@ been imported (possibly running any initialization code in :file:`__init__.py`)
and then imports whatever names are defined in the package. This includes any
names defined (and submodules explicitly loaded) by :file:`__init__.py`. It
also includes any submodules of the package that were explicitly loaded by
previous import statements. Consider this code::
previous :keyword:`import` statements. Consider this code::
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
In this example, the echo and surround modules are imported in the current
namespace because they are defined in the :mod:`sound.effects` package when the
``from...import`` statement is executed. (This also works when ``__all__`` is
defined.)
In this example, the :mod:`echo` and :mod:`surround` modules are imported in the
current namespace because they are defined in the :mod:`sound.effects` package
when the ``from...import`` statement is executed. (This also works when
``__all__`` is defined.)
Note that in general the practice of importing ``*`` from a module or package is
frowned upon, since it often causes poorly readable code. However, it is okay to
@ -546,5 +546,6 @@ modules found in a package.
.. rubric:: Footnotes
.. [#] In fact function definitions are also 'statements' that are 'executed'; the
execution enters the function name in the module's global symbol table.
execution of a module-level function enters the function name in the module's
global symbol table.

View File

@ -61,8 +61,8 @@ formatting numbers with group separators::
>>> x = 1234567.8
>>> locale.format("%d", x, grouping=True)
'1,234,567'
>>> locale.format("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
@ -347,12 +347,15 @@ Decimal Floating Point Arithmetic
The :mod:`decimal` module offers a :class:`Decimal` datatype for decimal
floating point arithmetic. Compared to the built-in :class:`float`
implementation of binary floating point, the new class is especially helpful for
financial applications and other uses which require exact decimal
representation, control over precision, control over rounding to meet legal or
regulatory requirements, tracking of significant decimal places, or for
applications where the user expects the results to match calculations done by
hand.
implementation of binary floating point, the class is especially helpful for
* financial applications and other uses which require exact decimal
representation,
* control over precision,
* control over rounding to meet legal or regulatory requirements,
* tracking of significant decimal places, or
* applications where the user expects the results to match calculations done by
hand.
For example, calculating a 5% tax on a 70 cent phone charge gives different
results in decimal floating point and binary floating point. The difference