leaves the module in ``sys.modules``.
.. versionchanged:: 2.4
- failing imports remove incomplete module objects.
+ Failing imports remove incomplete module objects.
.. versionchanged:: 2.6
- always use absolute imports
+ Always uses absolute imports.
.. cfunction:: PyObject* PyImport_ImportModuleNoBlock(const char *name)
unless a non-empty *fromlist* was given.
.. versionchanged:: 2.4
- failing imports remove incomplete module objects.
+ Failing imports remove incomplete module objects.
.. versionchanged:: 2.6
The function is an alias for :cfunc:`PyImport_ImportModuleLevel` with
are installed in the current environment, e.g. by :mod:`rexec` or :mod:`ihooks`.
.. versionchanged:: 2.6
- always use absolute imports
+ Always uses absolute imports.
.. cfunction:: PyObject* PyImport_ReloadModule(PyObject *m)
.. cfunction:: PyObject* PyInt_FromSsize_t(Py_ssize_t ival)
+ Create a new integer object with a value of *ival*. If the value is larger
+ than ``LONG_MAX`` or smaller than ``LONG_MIN``, a long integer object is
+ returned.
+
+ .. versionadded:: 2.5
+
+
+.. cfunction:: PyObject* PyInt_FromSize_t(size_t ival)
+
Create a new integer object with a value of *ival*. If the value exceeds
``LONG_MAX``, a long integer object is returned.
static int
import_spam(void)
{
- PyObject *module = PyImport_ImportModule("spam");
-
- if (module != NULL) {
- PyObject *c_api_object = PyObject_GetAttrString(module, "_C_API");
- if (c_api_object == NULL)
- return -1;
- if (PyCObject_Check(c_api_object))
- PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object);
- Py_DECREF(c_api_object);
+ PyObject *c_api_object;
+ PyObject *module;
+
+ module = PyImport_ImportModule("spam");
+ if (module == NULL)
+ return -1;
+
+ c_api_object = PyObject_GetAttrString(module, "_C_API");
+ if (c_api_object == NULL) {
+ Py_DECREF(module);
+ return -1;
}
+ if (PyCObject_Check(c_api_object))
+ PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object);
+
+ Py_DECREF(c_api_object);
+ Py_DECREF(module);
return 0;
}
+-----------+----------------+-------------------+-----------------------+
| ``'B'`` | unsigned char | int | 1 |
+-----------+----------------+-------------------+-----------------------+
-| ``'u'`` | Py_UNICODE | Unicode character | 2 |
+| ``'u'`` | Py_UNICODE | Unicode character | 2 (see note) |
+-----------+----------------+-------------------+-----------------------+
| ``'h'`` | signed short | int | 2 |
+-----------+----------------+-------------------+-----------------------+
| ``'d'`` | double | float | 8 |
+-----------+----------------+-------------------+-----------------------+
+.. note::
+
+ The ``'u'`` typecode corresponds to Python's unicode character. On narrow
+ Unicode builds this is 2-bytes, on wide builds this is 4-bytes.
+
The actual representation of values is determined by the machine architecture
(strictly speaking, by the C implementation). The actual size can be accessed
through the :attr:`itemsize` attribute. The values stored for ``'L'`` and
The module defines the following type:
-.. function:: array(typecode[, initializer])
+.. class:: array(typecode[, initializer])
- Return a new array whose items are restricted by *typecode*, and initialized
+ A new array whose items are restricted by *typecode*, and initialized
from the optional *initializer* value, which must be a list, string, or iterable
over elements of the appropriate type.
.. data:: ArrayType
- Obsolete alias for :func:`array`.
+ Obsolete alias for :class:`array`.
Array objects support the ordinary sequence operations of indexing, slicing,
concatenation, and multiplication. When using slice assignment, the assigned
The following data items and methods are also supported:
-
.. attribute:: array.typecode
The typecode character used to create the array.
-
-:mod:`cgi` --- Common Gateway Interface support.
-================================================
+:mod:`cgi` --- Common Gateway Interface support
+===============================================
.. module:: cgi
:synopsis: Helpers for running Python scripts via the Common Gateway Interface.
-
-:mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts.
-=========================================================================
+:mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts
+========================================================================
.. module:: contextlib
:synopsis: Utilities for with-statement contexts.
-
-:mod:`ctypes` --- A foreign function library for Python.
-========================================================
+:mod:`ctypes` --- A foreign function library for Python
+=======================================================
.. module:: ctypes
:synopsis: A foreign function library for Python.
-
-:mod:`curses.panel` --- A panel stack extension for curses.
-===========================================================
+:mod:`curses.panel` --- A panel stack extension for curses
+==========================================================
.. module:: curses.panel
:synopsis: A panel stack extension that adds depth to curses windows.
Get a character. Note that the integer returned does *not* have to be in ASCII
range: function keys, keypad keys and so on return numbers higher than 256. In
- no-delay mode, -1 is returned if there is no input.
+ no-delay mode, -1 is returned if there is no input, else :func:`getch` waits
+ until a key is pressed.
.. method:: window.getkey([y, x])
.. versionadded:: 2.6
- .. method:: logical_invert(other[, context])
+ .. method:: logical_invert([context])
- :meth:`logical_invert` is a logical operation. The argument must
- be a *logical operand* (see :ref:`logical_operands_label`). The
+ :meth:`logical_invert` is a logical operation. The
result is the digit-wise inversion of the operand.
.. versionadded:: 2.6
Module :mod:`os`
If the locking flags :const:`O_SHLOCK` and :const:`O_EXLOCK` are present
- in the :mod:`os` module, the :func:`os.open` function provides a more
- platform-independent alternative to the :func:`lockf` and :func:`flock`
- functions.
+ in the :mod:`os` module (on BSD only), the :func:`os.open` function
+ provides an alternative to the :func:`lockf` and :func:`flock` functions.
.. function:: find_module(name[, path])
- Try to find the module *name* on the search path *path*. If *path* is a list
- of directory names, each directory is searched for files with any of the
- suffixes returned by :func:`get_suffixes` above. Invalid names in the list
- are silently ignored (but all list items must be strings). If *path* is
- omitted or ``None``, the list of directory names given by ``sys.path`` is
- searched, but first it searches a few special places: it tries to find a
- built-in module with the given name (:const:`C_BUILTIN`), then a frozen
- module (:const:`PY_FROZEN`), and on some systems some other places are looked
- in as well (on Windows, it looks in the registry which may point to a
- specific file).
+ Try to find the module *name*. If *path* is omitted or ``None``, the list of
+ directory names given by ``sys.path`` is searched, but first a few special
+ places are searched: the function tries to find a built-in module with the
+ given name (:const:`C_BUILTIN`), then a frozen module (:const:`PY_FROZEN`),
+ and on some systems some other places are looked in as well (on Windows, it
+ looks in the registry which may point to a specific file).
+
+ Otherwise, *path* must be a list of directory names; each directory is
+ searched for files with any of the suffixes returned by :func:`get_suffixes`
+ above. Invalid names in the list are silently ignored (but all list items
+ must be strings).
If search is successful, the return value is a 3-element tuple ``(file,
pathname, description)``:
.. function:: nl_langinfo(option)
- Return some locale-specific information as a string. This function is not
- available on all systems, and the set of possible options might also vary across
- platforms. The possible argument values are numbers, for which symbolic
- constants are available in the locale module.
+ Return some locale-specific information as a string. This function is not
+ available on all systems, and the set of possible options might also vary
+ across platforms. The possible argument values are numbers, for which
+ symbolic constants are available in the locale module.
+
+ The :func:`nl_langinfo` function accepts one of the following keys. Most
+ descriptions are taken from the corresponding description in the GNU C
+ library.
+
+ .. data:: CODESET
+
+ Get a string with the name of the character encoding used in the
+ selected locale.
+
+ .. data:: D_T_FMT
+
+ Get a string that can be used as a format string for :func:`strftime` to
+ represent time and date in a locale-specific way.
+
+ .. data:: D_FMT
+
+ Get a string that can be used as a format string for :func:`strftime` to
+ represent a date in a locale-specific way.
+
+ .. data:: T_FMT
+
+ Get a string that can be used as a format string for :func:`strftime` to
+ represent a time in a locale-specific way.
+
+ .. data:: T_FMT_AMPM
+
+ Get a format string for :func:`strftime` to represent time in the am/pm
+ format.
+
+ .. data:: DAY_1 ... DAY_7
+
+ Get the name of the n-th day of the week.
+
+ .. note::
+
+ This follows the US convention of :const:`DAY_1` being Sunday, not the
+ international convention (ISO 8601) that Monday is the first day of the
+ week.
+
+ .. data:: ABDAY_1 ... ABDAY_7
+
+ Get the abbreviated name of the n-th day of the week.
+
+ .. data:: MON_1 ... MON_12
+
+ Get the name of the n-th month.
+
+ .. data:: ABMON_1 ... ABMON_12
+
+ Get the abbreviated name of the n-th month.
+
+ .. data:: RADIXCHAR
+
+ Get the radix character (decimal dot, decimal comma, etc.)
+
+ .. data:: THOUSEP
+
+ Get the separator character for thousands (groups of three digits).
+
+ .. data:: YESEXPR
+
+ Get a regular expression that can be used with the regex function to
+ recognize a positive response to a yes/no question.
+
+ .. note::
+
+ The expression is in the syntax suitable for the :cfunc:`regex` function
+ from the C library, which might differ from the syntax used in :mod:`re`.
+
+ .. data:: NOEXPR
+
+ Get a regular expression that can be used with the regex(3) function to
+ recognize a negative response to a yes/no question.
+
+ .. data:: CRNCYSTR
+
+ Get the currency symbol, preceded by "-" if the symbol should appear before
+ the value, "+" if the symbol should appear after the value, or "." if the
+ symbol should replace the radix character.
+
+ .. data:: ERA
+
+ Get a string that represents the era used in the current locale.
+
+ Most locales do not define this value. An example of a locale which does
+ define this value is the Japanese one. In Japan, the traditional
+ representation of dates includes the name of the era corresponding to the
+ then-emperor's reign.
+
+ Normally it should not be necessary to use this value directly. Specifying
+ the ``E`` modifier in their format strings causes the :func:`strftime`
+ function to use this information. The format of the returned string is not
+ specified, and therefore you should not assume knowledge of it on different
+ systems.
+
+ .. data:: ERA_YEAR
+
+ Get the year in the relevant era of the locale.
+
+ .. data:: ERA_D_T_FMT
+
+ Get a format string for :func:`strftime` to represent dates and times in a
+ locale-specific era-based way.
+
+ .. data:: ERA_D_FMT
+
+ Get a format string for :func:`strftime` to represent time in a
+ locale-specific era-based way.
+
+ .. data:: ALT_DIGITS
+
+ Get a representation of up to 100 values used to represent the values
+ 0 to 99.
.. function:: getdefaultlocale([envvars])
This is a symbolic constant used for different values returned by
:func:`localeconv`.
-The :func:`nl_langinfo` function accepts one of the following keys. Most
-descriptions are taken from the corresponding description in the GNU C library.
-
-
-.. data:: CODESET
-
- Return a string with the name of the character encoding used in the selected
- locale.
-
-
-.. data:: D_T_FMT
-
- Return a string that can be used as a format string for strftime(3) to represent
- time and date in a locale-specific way.
-
-
-.. data:: D_FMT
-
- Return a string that can be used as a format string for strftime(3) to represent
- a date in a locale-specific way.
-
-
-.. data:: T_FMT
-
- Return a string that can be used as a format string for strftime(3) to represent
- a time in a locale-specific way.
-
-
-.. data:: T_FMT_AMPM
-
- The return value can be used as a format string for 'strftime' to represent time
- in the am/pm format.
-
-
-.. data:: DAY_1 ... DAY_7
-
- Return name of the n-th day of the week.
-
- .. note::
-
- This follows the US convention of :const:`DAY_1` being Sunday, not the
- international convention (ISO 8601) that Monday is the first day of the week.
-
-
-.. data:: ABDAY_1 ... ABDAY_7
-
- Return abbreviated name of the n-th day of the week.
-
-
-.. data:: MON_1 ... MON_12
-
- Return name of the n-th month.
-
-
-.. data:: ABMON_1 ... ABMON_12
-
- Return abbreviated name of the n-th month.
-
-
-.. data:: RADIXCHAR
-
- Return radix character (decimal dot, decimal comma, etc.)
-
-
-.. data:: THOUSEP
-
- Return separator character for thousands (groups of three digits).
-
-
-.. data:: YESEXPR
-
- Return a regular expression that can be used with the regex function to
- recognize a positive response to a yes/no question.
-
- .. note::
-
- The expression is in the syntax suitable for the :cfunc:`regex` function from
- the C library, which might differ from the syntax used in :mod:`re`.
-
-
-.. data:: NOEXPR
-
- Return a regular expression that can be used with the regex(3) function to
- recognize a negative response to a yes/no question.
-
-
-.. data:: CRNCYSTR
-
- Return the currency symbol, preceded by "-" if the symbol should appear before
- the value, "+" if the symbol should appear after the value, or "." if the symbol
- should replace the radix character.
-
-
-.. data:: ERA
-
- The return value represents the era used in the current locale.
-
- Most locales do not define this value. An example of a locale which does define
- this value is the Japanese one. In Japan, the traditional representation of
- dates includes the name of the era corresponding to the then-emperor's reign.
-
- Normally it should not be necessary to use this value directly. Specifying the
- ``E`` modifier in their format strings causes the :func:`strftime` function to
- use this information. The format of the returned string is not specified, and
- therefore you should not assume knowledge of it on different systems.
-
-
-.. data:: ERA_YEAR
-
- The return value gives the year in the relevant era of the locale.
-
-
-.. data:: ERA_D_T_FMT
-
- This return value can be used as a format string for :func:`strftime` to
- represent dates and times in a locale-specific era-based way.
-
-
-.. data:: ERA_D_FMT
-
- This return value can be used as a format string for :func:`strftime` to
- represent time in a locale-specific era-based way.
-
-
-.. data:: ALT_DIGITS
-
- The return value is a representation of up to 100 values used to represent the
- values 0 to 99.
Example::
>>> import locale
>>> loc = locale.getlocale() # get current locale
- >>> locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform
+ # use German locale; name might vary with platform
+ >>> locale.setlocale(locale.LC_ALL, 'de_DE')
>>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
>>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
>>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
Note that a daemonic process is not allowed to create child processes.
Otherwise a daemonic process would leave its children orphaned if it gets
- terminated when its parent process exits.
+ terminated when its parent process exits. Additionally, these are **not**
+ Unix daemons or services, they are normal processes that will be
+ terminated (and not joined) if non-dameonic processes have exited.
In addition to the :class:`Threading.Thread` API, :class:`Process` objects
also support the following attributes and methods:
generally be omitted since it can usually be inferred from the format of
*address*. (See :ref:`multiprocessing-address-formats`)
- If *authentication* is ``True`` or *authkey* is a string then digest
+ If *authenticate* is ``True`` or *authkey* is a string then digest
authentication is used. The key used for authentication will be either
*authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
If authentication fails then :exc:`AuthenticationError` is raised. See
If *authkey* is ``None`` and *authenticate* is ``True`` then
``current_process().authkey`` is used as the authentication key. If
- *authkey* is ``None`` and *authentication* is ``False`` then no
+ *authkey* is ``None`` and *authenticate* is ``False`` then no
authentication is done. If authentication fails then
:exc:`AuthenticationError` is raised. See :ref:`multiprocessing-auth-keys`.
:func:`OptionParser.error` from your application code.
If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
-you'll need to subclass OptionParser and override its :meth:`exit` and/or
-:meth:`error` methods.
+you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
+and/or :meth:`~OptionParser.error` methods.
.. _optparse-putting-it-all-together:
-
-:mod:`pickletools` --- Tools for pickle developers.
-===================================================
+:mod:`pickletools` --- Tools for pickle developers
+==================================================
.. module:: pickletools
:synopsis: Contains extensive comments about the pickle protocols and pickle-machine
-
-:mod:`platform` --- Access to underlying platform's identifying data.
-======================================================================
+:mod:`platform` --- Access to underlying platform's identifying data
+=====================================================================
.. module:: platform
:synopsis: Retrieves as much platform identifying data as possible.
constraint was added in Python 2.3; in Python 2.2, various iterators are broken
according to this rule.)
+
+.. _generator-types:
+
+Generator Types
+---------------
+
Python's :term:`generator`\s provide a convenient way to implement the iterator
protocol. If a container object's :meth:`__iter__` method is implemented as a
generator, it will automatically return an iterator object (technically, a
-generator object) supplying the :meth:`__iter__` and :meth:`next` methods.
+generator object) supplying the :meth:`__iter__` and :meth:`next` methods. More
+information about generators can be found in :ref:`the documentation for the
+yield expression <yieldexpr>`.
.. _typesseq:
Return a copy of *s*, but with lower case letters converted to upper case.
-.. function:: ljust(s, width)
- rjust(s, width)
- center(s, width)
+.. function:: ljust(s, width[, fillchar])
+ rjust(s, width[, fillchar])
+ center(s, width[, fillchar])
These functions respectively left-justify, right-justify and center a string in
a field of given width. They return a string that is at least *width*
- characters wide, created by padding the string *s* with spaces until the given
- width on the right, left or both sides. The string is never truncated.
+ characters wide, created by padding the string *s* with the character *fillchar*
+ (default is a space) until the given width on the right, left or both sides.
+ The string is never truncated.
.. function:: zfill(s, width)
needed: Usually, the program to execute is defined by the *args* argument. If
``shell=True``, the *executable* argument specifies which shell to use. On Unix,
the default shell is :file:`/bin/sh`. On Windows, the default shell is
- specified by the :envvar:`COMSPEC` environment variable.
+ specified by the :envvar:`COMSPEC` environment variable. The only reason you
+ would need to specify ``shell=True`` on Windows is where the command you
+ wish to execute is actually built in to the shell, eg ``dir``, ``copy``.
+ You don't need ``shell=True`` to run a batch file, nor to run a console-based
+ executable.
*stdin*, *stdout* and *stderr* specify the executed programs' standard input,
standard output and standard error file handles, respectively. Valid values
Return ``True`` if the symbol is global.
+ .. method:: is_declared_global()
+
+ Return ``True`` if the symbol is declared global with a global statement.
+
.. method:: is_local()
Return ``True`` if the symbol is local to its block.
The constructor takes a statement to be timed, an additional statement used for
setup, and a timer function. Both statements default to ``'pass'``; the timer
- function is platform-dependent (see the module doc string). The statements may
- contain newlines, as long as they don't contain multi-line string literals.
+ function is platform-dependent (see the module doc string). *stmt* and *setup*
+ may also contain multiple statements separated by ``;`` or newlines, as long as
+ they don't contain multi-line string literals.
To measure the execution time of the first statement, use the :meth:`timeit`
method. The :meth:`repeat` method is a convenience to call :meth:`timeit`
be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k`
is using :exc:`DeprecationWarning` as default warning class.
+ .. versionadded:: 2.6
+
.. function:: showwarning(message, category, filename, lineno[, file[, line]])
warning is triggered repeatedly for the same source line, such as inside a
loop).
``module``
- Print each warning only only the first time it occurs in each module.
+ Print each warning only the first time it occurs in each module.
``once``
Print each warning only the first time it occurs in the program.
``error``
fixes old code: demo/scripts/classfix.py.
* There's a new reserved word: "access". The syntax and semantics are
-still subject of of research and debate (as well as undocumented), but
+still subject of research and debate (as well as undocumented), but
the parser knows about the keyword so you must not use it as a
variable, function, or attribute name.
(a) define a function of one argument and call it with any
number of arguments; if the actual argument count wasn't
one, the function would receive a tuple containing the
- arguments arguments (an empty tuple if there were none).
+ arguments (an empty tuple if there were none).
(b) define a function of two arguments, and call it with more
than two arguments; if there were more than two arguments,
----------------------------------------------------------
The function strdup() no longer exists (it was used only in one places
-and is somewhat of a a portability problem sice some systems have the
+and is somewhat of a portability problem since some systems have the
same function in their C library.
The functions NEW() and RENEW() allocate one spare byte to guard
- Bug #1565661: in webbrowser, split() the command for the default
GNOME browser in case it is a command with args.
-- Made the error message for time.strptime when the data data and
+- Made the error message for time.strptime when the data and
format do match be more clear.
- Fix a bug in traceback.format_exception_only() that led to an error
Then bang on it until it executes very simple Python statements.
Now bang on it some more. At some point you'll want to use the os
-module; this is the time to start thinking about what to to with the
+module; this is the time to start thinking about what to do with the
posix module. It's okay to simply #ifdef out those functions that
cause problems; the remaining ones will be quite useful.
Standard methods & operators redefinition in classes
Standard methods & operators map to special '__methods__' and thus may be
- redefined (mostly in in user-defined classes), e.g.:
+ redefined (mostly in user-defined classes), e.g.:
class x:
def __init__(self, v): self.value = v
def __add__(self, r): return self.value + r
- Heiko Weinen was given SVN access on 29 April 2008 by MvL,
for GSoC contributions.
-- Jesus Cea was was given SVN access on 24 April 2008 by MvL,
+- Jesus Cea was given SVN access on 24 April 2008 by MvL,
for maintenance of bsddb.
- Guilherme Polo was given SVN access on 24 April 2008 by MvL,
messages if a warning is triggered repeatedly for the same source
line, such as inside a loop);
.B module
-to print each warning only only the first time it occurs in each
+to print each warning only the first time it occurs in each
module;
.B once
to print each warning only the first time it occurs in the program; or