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

Merged revisions...

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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