Commit 5be70d44 authored by Georg Brandl's avatar Georg Brandl

Merged revisions...

Merged revisions 74492,74531,74545-74550,74553-74555,74588,74603,74608,74614,74616-74618,74631-74633,74652-74653,74666,74671,74737,74739,74779,74781-74782,74784,74791,74793,74818-74820,74822,74832 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk

........
  r74492 | r.david.murray | 2009-08-17 21:26:49 +0200 (Mo, 17 Aug 2009) | 2 lines

  Issue 6685: 'toupper' -> 'upper' in cgi doc example explanation.
........
  r74531 | vinay.sajip | 2009-08-21 00:04:32 +0200 (Fr, 21 Aug 2009) | 1 line

  Added section on exceptions raised during logging.
........
  r74545 | georg.brandl | 2009-08-24 19:14:29 +0200 (Mo, 24 Aug 2009) | 1 line

  #6772: mention utf-8 as utf8 alias.
........
  r74546 | georg.brandl | 2009-08-24 19:20:40 +0200 (Mo, 24 Aug 2009) | 1 line

  #6725: spell "namespace" consistently.
........
  r74547 | georg.brandl | 2009-08-24 19:22:05 +0200 (Mo, 24 Aug 2009) | 1 line

  #6718: fix example.
........
  r74548 | georg.brandl | 2009-08-24 19:24:27 +0200 (Mo, 24 Aug 2009) | 1 line

  #6677: mention "deleting" as an alias for removing files.
........
  r74549 | benjamin.peterson | 2009-08-24 19:42:36 +0200 (Mo, 24 Aug 2009) | 1 line

  fix pdf building by teaching latex the right encoding package
........
  r74550 | georg.brandl | 2009-08-24 19:48:40 +0200 (Mo, 24 Aug 2009) | 1 line

  #6677: note that rmdir only removes empty directories.
........
  r74553 | r.david.murray | 2009-08-27 03:04:59 +0200 (Do, 27 Aug 2009) | 2 lines

  Remove leftover text from end of sentence.
........
  r74554 | georg.brandl | 2009-08-27 20:59:02 +0200 (Do, 27 Aug 2009) | 1 line

  Typo fix.
........
  r74555 | georg.brandl | 2009-08-27 21:02:43 +0200 (Do, 27 Aug 2009) | 1 line

  #6787: reference fix.
........
  r74588 | georg.brandl | 2009-08-30 10:35:01 +0200 (So, 30 Aug 2009) | 1 line

  #6803: fix old name.
........
  r74603 | georg.brandl | 2009-08-31 08:38:29 +0200 (Mo, 31 Aug 2009) | 1 line

  other -> others where multiple arguments are accepted.
........
  r74608 | senthil.kumaran | 2009-08-31 18:40:27 +0200 (Mo, 31 Aug 2009) | 3 lines

  Doc fix for the issue2637.
........
  r74614 | georg.brandl | 2009-09-01 09:40:54 +0200 (Di, 01 Sep 2009) | 1 line

  #6813: better documentation for numberless string formats.
........
  r74616 | georg.brandl | 2009-09-01 09:46:26 +0200 (Di, 01 Sep 2009) | 1 line

  #6808: clarification.
........
  r74617 | georg.brandl | 2009-09-01 09:53:37 +0200 (Di, 01 Sep 2009) | 1 line

  #6765: hint that log(x, base) is not very sophisticated.
........
  r74618 | georg.brandl | 2009-09-01 10:00:47 +0200 (Di, 01 Sep 2009) | 1 line

  #6810: add a link to the section about frame objects instead of just a description where to find it.
........
  r74631 | georg.brandl | 2009-09-02 22:37:16 +0200 (Mi, 02 Sep 2009) | 1 line

  #6821: fix signature of PyBuffer_Release().
........
  r74632 | georg.brandl | 2009-09-03 09:27:26 +0200 (Do, 03 Sep 2009) | 1 line

  #6828: fix wrongly highlighted blocks.
........
  r74633 | georg.brandl | 2009-09-03 14:31:39 +0200 (Do, 03 Sep 2009) | 1 line

  #6757: complete the list of types that marshal can serialize.
........
  r74652 | georg.brandl | 2009-09-04 13:25:37 +0200 (Fr, 04 Sep 2009) | 1 line

  #6756: add some info about the "acct" parameter.
........
  r74653 | georg.brandl | 2009-09-04 13:32:18 +0200 (Fr, 04 Sep 2009) | 1 line

  #6777: dont discourage usage of Exception.args or promote usage of Exception.message.
........
  r74666 | georg.brandl | 2009-09-05 11:04:09 +0200 (Sa, 05 Sep 2009) | 1 line

  #6841: remove duplicated word.
