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 ...@@ -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. is no longer being used as it may free memory from it.
......
...@@ -148,7 +148,8 @@ latex_preamble = r''' ...@@ -148,7 +148,8 @@ latex_preamble = r'''
# Documents to append as an appendix to all manuals. # Documents to append as an appendix to all manuals.
latex_appendices = ['glossary', 'about', 'license', 'copyright'] 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 # Options for the coverage checker
# -------------------------------- # --------------------------------
......
...@@ -426,13 +426,6 @@ built-in functions in the installation script. ...@@ -426,13 +426,6 @@ built-in functions in the installation script.
also the configuration. For details refer to Microsoft's documentation of the also the configuration. For details refer to Microsoft's documentation of the
:cfunc:`SHGetSpecialFolderPath` function. :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]]]]) .. 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) ...@@ -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 and *iconindex* is the index of the icon in the file *iconpath*. Again, for
details consult the Microsoft documentation for the :class:`IShellLink` details consult the Microsoft documentation for the :class:`IShellLink`
interface. 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 ...@@ -210,11 +210,12 @@ To help understand the standard, Jukka Korpela has written an introductory guide
to reading the Unicode character tables, available at to reading the Unicode character tables, available at
<http://www.cs.tut.fi/~jkorpela/unicode/guide.html>. <http://www.cs.tut.fi/~jkorpela/unicode/guide.html>.
Two other good introductory articles were written by Joel Spolsky Another good introductory article was written by Joel Spolsky
<http://www.joelonsoftware.com/articles/Unicode.html> and Jason Orendorff <http://www.joelonsoftware.com/articles/Unicode.html>.
<http://www.jorendorff.com/articles/unicode/>. If this introduction didn't make If this introduction didn't make things clear to you, you should try reading this
things clear to you, you should try reading one of these alternate articles alternate article before continuing.
before continuing.
.. Jason Orendorff XXX http://www.jorendorff.com/articles/unicode/ is broken
Wikipedia entries are often helpful; see the entries for "character encoding" Wikipedia entries are often helpful; see the entries for "character encoding"
<http://en.wikipedia.org/wiki/Character_encoding> and UTF-8 <http://en.wikipedia.org/wiki/Character_encoding> and UTF-8
......
...@@ -10,9 +10,9 @@ ...@@ -10,9 +10,9 @@
* To avoid confusing existing tools that analyze import statements and expect to * To avoid confusing existing tools that analyze import statements and expect to
find the modules they're importing. find the modules they're importing.
* To ensure that future_statements run under releases prior to 2.1 at least * To ensure that :ref:`future statements <future>` run under releases prior to
yield runtime exceptions (the import of :mod:`__future__` will fail, because 2.1 at least yield runtime exceptions (the import of :mod:`__future__` will
there was no module of that name prior to 2.1). 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 * To document when incompatible changes were introduced, and when they will be
--- or were --- made mandatory. This is a form of executable documentation, and --- 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 ...@@ -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` dynamically compiled code. This flag is stored in the :attr:`compiler_flag`
attribute on :class:`_Feature` instances. 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:: .. seealso::
......
...@@ -213,7 +213,7 @@ The problem with the code is that you should never expect that a client will ...@@ -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 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, 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 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 (since lists do not have a method of this name) and results in an
:exc:`AttributeError` exception. :exc:`AttributeError` exception.
......
...@@ -863,7 +863,8 @@ or with dictionaries as mapping tables. The following table lists the codecs by ...@@ -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 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 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 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 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 characters (e.g. whether the EURO SIGN is supported or not), and in the
......
...@@ -62,7 +62,7 @@ should not be used in programs. ...@@ -62,7 +62,7 @@ should not be used in programs.
Objects that when printed, print a message like "Use quit() or Ctrl-D 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 (i.e. EOF) to exit", and when called, raise :exc:`SystemExit` with the
specified exit code, and when . specified exit code.
.. data:: copyright .. data:: copyright
license license
......
:mod:`copy` --- Shallow and deep copy operations :mod:`copy` --- Shallow and deep copy operations
================================================ ================================================
.. module:: copy .. module:: copy
:synopsis: Shallow and deep copy operations. :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 Raised for module specific errors.
x = copy.deepcopy(y) # make a deep copy of y
For module specific errors, :exc:`copy.error` is raised.
The difference between shallow and deep copying is only relevant for compound The difference between shallow and deep copying is only relevant for compound
objects (objects that contain other objects, like lists or class instances): objects (objects that contain other objects, like lists or class instances):
......
...@@ -1601,7 +1601,7 @@ type and the argument types of the function. ...@@ -1601,7 +1601,7 @@ type and the argument types of the function.
The returned function prototype creates functions that use the standard C The returned function prototype creates functions that use the standard C
calling convention. The function will release the GIL during the call. If 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 *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 and after the call; *use_last_error* does the same for the Windows error
code. code.
......
...@@ -147,7 +147,8 @@ followed by ``lines`` for the text version or ``binary`` for the binary version. ...@@ -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, ``'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 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 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() .. method:: FTP.abort()
......
...@@ -78,11 +78,11 @@ The following values are provided as constant attributes of the hash objects ...@@ -78,11 +78,11 @@ The following values are provided as constant attributes of the hash objects
returned by the constructors: returned by the constructors:
.. data:: digest_size .. data:: hash.digest_size
The size of the resulting hash in bytes. 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. The internal block size of the hash algorithm in bytes.
......
...@@ -567,6 +567,11 @@ line. ...@@ -567,6 +567,11 @@ line.
Return the frame object for the caller's stack frame. 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]) .. function:: stack([context])
......
...@@ -1195,6 +1195,28 @@ are sent to both destinations. ...@@ -1195,6 +1195,28 @@ are sent to both destinations.
This example uses console and file handlers, but you can use any number and This example uses console and file handlers, but you can use any number and
combination of handlers you choose. 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: .. _context-info:
......
...@@ -37,12 +37,14 @@ supports a substantially wider range of objects than marshal. ...@@ -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 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 is independent from a particular invocation of Python can be written and read by
this module. The following types are supported: ``None``, integers, long this module. The following types are supported: booleans, integers, long
integers, floating point numbers, strings, Unicode objects, tuples, lists, sets, integers, floating point numbers, complex numbers, strings, Unicode objects,
dictionaries, and code objects, where it should be understood that tuples, lists tuples, lists, sets, frozensets, dictionaries, and code objects, where it should
and dictionaries are only supported as long as the values contained therein are be understood that tuples, lists, sets, frozensets and dictionaries are only
themselves supported; and recursive lists and dictionaries should not be written supported as long as the values contained therein are themselves supported; and
(they will cause infinite loops). 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:: .. warning::
......
...@@ -166,8 +166,10 @@ Power and logarithmic functions ...@@ -166,8 +166,10 @@ Power and logarithmic functions
.. function:: log(x[, base]) .. function:: log(x[, base])
Return the logarithm of *x* to the given *base*. If the *base* is not specified, With one argument, return the natural logarithm of *x* (to base *e*).
return the natural logarithm of *x* (that is, the logarithm to base *e*).
With two arguments, return the logarithm of *x* to the given *base*,
calculated as ``log(x)/log(base)``.
.. versionchanged:: 2.3 .. versionchanged:: 2.3
*base* argument added. *base* argument added.
...@@ -183,7 +185,8 @@ Power and logarithmic functions ...@@ -183,7 +185,8 @@ Power and logarithmic functions
.. function:: log10(x) .. 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) .. function:: pow(x, y)
......
...@@ -1067,12 +1067,12 @@ Files and Directories ...@@ -1067,12 +1067,12 @@ Files and Directories
.. function:: remove(path) .. function:: remove(path)
Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
:func:`rmdir` below to remove a directory. This is identical to the raised; see :func:`rmdir` below to remove a directory. This is identical to
:func:`unlink` function documented below. On Windows, attempting to remove a the :func:`unlink` function documented below. On Windows, attempting to
file that is in use causes an exception to be raised; on Unix, the directory remove a file that is in use causes an exception to be raised; on Unix, the
entry is removed but the storage allocated to the file is not made available directory entry is removed but the storage allocated to the file is not made
until the original file is no longer in use. Availability: Unix, available until the original file is no longer in use. Availability: Unix,
Windows. Windows.
...@@ -1121,7 +1121,10 @@ Files and Directories ...@@ -1121,7 +1121,10 @@ Files and Directories
.. function:: rmdir(path) .. 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) .. function:: stat(path)
...@@ -1297,9 +1300,9 @@ Files and Directories ...@@ -1297,9 +1300,9 @@ Files and Directories
.. function:: unlink(path) .. function:: unlink(path)
Remove the file *path*. This is the same function as :func:`remove`; the Remove (delete) the file *path*. This is the same function as
:func:`unlink` name is its traditional Unix name. Availability: Unix, :func:`remove`; the :func:`unlink` name is its traditional Unix
Windows. name. Availability: Unix, Windows.
.. function:: utime(path, times) .. function:: utime(path, times)
......
:mod:`readline` --- GNU readline interface :mod:`readline` --- GNU readline interface
========================================== ==========================================
...@@ -221,7 +220,7 @@ support history save/restore. :: ...@@ -221,7 +220,7 @@ support history save/restore. ::
class HistoryConsole(code.InteractiveConsole): class HistoryConsole(code.InteractiveConsole):
def __init__(self, locals=None, filename="<console>", def __init__(self, locals=None, filename="<console>",
histfile=os.path.expanduser("~/.console-history")): histfile=os.path.expanduser("~/.console-history")):
code.InteractiveConsole.__init__(self) code.InteractiveConsole.__init__(self, locals, filename)
self.init_history(histfile) self.init_history(histfile)
def init_history(self, histfile): def init_history(self, histfile):
......
...@@ -211,9 +211,9 @@ The :mod:`signal` module defines the following functions: ...@@ -211,9 +211,9 @@ The :mod:`signal` module defines the following functions:
exception to be raised. exception to be raised.
The *handler* is called with two arguments: the signal number and the current 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 stack frame (``None`` or a frame object; for a description of frame objects,
the reference manual section on the standard type hierarchy or see the attribute see the :ref:`description in the type hierarchy <frame-objects>` or see the
descriptions in the :mod:`inspect` module). attribute descriptions in the :mod:`inspect` module).
.. _signal-example: .. _signal-example:
......
...@@ -465,7 +465,7 @@ This is the client side:: ...@@ -465,7 +465,7 @@ This is the client side::
import socket import socket
import sys import sys
HOST, PORT = "localhost" HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:]) data = " ".join(sys.argv[1:])
# SOCK_DGRAM is the socket type to use for UDP sockets # SOCK_DGRAM is the socket type to use for UDP sockets
......
:mod:`ssl` --- SSL wrapper for socket objects :mod:`ssl` --- SSL wrapper for socket objects
==================================================================== =============================================
.. module:: ssl .. module:: ssl
:synopsis: SSL wrapper for socket objects :synopsis: SSL wrapper for socket objects
...@@ -16,32 +15,29 @@ ...@@ -16,32 +15,29 @@
.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer .. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
This module provides access to Transport Layer Security (often known This module provides access to Transport Layer Security (often known as "Secure
as "Secure Sockets Layer") encryption and peer authentication Sockets Layer") encryption and peer authentication facilities for network
facilities for network sockets, both client-side and server-side. sockets, both client-side and server-side. This module uses the OpenSSL
This module uses the OpenSSL library. It is available on all modern library. It is available on all modern Unix systems, Windows, Mac OS X, and
Unix systems, Windows, Mac OS X, and probably additional probably additional platforms, as long as OpenSSL is installed on that platform.
platforms, as long as OpenSSL is installed on that platform.
.. note:: .. note::
Some behavior may be platform dependent, since calls are made to the operating Some behavior may be platform dependent, since calls are made to the
system socket APIs. The installed version of OpenSSL may also cause operating system socket APIs. The installed version of OpenSSL may also
variations in behavior. cause variations in behavior.
This section documents the objects and functions in the ``ssl`` module; This section documents the objects and functions in the ``ssl`` module; for more
for more general information about TLS, SSL, and certificates, the general information about TLS, SSL, and certificates, the reader is referred to
reader is referred to the documents in the "See Also" section at the documents in the "See Also" section at the bottom.
the bottom.
This module provides a class, :class:`ssl.SSLSocket`, which is This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
derived from the :class:`socket.socket` type, and provides :class:`socket.socket` type, and provides a socket-like wrapper that also
a socket-like wrapper that also encrypts and decrypts the data encrypts and decrypts the data going over the socket with SSL. It supports
going over the socket with SSL. It supports additional additional :meth:`read` and :meth:`write` methods, along with a method,
:meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`, :meth:`getpeercert`, to retrieve the certificate of the other side of the
to retrieve the certificate of the other side of the connection, and connection, and a method, :meth:`cipher`, to retrieve the cipher being used for
a method, :meth:`cipher`, to retrieve the cipher being used for the the secure connection.
secure connection.
Functions, Constants, and Exceptions Functions, Constants, and Exceptions
------------------------------------ ------------------------------------
...@@ -49,31 +45,33 @@ Functions, Constants, and Exceptions ...@@ -49,31 +45,33 @@ Functions, Constants, and Exceptions
.. exception:: SSLError .. exception:: SSLError
Raised to signal an error from the underlying SSL implementation. This Raised to signal an error from the underlying SSL implementation. This
signifies some problem in the higher-level signifies some problem in the higher-level encryption and authentication
encryption and authentication layer that's superimposed on the underlying layer that's superimposed on the underlying network connection. This error
network connection. This error is a subtype of :exc:`socket.error`, which is a subtype of :exc:`socket.error`, which in turn is a subtype of
in turn is a subtype of :exc:`IOError`. :exc:`IOError`.
.. function:: wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True) .. function:: wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True)
Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of :class:`ssl.SSLSocket`, a subtype Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
of :class:`socket.socket`, which wraps the underlying socket in an SSL context. of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
For client-side sockets, the context construction is lazy; if the underlying socket isn't the underlying socket in an SSL context. For client-side sockets, the
connected yet, the context construction will be performed after :meth:`connect` is called context construction is lazy; if the underlying socket isn't connected yet,
on the socket. For server-side sockets, if the socket has no remote peer, it is assumed the context construction will be performed after :meth:`connect` is called on
to be a listening socket, and the server-side SSL wrapping is automatically performed the socket. For server-side sockets, if the socket has no remote peer, it is
on client connections accepted via the :meth:`accept` method. :func:`wrap_socket` may assumed to be a listening socket, and the server-side SSL wrapping is
raise :exc:`SSLError`. automatically performed on client connections accepted via the :meth:`accept`
method. :func:`wrap_socket` may raise :exc:`SSLError`.
The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate
to be used to identify the local side of the connection. See the discussion of :ref:`ssl-certificates` The ``keyfile`` and ``certfile`` parameters specify optional files which
for more information on how the certificate is stored in the ``certfile``. contain a certificate to be used to identify the local side of the
connection. See the discussion of :ref:`ssl-certificates` for more
Often the private key is stored information on how the certificate is stored in the ``certfile``.
in the same file as the certificate; in this case, only the ``certfile`` parameter need be
passed. If the private key is stored in a separate file, both parameters must be used. Often the private key is stored in the same file as the certificate; in this
If the private key is stored in the ``certfile``, it should come before the first certificate case, only the ``certfile`` parameter need be passed. If the private key is
in the certificate chain:: stored in a separate file, both parameters must be used. If the private key
is stored in the ``certfile``, it should come before the first certificate in
the certificate chain::
-----BEGIN RSA PRIVATE KEY----- -----BEGIN RSA PRIVATE KEY-----
... (private key in base64 encoding) ... ... (private key in base64 encoding) ...
...@@ -82,31 +80,33 @@ Functions, Constants, and Exceptions ...@@ -82,31 +80,33 @@ Functions, Constants, and Exceptions
... (certificate in base64 PEM encoding) ... ... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE----- -----END CERTIFICATE-----
The parameter ``server_side`` is a boolean which identifies whether server-side or client-side The parameter ``server_side`` is a boolean which identifies whether
behavior is desired from this socket. server-side or client-side behavior is desired from this socket.
The parameter ``cert_reqs`` specifies whether a certificate is The parameter ``cert_reqs`` specifies whether a certificate is required from
required from the other side of the connection, and whether it will the other side of the connection, and whether it will be validated if
be validated if provided. It must be one of the three values provided. It must be one of the three values :const:`CERT_NONE`
:const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required, (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
but validated if provided), or :const:`CERT_REQUIRED` (required and if provided), or :const:`CERT_REQUIRED` (required and validated). If the
validated). If the value of this parameter is not :const:`CERT_NONE`, then value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
the ``ca_certs`` parameter must point to a file of CA certificates. parameter must point to a file of CA certificates.
The ``ca_certs`` file contains a set of concatenated "certification authority" certificates, The ``ca_certs`` file contains a set of concatenated "certification
which are used to validate certificates passed from the other end of the connection. authority" certificates, which are used to validate certificates passed from
See the discussion of :ref:`ssl-certificates` for more information about how to arrange the other end of the connection. See the discussion of
the certificates in this file. :ref:`ssl-certificates` for more information about how to arrange the
certificates in this file.
The parameter ``ssl_version`` specifies which version of the SSL protocol to use.
Typically, the server chooses a particular protocol version, and the client The parameter ``ssl_version`` specifies which version of the SSL protocol to
must adapt to the server's choice. Most of the versions are not interoperable use. Typically, the server chooses a particular protocol version, and the
with the other versions. If not specified, for client-side operation, the client must adapt to the server's choice. Most of the versions are not
default SSL version is SSLv3; for server-side operation, SSLv23. These interoperable with the other versions. If not specified, for client-side
version selections provide the most compatibility with other versions. operation, the default SSL version is SSLv3; for server-side operation,
SSLv23. These version selections provide the most compatibility with other
Here's a table showing which versions in a client (down the side) versions.
can connect to which versions in a server (along the top):
Here's a table showing which versions in a client (down the side) can connect
to which versions in a server (along the top):
.. table:: .. table::
...@@ -119,51 +119,52 @@ Functions, Constants, and Exceptions ...@@ -119,51 +119,52 @@ Functions, Constants, and Exceptions
*TLSv1* no no yes yes *TLSv1* no no yes yes
======================== ========= ========= ========== ========= ======================== ========= ========= ========== =========
In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4), In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4), an
an SSLv2 client could not connect to an SSLv23 server. SSLv2 client could not connect to an SSLv23 server.
The parameter ``do_handshake_on_connect`` specifies whether to do the SSL The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
handshake automatically after doing a :meth:`socket.connect`, or whether the handshake automatically after doing a :meth:`socket.connect`, or whether the
application program will call it explicitly, by invoking the :meth:`SSLSocket.do_handshake` application program will call it explicitly, by invoking the
method. Calling :meth:`SSLSocket.do_handshake` explicitly gives the program control over :meth:`SSLSocket.do_handshake` method. Calling
the blocking behavior of the socket I/O involved in the handshake. :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
blocking behavior of the socket I/O involved in the handshake.
The parameter ``suppress_ragged_eofs`` specifies how the :meth:`SSLSocket.read` The parameter ``suppress_ragged_eofs`` specifies how the
method should signal unexpected EOF from the other end of the connection. If specified :meth:`SSLSocket.read` method should signal unexpected EOF from the other end
as :const:`True` (the default), it returns a normal EOF in response to unexpected of the connection. If specified as :const:`True` (the default), it returns a
EOF errors raised from the underlying socket; if :const:`False`, it will raise normal EOF in response to unexpected EOF errors raised from the underlying
the exceptions back to the caller. socket; if :const:`False`, it will raise the exceptions back to the caller.
.. function:: RAND_status() .. function:: RAND_status()
Returns True if the SSL pseudo-random number generator has been Returns True if the SSL pseudo-random number generator has been seeded with
seeded with 'enough' randomness, and False otherwise. You can use 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
:func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
of the pseudo-random number generator. number generator.
.. function:: RAND_egd(path) .. function:: RAND_egd(path)
If you are running an entropy-gathering daemon (EGD) somewhere, and ``path`` If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
is the pathname of a socket connection open to it, this will read is the pathname of a socket connection open to it, this will read 256 bytes
256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator of randomness from the socket, and add it to the SSL pseudo-random number
to increase the security of generated secret keys. This is typically only generator to increase the security of generated secret keys. This is
necessary on systems without better sources of randomness. typically only necessary on systems without better sources of randomness.
See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
sources of entropy-gathering daemons. of entropy-gathering daemons.
.. function:: RAND_add(bytes, entropy) .. function:: RAND_add(bytes, entropy)
Mixes the given ``bytes`` into the SSL pseudo-random number generator. Mixes the given ``bytes`` into the SSL pseudo-random number generator. The
The parameter ``entropy`` (a float) is a lower bound on the entropy parameter ``entropy`` (a float) is a lower bound on the entropy contained in
contained in string (so you can always use :const:`0.0`). string (so you can always use :const:`0.0`). See :rfc:`1750` for more
See :rfc:`1750` for more information on sources of entropy. information on sources of entropy.
.. function:: cert_time_to_seconds(timestring) .. function:: cert_time_to_seconds(timestring)
Returns a floating-point value containing a normal seconds-after-the-epoch time Returns a floating-point value containing a normal seconds-after-the-epoch
value, given the time-string representing the "notBefore" or "notAfter" date time value, given the time-string representing the "notBefore" or "notAfter"
from a certificate. date from a certificate.
Here's an example:: Here's an example::
...@@ -177,14 +178,13 @@ Functions, Constants, and Exceptions ...@@ -177,14 +178,13 @@ Functions, Constants, and Exceptions
.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None) .. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Given the address ``addr`` of an SSL-protected server, as a Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
(*hostname*, *port-number*) pair, fetches the server's certificate, *port-number*) pair, fetches the server's certificate, and returns it as a
and returns it as a PEM-encoded string. If ``ssl_version`` is PEM-encoded string. If ``ssl_version`` is specified, uses that version of
specified, uses that version of the SSL protocol to attempt to the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
connect to the server. If ``ca_certs`` is specified, it should be specified, it should be a file containing a list of root certificates, the
a file containing a list of root certificates, the same format as same format as used for the same parameter in :func:`wrap_socket`. The call
used for the same parameter in :func:`wrap_socket`. The call will will attempt to validate the server certificate against that set of root
attempt to validate the server certificate against that set of root
certificates, and will fail if the validation attempt fails. certificates, and will fail if the validation attempt fails.
.. function:: DER_cert_to_PEM_cert (DER_cert_bytes) .. function:: DER_cert_to_PEM_cert (DER_cert_bytes)
...@@ -194,31 +194,29 @@ Functions, Constants, and Exceptions ...@@ -194,31 +194,29 @@ Functions, Constants, and Exceptions
.. function:: PEM_cert_to_DER_cert (PEM_cert_string) .. function:: PEM_cert_to_DER_cert (PEM_cert_string)
Given a certificate as an ASCII PEM string, returns a DER-encoded Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
sequence of bytes for that same certificate. bytes for that same certificate.
.. data:: CERT_NONE .. data:: CERT_NONE
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
when no certificates will be required or validated from the other certificates will be required or validated from the other side of the socket
side of the socket connection. connection.
.. data:: CERT_OPTIONAL .. data:: CERT_OPTIONAL
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
when no certificates will be required from the other side of the certificates will be required from the other side of the socket connection,
socket connection, but if they are provided, will be validated. but if they are provided, will be validated. Note that use of this setting
Note that use of this setting requires a valid certificate requires a valid certificate validation file also be passed as a value of the
validation file also be passed as a value of the ``ca_certs`` ``ca_certs`` parameter.
parameter.
.. data:: CERT_REQUIRED .. data:: CERT_REQUIRED
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when
when certificates will be required from the other side of the certificates will be required from the other side of the socket connection.
socket connection. Note that use of this setting requires a valid certificate Note that use of this setting requires a valid certificate validation file
validation file also be passed as a value of the ``ca_certs`` also be passed as a value of the ``ca_certs`` parameter.
parameter.
.. data:: PROTOCOL_SSLv2 .. data:: PROTOCOL_SSLv2
...@@ -226,22 +224,21 @@ Functions, Constants, and Exceptions ...@@ -226,22 +224,21 @@ Functions, Constants, and Exceptions
.. data:: PROTOCOL_SSLv23 .. data:: PROTOCOL_SSLv23
Selects SSL version 2 or 3 as the channel encryption protocol. Selects SSL version 2 or 3 as the channel encryption protocol. This is a
This is a setting to use with servers for maximum compatibility setting to use with servers for maximum compatibility with the other end of
with the other end of an SSL connection, but it may cause the an SSL connection, but it may cause the specific ciphers chosen for the
specific ciphers chosen for the encryption to be of fairly low encryption to be of fairly low quality.
quality.
.. data:: PROTOCOL_SSLv3 .. data:: PROTOCOL_SSLv3
Selects SSL version 3 as the channel encryption protocol. Selects SSL version 3 as the channel encryption protocol. For clients, this
For clients, this is the maximally compatible SSL variant. is the maximally compatible SSL variant.
.. data:: PROTOCOL_TLSv1 .. data:: PROTOCOL_TLSv1
Selects TLS version 1 as the channel encryption protocol. This is Selects TLS version 1 as the channel encryption protocol. This is the most
the most modern version, and probably the best choice for maximum modern version, and probably the best choice for maximum protection, if both
protection, if both sides can speak it. sides can speak it.
SSLSocket Objects SSLSocket Objects
...@@ -253,30 +250,28 @@ SSLSocket Objects ...@@ -253,30 +250,28 @@ SSLSocket Objects
.. method:: SSLSocket.write(data) .. method:: SSLSocket.write(data)
Writes the ``data`` to the other side of the connection, using the Writes the ``data`` to the other side of the connection, using the SSL
SSL channel to encrypt. Returns the number of bytes written. channel to encrypt. Returns the number of bytes written.
.. method:: SSLSocket.getpeercert(binary_form=False) .. method:: SSLSocket.getpeercert(binary_form=False)
If there is no certificate for the peer on the other end of the If there is no certificate for the peer on the other end of the connection,
connection, returns ``None``. returns ``None``.
If the parameter ``binary_form`` is :const:`False`, and a If the parameter ``binary_form`` is :const:`False`, and a certificate was
certificate was received from the peer, this method returns a received from the peer, this method returns a :class:`dict` instance. If the
:class:`dict` instance. If the certificate was not validated, the certificate was not validated, the dict is empty. If the certificate was
dict is empty. If the certificate was validated, it returns a dict validated, it returns a dict with the keys ``subject`` (the principal for
with the keys ``subject`` (the principal for which the certificate which the certificate was issued), and ``notAfter`` (the time after which the
was issued), and ``notAfter`` (the time after which the certificate certificate should not be trusted). The certificate was already validated,
should not be trusted). The certificate was already validated, so so the ``notBefore`` and ``issuer`` fields are not returned. If a
the ``notBefore`` and ``issuer`` fields are not returned. If a certificate contains an instance of the *Subject Alternative Name* extension
certificate contains an instance of the *Subject Alternative Name* (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the
extension (see :rfc:`3280`), there will also be a dictionary.
``subjectAltName`` key in the dictionary.
The "subject" field is a tuple containing the sequence of relative The "subject" field is a tuple containing the sequence of relative
distinguished names (RDNs) given in the certificate's data distinguished names (RDNs) given in the certificate's data structure for the
structure for the principal, and each RDN is a sequence of principal, and each RDN is a sequence of name-value pairs::
name-value pairs::
{'notAfter': 'Feb 16 16:54:50 2013 GMT', {'notAfter': 'Feb 16 16:54:50 2013 GMT',
'subject': ((('countryName', u'US'),), 'subject': ((('countryName', u'US'),),
...@@ -286,29 +281,27 @@ SSLSocket Objects ...@@ -286,29 +281,27 @@ SSLSocket Objects
(('organizationalUnitName', u'SSL'),), (('organizationalUnitName', u'SSL'),),
(('commonName', u'somemachine.python.org'),))} (('commonName', u'somemachine.python.org'),))}
If the ``binary_form`` parameter is :const:`True`, and a If the ``binary_form`` parameter is :const:`True`, and a certificate was
certificate was provided, this method returns the DER-encoded form provided, this method returns the DER-encoded form of the entire certificate
of the entire certificate as a sequence of bytes, or :const:`None` if the as a sequence of bytes, or :const:`None` if the peer did not provide a
peer did not provide a certificate. This return certificate. This return value is independent of validation; if validation
value is independent of validation; if validation was required was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
(:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
been validated, but if :const:`CERT_NONE` was used to establish the been validated, but if :const:`CERT_NONE` was used to establish the
connection, the certificate, if present, will not have been validated. connection, the certificate, if present, will not have been validated.
.. method:: SSLSocket.cipher() .. method:: SSLSocket.cipher()
Returns a three-value tuple containing the name of the cipher being Returns a three-value tuple containing the name of the cipher being used, the
used, the version of the SSL protocol that defines its use, and the version of the SSL protocol that defines its use, and the number of secret
number of secret bits being used. If no connection has been bits being used. If no connection has been established, returns ``None``.
established, returns ``None``.
.. method:: SSLSocket.do_handshake() .. method:: SSLSocket.do_handshake()
Perform a TLS/SSL handshake. If this is used with a non-blocking socket, Perform a TLS/SSL handshake. If this is used with a non-blocking socket, it
it may raise :exc:`SSLError` with an ``arg[0]`` of :const:`SSL_ERROR_WANT_READ` may raise :exc:`SSLError` with an ``arg[0]`` of :const:`SSL_ERROR_WANT_READ`
or :const:`SSL_ERROR_WANT_WRITE`, in which case it must be called again until it or :const:`SSL_ERROR_WANT_WRITE`, in which case it must be called again until
completes successfully. For example, to simulate the behavior of a blocking socket, it completes successfully. For example, to simulate the behavior of a
one might write:: blocking socket, one might write::
while True: while True:
try: try:
...@@ -324,13 +317,12 @@ SSLSocket Objects ...@@ -324,13 +317,12 @@ SSLSocket Objects
.. method:: SSLSocket.unwrap() .. method:: SSLSocket.unwrap()
Performs the SSL shutdown handshake, which removes the TLS layer Performs the SSL shutdown handshake, which removes the TLS layer from the
from the underlying socket, and returns the underlying socket underlying socket, and returns the underlying socket object. This can be
object. This can be used to go from encrypted operation over a used to go from encrypted operation over a connection to unencrypted. The
connection to unencrypted. The socket instance returned should always be socket instance returned should always be used for further communication with
used for further communication with the other side of the the other side of the connection, rather than the original socket instance
connection, rather than the original socket instance (which may (which may not function properly after the unwrap).
not function properly after the unwrap).
.. index:: single: certificates .. index:: single: certificates
...@@ -341,57 +333,54 @@ SSLSocket Objects ...@@ -341,57 +333,54 @@ SSLSocket Objects
Certificates Certificates
------------ ------------
Certificates in general are part of a public-key / private-key system. In this system, each *principal*, Certificates in general are part of a public-key / private-key system. In this
(which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key. system, each *principal*, (which may be a machine, or a person, or an
One part of the key is public, and is called the *public key*; the other part is kept secret, and is called organization) is assigned a unique two-part encryption key. One part of the key
the *private key*. The two parts are related, in that if you encrypt a message with one of the parts, you can is public, and is called the *public key*; the other part is kept secret, and is
decrypt it with the other part, and **only** with the other part. called the *private key*. The two parts are related, in that if you encrypt a
message with one of the parts, you can decrypt it with the other part, and
A certificate contains information about two principals. It contains **only** with the other part.
the name of a *subject*, and the subject's public key. It also
contains a statement by a second principal, the *issuer*, that the A certificate contains information about two principals. It contains the name
subject is who he claims to be, and that this is indeed the subject's of a *subject*, and the subject's public key. It also contains a statement by a
public key. The issuer's statement is signed with the issuer's second principal, the *issuer*, that the subject is who he claims to be, and
private key, which only the issuer knows. However, anyone can verify that this is indeed the subject's public key. The issuer's statement is signed
the issuer's statement by finding the issuer's public key, decrypting with the issuer's private key, which only the issuer knows. However, anyone can
the statement with it, and comparing it to the other information in verify the issuer's statement by finding the issuer's public key, decrypting the
the certificate. The certificate also contains information about the statement with it, and comparing it to the other information in the certificate.
time period over which it is valid. This is expressed as two fields, The certificate also contains information about the time period over which it is
called "notBefore" and "notAfter". valid. This is expressed as two fields, called "notBefore" and "notAfter".
In the Python use of certificates, a client or server In the Python use of certificates, a client or server can use a certificate to
can use a certificate to prove who they are. The other prove who they are. The other side of a network connection can also be required
side of a network connection can also be required to produce a certificate, to produce a certificate, and that certificate can be validated to the
and that certificate can be validated to the satisfaction satisfaction of the client or server that requires such validation. The
of the client or server that requires such validation. connection attempt can be set to raise an exception if the validation fails.
The connection attempt can be set to raise an exception if Validation is done automatically, by the underlying OpenSSL framework; the
the validation fails. Validation is done application need not concern itself with its mechanics. But the application
automatically, by the underlying OpenSSL framework; the does usually need to provide sets of certificates to allow this process to take
application need not concern itself with its mechanics. place.
But the application does usually need to provide
sets of certificates to allow this process to take place. Python uses files to contain certificates. They should be formatted as "PEM"
(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
Python uses files to contain certificates. They should be formatted and a footer line::
as "PEM" (see :rfc:`1422`), which is a base-64 encoded form wrapped
with a header line and a footer line::
-----BEGIN CERTIFICATE----- -----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ... ... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE----- -----END CERTIFICATE-----
The Python files which contain certificates can contain a sequence The Python files which contain certificates can contain a sequence of
of certificates, sometimes called a *certificate chain*. This chain certificates, sometimes called a *certificate chain*. This chain should start
should start with the specific certificate for the principal who "is" with the specific certificate for the principal who "is" the client or server,
the client or server, and then the certificate for the issuer of that and then the certificate for the issuer of that certificate, and then the
certificate, and then the certificate for the issuer of *that* certificate, certificate for the issuer of *that* certificate, and so on up the chain till
and so on up the chain till you get to a certificate which is *self-signed*, you get to a certificate which is *self-signed*, that is, a certificate which
that is, a certificate which has the same subject and issuer, has the same subject and issuer, sometimes called a *root certificate*. The
sometimes called a *root certificate*. The certificates should just certificates should just be concatenated together in the certificate file. For
be concatenated together in the certificate file. For example, suppose example, suppose we had a three certificate chain, from our server certificate
we had a three certificate chain, from our server certificate to the to the certificate of the certification authority that signed our server
certificate of the certification authority that signed our server certificate, certificate, to the root certificate of the agency which issued the
to the root certificate of the agency which issued the certification authority's certification authority's certificate::
certificate::
-----BEGIN CERTIFICATE----- -----BEGIN CERTIFICATE-----
... (certificate for your server)... ... (certificate for your server)...
...@@ -405,33 +394,30 @@ certificate:: ...@@ -405,33 +394,30 @@ certificate::
If you are going to require validation of the other side of the connection's If you are going to require validation of the other side of the connection's
certificate, you need to provide a "CA certs" file, filled with the certificate certificate, you need to provide a "CA certs" file, filled with the certificate
chains for each issuer you are willing to trust. Again, this file just chains for each issuer you are willing to trust. Again, this file just contains
contains these chains concatenated together. For validation, Python will these chains concatenated together. For validation, Python will use the first
use the first chain it finds in the file which matches. chain it finds in the file which matches.
Some "standard" root certificates are available from various certification Some "standard" root certificates are available from various certification
authorities: authorities: `CACert.org <http://www.cacert.org/index.php?id=3>`_, `Thawte
`CACert.org <http://www.cacert.org/index.php?id=3>`_, <http://www.thawte.com/roots/>`_, `Verisign
`Thawte <http://www.thawte.com/roots/>`_, <http://www.verisign.com/support/roots.html>`_, `Positive SSL
`Verisign <http://www.verisign.com/support/roots.html>`_, <http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
`Positive SSL <http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_ (used by python.org), (used by python.org), `Equifax and GeoTrust
`Equifax and GeoTrust <http://www.geotrust.com/resources/root_certificates/index.asp>`_. <http://www.geotrust.com/resources/root_certificates/index.asp>`_.
In general, if you are using In general, if you are using SSL3 or TLS1, you don't need to put the full chain
SSL3 or TLS1, you don't need to put the full chain in your "CA certs" file; in your "CA certs" file; you only need the root certificates, and the remote
you only need the root certificates, and the remote peer is supposed to peer is supposed to furnish the other certificates necessary to chain from its
furnish the other certificates necessary to chain from its certificate to certificate to a root certificate. See :rfc:`4158` for more discussion of the
a root certificate. way in which certification chains can be built.
See :rfc:`4158` for more discussion of the way in which
certification chains can be built. If you are going to create a server that provides SSL-encrypted connection
services, you will need to acquire a certificate for that service. There are
If you are going to create a server that provides SSL-encrypted many ways of acquiring appropriate certificates, such as buying one from a
connection services, you will need to acquire a certificate for that certification authority. Another common practice is to generate a self-signed
service. There are many ways of acquiring appropriate certificates, certificate. The simplest way to do this is with the OpenSSL package, using
such as buying one from a certification authority. Another common something like the following::
practice is to generate a self-signed certificate. The simplest
way to do this is with the OpenSSL package, using something like
the following::
% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
Generating a 1024 bit RSA private key Generating a 1024 bit RSA private key
...@@ -455,9 +441,9 @@ the following:: ...@@ -455,9 +441,9 @@ the following::
Email Address []:ops@myserver.mygroup.myorganization.com Email Address []:ops@myserver.mygroup.myorganization.com
% %
The disadvantage of a self-signed certificate is that it is its The disadvantage of a self-signed certificate is that it is its own root
own root certificate, and no one else will have it in their cache certificate, and no one else will have it in their cache of known (and trusted)
of known (and trusted) root certificates. root certificates.
Examples Examples
...@@ -466,7 +452,8 @@ Examples ...@@ -466,7 +452,8 @@ Examples
Testing for SSL support Testing for SSL support
^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
To test for the presence of SSL support in a Python installation, user code should use the following idiom:: To test for the presence of SSL support in a Python installation, user code
should use the following idiom::
try: try:
import ssl import ssl
...@@ -478,8 +465,8 @@ To test for the presence of SSL support in a Python installation, user code shou ...@@ -478,8 +465,8 @@ To test for the presence of SSL support in a Python installation, user code shou
Client-side operation Client-side operation
^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
This example connects to an SSL server, prints the server's address and certificate, This example connects to an SSL server, prints the server's address and
sends some bytes, and reads part of the response:: certificate, sends some bytes, and reads part of the response::
import socket, ssl, pprint import socket, ssl, pprint
...@@ -507,8 +494,8 @@ sends some bytes, and reads part of the response:: ...@@ -507,8 +494,8 @@ sends some bytes, and reads part of the response::
# note that closing the SSLSocket will also close the underlying socket # note that closing the SSLSocket will also close the underlying socket
ssl_sock.close() ssl_sock.close()
As of September 6, 2007, the certificate printed by this program As of September 6, 2007, the certificate printed by this program looked like
looked like this:: this::
{'notAfter': 'May 8 23:59:59 2009 GMT', {'notAfter': 'May 8 23:59:59 2009 GMT',
'subject': ((('serialNumber', u'2497886'),), 'subject': ((('serialNumber', u'2497886'),),
...@@ -531,9 +518,9 @@ which is a fairly poorly-formed ``subject`` field. ...@@ -531,9 +518,9 @@ which is a fairly poorly-formed ``subject`` field.
Server-side operation Server-side operation
^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
For server operation, typically you'd need to have a server certificate, and private key, each in a file. For server operation, typically you'd need to have a server certificate, and
You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients private key, each in a file. You'd open a socket, bind it to a port, call
to connect:: :meth:`listen` on it, then start waiting for clients to connect::
import socket, ssl import socket, ssl
...@@ -541,8 +528,9 @@ to connect:: ...@@ -541,8 +528,9 @@ to connect::
bindsocket.bind(('myaddr.mydomain.com', 10023)) bindsocket.bind(('myaddr.mydomain.com', 10023))
bindsocket.listen(5) bindsocket.listen(5)
When one did, you'd call :meth:`accept` on the socket to get the new socket from the other When one did, you'd call :meth:`accept` on the socket to get the new socket from
end, and use :func:`wrap_socket` to create a server-side SSL context for it:: the other end, and use :func:`wrap_socket` to create a server-side SSL context
for it::
while True: while True:
newsocket, fromaddr = bindsocket.accept() newsocket, fromaddr = bindsocket.accept()
...@@ -553,7 +541,8 @@ end, and use :func:`wrap_socket` to create a server-side SSL context for it:: ...@@ -553,7 +541,8 @@ end, and use :func:`wrap_socket` to create a server-side SSL context for it::
ssl_version=ssl.PROTOCOL_TLSv1) ssl_version=ssl.PROTOCOL_TLSv1)
deal_with_client(connstream) deal_with_client(connstream)
Then you'd read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you):: Then you'd read data from the ``connstream`` and do something with it till you
are finished with the client (or the client is finished with you)::
def deal_with_client(connstream): def deal_with_client(connstream):
......
...@@ -1754,7 +1754,7 @@ The constructors for both classes work the same: ...@@ -1754,7 +1754,7 @@ The constructors for both classes work the same:
.. method:: update(other, ...) .. method:: update(other, ...)
set |= other | ... set |= other | ...
Update the set, adding elements from *other*. Update the set, adding elements from all others.
.. versionchanged:: 2.6 .. versionchanged:: 2.6
Accepts multiple input iterables. Accepts multiple input iterables.
...@@ -1762,7 +1762,7 @@ The constructors for both classes work the same: ...@@ -1762,7 +1762,7 @@ The constructors for both classes work the same:
.. method:: intersection_update(other, ...) .. method:: intersection_update(other, ...)
set &= 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 .. versionchanged:: 2.6
Accepts multiple input iterables. Accepts multiple input iterables.
...@@ -2050,7 +2050,7 @@ pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: ...@@ -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 :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 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)``. key/value pairs: ``d.update(red=1, blue=2)``.
.. versionchanged:: 2.4 .. versionchanged:: 2.4
...@@ -2440,9 +2440,9 @@ decimal arithmetic context. The specific types are not treated specially beyond ...@@ -2440,9 +2440,9 @@ decimal arithmetic context. The specific types are not treated specially beyond
their implementation of the context management protocol. See the their implementation of the context management protocol. See the
:mod:`contextlib` module for some examples. :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 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 context manager implementing the necessary :meth:`__enter__` and
:meth:`__exit__` methods, rather than the iterator produced by an undecorated :meth:`__exit__` methods, rather than the iterator produced by an undecorated
generator function. generator function.
......
...@@ -243,7 +243,6 @@ does an index lookup using :func:`__getitem__`. ...@@ -243,7 +243,6 @@ does an index lookup using :func:`__getitem__`.
Some simple format string examples:: Some simple format string examples::
"First, thou shalt count to {0}" # References first positional argument "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' "My quest is {name}" # References keyword argument 'name'
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument 'players'. "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
......
...@@ -417,7 +417,8 @@ always available. ...@@ -417,7 +417,8 @@ always available.
that is deeper than the call stack, :exc:`ValueError` is raised. The default 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. 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() .. function:: getprofile()
......
...@@ -156,7 +156,7 @@ In addition to these methods, lock objects can also be used via the ...@@ -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.) module is available, interrupts always go to the main thread.)
* Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is * 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 * 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`, to run. (The most popular ones (:func:`time.sleep`, :meth:`file.read`,
......
...@@ -205,9 +205,10 @@ Utility functions ...@@ -205,9 +205,10 @@ Utility functions
.. function:: quote(string[, safe]) .. function:: quote(string[, safe])
Replace special characters in *string* using the ``%xx`` escape. Letters, Replace special characters in *string* using the ``%xx`` escape. Letters,
digits, and the characters ``'_.-'`` are never quoted. The optional *safe* digits, and the characters ``'_.-'`` are never quoted. By default, this
parameter specifies additional characters that should not be quoted --- its function is intended for quoting the path section of the URL.The optional
default value is ``'/'``. *safe* parameter specifies additional characters that should not be quoted
--- its default value is ``'/'``.
Example: ``quote('/~connolly/')`` yields ``'/%7econnolly/'``. Example: ``quote('/~connolly/')`` yields ``'/%7econnolly/'``.
......
:mod:`warnings` --- Warning control :mod:`warnings` --- Warning control
=================================== ===================================
...@@ -129,16 +128,16 @@ the disposition of the match. Each entry is a tuple of the form (*action*, ...@@ -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 * *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* 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 * *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 * *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` 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)``. class, to turn a warning into an error we simply raise ``category(message)``.
...@@ -300,10 +299,11 @@ Available Functions ...@@ -300,10 +299,11 @@ Available Functions
.. function:: formatwarning(message, category, filename, lineno[, line]) .. function:: formatwarning(message, category, filename, lineno[, line])
Format a warning the standard way. This returns a string which may contain Format a warning the standard way. This returns a string which may contain
embedded newlines and ends in a newline. *line* is embedded newlines and ends in a newline. *line* is a line of source code to
a line of source code to be included in the warning message; if *line* is not supplied, be included in the warning message; if *line* is not supplied,
:func:`formatwarning` will try to read the line specified by *filename* and *lineno*. :func:`formatwarning` will try to read the line specified by *filename* and
*lineno*.
.. versionchanged:: 2.6 .. versionchanged:: 2.6
Added the *line* argument. Added the *line* argument.
...@@ -311,10 +311,11 @@ Available Functions ...@@ -311,10 +311,11 @@ Available Functions
.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]]) .. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])
Insert an entry into the list of warnings filters. The entry is inserted at the Insert an entry into the list of :ref:`warnings filter specifications
front by default; if *append* is true, it is inserted at the end. This checks <warning-filter>`. The entry is inserted at the front by default; if
the types of the arguments, compiles the message and module regular expressions, *append* is true, it is inserted at the end. This checks the types of the
and inserts them as a tuple in the list of warnings filters. Entries closer to 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 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 particular warning. Omitted arguments default to a value that matches
everything. everything.
...@@ -322,10 +323,11 @@ Available Functions ...@@ -322,10 +323,11 @@ Available Functions
.. function:: simplefilter(action[, category[, lineno[, append]]]) .. function:: simplefilter(action[, category[, lineno[, append]]])
Insert a simple entry into the list of warnings filters. The meaning of the Insert a simple entry into the list of :ref:`warnings filter specifications
function parameters is as for :func:`filterwarnings`, but regular expressions <warning-filter>`. The meaning of the function parameters is as for
are not needed as the filter inserted always matches any message in any module :func:`filterwarnings`, but regular expressions are not needed as the filter
as long as the category and line number match. inserted always matches any message in any module as long as the category and
line number match.
.. function:: resetwarnings() .. function:: resetwarnings()
......
...@@ -959,6 +959,8 @@ Internal types ...@@ -959,6 +959,8 @@ Internal types
If a code object represents a function, the first item in :attr:`co_consts` is 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. the documentation string of the function, or ``None`` if undefined.
.. _frame-objects:
Frame objects Frame objects
.. index:: object: frame .. index:: object: frame
......
...@@ -151,11 +151,30 @@ Assignment of an object to a single target is recursively defined as follows. ...@@ -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 * If the target is an attribute reference: The primary expression in the
reference is evaluated. It should yield an object with assignable attributes; 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 if this is not the case, :exc:`TypeError` is raised. That object is then
to assign the assigned object to the given attribute; if it cannot perform the asked to assign the assigned object to the given attribute; if it cannot
assignment, it raises an exception (usually but not necessarily perform the assignment, it raises an exception (usually but not necessarily
:exc:`AttributeError`). :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:: .. index::
pair: subscription; assignment pair: subscription; assignment
object: mutable object: mutable
...@@ -253,16 +272,8 @@ same way as normal assignments. Similarly, with the exception of the possible ...@@ -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 *in-place* behavior, the binary operation performed by augmented assignment is
the same as the normal binary operations. the same as the normal binary operations.
For targets which are attribute references, the initial value is retrieved with For targets which are attribute references, the same :ref:`caveat about class
a :meth:`getattr` and the result is assigned with a :meth:`setattr`. Notice and instance attributes <attr-target-note>` applies as for regular assignments.
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
.. _assert: .. _assert:
......
...@@ -50,8 +50,8 @@ need for two different argument passing mechanisms as in Pascal. ...@@ -50,8 +50,8 @@ need for two different argument passing mechanisms as in Pascal.
.. _tut-scopes: .. _tut-scopes:
Python Scopes and Name Spaces Python Scopes and Namespaces
============================= ============================
Before introducing classes, I first have to tell you something about Python's 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 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 ...@@ -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 :keyword:`del` statement. For example, ``del modname.the_answer`` will remove
the attribute :attr:`the_answer` from the object named by ``modname``. 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 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 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 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 ...@@ -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 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 (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 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 with an argument list, a new argument list is constructed from the instance
from the instance object and the original argument list, and the function object object and the argument list, and the function object is called with this new
is called with this new argument list. argument list.
.. _tut-remarks: .. _tut-remarks:
......
...@@ -165,14 +165,11 @@ exception type. ...@@ -165,14 +165,11 @@ exception type.
The except clause may specify a variable after the exception name (or tuple). 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 The variable is bound to an exception instance with the arguments stored in
``instance.args``. For convenience, the exception instance defines ``instance.args``. For convenience, the exception instance defines
:meth:`__getitem__` and :meth:`__str__` so the arguments can be accessed or :meth:`__str__` so the arguments can be printed directly without having to
printed directly without having to reference ``.args``. reference ``.args``.
But use of ``.args`` is discouraged. Instead, the preferred use is to pass a One may also instantiate an exception first before raising it and add any
single argument to an exception (which can be a tuple if multiple arguments are attributes to it as desired. ::
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. ::
>>> try: >>> try:
... raise Exception('spam', 'eggs') ... raise Exception('spam', 'eggs')
...@@ -248,9 +245,10 @@ re-raise the exception:: ...@@ -248,9 +245,10 @@ re-raise the exception::
User-defined Exceptions User-defined Exceptions
======================= =======================
Programs may name their own exceptions by creating a new exception class. Programs may name their own exceptions by creating a new exception class (see
Exceptions should typically be derived from the :exc:`Exception` class, either :ref:`tut-classes` for more about Python classes). Exceptions should typically
directly or indirectly. For example:: be derived from the :exc:`Exception` class, either directly or indirectly. For
example::
>>> class MyError(Exception): >>> class MyError(Exception):
... def __init__(self, value): ... def __init__(self, value):
...@@ -288,28 +286,28 @@ to create specific exception classes for different error conditions:: ...@@ -288,28 +286,28 @@ to create specific exception classes for different error conditions::
"""Exception raised for errors in the input. """Exception raised for errors in the input.
Attributes: Attributes:
expression -- input expression in which the error occurred expr -- input expression in which the error occurred
message -- explanation of the error msg -- explanation of the error
""" """
def __init__(self, expression, message): def __init__(self, expr, msg):
self.expression = expression self.expr = expr
self.message = message self.msg = msg
class TransitionError(Error): class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not """Raised when an operation attempts a state transition that's not
allowed. allowed.
Attributes: Attributes:
previous -- state at beginning of transition prev -- state at beginning of transition
next -- attempted new state 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): def __init__(self, prev, next, msg):
self.previous = previous self.prev = prev
self.next = next self.next = next
self.message = message self.msg = msg
Most exceptions are defined with names that end in "Error," similar to the Most exceptions are defined with names that end in "Error," similar to the
naming of the standard exceptions. naming of the standard exceptions.
......
...@@ -123,11 +123,11 @@ with zeros. It understands about plus and minus signs:: ...@@ -123,11 +123,11 @@ with zeros. It understands about plus and minus signs::
Basic usage of the :meth:`str.format` method looks like this:: 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!" We are the knights who say "Ni!"
The brackets and characters within them (called format fields) are replaced with 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 brackets refers to the position of the object passed into the
:meth:`~str.format` method. :: :meth:`~str.format` method. ::
...@@ -149,6 +149,15 @@ Positional and keyword arguments can be arbitrarily combined:: ...@@ -149,6 +149,15 @@ Positional and keyword arguments can be arbitrarily combined::
... other='Georg') ... other='Georg')
The story of Bill, Manfred, and 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 An optional ``':'`` and format specifier can follow the field name. This allows
greater control over how the value is formatted. The following example greater control over how the value is formatted. The following example
truncates Pi to three places after the decimal. 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 ...@@ -239,8 +248,8 @@ writing. The *mode* argument is optional; ``'r'`` will be assumed if it's
omitted. omitted.
On Windows, ``'b'`` appended to the mode opens the file in binary mode, so there 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 are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. Python on Windows makes
distinction between text and binary files; the end-of-line characters in text 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 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 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 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. :: ...@@ -138,7 +138,6 @@ its magnitude (as a float) or ``z.real`` to get its real part. ::
4.0 4.0
>>> abs(a) # sqrt(a.real**2 + a.imag**2) >>> abs(a) # sqrt(a.real**2 + a.imag**2)
5.0 5.0
>>>
In interactive mode, the last printed expression is assigned to the variable 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 ``_``. 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:: ...@@ -152,7 +151,6 @@ somewhat easier to continue calculations, for example::
113.0625 113.0625
>>> round(_, 2) >>> round(_, 2)
113.06 113.06
>>>
This variable should be treated as read-only by the user. Don't explicitly 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 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:: ...@@ -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 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 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 This is a rather long string containing
several lines of text just as you would do in C. several lines of text just as you would do in C.
...@@ -209,7 +209,9 @@ they will be included in the string. :: ...@@ -209,7 +209,9 @@ they will be included in the string. ::
-H hostname Hostname to connect to -H hostname Hostname to connect to
""" """
produces the following output:: produces the following output:
.. code-block:: text
Usage: thingy [OPTIONS] Usage: thingy [OPTIONS]
-h Display this usage message -h Display this usage message
...@@ -224,7 +226,9 @@ in the source, are both included in the string as data. Thus, the example:: ...@@ -224,7 +226,9 @@ in the source, are both included in the string as data. Thus, the example::
print hello print hello
would print:: would print:
.. code-block:: text
This is a rather long string containing\n\ This is a rather long string containing\n\
several lines of text much as you would do in C. 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:: ...@@ -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 (``_``). 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:: .. note::
For efficiency reasons, each module is only imported once per interpreter For efficiency reasons, each module is only imported once per interpreter
...@@ -443,14 +447,9 @@ Importing \* From a Package ...@@ -443,14 +447,9 @@ Importing \* From a Package
Now what happens when the user writes ``from sound.effects import *``? Ideally, 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 one would hope that this somehow goes out to the filesystem, finds which
submodules are present in the package, and imports them all. Unfortunately, submodules are present in the package, and imports them all. This could take a
this operation does not work very well on Windows platforms, where the long time and importing sub-modules might have unwanted side-effects that should
filesystem does not always have accurate information about the case of a only happen when the sub-module is explicitly imported.
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 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 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 ...@@ -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 when the ``from...import`` statement is executed. (This also works when
``__all__`` is defined.) ``__all__`` is defined.)
Note that in general the practice of importing ``*`` from a module or package is Although certain modules are designed to export only names that follow certain
frowned upon, since it often causes poorly readable code. However, it is okay to patterns when you use ``import *``, it is still considered bad practise in
use it to save typing in interactive sessions, and certain modules are designed production code.
to export only names that follow certain patterns.
Remember, there is nothing wrong with using ``from Package import Remember, there is nothing wrong with using ``from Package import
specific_submodule``! In fact, this is the recommended notation unless the 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