........
  r74671 | georg.brandl | 2009-09-05 18:47:17 +0200 (Sa, 05 Sep 2009) | 1 line

  #6843: add link from filterwarnings to where the meaning of the arguments is covered.
........
  r74737 | georg.brandl | 2009-09-09 18:49:13 +0200 (Mi, 09 Sep 2009) | 1 line

  Properly document copy and deepcopy as functions.
........
  r74739 | georg.brandl | 2009-09-11 09:55:20 +0200 (Fr, 11 Sep 2009) | 1 line

  Move function back to its section.
........
  r74779 | michael.foord | 2009-09-13 18:13:36 +0200 (So, 13 Sep 2009) | 1 line

  Change to tutorial wording for reading text / binary files on Windows. Issue #6301.
........
  r74781 | michael.foord | 2009-09-13 18:46:19 +0200 (So, 13 Sep 2009) | 1 line

  Note that sys._getframe is not guaranteed to exist in all implementations of Python, and a corresponding note in inspect.currentframe. Issue 6712.
........
  r74782 | michael.foord | 2009-09-13 19:07:46 +0200 (So, 13 Sep 2009) | 1 line

  Tutorial tweaks. Issue 6849.
........
  r74784 | georg.brandl | 2009-09-13 20:15:07 +0200 (So, 13 Sep 2009) | 1 line

  Typo fix.
........
  r74791 | georg.brandl | 2009-09-14 16:08:54 +0200 (Mo, 14 Sep 2009) | 1 line

  #6574: list the future features in a table.
........
  r74793 | georg.brandl | 2009-09-14 16:50:47 +0200 (Mo, 14 Sep 2009) | 1 line

  #6908: fix association of hashlib hash attributes.
........
  r74818 | georg.brandl | 2009-09-16 11:23:04 +0200 (Mi, 16 Sep 2009) | 1 line

  #6880: add reference to classes section in exceptions section, which comes earlier.
........
  r74819 | georg.brandl | 2009-09-16 11:24:57 +0200 (Mi, 16 Sep 2009) | 1 line

  #6876: fix base class constructor invocation in example.
........
  r74820 | georg.brandl | 2009-09-16 11:30:48 +0200 (Mi, 16 Sep 2009) | 1 line

  #6891: comment out dead link to Unicode article.
........
  r74822 | georg.brandl | 2009-09-16 12:12:06 +0200 (Mi, 16 Sep 2009) | 1 line

  #5621: refactor description of how class/instance attributes interact on a.x=a.x+1 or augassign.
........
  r74832 | georg.brandl | 2009-09-16 17:57:46 +0200 (Mi, 16 Sep 2009) | 1 line

  Rewrap long lines.
........
parent 46e9daa3
......@@ -253,9 +253,9 @@ Buffer related functions
+------------------------------+---------------------------------------------------+
.. cfunction:: void PyBuffer_Release(PyObject *obj, Py_buffer *view)
.. cfunction:: void PyBuffer_Release(Py_buffer *view)
Release the buffer *view* over *obj*. This should be called when the buffer
Release the buffer *view*. This should be called when the buffer
is no longer being used as it may free memory from it.
......
......@@ -148,7 +148,8 @@ latex_preamble = r'''
# Documents to append as an appendix to all manuals.
latex_appendices = ['glossary', 'about', 'license', 'copyright']
latex_elements = {'inputenc': '\\usepackage[utf8x]{inputenc}'}
# Get LaTeX to handle Unicode correctly
latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}'}
# Options for the coverage checker
# --------------------------------
......
......@@ -426,13 +426,6 @@ built-in functions in the installation script.
also the configuration. For details refer to Microsoft's documentation of the
:cfunc:`SHGetSpecialFolderPath` function.
Vista User Access Control (UAC)
===============================
Starting with Python 2.6, bdist_wininst supports a :option:`--user-access-control`
option. The default is 'none' (meaning no UAC handling is done), and other
valid values are 'auto' (meaning prompt for UAC elevation if Python was
installed for all users) and 'force' (meaning always prompt for elevation)
.. function:: create_shortcut(target, description, filename[, arguments[, workdir[, iconpath[, iconindex]]]])
......@@ -444,3 +437,12 @@ installed for all users) and 'force' (meaning always prompt for elevation)
and *iconindex* is the index of the icon in the file *iconpath*. Again, for
details consult the Microsoft documentation for the :class:`IShellLink`
interface.
Vista User Access Control (UAC)
===============================
Starting with Python 2.6, bdist_wininst supports a :option:`--user-access-control`
option. The default is 'none' (meaning no UAC handling is done), and other
valid values are 'auto' (meaning prompt for UAC elevation if Python was
installed for all users) and 'force' (meaning always prompt for elevation).
......@@ -210,11 +210,12 @@ To help understand the standard, Jukka Korpela has written an introductory guide
to reading the Unicode character tables, available at
<http://www.cs.tut.fi/~jkorpela/unicode/guide.html>.
Two other good introductory articles were written by Joel Spolsky
<http://www.joelonsoftware.com/articles/Unicode.html> and Jason Orendorff
<http://www.jorendorff.com/articles/unicode/>. If this introduction didn't make
things clear to you, you should try reading one of these alternate articles
before continuing.
Another good introductory article was written by Joel Spolsky
<http://www.joelonsoftware.com/articles/Unicode.html>.
If this introduction didn't make things clear to you, you should try reading this
alternate article before continuing.
.. Jason Orendorff XXX http://www.jorendorff.com/articles/unicode/ is broken
Wikipedia entries are often helpful; see the entries for "character encoding"
<http://en.wikipedia.org/wiki/Character_encoding> and UTF-8
......
......@@ -10,9 +10,9 @@
* To avoid confusing existing tools that analyze import statements and expect to
find the modules they're importing.
* To ensure that future_statements run under releases prior to 2.1 at least
yield runtime exceptions (the import of :mod:`__future__` will fail, because
there was no module of that name prior to 2.1).
* To ensure that :ref:`future statements <future>` run under releases prior to
2.1 at least yield runtime exceptions (the import of :mod:`__future__` will
fail, because there was no module of that name prior to 2.1).
* To document when incompatible changes were introduced, and when they will be
--- or were --- made mandatory. This is a form of executable documentation, and
......@@ -56,7 +56,34 @@ argument to the built-in function :func:`compile` to enable the feature in
dynamically compiled code. This flag is stored in the :attr:`compiler_flag`
attribute on :class:`_Feature` instances.
No feature description will ever be deleted from :mod:`__future__`.
No feature description will ever be deleted from :mod:`__future__`. Since its
introduction in Python 2.1 the following features have found their way into the
language using this mechanism:
+------------------+-------------+--------------+---------------------------------------------+
| feature | optional in | mandatory in | effect |
+==================+=============+==============+=============================================+
| nested_scopes | 2.1.0b1 | 2.2 | :pep:`227`: |
| | | | *Statically Nested Scopes* |
+------------------+-------------+--------------+---------------------------------------------+
| generators | 2.2.0a1 | 2.3 | :pep:`255`: |
| | | | *Simple Generators* |
+------------------+-------------+--------------+---------------------------------------------+
| division | 2.2.0a2 | 3.0 | :pep:`238`: |
| | | | *Changing the Division Operator* |
+------------------+-------------+--------------+---------------------------------------------+
| absolute_import | 2.5.0a1 | 2.7 | :pep:`328`: |
| | | | *Imports: Multi-Line and Absolute/Relative* |
+------------------+-------------+--------------+---------------------------------------------+
| with_statement | 2.5.0a1 | 2.6 | :pep:`343`: |
| | | | *The "with" Statement* |
+------------------+-------------+--------------+---------------------------------------------+
| print_function | 2.6.0a2 | 3.0 | :pep:`3105`: |
| | | | *Make print a function* |
+------------------+-------------+--------------+---------------------------------------------+
| unicode_literals | 2.6.0a2 | 3.0 | :pep:`3112`: |
| | | | *Bytes literals in Python 3000* |
+------------------+-------------+--------------+---------------------------------------------+
.. seealso::
......
......@@ -213,7 +213,7 @@ The problem with the code is that you should never expect that a client will
provide valid input to your scripts. For example, if a curious user appends
another ``user=foo`` pair to the query string, then the script would crash,
because in this situation the ``getvalue("user")`` method call returns a list
instead of a string. Calling the :meth:`toupper` method on a list is not valid
instead of a string. Calling the :meth:`~str.upper` method on a list is not valid
(since lists do not have a method of this name) and results in an
:exc:`AttributeError` exception.
......
......@@ -863,7 +863,8 @@ or with dictionaries as mapping tables. The following table lists the codecs by
name, together with a few common aliases, and the languages for which the
encoding is likely used. Neither the list of aliases nor the list of languages
is meant to be exhaustive. Notice that spelling alternatives that only differ in
case or use a hyphen instead of an underscore are also valid aliases.
case or use a hyphen instead of an underscore are also valid aliases; therefore,
e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Many of the character sets support the same languages. They vary in individual
characters (e.g. whether the EURO SIGN is supported or not), and in the
......
......@@ -62,7 +62,7 @@ should not be used in programs.
Objects that when printed, print a message like "Use quit() or Ctrl-D
(i.e. EOF) to exit", and when called, raise :exc:`SystemExit` with the
specified exit code, and when .
specified exit code.
.. data:: copyright
license
......
:mod:`copy` --- Shallow and deep copy operations
================================================
.. module:: copy
:synopsis: Shallow and deep copy operations.
This module provides generic (shallow and deep) copying operations.
.. index::
single: copy() (in copy)
single: deepcopy() (in copy)
This module provides generic (shallow and deep) copying operations.
Interface summary:
.. function:: copy(x)
Return a shallow copy of *x*.
.. function:: deepcopy(x)
Return a deep copy of *x*.
Interface summary::
import copy
.. exception:: error
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
Raised for module specific errors.
For module specific errors, :exc:`copy.error` is raised.
The difference between shallow and deep copying is only relevant for compound
objects (objects that contain other objects, like lists or class instances):
......
......@@ -1601,7 +1601,7 @@ type and the argument types of the function.
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
:data:`errno` variable is exchanged with the real :data:`errno` value bafore
:data:`errno` variable is exchanged with the real :data:`errno` value before
and after the call; *use_last_error* does the same for the Windows error
code.
......
......@@ -147,7 +147,8 @@ followed by ``lines`` for the text version or ``binary`` for the binary version.
``'anonymous@'``. This function should be called only once for each instance,
after a connection has been established; it should not be called at all if a
host and user were given when the instance was created. Most FTP commands are
only allowed after the client has logged in.
only allowed after the client has logged in. The *acct* parameter supplies
"accounting information"; few systems implement this.
.. method:: FTP.abort()
......
......@@ -78,11 +78,11 @@ The following values are provided as constant attributes of the hash objects
returned by the constructors:
.. data:: digest_size
.. data:: hash.digest_size
The size of the resulting hash in bytes.
.. data:: block_size
.. data:: hash.block_size
The internal block size of the hash algorithm in bytes.
......
......@@ -567,6 +567,11 @@ line.
Return the frame object for the caller's stack frame.
This function relies on Python stack frame support in the interpreter, which
isn't guaranteed to exist in all implementations of Python. If running in
an implementation without Python stack frame support this function returns
``None``.
.. function:: stack([context])
......
......@@ -1195,6 +1195,28 @@ are sent to both destinations.
This example uses console and file handlers, but you can use any number and
combination of handlers you choose.
.. _logging-exceptions:
Exceptions raised during logging
--------------------------------
The logging package is designed to swallow exceptions which occur while logging
in production. This is so that errors which occur while handling logging events
- such as logging misconfiguration, network or other similar errors - do not
cause the application using logging to terminate prematurely.
:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
swallowed. Other exceptions which occur during the :meth:`emit` method of a
:class:`Handler` subclass are passed to its :meth:`handleError` method.
The default implementation of :meth:`handleError` in :class:`Handler` checks
to see if a module-level variable, `raiseExceptions`, is set. If set, a
traceback is printed to `sys.stderr`. If not set, the exception is swallowed.
**Note:** The default value of `raiseExceptions` is `True`. This is because
during development, you typically want to be notified of any exceptions that
occur. It's advised that you set `raiseExceptions` to `False` for production
usage.
.. _context-info:
......
......@@ -37,12 +37,14 @@ supports a substantially wider range of objects than marshal.
Not all Python object types are supported; in general, only objects whose value
is independent from a particular invocation of Python can be written and read by
this module. The following types are supported: ``None``, integers, long
integers, floating point numbers, strings, Unicode objects, tuples, lists, sets,
dictionaries, and code objects, where it should be understood that tuples, lists
and dictionaries are only supported as long as the values contained therein are
themselves supported; and recursive lists and dictionaries should not be written
(they will cause infinite loops).
this module. The following types are supported: booleans, integers, long
integers, floating point numbers, complex numbers, strings, Unicode objects,
tuples, lists, sets, frozensets, dictionaries, and code objects, where it should
be understood that tuples, lists, sets, frozensets and dictionaries are only
supported as long as the values contained therein are themselves supported; and
recursive lists, sets and dictionaries should not be written (they will cause
infinite loops). The singletons :const:`None`, :const:`Ellipsis` and
:exc:`StopIteration` can also be marshalled and unmarshalled.
.. warning::
......
......@@ -166,8 +166,10 @@ Power and logarithmic functions
.. function:: log(x[, base])
Return the logarithm of *x* to the given *base*. If the *base* is not specified,
return the natural logarithm of *x* (that is, the logarithm to base *e*).
With one argument, return the natural logarithm of *x* (to base *e*).
With two arguments, return the logarithm of *x* to the given *base*,
calculated as ``log(x)/log(base)``.
.. versionchanged:: 2.3
*base* argument added.
......@@ -183,7 +185,8 @@ Power and logarithmic functions
.. function:: log10(x)
Return the base-10 logarithm of *x*.
Return the base-10 logarithm of *x*. This is usually more accurate
than ``log(x, 10)``.
.. function:: pow(x, y)
......
......@@ -1067,12 +1067,12 @@ Files and Directories
.. function:: remove(path)
Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
:func:`rmdir` below to remove a directory. This is identical to the
:func:`unlink` function documented below. On Windows, attempting to remove a
file that is in use causes an exception to be raised; on Unix, the directory
entry is removed but the storage allocated to the file is not made available
until the original file is no longer in use. Availability: Unix,
Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
raised; see :func:`rmdir` below to remove a directory. This is identical to
the :func:`unlink` function documented below. On Windows, attempting to
remove a file that is in use causes an exception to be raised; on Unix, the
directory entry is removed but the storage allocated to the file is not made
available until the original file is no longer in use. Availability: Unix,
Windows.
......@@ -1121,7 +1121,10 @@ Files and Directories
.. function:: rmdir(path)
Remove the directory *path*. Availability: Unix, Windows.
Remove (delete) the directory *path*. Only works when the directory is
empty, otherwise, :exc:`OSError` is raised. In order to remove whole
directory trees, :func:`shutil.rmtree` can be used. Availability: Unix,
Windows.
.. function:: stat(path)
......@@ -1297,9 +1300,9 @@ Files and Directories
.. function:: unlink(path)
Remove the file *path*. This is the same function as :func:`remove`; the
:func:`unlink` name is its traditional Unix name. Availability: Unix,
Windows.
Remove (delete) the file *path*. This is the same function as
:func:`remove`; the :func:`unlink` name is its traditional Unix
name. Availability: Unix, Windows.
.. function:: utime(path, times)
......
:mod:`readline` --- GNU readline interface
==========================================
......@@ -221,7 +220,7 @@ support history save/restore. ::
class HistoryConsole(code.InteractiveConsole):
def __init__(self, locals=None, filename="<console>",
histfile=os.path.expanduser("~/.console-history")):
code.InteractiveConsole.__init__(self)
code.InteractiveConsole.__init__(self, locals, filename)
self.init_history(histfile)
def init_history(self, histfile):
......
......@@ -211,9 +211,9 @@ The :mod:`signal` module defines the following functions:
exception to be raised.
The *handler* is called with two arguments: the signal number and the current
stack frame (``None`` or a frame object; for a description of frame objects, see
the reference manual section on the standard type hierarchy or see the attribute
descriptions in the :mod:`inspect` module).
stack frame (``None`` or a frame object; for a description of frame objects,
see the :ref:`description in the type hierarchy <frame-objects>` or see the
attribute descriptions in the :mod:`inspect` module).
.. _signal-example:
......
......@@ -465,7 +465,7 @@ This is the client side::
import socket
import sys
HOST, PORT = "localhost"
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
# SOCK_DGRAM is the socket type to use for UDP sockets
......
This diff is collapsed.
......@@ -1754,7 +1754,7 @@ The constructors for both classes work the same:
.. method:: update(other, ...)
set |= other | ...
Update the set, adding elements from *other*.
Update the set, adding elements from all others.
.. versionchanged:: 2.6
Accepts multiple input iterables.
......@@ -1762,7 +1762,7 @@ The constructors for both classes work the same:
.. method:: intersection_update(other, ...)
set &= other & ...
Update the set, keeping only elements found in it and *other*.
Update the set, keeping only elements found in it and all others.
.. versionchanged:: 2.6
Accepts multiple input iterables.
......@@ -2050,7 +2050,7 @@ pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
:func:`update` accepts either another dictionary object or an iterable of
key/value pairs (as a tuple or other iterable of length two). If keyword
arguments are specified, the dictionary is then is updated with those
arguments are specified, the dictionary is then updated with those
key/value pairs: ``d.update(red=1, blue=2)``.
.. versionchanged:: 2.4
......@@ -2440,9 +2440,9 @@ decimal arithmetic context. The specific types are not treated specially beyond
their implementation of the context management protocol. See the
:mod:`contextlib` module for some examples.
Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator`
Python's :term:`generator`\s and the ``contextlib.contextmanager`` :term:`decorator`
provide a convenient way to implement these protocols. If a generator function is
decorated with the ``contextlib.contextfactory`` decorator, it will return a
decorated with the ``contextlib.contextmanager`` decorator, it will return a
context manager implementing the necessary :meth:`__enter__` and
:meth:`__exit__` methods, rather than the iterator produced by an undecorated
generator function.
......
......@@ -243,7 +243,6 @@ does an index lookup using :func:`__getitem__`.
Some simple format string examples::
"First, thou shalt count to {0}" # References first positional argument
"Bring me a {}" # Implicitly references the first positional argument
"My quest is {name}" # References keyword argument 'name'
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument 'players'.
......
......@@ -417,7 +417,8 @@ always available.
that is deeper than the call stack, :exc:`ValueError` is raised. The default
for *depth* is zero, returning the frame at the top of the call stack.
This function should be used for internal and specialized purposes only.
This function should be used for internal and specialized purposes only. It
is not guaranteed to exist in all implementations of Python.
.. function:: getprofile()
......
......@@ -156,7 +156,7 @@ In addition to these methods, lock objects can also be used via the
module is available, interrupts always go to the main thread.)
* Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is
equivalent to calling :func:`exit`.
equivalent to calling :func:`thread.exit`.
* Not all built-in functions that may block waiting for I/O allow other threads
to run. (The most popular ones (:func:`time.sleep`, :meth:`file.read`,
......
......@@ -205,9 +205,10 @@ Utility functions
.. function:: quote(string[, safe])
Replace special characters in *string* using the ``%xx`` escape. Letters,
digits, and the characters ``'_.-'`` are never quoted. The optional *safe*
parameter specifies additional characters that should not be quoted --- its
default value is ``'/'``.
digits, and the characters ``'_.-'`` are never quoted. By default, this
function is intended for quoting the path section of the URL.The optional
*safe* parameter specifies additional characters that should not be quoted
--- its default value is ``'/'``.
Example: ``quote('/~connolly/')`` yields ``'/%7econnolly/'``.
......
:mod:`warnings` --- Warning control
===================================
......@@ -129,16 +128,16 @@ the disposition of the match. Each entry is a tuple of the form (*action*,
+---------------+----------------------------------------------+
* *message* is a string containing a regular expression that the warning message
must match (the match is compiled to always be case-insensitive)
must match (the match is compiled to always be case-insensitive).
* *category* is a class (a subclass of :exc:`Warning`) of which the warning
category must be a subclass in order to match
category must be a subclass in order to match.
* *module* is a string containing a regular expression that the module name must
match (the match is compiled to be case-sensitive)
match (the match is compiled to be case-sensitive).
* *lineno* is an integer that the line number where the warning occurred must
match, or ``0`` to match all line numbers
match, or ``0`` to match all line numbers.
Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
class, to turn a warning into an error we simply raise ``category(message)``.
......@@ -300,10 +299,11 @@ Available Functions
.. function:: formatwarning(message, category, filename, lineno[, line])
Format a warning the standard way. This returns a string which may contain
embedded newlines and ends in a newline. *line* is
a line of source code to be included in the warning message; if *line* is not supplied,
:func:`formatwarning` will try to read the line specified by *filename* and *lineno*.
Format a warning the standard way. This returns a string which may contain
embedded newlines and ends in a newline. *line* is a line of source code to
be included in the warning message; if *line* is not supplied,
:func:`formatwarning` will try to read the line specified by *filename* and
*lineno*.
.. versionchanged:: 2.6
Added the *line* argument.
......@@ -311,10 +311,11 @@ Available Functions
.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])
Insert an entry into the list of warnings filters. The entry is inserted at the
front by default; if *append* is true, it is inserted at the end. This checks
the types of the arguments, compiles the message and module regular expressions,
and inserts them as a tuple in the list of warnings filters. Entries closer to
Insert an entry into the list of :ref:`warnings filter specifications
<warning-filter>`. The entry is inserted at the front by default; if
*append* is true, it is inserted at the end. This checks the types of the
arguments, compiles the *message* and *module* regular expressions, and
inserts them as a tuple in the list of warnings filters. Entries closer to
the front of the list override entries later in the list, if both match a
particular warning. Omitted arguments default to a value that matches
everything.
......@@ -322,10 +323,11 @@ Available Functions
.. function:: simplefilter(action[, category[, lineno[, append]]])
Insert a simple entry into the list of warnings filters. The meaning of the
function parameters is as for :func:`filterwarnings`, but regular expressions
are not needed as the filter inserted always matches any message in any module
as long as the category and line number match.
Insert a simple entry into the list of :ref:`warnings filter specifications
<warning-filter>`. The meaning of the function parameters is as for
:func:`filterwarnings`, but regular expressions are not needed as the filter
inserted always matches any message in any module as long as the category and
line number match.
.. function:: resetwarnings()
......
......@@ -959,6 +959,8 @@ Internal types
If a code object represents a function, the first item in :attr:`co_consts` is
the documentation string of the function, or ``None`` if undefined.
.. _frame-objects:
Frame objects
.. index:: object: frame
......
......@@ -151,11 +151,30 @@ Assignment of an object to a single target is recursively defined as follows.
* If the target is an attribute reference: The primary expression in the
reference is evaluated. It should yield an object with assignable attributes;
if this is not the case, :exc:`TypeError` is raised. That object is then asked
to assign the assigned object to the given attribute; if it cannot perform the
assignment, it raises an exception (usually but not necessarily
if this is not the case, :exc:`TypeError` is raised. That object is then
asked to assign the assigned object to the given attribute; if it cannot
perform the assignment, it raises an exception (usually but not necessarily
:exc:`AttributeError`).
.. _attr-target-note:
Note: If the object is a class instance and the attribute reference occurs on
both sides of the assignment operator, the RHS expression, ``a.x`` can access
either an instance attribute or (if no instance attribute exists) a class
attribute. The LHS target ``a.x`` is always set as an instance attribute,
creating it if necessary. Thus, the two occurrences of ``a.x`` do not
necessarily refer to the same attribute: if the RHS expression refers to a
class attribute, the LHS creates a new instance attribute as the target of the
assignment::
class Cls:
x = 3 # class variable
inst = Cls()
inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
This description does not necessarily apply to descriptor attributes, such as
properties created with :func:`property`.
.. index::
pair: subscription; assignment
object: mutable
......@@ -253,16 +272,8 @@ same way as normal assignments. Similarly, with the exception of the possible
*in-place* behavior, the binary operation performed by augmented assignment is
the same as the normal binary operations.
For targets which are attribute references, the initial value is retrieved with
a :meth:`getattr` and the result is assigned with a :meth:`setattr`. Notice
that the two methods do not necessarily refer to the same variable. When
:meth:`getattr` refers to a class variable, :meth:`setattr` still writes to an
instance variable. For example::
class A:
x = 3 # class variable
a = A()
a.x += 1 # writes a.x as 4 leaving A.x as 3
For targets which are attribute references, the same :ref:`caveat about class
and instance attributes <attr-target-note>` applies as for regular assignments.
.. _assert:
......
......@@ -50,8 +50,8 @@ need for two different argument passing mechanisms as in Pascal.
.. _tut-scopes:
Python Scopes and Name Spaces
=============================
Python Scopes and Namespaces
============================
Before introducing classes, I first have to tell you something about Python's
scope rules. Class definitions play some neat tricks with namespaces, and you
......@@ -86,7 +86,7 @@ attributes is possible. Module attributes are writable: you can write
:keyword:`del` statement. For example, ``del modname.the_answer`` will remove
the attribute :attr:`the_answer` from the object named by ``modname``.
Name spaces are created at different moments and have different lifetimes. The
Namespaces are created at different moments and have different lifetimes. The
namespace containing the built-in names is created when the Python interpreter
starts up, and is never deleted. The global namespace for a module is created
when the module definition is read in; normally, module namespaces also last
......@@ -331,9 +331,9 @@ data attribute, its class is searched. If the name denotes a valid class
attribute that is a function object, a method object is created by packing
(pointers to) the instance object and the function object just found together in
an abstract object: this is the method object. When the method object is called
with an argument list, it is unpacked again, a new argument list is constructed
from the instance object and the original argument list, and the function object
is called with this new argument list.
with an argument list, a new argument list is constructed from the instance
object and the argument list, and the function object is called with this new
argument list.
.. _tut-remarks:
......
......@@ -165,14 +165,11 @@ exception type.
The except clause may specify a variable after the exception name (or tuple).
The variable is bound to an exception instance with the arguments stored in
``instance.args``. For convenience, the exception instance defines
:meth:`__getitem__` and :meth:`__str__` so the arguments can be accessed or
printed directly without having to reference ``.args``.
:meth:`__str__` so the arguments can be printed directly without having to
reference ``.args``.
But use of ``.args`` is discouraged. Instead, the preferred use is to pass a
single argument to an exception (which can be a tuple if multiple arguments are
needed) and have it bound to the ``message`` attribute. One may also
instantiate an exception first before raising it and add any attributes to it as
desired. ::
One may also instantiate an exception first before raising it and add any
attributes to it as desired. ::
>>> try:
... raise Exception('spam', 'eggs')
......@@ -248,9 +245,10 @@ re-raise the exception::
User-defined Exceptions
=======================
Programs may name their own exceptions by creating a new exception class.
Exceptions should typically be derived from the :exc:`Exception` class, either
directly or indirectly. For example::
Programs may name their own exceptions by creating a new exception class (see
:ref:`tut-classes` for more about Python classes). Exceptions should typically
be derived from the :exc:`Exception` class, either directly or indirectly. For
example::
>>> class MyError(Exception):
... def __init__(self, value):
......@@ -288,28 +286,28 @@ to create specific exception classes for different error conditions::
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
expr -- input expression in which the error occurred
msg -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
def __init__(self, expr, msg):
self.expr = expr
self.msg = msg
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
prev -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
msg -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
def __init__(self, prev, next, msg):
self.prev = prev
self.next = next
self.message = message
self.msg = msg
Most exceptions are defined with names that end in "Error," similar to the
naming of the standard exceptions.
......
......@@ -123,11 +123,11 @@ with zeros. It understands about plus and minus signs::
Basic usage of the :meth:`str.format` method looks like this::
>>> print 'We are the {0} who say "{1}!"'.format('knights', 'Ni')
>>> print 'We are the {} who say "{}!"'.format('knights', 'Ni')
We are the knights who say "Ni!"
The brackets and characters within them (called format fields) are replaced with
the objects passed into the :meth:`~str.format` method. The number in the
the objects passed into the :meth:`~str.format` method. A number in the
brackets refers to the position of the object passed into the
:meth:`~str.format` method. ::
......@@ -149,6 +149,15 @@ Positional and keyword arguments can be arbitrarily combined::
... other='Georg')
The story of Bill, Manfred, and Georg.
``'!s'`` (apply :func:`str`) and ``'!r'`` (apply :func:`repr`) can be used to
convert the value before it is formatted. ::
>>> import math
>>> print 'The value of PI is approximately {}.'.format(math.pi)
The value of PI is approximately 3.14159265359.
>>> print 'The value of PI is approximately {!r}.'.format(math.pi)
The value of PI is approximately 3.141592653589793.
An optional ``':'`` and format specifier can follow the field name. This allows
greater control over how the value is formatted. The following example
truncates Pi to three places after the decimal.
......@@ -239,8 +248,8 @@ writing. The *mode* argument is optional; ``'r'`` will be assumed if it's
omitted.
On Windows, ``'b'`` appended to the mode opens the file in binary mode, so there
are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. Windows makes a
distinction between text and binary files; the end-of-line characters in text
are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. Python on Windows makes
a distinction between text and binary files; the end-of-line characters in text
files are automatically altered slightly when data is read or written. This
behind-the-scenes modification to file data is fine for ASCII text files, but
it'll corrupt binary data like that in :file:`JPEG` or :file:`EXE` files. Be
......
......@@ -138,7 +138,6 @@ its magnitude (as a float) or ``z.real`` to get its real part. ::
4.0
>>> abs(a) # sqrt(a.real**2 + a.imag**2)
5.0
>>>
In interactive mode, the last printed expression is assigned to the variable
``_``. This means that when you are using Python as a desk calculator, it is
......@@ -152,7 +151,6 @@ somewhat easier to continue calculations, for example::
113.0625
>>> round(_, 2)
113.06
>>>
This variable should be treated as read-only by the user. Don't explicitly
assign a value to it --- you would create an independent local variable with the
......@@ -193,7 +191,9 @@ next line is a logical continuation of the line::
Note that newlines still need to be embedded in the string using ``\n``; the
newline following the trailing backslash is discarded. This example would print
the following::
the following:
.. code-block:: text
This is a rather long string containing
several lines of text just as you would do in C.
......@@ -209,7 +209,9 @@ they will be included in the string. ::
-H hostname Hostname to connect to
"""
produces the following output::
produces the following output:
.. code-block:: text
Usage: thingy [OPTIONS]
-h Display this usage message
......@@ -224,7 +226,9 @@ in the source, are both included in the string as data. Thus, the example::
print hello
would print::
would print:
.. code-block:: text
This is a rather long string containing\n\
several lines of text much as you would do in C.
......
......@@ -103,6 +103,10 @@ There is even a variant to import all names that a module defines::
This imports all names except those beginning with an underscore (``_``).
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
use it to save typing in interactive sessions.
.. note::
For efficiency reasons, each module is only imported once per interpreter
......@@ -443,14 +447,9 @@ Importing \* From a Package
Now what happens when the user writes ``from sound.effects import *``? Ideally,
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
: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.
submodules are present in the package, and imports them all. This could take a
long time and importing sub-modules might have unwanted side-effects that should
only happen when the sub-module is explicitly imported.
The only solution is for the package author to provide an explicit index of the
package. The :keyword:`import` statement uses the following convention: if a package's
......@@ -485,10 +484,9 @@ 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
use it to save typing in interactive sessions, and certain modules are designed
to export only names that follow certain patterns.
Although certain modules are designed to export only names that follow certain
patterns when you use ``import *``, it is still considered bad practise in
production code.
Remember, there is nothing wrong with using ``from Package import
specific_submodule``! In fact, this is the recommended notation unless the
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment