diff options
author | Georg Brandl <georg@python.org> | 2009-01-03 21:18:54 (GMT) |
---|---|---|
committer | Georg Brandl <georg@python.org> | 2009-01-03 21:18:54 (GMT) |
commit | 48310cd3f2e02ced9ae836ccbcb67e9af3097d62 (patch) | |
tree | 04c86b387c11bfd4835a320e76bbb2ee24626e0d /Doc | |
parent | 3d3558a4653fcfcbdcbb75bda5d61e93c48f4d51 (diff) | |
download | cpython-48310cd3f2e02ced9ae836ccbcb67e9af3097d62.zip cpython-48310cd3f2e02ced9ae836ccbcb67e9af3097d62.tar.gz cpython-48310cd3f2e02ced9ae836ccbcb67e9af3097d62.tar.bz2 |
Remove trailing whitespace.
Diffstat (limited to 'Doc')
127 files changed, 825 insertions, 825 deletions
diff --git a/Doc/c-api/buffer.rst b/Doc/c-api/buffer.rst index 255f45a..9467253 100644 --- a/Doc/c-api/buffer.rst +++ b/Doc/c-api/buffer.rst @@ -31,7 +31,7 @@ returning data from the target object. .. index:: single: PyBufferProcs -More information on the buffer interface is provided in the section +More information on the buffer interface is provided in the section :ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`. Buffer objects are useful as a way to expose the data from another object's @@ -104,7 +104,7 @@ could be used to pass around structured data in its native, in-memory format. pointer += strides[i] * indices[i]; if (suboffsets[i] >=0 ) { pointer = *((char**)pointer) + suboffsets[i]; - } + } } return (void*)pointer; } diff --git a/Doc/c-api/conversion.rst b/Doc/c-api/conversion.rst index b71283b..1c19879 100644 --- a/Doc/c-api/conversion.rst +++ b/Doc/c-api/conversion.rst @@ -80,7 +80,7 @@ The following functions provide locale-independent string to number conversions. See the Unix man page :manpage:`atof(2)` for details. - + .. cfunction:: char * PyOS_stricmp(char *s1, char *s2) Case insensitive comparison of strings. The function works almost diff --git a/Doc/c-api/file.rst b/Doc/c-api/file.rst index c76fd22..599717b 100644 --- a/Doc/c-api/file.rst +++ b/Doc/c-api/file.rst @@ -22,7 +22,7 @@ the :mod:`io` module. .. warning:: - Take care when you are mixing streams and descriptors! For more + Take care when you are mixing streams and descriptors! For more information, see `the GNU C Library docs <http://www.gnu.org/software/libc/manual/html_node/Stream_002fDescriptor-Precautions.html#Stream_002fDescriptor-Precautions>`_. diff --git a/Doc/c-api/init.rst b/Doc/c-api/init.rst index 89bcff3..0ac8d5b 100644 --- a/Doc/c-api/init.rst +++ b/Doc/c-api/init.rst @@ -885,7 +885,7 @@ Python-level trace functions in previous versions. Return a tuple of function call counts. There are constants defined for the positions within the tuple: - + +-------------------------------+-------+ | Name | Value | +===============================+=======+ @@ -911,7 +911,7 @@ Python-level trace functions in previous versions. +-------------------------------+-------+ | :const:`PCALL_POP` | 10 | +-------------------------------+-------+ - + :const:`PCALL_FAST_FUNCTION` means no argument tuple needs to be created. :const:`PCALL_FASTER_FUNCTION` means that the fast-path frame setup code is used. diff --git a/Doc/c-api/long.rst b/Doc/c-api/long.rst index b0debe3..a7fe4b5 100644 --- a/Doc/c-api/long.rst +++ b/Doc/c-api/long.rst @@ -107,7 +107,7 @@ All integers are implemented as "long" integer objects of arbitrary size. retrieved from the resulting value using :cfunc:`PyLong_AsVoidPtr`. -.. XXX alias PyLong_AS_LONG (for now) +.. XXX alias PyLong_AS_LONG (for now) .. cfunction:: long PyLong_AsLong(PyObject *pylong) .. index:: @@ -123,7 +123,7 @@ All integers are implemented as "long" integer objects of arbitrary size. Return a C :ctype:`long` representation of the contents of *pylong*. If *pylong* is greater than :const:`LONG_MAX`, return -1 and - set `*overflow` to 1 (for overflow) or -1 (for underflow). + set `*overflow` to 1 (for overflow) or -1 (for underflow). If an exception is set because of type errors, also return -1. diff --git a/Doc/c-api/module.rst b/Doc/c-api/module.rst index 9be2a11..3a612e0 100644 --- a/Doc/c-api/module.rst +++ b/Doc/c-api/module.rst @@ -96,7 +96,7 @@ There are only a few functions special to module objects. .. cfunction:: int PyModule_AddIntMacro(PyObject *module, macro) - Add an int constant to *module*. The name and the value are taken from + Add an int constant to *module*. The name and the value are taken from *macro*. For example ``PyModule_AddConstant(module, AF_INET)`` adds the int constant *AF_INET* with the value of *AF_INET* to *module*. Return ``-1`` on error, ``0`` on success. diff --git a/Doc/c-api/reflection.rst b/Doc/c-api/reflection.rst index 8a96ce3..822c593 100644 --- a/Doc/c-api/reflection.rst +++ b/Doc/c-api/reflection.rst @@ -15,7 +15,7 @@ Reflection Return a dictionary of the local variables in the current execution frame, or *NULL* if no frame is currently executing. - + .. cfunction:: PyObject* PyEval_GetGlobals() diff --git a/Doc/c-api/sequence.rst b/Doc/c-api/sequence.rst index 0ebc0f3..51f9a7d 100644 --- a/Doc/c-api/sequence.rst +++ b/Doc/c-api/sequence.rst @@ -143,9 +143,9 @@ Sequence Protocol Return the underlying array of PyObject pointers. Assumes that *o* was returned by :cfunc:`PySequence_Fast` and *o* is not *NULL*. - + Note, if a list gets resized, the reallocation may relocate the items array. - So, only use the underlying array pointer in contexts where the sequence + So, only use the underlying array pointer in contexts where the sequence cannot change. diff --git a/Doc/distutils/apiref.rst b/Doc/distutils/apiref.rst index aec68c0..868099b 100644 --- a/Doc/distutils/apiref.rst +++ b/Doc/distutils/apiref.rst @@ -104,7 +104,7 @@ setup script). Indirectly provides the :class:`distutils.dist.Distribution` and | *package_dir* | A mapping of package to | a dictionary | | | directory names | | +--------------------+--------------------------------+-------------------------------------------------------------+ - + .. function:: run_setup(script_name[, script_args=None, stop_after='run']) @@ -754,7 +754,7 @@ This module provides the following functions. standard output, otherwise do nothing. .. % \subsection{Compiler-specific modules} -.. % +.. % .. % The following modules implement concrete subclasses of the abstract .. % \class{CCompiler} class. They should not be instantiated directly, but should .. % be created using \function{distutils.ccompiler.new_compiler()} factory @@ -858,7 +858,7 @@ Contains :class:`MWerksCompiler`, an implementation of the abstract Macintosh. Needs work to support CW on Windows or Mac OS X. .. % \subsection{Utility modules} -.. % +.. % .. % The following modules all provide general utility functions. They haven't .. % all been documented yet. @@ -1109,13 +1109,13 @@ other utility module. For MacOS X systems the OS version reflects the minimal version on which binaries will run (that is, the value of ``MACOSX_DEPLOYMENT_TARGET`` - during the build of Python), not the OS version of the current system. + during the build of Python), not the OS version of the current system. For universal binary builds on MacOS X the architecture value reflects the univeral binary status instead of the architecture of the current - processor. For 32-bit universal binaries the architecture is ``fat``, - for 64-bit universal binaries the architecture is ``fat64``, and - for 4-way universal binaries the architecture is ``universal``. + processor. For 32-bit universal binaries the architecture is ``fat``, + for 64-bit universal binaries the architecture is ``fat64``, and + for 4-way universal binaries the architecture is ``universal``. Examples of returned values on MacOS X: @@ -1692,7 +1692,7 @@ lines, and joining lines with backslashes. .. % todo .. % \section{Distutils Commands} -.. % +.. % .. % This part of Distutils implements the various Distutils commands, such .. % as \code{build}, \code{install} \&c. Each command is implemented as a .. % separate module, with the command name as the name of the module. diff --git a/Doc/distutils/builtdist.rst b/Doc/distutils/builtdist.rst index 58b62f8..672faee 100644 --- a/Doc/distutils/builtdist.rst +++ b/Doc/distutils/builtdist.rst @@ -268,13 +268,13 @@ file winds up deep in the "build tree," in a temporary directory created by .. % \longprogramopt{spec-file} option; used in conjunction with .. % \longprogramopt{spec-only}, this gives you an opportunity to customize .. % the \file{.spec} file manually: -.. % +.. % .. % \ begin{verbatim} .. % > python setup.py bdist_rpm --spec-only .. % # ...edit dist/FooBar-1.0.spec .. % > python setup.py bdist_rpm --spec-file=dist/FooBar-1.0.spec .. % \ end{verbatim} -.. % +.. % .. % (Although a better way to do this is probably to override the standard .. % \command{bdist\_rpm} command with one that writes whatever else you want .. % to the \file{.spec} file.) @@ -334,31 +334,31 @@ The installer file will be written to the "distribution directory" --- normally Cross-compiling on Windows ========================== -Starting with Python 2.6, distutils is capable of cross-compiling between -Windows platforms. In practice, this means that with the correct tools +Starting with Python 2.6, distutils is capable of cross-compiling between +Windows platforms. In practice, this means that with the correct tools installed, you can use a 32bit version of Windows to create 64bit extensions and vice-versa. -To build for an alternate platform, specify the :option:`--plat-name` option -to the build command. Valid values are currently 'win32', 'win-amd64' and +To build for an alternate platform, specify the :option:`--plat-name` option +to the build command. Valid values are currently 'win32', 'win-amd64' and 'win-ia64'. For example, on a 32bit version of Windows, you could execute:: python setup.py build --plat-name=win-amd64 -to build a 64bit version of your extension. The Windows Installers also +to build a 64bit version of your extension. The Windows Installers also support this option, so the command:: python setup.py build --plat-name=win-amd64 bdist_wininst would create a 64bit installation executable on your 32bit version of Windows. -To cross-compile, you must download the Python source code and cross-compile +To cross-compile, you must download the Python source code and cross-compile Python itself for the platform you are targetting - it is not possible from a binary installtion of Python (as the .lib etc file for other platforms are -not included.) In practice, this means the user of a 32 bit operating -system will need to use Visual Studio 2008 to open the -:file:`PCBuild/PCbuild.sln` solution in the Python source tree and build the -"x64" configuration of the 'pythoncore' project before cross-compiling +not included.) In practice, this means the user of a 32 bit operating +system will need to use Visual Studio 2008 to open the +:file:`PCBuild/PCbuild.sln` solution in the Python source tree and build the +"x64" configuration of the 'pythoncore' project before cross-compiling extensions is possible. Note that by default, Visual Studio 2008 does not install 64bit compilers or diff --git a/Doc/distutils/configfile.rst b/Doc/distutils/configfile.rst index 0ccd5fd..890047c 100644 --- a/Doc/distutils/configfile.rst +++ b/Doc/distutils/configfile.rst @@ -63,7 +63,7 @@ universal :option:`--help` option, e.g. :: --include-dirs (-I) list of directories to search for header files --define (-D) C preprocessor macros to define --undef (-U) C preprocessor macros to undefine - --swig-opts list of SWIG command line options + --swig-opts list of SWIG command line options [...] Note that an option spelled :option:`--foo-bar` on the command-line is spelled diff --git a/Doc/distutils/packageindex.rst b/Doc/distutils/packageindex.rst index ef81d64..3715c82 100644 --- a/Doc/distutils/packageindex.rst +++ b/Doc/distutils/packageindex.rst @@ -72,7 +72,7 @@ If you want to define another server a new section can be created:: index-servers = pypi other - + [pypi] repository: <repository-url> username: <username> @@ -91,4 +91,4 @@ Or even with the section name:: python setup.py register -r other - + diff --git a/Doc/distutils/setupscript.rst b/Doc/distutils/setupscript.rst index 7a6be8b..666b7d6 100644 --- a/Doc/distutils/setupscript.rst +++ b/Doc/distutils/setupscript.rst @@ -213,7 +213,7 @@ This warning notwithstanding, options to SWIG can be currently passed like this:: setup(..., - ext_modules=[Extension('_foo', ['foo.i'], + ext_modules=[Extension('_foo', ['foo.i'], swig_opts=['-modern', '-I../include'])], py_modules=['foo'], ) diff --git a/Doc/documenting/markup.rst b/Doc/documenting/markup.rst index b3f5a4a..80b43b9 100644 --- a/Doc/documenting/markup.rst +++ b/Doc/documenting/markup.rst @@ -508,7 +508,7 @@ in a different style: curly braces to indicate a "variable" part, as in ``:file:``. If you don't need the "variable part" indication, use the standard - ````code```` instead. + ````code```` instead. .. describe:: var @@ -767,7 +767,7 @@ the definition of the symbol. There is this directive: don't have to escape ``*`` or ``|`` characters. -.. XXX describe optional first parameter +.. XXX describe optional first parameter The following is an example taken from the Python Reference Manual:: diff --git a/Doc/extending/building.rst b/Doc/extending/building.rst index 1c7b53f..f4d95b2 100644 --- a/Doc/extending/building.rst +++ b/Doc/extending/building.rst @@ -39,7 +39,7 @@ Python file, which, in the most simple case, could look like this:: With this :file:`setup.py`, and a file :file:`demo.c`, running :: - python setup.py build + python setup.py build will compile :file:`demo.c`, and produce an extension module named ``demo`` in the :file:`build` directory. Depending on the system, the module file will end diff --git a/Doc/extending/extending.rst b/Doc/extending/extending.rst index 17a8110..ed86073 100644 --- a/Doc/extending/extending.rst +++ b/Doc/extending/extending.rst @@ -334,7 +334,7 @@ When the Python program imports module :mod:`spam` for the first time, :cfunc:`PyInit_spam` is called. (See below for comments about embedding Python.) It calls :cfunc:`PyModule_Create`, which returns a module object, and inserts built-in function objects into the newly created module based upon the -table (an array of :ctype:`PyMethodDef` structures) found in the module definition. +table (an array of :ctype:`PyMethodDef` structures) found in the module definition. :cfunc:`PyModule_Create` returns a pointer to the module object that it creates. It may abort with a fatal error for certain errors, or return *NULL* if the module could not be initialized @@ -482,7 +482,7 @@ Later, when it is time to call the function, you call the C function :cfunc:`PyEval_CallObject`. This function has two arguments, both pointers to arbitrary Python objects: the Python function, and the argument list. The argument list must always be a tuple object, whose length is the number of -arguments. To call the Python function with no arguments, pass in NULL, or +arguments. To call the Python function with no arguments, pass in NULL, or an empty tuple; to call it with one argument, pass a singleton tuple. :cfunc:`Py_BuildValue` returns a tuple when its format string consists of zero or more format codes between parentheses. For example:: @@ -521,7 +521,7 @@ If this is not possible or desirable, the exception should be cleared by calling if (result == NULL) return NULL; /* Pass error back */ ...use result... - Py_DECREF(result); + Py_DECREF(result); Depending on the desired interface to the Python callback function, you may also have to provide an argument list to :cfunc:`PyEval_CallObject`. In some cases @@ -546,7 +546,7 @@ Note the placement of ``Py_DECREF(arglist)`` immediately after the call, before the error check! Also note that strictly speaking this code is not complete: :cfunc:`Py_BuildValue` may run out of memory, and this should be checked. -You may also call a function with keyword arguments by using +You may also call a function with keyword arguments by using :cfunc:`PyEval_CallObjectWithKeywords`. As in the above example, we use :cfunc:`Py_BuildValue` to construct the dictionary. :: @@ -687,7 +687,7 @@ Philbrick (philbrick@hks.com):: static PyObject * keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds) - { + { int voltage; char *state = "a stiff"; char *action = "voom"; @@ -695,11 +695,11 @@ Philbrick (philbrick@hks.com):: static char *kwlist[] = {"voltage", "state", "action", "type", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, &voltage, &state, &action, &type)) - return NULL; + return NULL; - printf("-- This parrot wouldn't %s if you put %i Volts through it.\n", + printf("-- This parrot wouldn't %s if you put %i Volts through it.\n", action, voltage); printf("-- Lovely plumage, the %s -- It's %s!\n", type, state); diff --git a/Doc/extending/newtypes.rst b/Doc/extending/newtypes.rst index e6b52c5..66af3bf 100644 --- a/Doc/extending/newtypes.rst +++ b/Doc/extending/newtypes.rst @@ -1180,7 +1180,7 @@ As with the :attr:`tp_methods` table, a sentinel entry with a :attr:`name` value of *NULL* is required. .. XXX Descriptors need to be explained in more detail somewhere, but not here. - + Descriptor objects have two handler functions which correspond to the \member{tp_getattro} and \member{tp_setattro} handlers. The \method{__get__()} handler is a function which is passed the descriptor, @@ -1233,15 +1233,15 @@ example that simply raises an exception; if this were really all you wanted, the return -1; } -.. XXX tp_compare is dead; need to rewrite for tp_richcompare! +.. XXX tp_compare is dead; need to rewrite for tp_richcompare! Object Comparison ----------------- - + :: - + cmpfunc tp_compare; - + The :attr:`tp_compare` handler is called when comparisons are needed and the object does not implement the specific rich comparison method which matches the requested comparison. (It is always used if defined and the @@ -1252,18 +1252,18 @@ example that simply raises an exception; if this were really all you wanted, the allowed to return arbitrary negative or positive integers for less than and greater than, respectively; as of Python 2.2, this is no longer allowed. In the future, other return values may be assigned a different meaning.) - + A :attr:`tp_compare` handler may raise an exception. In this case it should return a negative value. The caller has to test for the exception using :cfunc:`PyErr_Occurred`. - + Here is a sample implementation:: - + static int newdatatype_compare(newdatatypeobject * obj1, newdatatypeobject * obj2) { long result; - + if (obj1->obj_UnderlyingDatatypePtr->size < obj2->obj_UnderlyingDatatypePtr->size) { result = -1; diff --git a/Doc/extending/windows.rst b/Doc/extending/windows.rst index 1675a0d..aac1d2d 100644 --- a/Doc/extending/windows.rst +++ b/Doc/extending/windows.rst @@ -102,7 +102,7 @@ described here are distributed with the Python sources in the and it should call :cfunc:`Py_InitModule` with the string ``"spam"`` as its first argument (use the minimal :file:`example.c` in this directory as a guide). By convention, it lives in a file called :file:`spam.c` or :file:`spammodule.c`. - The output file should be called :file:`spam.pyd` (in Release mode) or + The output file should be called :file:`spam.pyd` (in Release mode) or :file:`spam_d.pyd` (in Debug mode). The extension :file:`.pyd` was chosen to avoid confusion with a system library :file:`spam.dll` to which your module could be a Python interface. diff --git a/Doc/glossary.rst b/Doc/glossary.rst index eb2614f..9e3cbeb 100644 --- a/Doc/glossary.rst +++ b/Doc/glossary.rst @@ -11,7 +11,7 @@ Glossary ``>>>`` The default Python prompt of the interactive shell. Often seen for code examples which can be executed interactively in the interpreter. - + ``...`` The default Python prompt of the interactive shell when entering code for an indented code block or within a pair of matching left and right @@ -50,11 +50,11 @@ Glossary A value associated with an object which is referenced by name using dotted expressions. For example, if an object *o* has an attribute *a* it would be referenced as *o.a*. - + BDFL Benevolent Dictator For Life, a.k.a. `Guido van Rossum <http://www.python.org/~guido/>`_, Python's creator. - + bytecode Python source code is compiled into bytecode, the internal representation of a Python program in the interpreter. The bytecode is also cached in @@ -67,7 +67,7 @@ Glossary A template for creating user-defined objects. Class definitions normally contain method definitions which operate on instances of the class. - + coercion The implicit conversion of an instance of one type to another during an operation which involves two arguments of the same type. For example, @@ -77,7 +77,7 @@ Glossary will raise a ``TypeError``. Without coercion, all arguments of even compatible types would have to be normalized to the same value by the programmer, e.g., ``float(3)+4.5`` rather than just ``3+4.5``. - + complex number An extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. Imaginary @@ -89,7 +89,7 @@ Glossary :mod:`math` module, use :mod:`cmath`. Use of complex numbers is a fairly advanced mathematical feature. If you're not aware of a need for them, it's almost certain you can safely ignore them. - + context manager An object which controls the environment seen in a :keyword:`with` statement by defining :meth:`__enter__` and :meth:`__exit__` methods. @@ -132,7 +132,7 @@ Glossary and reference to super classes. For more information about descriptors' methods, see :ref:`descriptors`. - + dictionary An associative array, where arbitrary keys are mapped to values. The use of :class:`dict` closely resembles that for :class:`list`, but the keys can @@ -146,8 +146,8 @@ Glossary of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object. - - duck-typing + + duck-typing A pythonic programming style which determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it @@ -157,13 +157,13 @@ Glossary :func:`isinstance`. (Note, however, that duck-typing can be complemented with abstract base classes.) Instead, it typically employs :func:`hasattr` tests or :term:`EAFP` programming. - + EAFP Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many :keyword:`try` and :keyword:`except` - statements. The technique contrasts with the :term:`LBYL` style + statements. The technique contrasts with the :term:`LBYL` style common to many other languages such as C. expression @@ -196,7 +196,7 @@ Glossary By importing the :mod:`__future__` module and evaluating its variables, you can see when a new feature was first added to the language and when it becomes the default:: - + >>> import __future__ >>> __future__.division _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192) @@ -205,7 +205,7 @@ Glossary The process of freeing memory when it is not used anymore. Python performs garbage collection via reference counting and a cyclic garbage collector that is able to detect and break reference cycles. - + generator A function which returns an iterator. It looks like a normal function except that values are returned to the caller using a :keyword:`yield` @@ -215,21 +215,21 @@ Glossary stopped at the :keyword:`yield` keyword (returning the result) and is resumed there when the next element is requested by calling the :meth:`__next__` method of the returned iterator. - + .. index:: single: generator expression - + generator expression An expression that returns a generator. It looks like a normal expression followed by a :keyword:`for` expression defining a loop variable, range, and an optional :keyword:`if` expression. The combined expression generates values for an enclosing function:: - + >>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81 285 - + GIL See :term:`global interpreter lock`. - + global interpreter lock The lock used by Python threads to assure that only one thread executes in the :term:`CPython` :term:`virtual machine` at a time. @@ -255,14 +255,14 @@ Glossary containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their :func:`id`. - + IDLE An Integrated Development Environment for Python. IDLE is a basic editor and interpreter environment which ships with the standard distribution of Python. Good for beginners, it also serves as clear example code for those wanting to implement a moderately sophisticated, multi-platform GUI application. - + immutable An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to @@ -277,7 +277,7 @@ Glossary arguments (possibly by selecting it from your computer's main menu). It is a very powerful way to test out new ideas or inspect modules and packages (remember ``help(x)``). - + interpreted Python is an interpreted language, as opposed to a compiled one, though the distinction can be blurry because of the presence of the @@ -286,7 +286,7 @@ Glossary Interpreted languages typically have a shorter development/debug cycle than compiled ones, though their programs generally also run more slowly. See also :term:`interactive`. - + iterable A container object capable of returning its members one at a time. Examples of iterables include all sequence types (such as @@ -302,7 +302,7 @@ Glossary statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also :term:`iterator`, :term:`sequence`, and :term:`generator`. - + iterator An object representing a stream of data. Repeated calls to the iterator's :meth:`__next__` (or passing it to the builtin function) :func:`next` @@ -318,7 +318,7 @@ Glossary :func:`iter` function or use it in a :keyword:`for` loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container. - + More information can be found in :ref:`typeiter`. keyword argument @@ -342,7 +342,7 @@ Glossary A built-in Python :term:`sequence`. Despite its name it is more akin to an array in other languages than to a linked list since access to elements are O(1). - + list comprehension A compact way to process all or part of the elements in a sequence and return a list with the results. ``result = ["0x%02x" % x for x in @@ -350,11 +350,11 @@ Glossary even hex numbers (0x..) in the range from 0 to 255. The :keyword:`if` clause is optional. If omitted, all elements in ``range(256)`` are processed. - + mapping A container object (such as :class:`dict`) which supports arbitrary key lookups using the special method :meth:`__getitem__`. - + metaclass The class of a class. Class definitions create a class name, a class dictionary, and a list of base classes. The metaclass is responsible for @@ -373,7 +373,7 @@ Glossary of an instance of that class, the method will get the instance object as its first :term:`argument` (which is usually called ``self``). See :term:`function` and :term:`nested scope`. - + mutable Mutable objects can change their value but keep their :func:`id`. See also :term:`immutable`. @@ -390,7 +390,7 @@ Glossary :func:`collections.namedtuple`. The latter approach automatically provides extra features such as a self-documenting representation like ``Employee(name='jones', title='programmer')``. - + namespace The place where a variable is stored. Namespaces are implemented as dictionaries. There are the local, global and builtin namespaces as well @@ -402,7 +402,7 @@ Glossary :func:`random.seed` or :func:`itertools.izip` makes it clear that those functions are implemented by the :mod:`random` and :mod:`itertools` modules, respectively. - + nested scope The ability to refer to a variable in an enclosing definition. For instance, a function defined inside another function can refer to @@ -410,7 +410,7 @@ Glossary reference and not for assignment which will always write to the innermost scope. In contrast, local variables both read and write in the innermost scope. Likewise, global variables read and write to the global namespace. - + new-style class Old name for the flavor of classes now used for all class objects. In earlier Python versions, only new-style classes could use Python's newer, @@ -421,7 +421,7 @@ Glossary Any data with state (attributes or value) and defined behavior (methods). Also the ultimate base class of any :term:`new-style class`. - + positional argument The arguments assigned to local names inside a function or method, determined by the order in which they were given in the call. ``*`` is @@ -441,7 +441,7 @@ Glossary to loop over all elements of an iterable using a :keyword:`for` statement. Many other languages don't have this type of construct, so people unfamiliar with Python sometimes use a numerical counter instead:: - + for i in range(len(food)): print(food[i]) @@ -464,7 +464,7 @@ Glossary popular, the technique is somewhat tricky to get right and is best reserved for rare cases where there are large numbers of instances in a memory-critical application. - + sequence An :term:`iterable` which supports efficient element access using integer indices via the :meth:`__getitem__` special method and defines a @@ -516,7 +516,7 @@ Glossary virtual machine A computer defined entirely in software. Python's virtual machine executes the :term:`bytecode` emitted by the bytecode compiler. - + Zen of Python Listing of Python design principles and philosophies that are helpful in understanding and using the language. The listing can be found by typing diff --git a/Doc/howto/curses.rst b/Doc/howto/curses.rst index b56b2c8..7e69006 100644 --- a/Doc/howto/curses.rst +++ b/Doc/howto/curses.rst @@ -399,8 +399,8 @@ string. It can optionally be limited to a fixed number of characters. :: curses.echo() # Enable echoing of characters - # Get a 15-character string, with the cursor on the top line - s = stdscr.getstr(0,0, 15) + # Get a 15-character string, with the cursor on the top line + s = stdscr.getstr(0,0, 15) The Python :mod:`curses.textpad` module supplies something better. With it, you can turn a window into a text box that supports an Emacs-like set of diff --git a/Doc/howto/doanddont.rst b/Doc/howto/doanddont.rst index 99d28a8..4d3ae88 100644 --- a/Doc/howto/doanddont.rst +++ b/Doc/howto/doanddont.rst @@ -1,5 +1,5 @@ ************************************ - Idioms and Anti-Idioms in Python + Idioms and Anti-Idioms in Python ************************************ :Author: Moshe Zadka @@ -94,7 +94,7 @@ Bad example:: # bar.py from foo import a if something(): - a = 2 # danger: foo.a != a + a = 2 # danger: foo.a != a Good example:: @@ -271,6 +271,6 @@ It is usually much better to use the implicit continuation inside parenthesis: This version is bulletproof:: - value = (foo.bar()['first'][0]*baz.quux(1, 2)[5:9] + value = (foo.bar()['first'][0]*baz.quux(1, 2)[5:9] + calculate_number(10, 20)*forbulate(500, 360)) diff --git a/Doc/howto/functional.rst b/Doc/howto/functional.rst index 1d9b42d..cfa831e 100644 --- a/Doc/howto/functional.rst +++ b/Doc/howto/functional.rst @@ -145,7 +145,7 @@ than a large function that performs a complicated transformation. Small functions are also easier to read and to check for errors. -Ease of debugging and testing +Ease of debugging and testing ----------------------------- Testing and debugging a functional-style program is easier. @@ -213,7 +213,7 @@ You can experiment with the iteration interface manually: Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration - >>> + >>> Python expects iterable objects in several different contexts, the most important being the ``for`` statement. In the statement ``for X in Y``, Y must @@ -363,7 +363,7 @@ Generator expressions are surrounded by parentheses ("()") and list comprehensions are surrounded by square brackets ("[]"). Generator expressions have the form:: - ( expression for expr in sequence1 + ( expression for expr in sequence1 if condition1 for expr2 in sequence2 if condition2 @@ -405,7 +405,7 @@ equivalent to the following Python code:: if not (conditionN): continue # Skip this element - # Output the value of + # Output the value of # the expression. This means that when there are multiple ``for...in`` clauses but no ``if`` @@ -419,8 +419,8 @@ list is 9 elements long: >>> seq1 = 'abc' >>> seq2 = (1,2,3) >>> [(x,y) for x in seq1 for y in seq2] - [('a', 1), ('a', 2), ('a', 3), - ('b', 1), ('b', 2), ('b', 3), + [('a', 1), ('a', 2), ('a', 3), + ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)] To avoid introducing an ambiguity into Python's grammar, if ``expression`` is @@ -627,7 +627,7 @@ Let's look in more detail at built-in functions often used with iterators. Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate the features of generator expressions: -``map(f, iterA, iterB, ...)`` returns an iterator over the sequence +``map(f, iterA, iterB, ...)`` returns an iterator over the sequence ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``. >>> def upper(s): @@ -639,7 +639,7 @@ features of generator expressions: >>> [upper(s) for s in ['sentence', 'fragment']] ['SENTENCE', 'FRAGMENT'] -You can of course achieve the same effect with a list comprehension. +You can of course achieve the same effect with a list comprehension. ``filter(predicate, iter)`` returns an iterator over all the sequence elements that meet a certain condition, and is similarly duplicated by list @@ -709,7 +709,7 @@ values: True >>> all([0,1,0]) False - >>> all([0,0,0]) + >>> all([0,0,0]) False >>> all([1,1,1]) True @@ -827,7 +827,7 @@ operators. Some examples are ``operator.add(a, b)`` (adds two values), ``itertools.starmap(func, iter)`` assumes that the iterable will return a stream of tuples, and calls ``f()`` using these tuples as the arguments:: - itertools.starmap(os.path.join, + itertools.starmap(os.path.join, [('/usr', 'bin', 'java'), ('/bin', 'python'), ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')]) => @@ -887,9 +887,9 @@ value and an iterator for the elements with that key. :: - city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), + city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), ('Anchorage', 'AK'), ('Nome', 'AK'), - ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), + ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), ... ] @@ -904,7 +904,7 @@ value and an iterator for the elements with that key. where iterator-1 => ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL') - iterator-2 => + iterator-2 => ('Anchorage', 'AK'), ('Nome', 'AK') iterator-3 => ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ') @@ -1045,7 +1045,7 @@ is equivalent to :: >>> double(add(5, 6)) 22 - + The ``unpack`` keyword is provided to work around the fact that Python functions are not always `fully curried <http://en.wikipedia.org/wiki/Currying>`__. By default, it is expected that the ``inner`` function will return a single object @@ -1054,15 +1054,15 @@ and that the ``outer`` function will take a single argument. Setting the will be expanded before being passed to ``outer``. Put simply, :: compose(f, g)(5, 6) - + is equivalent to:: f(g(5, 6)) - + while :: compose(f, g, unpack=True)(5, 6) - + is equivalent to:: f(*g(5, 6)) @@ -1074,21 +1074,21 @@ provided by both ``functional`` and ``functools``). :: from functional import compose, partial import functools - + multi_compose = partial(functools.reduce, compose) - - + + We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of ``"".join(...)`` that converts its arguments to string:: from functional import compose, partial - + join = compose("".join, partial(map, str)) ``flip(func)`` - + ``flip()`` wraps the callable in ``func`` and causes it to receive its non-keyword arguments in reverse order. :: @@ -1103,7 +1103,7 @@ non-keyword arguments in reverse order. :: (7, 6, 5) ``foldl(func, start, iterable)`` - + ``foldl()`` takes a binary function, a starting value (usually some kind of 'zero'), and an iterable. The function is applied to the starting value and the first element of the list, then the result of that and the second element of the @@ -1117,7 +1117,7 @@ is equivalent to:: f(f(f(0, 1), 2), 3) - + ``foldl()`` is roughly equivalent to the following recursive function:: def foldl(func, start, seq): @@ -1224,7 +1224,7 @@ Fredrik Lundh once suggested the following set of rules for refactoring uses of 4) Convert the lambda to a def statement, using that name. 5) Remove the comment. -I really like these rules, but you're free to disagree +I really like these rules, but you're free to disagree about whether this lambda-free style is better. @@ -1282,7 +1282,7 @@ for text processing, in the section titled "Utilizing Higher-Order Functions in Text Processing". Mertz also wrote a 3-part series of articles on functional programming -for IBM's DeveloperWorks site; see +for IBM's DeveloperWorks site; see `part 1 <http://www-128.ibm.com/developerworks/library/l-prog.html>`__, `part 2 <http://www-128.ibm.com/developerworks/library/l-prog2.html>`__, and `part 3 <http://www-128.ibm.com/developerworks/linux/library/l-prog3.html>`__, diff --git a/Doc/howto/sockets.rst b/Doc/howto/sockets.rst index 2629d44..69130c4 100644 --- a/Doc/howto/sockets.rst +++ b/Doc/howto/sockets.rst @@ -1,5 +1,5 @@ **************************** - Socket Programming HOWTO + Socket Programming HOWTO **************************** :Author: Gordon McMillan @@ -62,7 +62,7 @@ your browser did something like the following:: #create an INET, STREAMing socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - #now connect to the web server on port 80 + #now connect to the web server on port 80 # - the normal http port s.connect(("www.mcmillan-inc.com", 80)) @@ -77,7 +77,7 @@ creates a "server socket". :: #create an INET, STREAMing socket serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) - #bind the socket to a public host, + #bind the socket to a public host, # and a well-known port serversocket.bind((socket.gethostname(), 80)) #become a server socket @@ -184,7 +184,7 @@ Assuming you don't want to end the connection, the simplest solution is a fixed length message:: class mysocket: - """demonstration class only + """demonstration class only - coded for clarity, not efficiency """ @@ -340,9 +340,9 @@ you'll have little trouble with it in C. :: ready_to_read, ready_to_write, in_error = \ select.select( - potential_readers, - potential_writers, - potential_errs, + potential_readers, + potential_writers, + potential_errs, timeout) You pass ``select`` three lists: the first contains all sockets that you might diff --git a/Doc/howto/urllib2.rst b/Doc/howto/urllib2.rst index d74729b..b71b300 100644 --- a/Doc/howto/urllib2.rst +++ b/Doc/howto/urllib2.rst @@ -10,7 +10,7 @@ HOWTO, available at `urllib2 - Le Manuel manquant <http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml>`_. - + Introduction ============ @@ -19,9 +19,9 @@ Introduction You may also find useful the following article on fetching web resources with Python: - + * `Basic Authentication <http://www.voidspace.org.uk/python/articles/authentication.shtml>`_ - + A tutorial on *Basic Authentication*, with examples in Python. **urllib.request** is a `Python <http://www.python.org>`_ module for fetching URLs @@ -98,7 +98,7 @@ argument. The encoding is done using a function from the :mod:`urllib.parse` library. :: import urllib.parse - import urllib.request + import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' values = {'name' : 'Michael Foord', @@ -161,15 +161,15 @@ request as above, but identifies itself as a version of Internet Explorer [#]_. :: import urllib.parse - import urllib.request - + import urllib.request + url = 'http://www.someserver.com/cgi-bin/register.cgi' - user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' + user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } - + data = urllib.parse.urlencode(values) req = urllib.request.Request(url, data, headers) response = urllib.request.urlopen(req) @@ -183,7 +183,7 @@ Handling Exceptions =================== *urlopen* raises :exc:`URLError` when it cannot handle a response (though as usual -with Python APIs, builtin exceptions such as +with Python APIs, builtin exceptions such as :exc:`ValueError`, :exc:`TypeError` etc. may also be raised). @@ -311,18 +311,18 @@ page returned. This means that as well as the code attribute, it also has read, geturl, and info, methods as returned by the ``urllib.response`` module:: >>> req = urllib.request.Request('http://www.python.org/fish.html') - >>> try: + >>> try: >>> urllib.request.urlopen(req) >>> except urllib.error.URLError, e: >>> print(e.code) >>> print(e.read()) - >>> + >>> 404 - <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" + <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> - <?xml-stylesheet href="./css/ht2html.css" + <?xml-stylesheet href="./css/ht2html.css" type="text/css"?> - <html><head><title>Error 404: File Not Found</title> + <html><head><title>Error 404: File Not Found</title> ...... etc... Wrapping it Up @@ -376,7 +376,7 @@ Number 2 print('Error code: ', e.code) else: # everything is fine - + info and geturl =============== @@ -448,7 +448,7 @@ error code) requesting authentication. This specifies the authentication scheme and a 'realm'. The header looks like : ``Www-authenticate: SCHEME realm="REALM"``. -e.g. :: +e.g. :: Www-authenticate: Basic realm="cPanel Users" @@ -472,24 +472,24 @@ The top-level URL is the first URL that requires authentication. URLs "deeper" than the URL you pass to .add_password() will also match. :: # create a password manager - password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() + password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() # Add the username and password. # If we knew the realm, we could use it instead of ``None``. top_level_url = "http://example.com/foo/" password_mgr.add_password(None, top_level_url, username, password) - handler = urllib.request.HTTPBasicAuthHandler(password_mgr) + handler = urllib.request.HTTPBasicAuthHandler(password_mgr) # create "opener" (OpenerDirector instance) - opener = urllib.request.build_opener(handler) + opener = urllib.request.build_opener(handler) # use the opener to fetch a URL - opener.open(a_url) + opener.open(a_url) # Install the opener. # Now all calls to urllib.request.urlopen use our opener. - urllib.request.install_opener(opener) + urllib.request.install_opener(opener) .. note:: @@ -545,7 +545,7 @@ However, you can set the default timeout globally for all sockets using :: # timeout in seconds timeout = 10 - socket.setdefaulttimeout(timeout) + socket.setdefaulttimeout(timeout) # this call to urllib.request.urlopen now uses the default timeout # we have set in the socket module @@ -562,7 +562,7 @@ Footnotes This document was reviewed and revised by John Lee. .. [#] For an introduction to the CGI protocol see - `Writing Web Applications in Python <http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html>`_. + `Writing Web Applications in Python <http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html>`_. .. [#] Like Google for example. The *proper* way to use google from a program is to use `PyGoogle <http://pygoogle.sourceforge.net>`_ of course. See `Voidspace Google <http://www.voidspace.org.uk/python/recipebook.shtml#google>`_ @@ -579,6 +579,6 @@ This document was reviewed and revised by John Lee. is set to use the proxy, which urllib picks up on. In order to test scripts with a localhost server, I have to prevent urllib from using the proxy. -.. [#] urllib opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe +.. [#] urllib opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456195>`_. - + diff --git a/Doc/howto/webservers.rst b/Doc/howto/webservers.rst index 401f94e..8cc53b8 100644 --- a/Doc/howto/webservers.rst +++ b/Doc/howto/webservers.rst @@ -88,7 +88,7 @@ they can be run as CGI if no better option is available. <http://wiki.python.org/moin/CgiScripts>`_ with some additional information about CGI in Python. - + Simple script for testing CGI ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -387,7 +387,7 @@ compared with other web techniques. You might be interested in some WSGI-supporting modules already contained in the standard library, namely: - + * :mod:`wsgiref` -- some tiny utilities and servers for WSGI @@ -500,7 +500,7 @@ using these is a good idea. time in looking through the most popular ones. Some frameworks have their own template engine or have a recommentation for one. It's wise to use these. - + Popular template engines include: * Mako @@ -688,7 +688,7 @@ And that's still not everything. The most up-to-date information can always be found in the Python wiki. .. seealso:: - + The Python wiki contains an extensive list of `web frameworks <http://wiki.python.org/moin/WebFrameworks>`_. diff --git a/Doc/install/index.rst b/Doc/install/index.rst index d83e3f2..3b47f72 100644 --- a/Doc/install/index.rst +++ b/Doc/install/index.rst @@ -3,7 +3,7 @@ .. _install-index: ***************************** - Installing Python Modules + Installing Python Modules ***************************** :Author: Greg Ward @@ -18,7 +18,7 @@ Thus, I have to be sure to explain the basics at some point: sys.path and PYTHONPATH at least. Should probably give pointers to other docs on "import site", PYTHONSTARTUP, PYTHONHOME, etc. - + Finally, it might be useful to include all the material from my "Care and Feeding of a Python Installation" talk in here somewhere. Yow! @@ -268,7 +268,7 @@ at the prompt. For example, on my Linux system, I type the three Python statements shown below, and get the output as shown, to find out my :file:`{prefix}` and :file:`{exec-prefix}`:: - Python 2.4 (#26, Aug 7 2004, 17:19:02) + Python 2.4 (#26, Aug 7 2004, 17:19:02) Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.prefix @@ -587,8 +587,8 @@ value of ``sys.path``. :: Type ``help'', ``copyright'', ``credits'' or ``license'' for more information. >>> import sys >>> sys.path - ['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', - '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload', + ['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', + '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload', '/usr/local/lib/python2.3/site-packages'] >>> diff --git a/Doc/library/abc.rst b/Doc/library/abc.rst index b03fc83..bf3b0b1 100644 --- a/Doc/library/abc.rst +++ b/Doc/library/abc.rst @@ -128,7 +128,7 @@ It also provides the following decorators: A decorator indicating abstract methods. Using this decorator requires that the class's metaclass is :class:`ABCMeta` or - is derived from it. + is derived from it. A class that has a metaclass derived from :class:`ABCMeta` cannot be instantiated unless all of its abstract methods and properties are overridden. @@ -163,7 +163,7 @@ It also provides the following decorators: A subclass of the built-in :func:`property`, indicating an abstract property. Using this function requires that the class's metaclass is :class:`ABCMeta` or - is derived from it. + is derived from it. A class that has a metaclass derived from :class:`ABCMeta` cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract properties can be called using any of the normal diff --git a/Doc/library/aifc.rst b/Doc/library/aifc.rst index 7f7d7fe..e3bb51a 100644 --- a/Doc/library/aifc.rst +++ b/Doc/library/aifc.rst @@ -17,7 +17,7 @@ samples in a file. AIFF-C is a newer version of the format that includes the ability to compress the audio data. .. warning:: - + Some operations may only work under IRIX; these will raise :exc:`ImportError` when attempting to import the :mod:`cl` module, which is only available on IRIX. diff --git a/Doc/library/array.rst b/Doc/library/array.rst index 2fb4f8a..4900509 100644 --- a/Doc/library/array.rst +++ b/Doc/library/array.rst @@ -52,7 +52,7 @@ The module defines the following type: Return a new array whose items are restricted by *typecode*, and initialized from the optional *initializer* value, which must be a list, object - supporting the buffer interface, or iterable over elements of the + supporting the buffer interface, or iterable over elements of the appropriate type. If given a list or string, the initializer is passed to the new array's diff --git a/Doc/library/ast.rst b/Doc/library/ast.rst index b8bc896..2cf9da1 100644 --- a/Doc/library/ast.rst +++ b/Doc/library/ast.rst @@ -114,7 +114,7 @@ and classes for traversing abstract syntax trees: Parse an expression into an AST node. Equivalent to ``compile(expr, filename, mode, ast.PyCF_ONLY_AST)``. - + .. function:: literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python @@ -192,7 +192,7 @@ and classes for traversing abstract syntax trees: .. method:: generic_visit(node) This visitor calls :meth:`visit` on all children of the node. - + Note that child nodes of nodes that have a custom visitor method won't be visited unless the visitor calls :meth:`generic_visit` or visits them itself. diff --git a/Doc/library/audioop.rst b/Doc/library/audioop.rst index 9eb315f..fe6e86f 100644 --- a/Doc/library/audioop.rst +++ b/Doc/library/audioop.rst @@ -260,7 +260,7 @@ sample and subtract the whole output sample from the input sample:: in_test = inputdata[pos*2:] ipos, factor = audioop.findfit(in_test, out_test) # Optional (for better cancellation): - # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)], + # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)], # out_test) prefill = '\0'*(pos+ipos)*2 postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata)) diff --git a/Doc/library/bdb.rst b/Doc/library/bdb.rst index 555b634..b1cf200 100644 --- a/Doc/library/bdb.rst +++ b/Doc/library/bdb.rst @@ -325,7 +325,7 @@ Finally, the module defines the following functions: Check whether we should break here, depending on the way the breakpoint *b* was set. - + If it was set via line number, it checks if ``b.line`` is the same as the one in the frame also passed as argument. If the breakpoint was set via function name, we have to check we are in the right frame (the right function) and if diff --git a/Doc/library/cmath.rst b/Doc/library/cmath.rst index 2d804c97..682e6db 100644 --- a/Doc/library/cmath.rst +++ b/Doc/library/cmath.rst @@ -68,9 +68,9 @@ Definition:: .. function:: polar(x) - Convert a :class:`complex` from rectangular coordinates to polar + Convert a :class:`complex` from rectangular coordinates to polar coordinates. The function returns a tuple with the two elements - *r* and *phi*. *r* is the distance from 0 and *phi* the phase + *r* and *phi*. *r* is the distance from 0 and *phi* the phase angle. diff --git a/Doc/library/codeop.rst b/Doc/library/codeop.rst index 97b6267..e4523b6 100644 --- a/Doc/library/codeop.rst +++ b/Doc/library/codeop.rst @@ -43,7 +43,7 @@ To do just the former: other value will cause :exc:`ValueError` to be raised. .. warning:: - + It is possible (but not likely) that the parser stops parsing with a successful outcome before reaching the end of the source; in this case, trailing symbols may be ignored instead of causing an error. For example, diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index b12bd7a..f41abd6 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -43,34 +43,34 @@ ABC Inherits Abstract Methods Mixin :class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__`` :class:`Sized` ``__len__`` :class:`Callable` ``__call__`` - + :class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``. :class:`Iterable`, and ``__len__`` ``index``, and ``count`` - :class:`Container` - + :class:`Container` + :class:`MutableSequence` :class:`Sequence` ``__getitem__`` Inherited Sequence methods and ``__delitem__``, ``append``, ``reverse``, ``extend``, ``pop``, ``insert``, ``remove``, and ``__iadd__`` and ``__len__`` - + :class:`Set` :class:`Sized`, ``__len__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``, :class:`Iterable`, ``__iter__``, and ``__gt__``, ``__ge__``, ``__and__``, ``__or__`` :class:`Container` ``__contains__`` ``__sub__``, ``__xor__``, and ``isdisjoint`` - + :class:`MutableSet` :class:`Set` ``add`` and Inherited Set methods and ``discard`` ``clear``, ``pop``, ``remove``, ``__ior__``, ``__iand__``, ``__ixor__``, and ``__isub__`` - + :class:`Mapping` :class:`Sized`, ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``, :class:`Iterable`, ``__len__``. and ``get``, ``__eq__``, and ``__ne__`` :class:`Container` ``__iter__`` - + :class:`MutableMapping` :class:`Mapping` ``__getitem__`` Inherited Mapping methods and ``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``, ``__delitem__``, and ``setdefault`` ``__iter__``, and ``__len__`` - + :class:`MappingView` :class:`Sized` ``__len__`` :class:`KeysView` :class:`MappingView`, ``__contains__``, :class:`Set` ``__iter__`` @@ -526,8 +526,8 @@ Example: if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result - <BLANKLINE> - def __getnewargs__(self): + <BLANKLINE> + def __getnewargs__(self): return tuple(self) <BLANKLINE> x = property(itemgetter(0)) @@ -674,8 +674,8 @@ and more efficient to use a simple class declaration: :class:`UserDict` objects ------------------------- -The class, :class:`UserDict` acts as a wrapper around dictionary objects. -The need for this class has been partially supplanted by the ability to +The class, :class:`UserDict` acts as a wrapper around dictionary objects. +The need for this class has been partially supplanted by the ability to subclass directly from :class:`dict`; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute. @@ -688,7 +688,7 @@ attribute. initialized with its contents; note that a reference to *initialdata* will not be kept, allowing it be used for other purposes. -In addition to supporting the methods and operations of mappings, +In addition to supporting the methods and operations of mappings, :class:`UserDict` instances provide the following attribute: .. attribute:: UserDict.data @@ -701,11 +701,11 @@ In addition to supporting the methods and operations of mappings, ------------------------- This class acts as a wrapper around list objects. It is a useful base class -for your own list-like classes which can inherit from them and override +for your own list-like classes which can inherit from them and override existing methods or add new ones. In this way, one can add new behaviors to lists. -The need for this class has been partially supplanted by the ability to +The need for this class has been partially supplanted by the ability to subclass directly from :class:`list`; however, this class can be easier to work with because the underlying list is accessible as an attribute. @@ -717,12 +717,12 @@ to work with because the underlying list is accessible as an attribute. defaulting to the empty list ``[]``. *list* can be any iterable, for example a real Python list or a :class:`UserList` object. -In addition to supporting the methods and operations of mutable sequences, +In addition to supporting the methods and operations of mutable sequences, :class:`UserList` instances provide the following attribute: .. attribute:: UserList.data - A real :class:`list` object used to store the contents of the + A real :class:`list` object used to store the contents of the :class:`UserList` class. **Subclassing requirements:** Subclasses of :class:`UserList` are expect to @@ -740,8 +740,8 @@ in that case. :class:`UserString` objects --------------------------- -The class, :class:`UserString` acts as a wrapper around string objects. -The need for this class has been partially supplanted by the ability to +The class, :class:`UserString` acts as a wrapper around string objects. +The need for this class has been partially supplanted by the ability to subclass directly from :class:`str`; however, this class can be easier to work with because the underlying string is accessible as an attribute. @@ -749,8 +749,8 @@ attribute. .. class:: UserString([sequence]) Class that simulates a string or a Unicode string object. The instance's - content is kept in a regular string object, which is accessible via the - :attr:`data` attribute of :class:`UserString` instances. The instance's + content is kept in a regular string object, which is accessible via the + :attr:`data` attribute of :class:`UserString` instances. The instance's contents are initially set to a copy of *sequence*. The *sequence* can be an instance of :class:`bytes`, :class:`str`, :class:`UserString` (or a subclass) or an arbitrary sequence which can be converted into a string using diff --git a/Doc/library/configparser.rst b/Doc/library/configparser.rst index 75bfd92..445e65f 100644 --- a/Doc/library/configparser.rst +++ b/Doc/library/configparser.rst @@ -344,7 +344,7 @@ An example of writing to a configuration file:: import configparser config = configparser.RawConfigParser() - + # When adding sections or items, add them in the reverse order of # how you want them to be displayed in the actual file. # In addition, please note that using RawConfigParser's and the raw @@ -359,7 +359,7 @@ An example of writing to a configuration file:: config.set('Section1', 'baz', 'fun') config.set('Section1', 'bar', 'Python') config.set('Section1', 'foo', '%(bar)s is %(baz)s!') - + # Writing our configuration file to 'example.cfg' with open('example.cfg', 'wb') as configfile: config.write(configfile) @@ -399,7 +399,7 @@ To get interpolation, you will need to use a :class:`ConfigParser` or print(config.get('Section1', 'foo', 0, {'bar': 'Documentation', 'baz': 'evil'})) -Defaults are available in all three types of ConfigParsers. They are used in +Defaults are available in all three types of ConfigParsers. They are used in interpolation if an option used is not defined elsewhere. :: import configparser @@ -407,7 +407,7 @@ interpolation if an option used is not defined elsewhere. :: # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'}) config.read('example.cfg') - + print(config.get('Section1', 'foo')) # -> "Python is fun!" config.remove_option('Section1', 'bar') config.remove_option('Section1', 'baz') diff --git a/Doc/library/constants.rst b/Doc/library/constants.rst index 12b56f8..39d61cb 100644 --- a/Doc/library/constants.rst +++ b/Doc/library/constants.rst @@ -14,13 +14,13 @@ A small number of constants live in the built-in namespace. They are: .. data:: False - The false value of the :class:`bool` type. Assignments to ``False`` + The false value of the :class:`bool` type. Assignments to ``False`` are illegal and raise a :exc:`SyntaxError`. .. data:: True - The true value of the :class:`bool` type. Assignments to ``True`` + The true value of the :class:`bool` type. Assignments to ``True`` are illegal and raise a :exc:`SyntaxError`. diff --git a/Doc/library/crypt.rst b/Doc/library/crypt.rst index 7e0cb9c..b6c3d21 100644 --- a/Doc/library/crypt.rst +++ b/Doc/library/crypt.rst @@ -51,7 +51,7 @@ A simple example illustrating typical use:: username = input('Python login:') cryptedpasswd = pwd.getpwnam(username)[1] if cryptedpasswd: - if cryptedpasswd == 'x' or cryptedpasswd == '*': + if cryptedpasswd == 'x' or cryptedpasswd == '*': raise "Sorry, currently no support for shadow passwords" cleartext = getpass.getpass() return crypt.crypt(cleartext, cryptedpasswd) == cryptedpasswd diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst index 7752ac7..8c4554a 100644 --- a/Doc/library/csv.rst +++ b/Doc/library/csv.rst @@ -82,7 +82,7 @@ The :mod:`csv` module defines the following functions: be split into lines in a manner which preserves the newline characters. A short usage example:: - + >>> import csv >>> spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|') >>> for row in spamReader: diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst index 9401b38..c37ceb9 100644 --- a/Doc/library/datetime.rst +++ b/Doc/library/datetime.rst @@ -264,10 +264,10 @@ efficient pickling, and in Boolean contexts, a :class:`timedelta` object is considered to be true if and only if it isn't equal to ``timedelta(0)``. Example usage: - + >>> from datetime import timedelta >>> year = timedelta(days=365) - >>> another_year = timedelta(weeks=40, days=84, hours=23, + >>> another_year = timedelta(weeks=40, days=84, hours=23, ... minutes=50, seconds=600) # adds up to 365 days >>> year == another_year True @@ -515,10 +515,10 @@ Example of counting days to an event:: True >>> my_birthday = date(today.year, 6, 24) >>> if my_birthday < today: - ... my_birthday = my_birthday.replace(year=today.year + 1) + ... my_birthday = my_birthday.replace(year=today.year + 1) >>> my_birthday datetime.date(2008, 6, 24) - >>> time_to_birthday = abs(my_birthday - today) + >>> time_to_birthday = abs(my_birthday - today) >>> time_to_birthday.days 202 @@ -1012,7 +1012,7 @@ Examples of working with datetime objects: >>> tt = dt.timetuple() >>> for it in tt: # doctest: +SKIP ... print(it) - ... + ... 2006 # year 11 # month 21 # day @@ -1041,23 +1041,23 @@ Using datetime with tzinfo: ... def __init__(self): # DST starts last Sunday in March ... d = datetime(dt.year, 4, 1) # ends last Sunday in October ... self.dston = d - timedelta(days=d.weekday() + 1) - ... d = datetime(dt.year, 11, 1) + ... d = datetime(dt.year, 11, 1) ... self.dstoff = d - timedelta(days=d.weekday() + 1) ... def utcoffset(self, dt): ... return timedelta(hours=1) + self.dst(dt) - ... def dst(self, dt): + ... def dst(self, dt): ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff: ... return timedelta(hours=1) ... else: ... return timedelta(0) ... def tzname(self,dt): ... return "GMT +1" - ... + ... >>> class GMT2(tzinfo): ... def __init__(self): - ... d = datetime(dt.year, 4, 1) + ... d = datetime(dt.year, 4, 1) ... self.dston = d - timedelta(days=d.weekday() + 1) - ... d = datetime(dt.year, 11, 1) + ... d = datetime(dt.year, 11, 1) ... self.dstoff = d - timedelta(days=d.weekday() + 1) ... def utcoffset(self, dt): ... return timedelta(hours=1) + self.dst(dt) @@ -1068,7 +1068,7 @@ Using datetime with tzinfo: ... return timedelta(0) ... def tzname(self,dt): ... return "GMT +2" - ... + ... >>> gmt1 = GMT1() >>> # Daylight Saving Time >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1) @@ -1089,7 +1089,7 @@ Using datetime with tzinfo: datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>) >>> dt2.utctimetuple() == dt3.utctimetuple() True - + .. _datetime-time: @@ -1237,12 +1237,12 @@ Instance methods: return ``None`` or a string object. Example: - + >>> from datetime import time, tzinfo >>> class GMT1(tzinfo): ... def utcoffset(self, dt): - ... return timedelta(hours=1) - ... def dst(self, dt): + ... return timedelta(hours=1) + ... def dst(self, dt): ... return timedelta(0) ... def tzname(self,dt): ... return "Europe/Prague" @@ -1473,7 +1473,7 @@ Applications that can't bear such ambiguities should avoid using hybrid :class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any other fixed-offset :class:`tzinfo` subclass (such as a class representing only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)). - + .. _strftime-behavior: @@ -1516,7 +1516,7 @@ For an aware object: The full set of format codes supported varies across platforms, because Python calls the platform C library's :func:`strftime` function, and platform -variations are common. +variations are common. The following is a list of all the format codes that the C standard (1989 version) requires, and these work on all platforms with a standard C diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst index 3d84f8c..350413f 100644 --- a/Doc/library/decimal.rst +++ b/Doc/library/decimal.rst @@ -323,7 +323,7 @@ Decimal objects infinity ::= 'Infinity' | 'Inf' nan ::= 'NaN' [digits] | 'sNaN' [digits] numeric-value ::= decimal-part [exponent-part] | infinity - numeric-string ::= [sign] numeric-value | [sign] nan + numeric-string ::= [sign] numeric-value | [sign] nan If *value* is a :class:`tuple`, it should have three components, a sign (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of @@ -875,7 +875,7 @@ In addition to the three supplied contexts, new contexts can be created with the * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer), * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or * :const:`ROUND_UP` (away from zero). - * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero + * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero) The *traps* and *flags* fields list any signals to be set. Generally, new @@ -1355,7 +1355,7 @@ condition. sqrt(-x) and x > 0 0 ** 0 x ** (non-integer) - x ** Infinity + x ** Infinity .. class:: Overflow @@ -1458,7 +1458,7 @@ expanding the precision sufficiently to avoid loss of significance: Decimal('9.51111111') >>> u + (v + w) Decimal('9.51111111') - >>> + >>> >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') >>> (u*v) + (u*w) Decimal('0.0060000') @@ -1597,7 +1597,7 @@ to work with the :class:`Decimal` class:: """ q = Decimal(10) ** -places # 2 places --> '0.01' - sign, digits, exp = value.quantize(q).as_tuple() + sign, digits, exp = value.quantize(q).as_tuple() result = [] digits = list(map(str, digits)) build, next = result.append, digits.pop @@ -1654,12 +1654,12 @@ to work with the :class:`Decimal` class:: getcontext().prec += 2 i, lasts, s, fact, num = 0, 0, 1, 1, 1 while s != lasts: - lasts = s + lasts = s i += 1 fact *= i - num *= x - s += num / fact - getcontext().prec -= 2 + num *= x + s += num / fact + getcontext().prec -= 2 return +s def cos(x): @@ -1676,13 +1676,13 @@ to work with the :class:`Decimal` class:: getcontext().prec += 2 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 while s != lasts: - lasts = s + lasts = s i += 2 fact *= i * (i-1) num *= x * x sign *= -1 - s += num / fact * sign - getcontext().prec -= 2 + s += num / fact * sign + getcontext().prec -= 2 return +s def sin(x): @@ -1699,13 +1699,13 @@ to work with the :class:`Decimal` class:: getcontext().prec += 2 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1 while s != lasts: - lasts = s + lasts = s i += 2 fact *= i * (i-1) num *= x * x sign *= -1 - s += num / fact * sign - getcontext().prec -= 2 + s += num / fact * sign + getcontext().prec -= 2 return +s @@ -1739,7 +1739,7 @@ the :const:`Inexact` trap is set, it is also useful for validation: >>> Decimal('3.214').quantize(TWOPLACES) Decimal('3.21') - >>> # Validate that a number does not exceed two places + >>> # Validate that a number does not exceed two places >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact])) Decimal('3.21') diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst index 39d37df..7dc8a3c 100644 --- a/Doc/library/dis.rst +++ b/Doc/library/dis.rst @@ -79,8 +79,8 @@ The :mod:`dis` module defines the following functions and constants: Detect all offsets in the code object *code* which are jump targets, and return a list of these offsets. - - + + .. data:: opname Sequence of operation names, indexable using the bytecode. @@ -502,7 +502,7 @@ the more significant byte last. The low byte of *counts* is the number of values before the list value, the high byte of *counts* the number of values after it. The resulting values are put onto the stack right-to-left. - + .. opcode:: DUP_TOPX (count) @@ -701,7 +701,7 @@ the more significant byte last. opcode finds the keyword parameters first. For each keyword argument, the value is on top of the key. Below the keyword parameters, the positional parameters are on the stack, with the right-most parameter on top. Below the parameters, - the function object to call is on the stack. Pops all function arguments, and + the function object to call is on the stack. Pops all function arguments, and the function itself off the stack, and pushes the return value. diff --git a/Doc/library/email.mime.rst b/Doc/library/email.mime.rst index b0d2adc..83f4228 100644 --- a/Doc/library/email.mime.rst +++ b/Doc/library/email.mime.rst @@ -2,7 +2,7 @@ ---------------------------------------------------------- .. module:: email.mime - :synopsis: Build MIME messages. + :synopsis: Build MIME messages. Ordinarily, you get a message object structure by passing a file or some text to diff --git a/Doc/library/fileinput.rst b/Doc/library/fileinput.rst index 8e70380..889fdff 100644 --- a/Doc/library/fileinput.rst +++ b/Doc/library/fileinput.rst @@ -145,7 +145,7 @@ it is deleted when the output file is closed. In-place filtering is disabled when standard input is read. .. warning:: - + The current implementation does not work for MS-DOS 8+3 filesystems. diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index 877d9b6..744a99f 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -95,7 +95,7 @@ are always available. They are listed here in alphabetical order. the range ``0 <= x < 256``. :class:`bytes` is an immutable version of :class:`bytearray` -- it has the same non-mutating methods and the same indexing and slicing behavior. - + Accordingly, constructor arguments are interpreted as for :func:`buffer`. Bytes objects can also be created with literals, see :ref:`strings`. @@ -271,7 +271,7 @@ are always available. They are listed here in alphabetical order. Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed - operand types, the rules for binary arithmetic operators apply. For integers, + operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as ``(a // b, a % b)``. For floating point numbers the result is ``(q, a % b)``, where *q* is usually ``math.floor(a / b)`` but may be 1 less than that. In any case ``q * b + a % b`` is very close to @@ -411,12 +411,12 @@ are always available. They are listed here in alphabetical order. .. index:: pair: str; format single: __format__ - + Convert a string or a number to a "formatted" representation, as controlled by *format_spec*. The interpretation of *format_spec* will depend on the type of the *value* argument, however there is a standard formatting syntax that is used by most built-in types: :ref:`formatspec`. - + .. note:: ``format(value, format_spec)`` merely calls ``value.__format__(format_spec)``. @@ -573,7 +573,7 @@ are always available. They are listed here in alphabetical order. returns ``['a', 'b', 'c']`` and ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``. If no argument is given, returns a new empty list, ``[]``. - :class:`list` is a mutable sequence type, as documented in :ref:`typesseq`. + :class:`list` is a mutable sequence type, as documented in :ref:`typesseq`. .. function:: locals() @@ -654,7 +654,7 @@ are always available. They are listed here in alphabetical order. .. function:: open(file[, mode='r'[, buffering=None[, encoding=None[, errors=None[, newline=None[, closefd=True]]]]]]) Open a file. If the file cannot be opened, :exc:`IOError` is raised. - + *file* is either a string or bytes object giving the name (and the path if the file isn't in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor @@ -699,7 +699,7 @@ are always available. They are listed here in alphabetical order. *buffering* is an optional integer used to set the buffering policy. By default full buffering is on. Pass 0 to switch buffering off (only allowed in binary mode), 1 to set line buffering, and an integer > 1 for full buffering. - + *encoding* is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the @@ -991,7 +991,7 @@ are always available. They are listed here in alphabetical order. .. function:: str([object[, encoding[, errors]]]) Return a string version of an object, using one of the following modes: - + If *encoding* and/or *errors* are given, :func:`str` will decode the *object* which can either be a byte string or a character buffer using the codec for *encoding*. The *encoding* parameter is a string giving @@ -1002,7 +1002,7 @@ are always available. They are listed here in alphabetical order. errors, while a value of ``'ignore'`` causes errors to be silently ignored, and a value of ``'replace'`` causes the official Unicode replacement character, U+FFFD, to be used to replace input characters which cannot be decoded. - See also the :mod:`codecs` module. + See also the :mod:`codecs` module. When only *object* is given, this returns its nicely printable representation. For strings, this is the string itself. The difference with ``repr(object)`` @@ -1042,10 +1042,10 @@ are always available. They are listed here in alphabetical order. single inheritance, :func:`super` can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of "super" in other programming languages. - + The second use case is to support cooperative multiple inheritence in a - dynamic execution environment. This use case is unique to Python and is - not found in statically compiled languages or languages that only support + dynamic execution environment. This use case is unique to Python and is + not found in statically compiled languages or languages that only support single inheritance. This makes in possible to implement "diamond diagrams" where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the @@ -1080,7 +1080,7 @@ are always available. They are listed here in alphabetical order. 3])`` returns ``(1, 2, 3)``. If no argument is given, returns a new empty tuple, ``()``. - :class:`tuple` is an immutable sequence type, as documented in :ref:`typesseq`. + :class:`tuple` is an immutable sequence type, as documented in :ref:`typesseq`. .. function:: type(object) @@ -1110,7 +1110,7 @@ are always available. They are listed here in alphabetical order. >>> class X(object): ... a = 1 - ... + ... >>> X = type('X', (object,), dict(a=1)) @@ -1125,12 +1125,12 @@ are always available. They are listed here in alphabetical order. .. function:: zip(*iterables) - Make an iterator that aggregates elements from each of the iterables. + Make an iterator that aggregates elements from each of the iterables. Returns an iterator of tuples, where the *i*-th tuple contains the *i*-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single - iterable argument, it returns an iterator of 1-tuples. With no arguments, + iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:: def zip(*iterables): @@ -1199,7 +1199,7 @@ are always available. They are listed here in alphabetical order. For example, the statement ``import spam`` results in bytecode resembling the following code:: - + spam = __import__('spam', globals(), locals(), [], -1) The statement ``import spam.ham`` results in this call:: diff --git a/Doc/library/gettext.rst b/Doc/library/gettext.rst index 458eec0..cd229e7 100644 --- a/Doc/library/gettext.rst +++ b/Doc/library/gettext.rst @@ -369,7 +369,7 @@ The following methods are overridden from the base class implementation: If the message id is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback's :meth:`ngettext` method. Otherwise, when *n* is 1 *singular* is returned, and *plural* is returned in all other cases. - + Here is an example:: n = len(os.listdir('.')) diff --git a/Doc/library/heapq.rst b/Doc/library/heapq.rst index 5138c83..4a18e02 100644 --- a/Doc/library/heapq.rst +++ b/Doc/library/heapq.rst @@ -100,7 +100,7 @@ Using a heap to insert items at the correct place in a priority queue: H N - + The module also offers three general purpose functions based on heaps. diff --git a/Doc/library/idle.rst b/Doc/library/idle.rst index 65101fc..413750f 100644 --- a/Doc/library/idle.rst +++ b/Doc/library/idle.rst @@ -230,7 +230,7 @@ Python syntax colors: Keywords orange - Strings + Strings green Comments diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst index 3752bf1..253c303 100644 --- a/Doc/library/inspect.rst +++ b/Doc/library/inspect.rst @@ -384,7 +384,7 @@ Classes and functions .. function:: getargspec(func) - Get the names and default values of a function's arguments. A + Get the names and default values of a function's arguments. A :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is returned. *args* is a list of the argument names. *varargs* and *varkw* are the names of the ``*`` and @@ -416,7 +416,7 @@ Classes and functions .. function:: getargvalues(frame) - Get information about arguments passed into a particular frame. A :term:`named tuple` + Get information about arguments passed into a particular frame. A :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is returned. *args* is a list of the argument names (it may contain nested lists). *varargs* and *varkw* are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the locals @@ -484,7 +484,7 @@ line. .. function:: getframeinfo(frame[, context]) - Get information about a frame or traceback object. A :term:`named tuple` + Get information about a frame or traceback object. A :term:`named tuple` ``Traceback(filename, lineno, function, code_context, index)`` is returned. diff --git a/Doc/library/io.rst b/Doc/library/io.rst index 14f7506..3b699cc 100644 --- a/Doc/library/io.rst +++ b/Doc/library/io.rst @@ -214,7 +214,7 @@ I/O Base Classes .. method:: close() Flush and close this stream. This method has no effect if the file is - already closed. Once the file is closed, any operation on the file + already closed. Once the file is closed, any operation on the file (e.g. reading or writing) will raise an :exc:`IOError`. The internal file descriptor isn't closed if *closefd* was False. @@ -628,7 +628,7 @@ Text I/O .. attribute:: line_buffering Whether line buffering is enabled. - + .. class:: StringIO([initial_value[, encoding[, errors[, newline]]]]) @@ -659,7 +659,7 @@ Text I/O # 'First line.\nSecond line.\n' contents = output.getvalue() - # Close object and discard memory buffer -- + # Close object and discard memory buffer -- # .getvalue() will now raise an exception. output.close() diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 2b27647..96515111 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -74,7 +74,7 @@ loops that truncate the stream. .. function:: itertools.chain.from_iterable(iterable) - Alternate constructor for :func:`chain`. Gets chained inputs from a + Alternate constructor for :func:`chain`. Gets chained inputs from a single iterable argument that is evaluated lazily. Equivalent to:: @classmethod @@ -89,9 +89,9 @@ loops that truncate the stream. Return *r* length subsequences of elements from the input *iterable*. - Combinations are emitted in lexicographic sort order. So, if the + Combinations are emitted in lexicographic sort order. So, if the input *iterable* is sorted, the combination tuples will be produced - in sorted order. + in sorted order. Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat @@ -306,12 +306,12 @@ loops that truncate the stream. Return successive *r* length permutations of elements in the *iterable*. If *r* is not specified or is ``None``, then *r* defaults to the length - of the *iterable* and all possible full-length permutations + of the *iterable* and all possible full-length permutations are generated. - Permutations are emitted in lexicographic sort order. So, if the + Permutations are emitted in lexicographic sort order. So, if the input *iterable* is sorted, the permutation tuples will be produced - in sorted order. + in sorted order. Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat @@ -342,7 +342,7 @@ loops that truncate the stream. else: return - The code for :func:`permutations` can be also expressed as a subsequence of + The code for :func:`permutations` can be also expressed as a subsequence of :func:`product`, filtered to exclude entries with repeated elements (those from the same position in the input pool):: @@ -483,7 +483,7 @@ can be combined. >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]): ... print(map(operator.itemgetter(1), g)) - ... + ... [1] [4, 5, 6] [10] @@ -610,7 +610,7 @@ which incur interpreter overhead. def unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D - # unique_everseen('ABBCcAD', str.lower) --> A B C D + # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: diff --git a/Doc/library/json.rst b/Doc/library/json.rst index cad841e..69d4c10 100644 --- a/Doc/library/json.rst +++ b/Doc/library/json.rst @@ -13,7 +13,7 @@ syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`marshal` and :mod:`pickle` modules. Encoding basic Python object hierarchies:: - + >>> import json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' @@ -42,12 +42,12 @@ Pretty printing:: >>> import json >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)) { - "4": 5, + "4": 5, "6": 7 } Decoding JSON:: - + >>> import json >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') ['foo', {'bar': ['baz', None, 1.0, 2]}] @@ -74,7 +74,7 @@ Specializing JSON object decoding:: Decimal('1.1') Extending :class:`JSONEncoder`:: - + >>> import json >>> class ComplexEncoder(json.JSONEncoder): ... def default(self, obj): @@ -88,12 +88,12 @@ Extending :class:`JSONEncoder`:: '[2.0, 1.0]' >>> list(ComplexEncoder().iterencode(2 + 1j)) ['[', '2.0', ', ', '1.0', ']'] - + .. highlight:: none Using json.tool from the shell to validate and pretty-print:: - + $ echo '{"json":"obj"}' | python -mjson.tool { "json": "obj" @@ -103,7 +103,7 @@ Using json.tool from the shell to validate and pretty-print:: .. highlight:: python -.. note:: +.. note:: The JSON produced by this module's default settings is a subset of YAML, so it may be used as a serializer for that as well. @@ -367,7 +367,7 @@ Encoders and decoders For example, to support arbitrary iterators, you could implement default like this:: - + def default(self, o): try: iterable = iter(o) @@ -391,6 +391,6 @@ Encoders and decoders Encode the given object, *o*, and yield each string representation as available. For example:: - + for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) diff --git a/Doc/library/locale.rst b/Doc/library/locale.rst index 3dfa666..381107e 100644 --- a/Doc/library/locale.rst +++ b/Doc/library/locale.rst @@ -474,7 +474,7 @@ Example:: >>> import locale >>> loc = locale.getlocale() # get current locale >>> locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform - >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut + >>> 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 >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale diff --git a/Doc/library/mailbox.rst b/Doc/library/mailbox.rst index 9cea071..1532c90 100644 --- a/Doc/library/mailbox.rst +++ b/Doc/library/mailbox.rst @@ -1553,7 +1553,7 @@ due to malformed messages in the mailbox:: # that's better than losing a message completely. box.lock() box.add(message) - box.flush() + box.flush() box.unlock() # Remove original message diff --git a/Doc/library/math.rst b/Doc/library/math.rst index 1e9611e..f171ec1 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -98,7 +98,7 @@ Number-theoretic and representation functions .. function:: isnan(x) Checks if the float *x* is a NaN (not a number). NaNs are part of the - IEEE 754 standards. Operation like but not limited to ``inf * 0``, + IEEE 754 standards. Operation like but not limited to ``inf * 0``, ``inf / inf`` or any operation involving a NaN, e.g. ``nan * 1``, return a NaN. diff --git a/Doc/library/mmap.rst b/Doc/library/mmap.rst index 4828935..e85a964 100644 --- a/Doc/library/mmap.rst +++ b/Doc/library/mmap.rst @@ -87,7 +87,7 @@ To map anonymous memory, -1 should be passed as the fileno along with the length will be relative to the offset from the beginning of the file. *offset* defaults to 0. *offset* must be a multiple of the PAGESIZE or ALLOCATIONGRANULARITY. - + This example shows a simple way of using :class:`mmap`:: import mmap diff --git a/Doc/library/msvcrt.rst b/Doc/library/msvcrt.rst index 8a0452f..9be792d 100644 --- a/Doc/library/msvcrt.rst +++ b/Doc/library/msvcrt.rst @@ -18,7 +18,7 @@ documentation. The module implements both the normal and wide char variants of the console I/O api. The normal API deals only with ASCII characters and is of limited use -for internationalized applications. The wide char API should be used where +for internationalized applications. The wide char API should be used where ever possible .. _msvcrt-files: @@ -98,11 +98,11 @@ Console I/O return the keycode. The :kbd:`Control-C` keypress cannot be read with this function. - + .. function:: getwch() Wide char variant of :func:`getch`, returning a Unicode value. - + .. function:: getche() @@ -113,28 +113,28 @@ Console I/O .. function:: getwche() Wide char variant of :func:`getche`, returning a Unicode value. - + .. function:: putch(char) Print the character *char* to the console without buffering. - + .. function:: putwch(unicode_char) Wide char variant of :func:`putch`, accepting a Unicode value. - + .. function:: ungetch(char) Cause the character *char* to be "pushed back" into the console buffer; it will be the next character read by :func:`getch` or :func:`getche`. - + .. function:: ungetwch(unicode_char) Wide char variant of :func:`ungetch`, accepting a Unicode value. - + .. _msvcrt-other: diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst index c2581c6..7e44423 100644 --- a/Doc/library/multiprocessing.rst +++ b/Doc/library/multiprocessing.rst @@ -19,9 +19,9 @@ Windows. .. warning:: Some of this package's functionality requires a functioning shared semaphore - implementation on the host operating system. Without one, the - :mod:`multiprocessing.synchronize` module will be disabled, and attempts to - import it will result in an :exc:`ImportError`. See + implementation on the host operating system. Without one, the + :mod:`multiprocessing.synchronize` module will be disabled, and attempts to + import it will result in an :exc:`ImportError`. See :issue:`3770` for additional information. .. note:: @@ -36,7 +36,7 @@ Windows. >>> p = Pool(5) >>> def f(x): ... return x*x - ... + ... >>> p.map(f, [1,2,3]) Process PoolWorker-1: Process PoolWorker-2: @@ -75,11 +75,11 @@ To show the individual process IDs involved, here is an expanded example:: print 'module name:', __name__ print 'parent process:', os.getppid() print 'process id:', os.getpid() - + def f(name): info('function f') print 'hello', name - + if __name__ == '__main__': info('main line') p = Process(target=f, args=('bob',)) @@ -541,7 +541,7 @@ For an example of the usage of queues for interprocess communication see .. method:: put(item[, block[, timeout]]) - Put item into the queue. If the optional argument *block* is ``True`` + Put item into the queue. If the optional argument *block* is ``True`` (the default) and *timeout* is ``None`` (the default), block if necessary until a free slot is available. If *timeout* is a positive number, it blocks at most *timeout* seconds and raises the :exc:`queue.Full` exception if no @@ -856,7 +856,7 @@ object -- see :ref:`multiprocessing-managers`. acceptable. If *block* is ``True`` and *timeout* is not ``None`` then it specifies a timeout in seconds. If *block* is ``False`` then *timeout* is ignored. - + Note that on OS/X ``sem_timedwait`` is unsupported, so timeout arguments for these will be ignored. @@ -1133,22 +1133,22 @@ their parent process exits. The manager classes are defined in the server process which is using the given address and authentication key. .. method:: get_server() - + Returns a :class:`Server` object which represents the actual server under - the control of the Manager. The :class:`Server` object supports the + the control of the Manager. The :class:`Server` object supports the :meth:`serve_forever` method:: - + >>> from multiprocessing.managers import BaseManager >>> m = BaseManager(address=('', 50000), authkey='abc')) >>> server = m.get_server() >>> s.serve_forever() - + :class:`Server` additionally have an :attr:`address` attribute. .. method:: connect() - + Connect a local manager object to a remote manager process:: - + >>> from multiprocessing.managers import BaseManager >>> m = BaseManager(address='127.0.0.1', authkey='abc)) >>> m.connect() @@ -1358,7 +1358,7 @@ Another client can also use it:: >>> queue.get() 'hello' -Local processes can also access that queue, using the code from above on the +Local processes can also access that queue, using the code from above on the client to access it remotely:: >>> from multiprocessing import Process, Queue @@ -1369,12 +1369,12 @@ client to access it remotely:: ... super(Worker, self).__init__() ... def run(self): ... self.q.put('local hello') - ... + ... >>> queue = Queue() >>> w = Worker(queue) >>> w.start() >>> class QueueManager(BaseManager): pass - ... + ... >>> QueueManager.register('get_queue', callable=lambda: queue) >>> m = QueueManager(address=('', 50000), authkey='abracadabra') >>> s = m.get_server() @@ -2118,7 +2118,7 @@ Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`: .. literalinclude:: ../includes/mp_benchmarks.py An example/demo of how to use the :class:`managers.SyncManager`, :class:`Process` -and others to build a system which can distribute processes and work via a +and others to build a system which can distribute processes and work via a distributed queue to a "cluster" of machines on a network, accessible via SSH. You will need to have private key authentication for all hosts configured for this to work. diff --git a/Doc/library/nntplib.rst b/Doc/library/nntplib.rst index 761190d..d8d9b0d 100644 --- a/Doc/library/nntplib.rst +++ b/Doc/library/nntplib.rst @@ -24,16 +24,16 @@ about a newsgroup and print the subjects of the last 10 articles:: Group comp.lang.python has 59 articles, range 3742 to 3803 >>> resp, subs = s.xhdr('subject', first + '-' + last) >>> for id, sub in subs[-10:]: print(id, sub) - ... + ... 3792 Re: Removing elements from a list while iterating... 3793 Re: Who likes Info files? 3794 Emacs and doc strings 3795 a few questions about the Mac implementation 3796 Re: executable python scripts 3797 Re: executable python scripts - 3798 Re: a few questions about the Mac implementation + 3798 Re: a few questions about the Mac implementation 3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules - 3802 Re: executable python scripts + 3802 Re: executable python scripts 3803 Re: \POSIX{} wait and SIGCHLD >>> s.quit() '205 news.cwi.nl closing connection. Goodbye.' diff --git a/Doc/library/operator.rst b/Doc/library/operator.rst index a67c6d8..d1d1c16 100644 --- a/Doc/library/operator.rst +++ b/Doc/library/operator.rst @@ -7,7 +7,7 @@ .. testsetup:: - + import operator from operator import itemgetter @@ -209,7 +209,7 @@ Operations which work with sequences include: Remove the value of *a* at index *b*. - + .. function:: getitem(a, b) __getitem__(a, b) @@ -337,7 +337,7 @@ objects. >>> class C: ... pass - ... + ... >>> import operator >>> obj = C() >>> operator.isMappingType(obj) @@ -427,9 +427,9 @@ expect a function argument. def g(obj): return tuple(obj[item] for item in items) return g - - The items can be any type accepted by the operand's :meth:`__getitem__` - method. Dictionaries accept any hashable value. Lists, tuples, and + + The items can be any type accepted by the operand's :meth:`__getitem__` + method. Dictionaries accept any hashable value. Lists, tuples, and strings accept an index or a slice: >>> itemgetter(1)('ABCDEFG') diff --git a/Doc/library/optparse.rst b/Doc/library/optparse.rst index 7989d33..3805d96 100644 --- a/Doc/library/optparse.rst +++ b/Doc/library/optparse.rst @@ -794,7 +794,7 @@ And to define an option with only a long option string:: The keyword arguments define attributes of the new Option object. The most important option attribute is :attr:`action`, and it largely determines which other attributes are relevant or required. If you pass irrelevant option -attributes, or fail to pass required ones, :mod:`optparse` raises an +attributes, or fail to pass required ones, :mod:`optparse` raises an :exc:`OptionError` exception explaining your mistake. An option's *action* determines what :mod:`optparse` does when it encounters diff --git a/Doc/library/os.rst b/Doc/library/os.rst index 1c69e25..ef5beaa 100644 --- a/Doc/library/os.rst +++ b/Doc/library/os.rst @@ -1226,7 +1226,7 @@ to be ignored. These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as - :exc:`OSError` exceptions. + :exc:`OSError` exceptions. The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered @@ -1258,7 +1258,7 @@ to be ignored. used to define the environment variables for the new process (these are used instead of the current process' environment); the functions :func:`execl`, :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to - inherit the environment of the current process. + inherit the environment of the current process. Availability: Unix, Windows. @@ -1456,7 +1456,7 @@ written in Python, such as a mail server's external command delivery program. (Note that the :mod:`subprocess` module provides more powerful facilities for spawning new processes and retrieving their results; using that module is - preferable to using these functions. Check specially the *Replacing Older + preferable to using these functions. Check specially the *Replacing Older Functions with the subprocess Module* section in that documentation page.) If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new diff --git a/Doc/library/ossaudiodev.rst b/Doc/library/ossaudiodev.rst index e23b049..3ed3fb8 100644 --- a/Doc/library/ossaudiodev.rst +++ b/Doc/library/ossaudiodev.rst @@ -16,26 +16,26 @@ the standard audio interface for Linux and recent versions of FreeBSD. use ALSA, you'll have to make sure its OSS compatibility layer is active to use ossaudiodev, but you're gonna need it for the vast majority of Linux audio apps anyways. - + Sounds like things are also complicated for other BSDs. In response to my python-dev query, Thomas Wouters said: - + > Likewise, googling shows OpenBSD also uses OSS/Free -- the commercial > OSS installation manual tells you to remove references to OSS/Free from the > kernel :) - + but Aleksander Piotrowsk actually has an OpenBSD box, and he quotes from its <soundcard.h>: > * WARNING! WARNING! > * This is an OSS (Linux) audio emulator. > * Use the Native NetBSD API for developing new code, and this > * only for compiling Linux programs. - + There's also an ossaudio manpage on OpenBSD that explains things further. Presumably NetBSD and OpenBSD have a different standard audio interface. That's the great thing about standards, there are so many to choose from ... ;-) - + This probably all warrants a footnote or two, but I don't understand things well enough right now to write it! --GPW diff --git a/Doc/library/othergui.rst b/Doc/library/othergui.rst index d2fad3e..471076c 100644 --- a/Doc/library/othergui.rst +++ b/Doc/library/othergui.rst @@ -70,7 +70,7 @@ also available for Python: Robin Dunn. PyGTK, PyQt, and wxPython, all have a modern look and feel and more -widgets than Tkinter. In addition, there are many other GUI toolkits for +widgets than Tkinter. In addition, there are many other GUI toolkits for Python, both cross-platform, and platform-specific. See the `GUI Programming <http://wiki.python.org/moin/GuiProgramming>`_ page in the Python Wiki for a much more complete list, and also for links to documents where the diff --git a/Doc/library/pdb.rst b/Doc/library/pdb.rst index 2537983..c7b34ab 100644 --- a/Doc/library/pdb.rst +++ b/Doc/library/pdb.rst @@ -37,7 +37,7 @@ of the debugger is:: (Pdb) continue NameError: 'spam' > <string>(1)?() - (Pdb) + (Pdb) :file:`pdb.py` can also be invoked as a script to debug other scripts. For example:: @@ -65,7 +65,7 @@ Typical usage to inspect a crashed program is:: >>> pdb.pm() > ./mymodule.py(3)test2() -> print(spam) - (Pdb) + (Pdb) The module defines the following functions; each enters the debugger in a slightly different way: @@ -105,7 +105,7 @@ slightly different way: .. function:: post_mortem([traceback]) - Enter post-mortem debugging of the given *traceback* object. If no + Enter post-mortem debugging of the given *traceback* object. If no *traceback* is given, it uses the one of the exception that is currently being handled (an exception must be being handled if the default is to be used). diff --git a/Doc/library/pickle.rst b/Doc/library/pickle.rst index b54de90..f326843 100644 --- a/Doc/library/pickle.rst +++ b/Doc/library/pickle.rst @@ -478,7 +478,7 @@ As we shall see, pickle does not use directly the methods described above. In fact, these methods are part of the copy protocol which implements the :meth:`__reduce__` special method. The copy protocol provides a unified interface for retrieving the data necessary for pickling and copying -objects. [#]_ +objects. [#]_ Although powerful, implementing :meth:`__reduce__` directly in your classes is error prone. For this reason, class designers should use the high-level @@ -715,7 +715,7 @@ A sample usage of our unpickler working has intended:: .. XXX Add note about how extension codes could evade our protection - mechanism (e.g. cached classes do not invokes find_class()). + mechanism (e.g. cached classes do not invokes find_class()). As our examples shows, you have to be careful with what you allow to be unpickled. Therefore if security is a concern, you may want to consider diff --git a/Doc/library/profile.rst b/Doc/library/profile.rst index 1bf1501..132365a 100644 --- a/Doc/library/profile.rst +++ b/Doc/library/profile.rst @@ -51,15 +51,15 @@ examine the results of a profile operation. The Python standard library provides two different profilers: -#. :mod:`cProfile` is recommended for most users; it's a C extension +#. :mod:`cProfile` is recommended for most users; it's a C extension with reasonable overhead - that makes it suitable for profiling long-running programs. + that makes it suitable for profiling long-running programs. Based on :mod:`lsprof`, - contributed by Brett Rosen and Ted Czotter. + contributed by Brett Rosen and Ted Czotter. #. :mod:`profile`, a pure Python module whose interface is imitated by - :mod:`cProfile`. Adds significant overhead to profiled programs. - If you're trying to extend + :mod:`cProfile`. Adds significant overhead to profiled programs. + If you're trying to extend the profiler in some way, the task might be easier with this module. Copyright © 1994, by InfoSeek Corporation. @@ -260,24 +260,24 @@ reading the source code for these modules. that the text string in the far right column was used to sort the output. The column headings include: - ncalls + ncalls for the number of calls, - tottime + tottime for the total time spent in the given function (and excluding time made in calls to sub-functions), - percall + percall is the quotient of ``tottime`` divided by ``ncalls`` - cumtime + cumtime is the total time spent in this and all subfunctions (from invocation till exit). This figure is accurate *even* for recursive functions. - percall + percall is the quotient of ``cumtime`` divided by primitive calls - filename:lineno(function) + filename:lineno(function) provides the respective data of each function When there are two numbers in the first column (for example, ``43/3``), then the diff --git a/Doc/library/pyexpat.rst b/Doc/library/pyexpat.rst index e819bd4..6fe60ad 100644 --- a/Doc/library/pyexpat.rst +++ b/Doc/library/pyexpat.rst @@ -177,9 +177,9 @@ XMLParser Objects .. attribute:: xmlparser.buffer_size - The size of the buffer used when :attr:`buffer_text` is true. - A new buffer size can be set by assigning a new integer value - to this attribute. + The size of the buffer used when :attr:`buffer_text` is true. + A new buffer size can be set by assigning a new integer value + to this attribute. When the size is changed, the buffer will be flushed. diff --git a/Doc/library/queue.rst b/Doc/library/queue.rst index fa09fc5..e90f276 100644 --- a/Doc/library/queue.rst +++ b/Doc/library/queue.rst @@ -68,7 +68,7 @@ Queue Objects ------------- Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`) -provide the public methods described below. +provide the public methods described below. .. method:: Queue.qsize() @@ -138,20 +138,20 @@ fully processed by daemon consumer threads. Example of how to wait for enqueued tasks to be completed:: - def worker(): - while True: - item = q.get() - do_work(item) - q.task_done() + def worker(): + while True: + item = q.get() + do_work(item) + q.task_done() - q = Queue() - for i in range(num_worker_threads): + q = Queue() + for i in range(num_worker_threads): t = Thread(target=worker) t.set_daemon(True) - t.start() + t.start() for item in source(): - q.put(item) + q.put(item) q.join() # block until all tasks are done diff --git a/Doc/library/re.rst b/Doc/library/re.rst index ce52185..f466614 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -221,7 +221,7 @@ The special characters are: ``'s'``, ``'u'``, ``'x'``.) The group matches the empty string; the letters set the corresponding flags: :const:`re.a` (ASCII-only matching), :const:`re.I` (ignore case), :const:`re.L` (locale dependent), - :const:`re.M` (multi-line), :const:`re.S` (dot matches all), + :const:`re.M` (multi-line), :const:`re.S` (dot matches all), and :const:`re.X` (verbose), for the entire regular expression. (The flags are described in :ref:`contents-of-module-re`.) This is useful if you wish to include the flags as part of the regular @@ -487,7 +487,7 @@ form. counterpart ``(?u)``), but these are redundant in Python 3.0 since matches are Unicode by default for strings (and Unicode matching isn't allowed for bytes). - + .. data:: I IGNORECASE @@ -1011,14 +1011,14 @@ method of :class:`MatchObject` in the following manner: >>> pair.match("717ak").group(1) '7' - + # Error because re.match() returns None, which doesn't have a group() method: >>> pair.match("718ak").group(1) Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> re.match(r".*(.).*\1", "718ak").group(1) AttributeError: 'NoneType' object has no attribute 'group' - + >>> pair.match("354aa").group(1) 'a' @@ -1127,7 +1127,7 @@ where the search is to start: Making a Phonebook ^^^^^^^^^^^^^^^^^^ -:func:`split` splits a string into a list delimited by the passed pattern. The +:func:`split` splits a string into a list delimited by the passed pattern. The method is invaluable for converting textual data into data structures that can be easily read and modified by Python as demonstrated in the following example that creates a phonebook. @@ -1136,7 +1136,7 @@ First, here is the input. Normally it may come from a file, here we are using triple-quoted string syntax: >>> input = """Ross McFluff: 834.345.1254 155 Elm Street - ... + ... ... Ronald Heathmore: 892.345.3428 436 Finley Avenue ... Frank Burger: 925.541.7625 662 South Dogwood Way ... diff --git a/Doc/library/rlcompleter.rst b/Doc/library/rlcompleter.rst index b09df54..293160a 100644 --- a/Doc/library/rlcompleter.rst +++ b/Doc/library/rlcompleter.rst @@ -61,6 +61,6 @@ Completer objects have the following method: If called for a dotted name, it will try to evaluate anything without obvious side-effects (functions will not be evaluated, but it can generate calls to :meth:`__getattr__`) up to the last part, and find matches for the rest via the - :func:`dir` function. Any exception raised during the evaluation of the + :func:`dir` function. Any exception raised during the evaluation of the expression is caught, silenced and :const:`None` is returned. diff --git a/Doc/library/sched.rst b/Doc/library/sched.rst index e0007fc..cab7f60 100644 --- a/Doc/library/sched.rst +++ b/Doc/library/sched.rst @@ -42,7 +42,7 @@ Example:: 930343700.276 In multi-threaded environments, the :class:`scheduler` class has limitations -with respect to thread-safety, inability to insert a new task before +with respect to thread-safety, inability to insert a new task before the one currently pending in a running scheduler, and holding up the main thread until the event queue is empty. Instead, the preferred approach is to use the :class:`threading.Timer` class instead. diff --git a/Doc/library/shutil.rst b/Doc/library/shutil.rst index b332d9a..7cf8550 100644 --- a/Doc/library/shutil.rst +++ b/Doc/library/shutil.rst @@ -20,7 +20,7 @@ copying and removal. For operations on individual files, see also the Even the higher-level file copying functions (:func:`copy`, :func:`copy2`) can't copy all file metadata. - + On POSIX platforms, this means that file owner and group are lost as well as ACLs. On Mac OS, the resource fork and other metadata are not used. This means that resources will be lost and file type and creator codes will diff --git a/Doc/library/signal.rst b/Doc/library/signal.rst index 5033e0e..2db17c5 100644 --- a/Doc/library/signal.rst +++ b/Doc/library/signal.rst @@ -39,12 +39,12 @@ rules for working with signals and their handlers: * Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform :func:`signal` operations in the main thread - of execution. Any thread can perform an :func:`alarm`, :func:`getsignal`, - :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread - can set a new signal handler, and the main thread will be the only one to - receive signals (this is enforced by the Python :mod:`signal` module, even - if the underlying thread implementation supports sending signals to - individual threads). This means that signals can't be used as a means of + of execution. Any thread can perform an :func:`alarm`, :func:`getsignal`, + :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread + can set a new signal handler, and the main thread will be the only one to + receive signals (this is enforced by the Python :mod:`signal` module, even + if the underlying thread implementation supports sending signals to + individual threads). This means that signals can't be used as a means of inter-thread communication. Use locks instead. The variables defined in the :mod:`signal` module are: @@ -80,22 +80,22 @@ The variables defined in the :mod:`signal` module are: One more than the number of the highest signal number. -.. data:: ITIMER_REAL +.. data:: ITIMER_REAL Decrements interval timer in real time, and delivers :const:`SIGALRM` upon expiration. -.. data:: ITIMER_VIRTUAL +.. data:: ITIMER_VIRTUAL - Decrements interval timer only when the process is executing, and delivers + Decrements interval timer only when the process is executing, and delivers SIGVTALRM upon expiration. .. data:: ITIMER_PROF - - Decrements interval timer both when the process executes and when the - system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, - this timer is usually used to profile the time spent by the application + + Decrements interval timer both when the process executes and when the + system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, + this timer is usually used to profile the time spent by the application in user and kernel space. SIGPROF is delivered upon expiration. @@ -105,7 +105,7 @@ The :mod:`signal` module defines one exception: Raised to signal an error from the underlying :func:`setitimer` or :func:`getitimer` implementation. Expect this error if an invalid - interval timer or a negative time is passed to :func:`setitimer`. + interval timer or a negative time is passed to :func:`setitimer`. This error is a subtype of :exc:`IOError`. @@ -143,21 +143,21 @@ The :mod:`signal` module defines the following functions: .. function:: setitimer(which, seconds[, interval]) - Sets given interval timer (one of :const:`signal.ITIMER_REAL`, + Sets given interval timer (one of :const:`signal.ITIMER_REAL`, :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified - by *which* to fire after *seconds* (float is accepted, different from + by *which* to fire after *seconds* (float is accepted, different from :func:`alarm`) and after that every *interval* seconds. The interval timer specified by *which* can be cleared by setting seconds to zero. When an interval timer fires, a signal is sent to the process. - The signal sent is dependent on the timer being used; - :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`, + The signal sent is dependent on the timer being used; + :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`, :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`, and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`. The old values are returned as a tuple: (delay, interval). - Attempting to pass an invalid interval timer will cause a + Attempting to pass an invalid interval timer will cause a :exc:`ItimerError`. @@ -186,7 +186,7 @@ The :mod:`signal` module defines the following functions: will be restarted when interrupted by signal *signalnum*, otherwise system calls will be interrupted. Returns nothing. Availability: Unix (see the man page :manpage:`siginterrupt(3)` for further information). - + Note that installing a signal handler with :func:`signal` will reset the restart behaviour to interruptible by implicitly calling :cfunc:`siginterrupt` with a true *flag* value for the given signal. @@ -233,7 +233,7 @@ be sent, and the handler raises an exception. :: signal.alarm(5) # This open() may hang indefinitely - fd = os.open('/dev/ttyS0', os.O_RDWR) + fd = os.open('/dev/ttyS0', os.O_RDWR) signal.alarm(0) # Disable the alarm diff --git a/Doc/library/smtplib.rst b/Doc/library/smtplib.rst index 74be645..21065b2 100644 --- a/Doc/library/smtplib.rst +++ b/Doc/library/smtplib.rst @@ -182,9 +182,9 @@ An :class:`SMTP` instance has the following methods: Identify yourself to an ESMTP server using ``EHLO``. The hostname argument defaults to the fully qualified domain name of the local host. Examine the - response for ESMTP option and store them for use by :meth:`has_extn`. - Also sets several informational attributes: the message returned by - the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp` + response for ESMTP option and store them for use by :meth:`has_extn`. + Also sets several informational attributes: the message returned by + the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp` is set to true or false depending on whether the server supports ESMTP, and :attr:`esmtp_features` will be a dictionary containing the names of the SMTP service extensions this server supports, and their diff --git a/Doc/library/socket.rst b/Doc/library/socket.rst index 536b3c5..c2e3d91 100644 --- a/Doc/library/socket.rst +++ b/Doc/library/socket.rst @@ -178,10 +178,10 @@ The module :mod:`socket` exports the following constants and functions: .. data:: SIO_* RCVALL_* - + Constants for Windows' WSAIoctl(). The constants are used as arguments to the :meth:`ioctl` method of socket objects. - + .. data:: TIPC_* @@ -210,7 +210,7 @@ The module :mod:`socket` exports the following constants and functions: all the necessary arguments for creating the corresponding socket. *host* is a domain name, a string representation of an IPv4/v6 address or ``None``. *port* is a string service name such as ``'http'``, a numeric port number or ``None``. - The rest of the arguments are optional and must be numeric if specified. + The rest of the arguments are optional and must be numeric if specified. By passing ``None`` as the value of *host* and *port*, , you can pass ``NULL`` to the C API. The :func:`getaddrinfo` function returns a list of 5-tuples with the following @@ -544,14 +544,14 @@ correspond to Unix system calls applicable to sockets. contents of the buffer (see the optional built-in module :mod:`struct` for a way to decode C structures encoded as byte strings). - + .. method:: socket.ioctl(control, option) - :platform: Windows - + :platform: Windows + The :meth:`ioctl` method is a limited interface to the WSAIoctl system interface. Please refer to the MSDN documentation for more information. - + .. method:: socket.listen(backlog) @@ -851,7 +851,7 @@ sends traffic to the first one connected successfully. :: s.close() print('Received', repr(data)) - + The last example shows how to write a very simple network sniffer with raw sockets on Windows. The example requires administrator privileges to modify the interface:: @@ -860,19 +860,19 @@ the interface:: # the public network interface HOST = socket.gethostbyname(socket.gethostname()) - + # create a raw socket and bind it to the public interface s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) s.bind((HOST, 0)) - + # Include IP headers s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) - + # receive all packages s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) - + # receive a package print(s.recvfrom(65565)) - + # disabled promiscuous mode s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst index 2dd29c1..c7c553f 100644 --- a/Doc/library/sqlite3.rst +++ b/Doc/library/sqlite3.rst @@ -541,8 +541,8 @@ Cursor Objects This read-only attribute provides the column names of the last query. To remain compatible with the Python DB API, it returns a 7-tuple for each - column where the last six items of each tuple are :const:`None`. - + column where the last six items of each tuple are :const:`None`. + It is set for ``SELECT`` statements without any matching rows as well. .. _sqlite3-row-objects: @@ -553,7 +553,7 @@ Row Objects .. class:: Row A :class:`Row` instance serves as a highly optimized - :attr:`~Connection.row_factory` for :class:`Connection` objects. + :attr:`~Connection.row_factory` for :class:`Connection` objects. It tries to mimic a tuple in most of its features. It supports mapping access by column name and index, iteration, @@ -561,7 +561,7 @@ Row Objects If two :class:`Row` objects have exactly the same columns and their members are equal, they compare equal. - + .. versionchanged:: 2.6 Added iteration and equality (hashability). @@ -780,7 +780,7 @@ Controlling Transactions ------------------------ By default, the :mod:`sqlite3` module opens transactions implicitly before a -Data Modification Language (DML) statement (i.e. +Data Modification Language (DML) statement (i.e. ``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions implicitly before a non-DML, non-query statement (i. e. anything other than ``SELECT`` or the aforementioned). diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst index 8e1c6b0..10c33f9 100644 --- a/Doc/library/ssl.rst +++ b/Doc/library/ssl.rst @@ -45,7 +45,7 @@ Functions, Constants, and Exceptions .. exception:: SSLError - Raised to signal an error from the underlying SSL implementation. This + Raised to signal an error from the underlying SSL implementation. This signifies some problem in the higher-level encryption and authentication layer that's superimposed on the underlying network connection. This error is a subtype of :exc:`socket.error`, which @@ -170,7 +170,7 @@ Functions, Constants, and Exceptions >>> import time >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")) 'Wed May 9 00:00:00 2007' - >>> + >>> .. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None) @@ -397,7 +397,7 @@ 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, +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 @@ -433,13 +433,13 @@ 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 +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 +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:: @@ -581,7 +581,7 @@ Then you'd read data from the ``connstream`` and do something with it till you a And go back to listening for new client connections. - + .. seealso:: Class :class:`socket.socket` diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index e8d8ba6..fb3a50d 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -172,7 +172,7 @@ notion of comparison where any two objects of that type are unequal. The ``<``, any operand is a complex number, the objects are of different types that cannot be compared, or other cases where there is no defined ordering. -.. index:: +.. index:: single: __eq__() (instance method) single: __ne__() (instance method) single: __lt__() (instance method) @@ -330,14 +330,14 @@ Notes: for well-defined conversions. (4) - float also accepts the strings "nan" and "inf" with an optional prefix "+" + float also accepts the strings "nan" and "inf" with an optional prefix "+" or "-" for Not a Number (NaN) and positive or negative infinity. (5) Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for programming languages. - + All :class:`numbers.Real` types (:class:`int` and :class:`float`) also include the following operations: @@ -460,7 +460,7 @@ The float type has some additional methods. original float and with a positive denominator. Raises :exc:`OverflowError` on infinities and a :exc:`ValueError` on NaNs. - + .. versionadded:: 2.6 Two methods support conversion to @@ -875,7 +875,7 @@ functions based on regular expressions. otherwise. Decimal characters include digit characters, and all characters that that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. - + .. method:: str.isdigit() @@ -903,7 +903,7 @@ functions based on regular expressions. that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. - + .. method:: str.isprintable() Return true if all characters in the string are printable or the string is @@ -1474,7 +1474,7 @@ Notes: example, sort by department, then by salary grade). While a list is being sorted, the effect of attempting to mutate, or even - inspect, the list is undefined. The C implementation + inspect, the list is undefined. The C implementation makes the list appear empty for the duration, and raises :exc:`ValueError` if it can detect that the list has been mutated during a sort. @@ -1525,7 +1525,7 @@ The bytes and bytearray types have an additional class method: b'\xf0\xf1\xf2' The translate method differs in semantics from the version available on strings: - + .. method:: bytes.translate(table[, delete]) Return a copy of the bytes or bytearray object where all bytes occurring in @@ -1807,7 +1807,7 @@ pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is not in the map. - + If a subclass of dict defines a method :meth:`__missing__`, if the key *key* is not present, the ``d[key]`` operation calls that method with the key *key* as argument. The ``d[key]`` operation then returns or raises whatever is @@ -2149,7 +2149,7 @@ Files have the following methods: positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end). There is no return value. - + For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last. diff --git a/Doc/library/string.rst b/Doc/library/string.rst index 37704b0..98c7051 100644 --- a/Doc/library/string.rst +++ b/Doc/library/string.rst @@ -98,7 +98,7 @@ implementation as the built-in :meth:`format` method. :meth:`format` is just a wrapper that calls :meth:`vformat`. .. method:: vformat(format_string, args, kwargs) - + This function does the actual work of formatting. It is exposed as a separate function for cases where you want to pass in a predefined dictionary of arguments, rather than unpacking and repacking the @@ -111,12 +111,12 @@ implementation as the built-in :meth:`format` method. intended to be replaced by subclasses: .. method:: parse(format_string) - + Loop over the format_string and return an iterable of tuples (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used by :meth:`vformat` to break the string in to either literal text, or replacement fields. - + The values in the tuple conceptually represent a span of literal text followed by a single replacement field. If there is no literal text (which can happen if two replacement fields occur consecutively), then @@ -134,7 +134,7 @@ implementation as the built-in :meth:`format` method. *key* parameter to :meth:`get_value`. .. method:: get_value(key, args, kwargs) - + Retrieve a given field value. The *key* argument will be either an integer or a string. If it is an integer, it represents the index of the positional argument in *args*; if it is a string, then it represents a @@ -172,7 +172,7 @@ implementation as the built-in :meth:`format` method. method is provided so that subclasses can override it. .. method:: convert_field(value, conversion) - + Converts the value (returned by :meth:`get_field`) given a conversion type (as in the tuple returned by the :meth:`parse` method.) The default version understands 'r' (repr) and 's' (str) conversion types. @@ -201,7 +201,7 @@ The grammar for a replacement field is as follows: element_index: `integer` conversion: "r" | "s" | "a" format_spec: <described in the next section> - + In less formal terms, the replacement field starts with a *field_name*, which can either be a number (for a positional argument), or an identifier (for keyword arguments). Following this is an optional *conversion* field, which is @@ -221,7 +221,7 @@ Some simple format string examples:: "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'. - + The *conversion* field causes a type coercion before formatting. Normally, the job of formatting a value is done by the :meth:`__format__` method of the value itself. However, in some cases it is desirable to force a type to be formatted @@ -265,11 +265,11 @@ effectively:: Then the outer replacement field would be evaluated, producing:: "noses " - + Which is substituted into the string, yielding:: - + "A man with two noses " - + (The extra space is because we specified a field width of 10, and because left alignment is the default for strings.) @@ -301,7 +301,7 @@ The general form of a *standard format specifier* is: width: `integer` precision: `integer` type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%" - + The *fill* character can be any character other than '}' (which signifies the end of the field). The presence of a fill character is signaled by the *next* character, which must be one of the alignment options. If the second character @@ -394,9 +394,9 @@ The available integer presentation types are: +---------+----------------------------------------------------------+ | None | The same as ``'d'``. | +---------+----------------------------------------------------------+ - + The available presentation types for floating point and decimal values are: - + +---------+----------------------------------------------------------+ | Type | Meaning | +=========+==========================================================+ diff --git a/Doc/library/subprocess.rst b/Doc/library/subprocess.rst index 57b83d3..da3d007 100644 --- a/Doc/library/subprocess.rst +++ b/Doc/library/subprocess.rst @@ -126,7 +126,7 @@ This module defines one class called :class:`Popen`: Special value that can be used as the *stderr* argument to :class:`Popen` and indicates that standard error should go into the same handle as standard output. - + Convenience Functions ^^^^^^^^^^^^^^^^^^^^^ @@ -346,7 +346,7 @@ The following attributes are also available: The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly by :meth:`communicate`). A ``None`` value indicates that the process hasn't terminated yet. - + A negative value ``-N`` indicates that the child was terminated by signal ``N`` (Unix only). diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index e5d1781..8596bd0 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -327,7 +327,7 @@ always available. The *default* argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would - cause a `TypeError`. + cause a `TypeError`. func:`getsizeof` calls the object's __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector. @@ -642,7 +642,7 @@ always available. The events have the following meaning: - ``'call'`` + ``'call'`` A function is called (or some other code block entered). The global trace function is called; *arg* is ``None``; the return value specifies the local trace function. @@ -704,7 +704,7 @@ always available. prompts of :func:`input`. The interpreter's own prompts and (almost all of) its error messages go to ``stderr``. ``stdout`` and ``stderr`` needn't be built-in file objects: any object is acceptable as long - as it has a :meth:`write` method that takes a string argument. (Changing these + as it has a :meth:`write` method that takes a string argument. (Changing these objects doesn't affect the standard I/O streams of processes executed by :func:`os.popen`, :func:`os.system` or the :func:`exec\*` family of functions in the :mod:`os` module.) diff --git a/Doc/library/tk.rst b/Doc/library/tk.rst index 959cdf4..da84791 100644 --- a/Doc/library/tk.rst +++ b/Doc/library/tk.rst @@ -12,7 +12,7 @@ Graphical User Interfaces with Tk Tk/Tcl has long been an integral part of Python. It provides a robust and platform independent windowing toolkit, that is available to Python programmers -using the :mod:`tkinter` package, and its extension, the :mod:`tkinter.tix` +using the :mod:`tkinter` package, and its extension, the :mod:`tkinter.tix` module. The :mod:`tkinter` package is a thin object-oriented layer on top of Tcl/Tk. To @@ -23,15 +23,15 @@ classes. In addition, the internal module :mod:`_tkinter` provides a threadsafe mechanism which allows Python and Tcl to interact. :mod:`tkinter`'s chief virtues are that it is fast, and that it usually comes -bundled with Python. Although its standard documentation is weak, good -material is available, which includes: references, tutorials, a book and -others. :mod:`tkinter` is also famous for having an outdated look and feel, -which has been vastly improved in Tk 8.5. Nevertheless, there are many other -GUI libraries that you could be interested in. For more information about +bundled with Python. Although its standard documentation is weak, good +material is available, which includes: references, tutorials, a book and +others. :mod:`tkinter` is also famous for having an outdated look and feel, +which has been vastly improved in Tk 8.5. Nevertheless, there are many other +GUI libraries that you could be interested in. For more information about alternatives, see the :ref:`other-gui-packages` section. .. toctree:: - + tkinter.rst tkinter.tix.rst tkinter.scrolledtext.rst diff --git a/Doc/library/tkinter.rst b/Doc/library/tkinter.rst index b40affa..55cc668 100644 --- a/Doc/library/tkinter.rst +++ b/Doc/library/tkinter.rst @@ -41,7 +41,7 @@ It is usually a shared library (or DLL), but might in some cases be statically linked with the Python interpreter. In addition to the Tk interface module, :mod:`tkinter` includes a number of -Python modules, :mod:`tkinter.constants` being one of the most important. +Python modules, :mod:`tkinter.constants` being one of the most important. Importing :mod:`tkinter` will automatically import :mod:`tkinter.constants`, so, usually, to use Tkinter all you need is a simple import statement:: @@ -96,7 +96,7 @@ Other modules that provide Tk support include: Basic dialogs and convenience functions. :mod:`tkinter.dnd` - Drag-and-drop support for :mod:`tkinter`. This is experimental and should + Drag-and-drop support for :mod:`tkinter`. This is experimental and should become deprecated when it is replaced with the Tk DND. :mod:`turtle` @@ -156,7 +156,7 @@ documentation that exists. Here are some hints: the novice. The book is not exhaustive, and for many details it defers to the man pages. -* :file:`tkinter/__init__.py` is a last resort for most, but can be a good +* :file:`tkinter/__init__.py` is a last resort for most, but can be a good place to go when nothing else makes sense. @@ -271,7 +271,7 @@ perform some *action*. In C, you'd express this as someAction(fred, someOptions), in C++, you would express this as fred.someAction(someOptions), and in Tk, you say:: - .fred someAction someOptions + .fred someAction someOptions Note that the object name, ``.fred``, starts with a dot. @@ -320,7 +320,7 @@ To give a widget to the packer (geometry manager), you call pack with optional arguments. In Tkinter, the Pack class holds all this functionality, and the various forms of the pack command are implemented as methods. All widgets in :mod:`tkinter` are subclassed from the Packer, and so inherit all the packing -methods. See the :mod:`tkinter.tix` module documentation for additional +methods. See the :mod:`tkinter.tix` module documentation for additional information on the Form geometry manager. :: pack .fred -side left =====> fred.pack(side = "left") @@ -477,7 +477,7 @@ Packer Options For more extensive information on the packer and the options that it can take, see the man pages and page 183 of John Ousterhout's book. -anchor +anchor Anchor type. Denotes where the packer is to place each slave in its parcel. expand @@ -707,7 +707,7 @@ event. The following table lists the other event fields you can access, and how they are denoted in Tk, which can be useful when referring to the Tk man pages. :: - Tk Tkinter Event Field Tk Tkinter Event Field + Tk Tkinter Event Field Tk Tkinter Event Field -- ------------------- -- ------------------- %f focus %A char %h height %E send_event diff --git a/Doc/library/tkinter.tix.rst b/Doc/library/tkinter.tix.rst index b555376..7cd343c 100644 --- a/Doc/library/tkinter.tix.rst +++ b/Doc/library/tkinter.tix.rst @@ -8,12 +8,12 @@ .. index:: single: Tix -The :mod:`tkinter.tix` (Tk Interface Extension) module provides an additional -rich set of widgets. Although the standard Tk library has many useful widgets, +The :mod:`tkinter.tix` (Tk Interface Extension) module provides an additional +rich set of widgets. Although the standard Tk library has many useful widgets, they are far from complete. The :mod:`tkinter.tix` library provides most of the -commonly needed widgets that are missing from standard Tk: :class:`HList`, -:class:`ComboBox`, :class:`Control` (a.k.a. SpinBox) and an assortment of -scrollable widgets. +commonly needed widgets that are missing from standard Tk: :class:`HList`, +:class:`ComboBox`, :class:`Control` (a.k.a. SpinBox) and an assortment of +scrollable widgets. :mod:`tkinter.tix` also includes many more widgets that are generally useful in a wide range of applications: :class:`NoteBook`, :class:`FileEntry`, :class:`PanedWindow`, etc; there are more than 40 of them. @@ -50,10 +50,10 @@ Using Tix Toplevel widget of Tix which represents mostly the main window of an application. It has an associated Tcl interpreter. - Classes in the :mod:`tkinter.tix` module subclasses the classes in the - :mod:`tkinter`. The former imports the latter, so to use :mod:`tkinter.tix` - with Tkinter, all you need to do is to import one module. In general, you - can just import :mod:`tkinter.tix`, and replace the toplevel call to + Classes in the :mod:`tkinter.tix` module subclasses the classes in the + :mod:`tkinter`. The former imports the latter, so to use :mod:`tkinter.tix` + with Tkinter, all you need to do is to import one module. In general, you + can just import :mod:`tkinter.tix`, and replace the toplevel call to :class:`tkinter.Tk` with :class:`tix.Tk`:: from tkinter import tix @@ -437,7 +437,7 @@ Image Types The :mod:`tkinter.tix` module adds: * `pixmap <http://tix.sourceforge.net/dist/current/man/html/TixCmd/pixmap.htm>`_ - capabilities to all :mod:`tkinter.tix` and :mod:`tkinter` widgets to create + capabilities to all :mod:`tkinter.tix` and :mod:`tkinter` widgets to create color images from XPM files. .. Python Demo of: diff --git a/Doc/library/tokenize.rst b/Doc/library/tokenize.rst index b2caded..197b574 100644 --- a/Doc/library/tokenize.rst +++ b/Doc/library/tokenize.rst @@ -19,16 +19,16 @@ The primary entry point is a :term:`generator`: The :func:`tokenize` generator requires one argument, *readline*, which must be a callable object which provides the same interface as the :meth:`readline` method of built-in file objects (see section - :ref:`bltin-file-objects`). Each call to the function should return one + :ref:`bltin-file-objects`). Each call to the function should return one line of input as bytes. - The generator produces 5-tuples with these members: the token type; the - token string; a 2-tuple ``(srow, scol)`` of ints specifying the row and - column where the token begins in the source; a 2-tuple ``(erow, ecol)`` of - ints specifying the row and column where the token ends in the source; and + The generator produces 5-tuples with these members: the token type; the + token string; a 2-tuple ``(srow, scol)`` of ints specifying the row and + column where the token begins in the source; a 2-tuple ``(erow, ecol)`` of + ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed (the last tuple item) is the *logical* line; continuation lines are included. - + :func:`tokenize` determines the source encoding of the file by looking for a UTF-8 BOM or encoding cookie, according to :pep:`263`. @@ -44,35 +44,35 @@ All constants from the :mod:`token` module are also exported from .. data:: NL Token value used to indicate a non-terminating newline. The NEWLINE token - indicates the end of a logical line of Python code; NL tokens are generated + indicates the end of a logical line of Python code; NL tokens are generated when a logical line of code is continued over multiple physical lines. .. data:: ENCODING - Token value that indicates the encoding used to decode the source bytes - into text. The first token returned by :func:`tokenize` will always be an + Token value that indicates the encoding used to decode the source bytes + into text. The first token returned by :func:`tokenize` will always be an ENCODING token. -Another function is provided to reverse the tokenization process. This is -useful for creating tools that tokenize a script, modify the token stream, and +Another function is provided to reverse the tokenization process. This is +useful for creating tools that tokenize a script, modify the token stream, and write back the modified script. .. function:: untokenize(iterable) Converts tokens back into Python source code. The *iterable* must return - sequences with at least two elements, the token type and the token string. + sequences with at least two elements, the token type and the token string. Any additional sequence elements are ignored. - + The reconstructed script is returned as a single string. The result is guaranteed to tokenize back to match the input so that the conversion is - lossless and round-trips are assured. The guarantee applies only to the - token type and token string as the spacing between tokens (column + lossless and round-trips are assured. The guarantee applies only to the + token type and token string as the spacing between tokens (column positions) may change. - - It returns bytes, encoded using the ENCODING token, which is the first + + It returns bytes, encoded using the ENCODING token, which is the first token sequence output by :func:`tokenize`. @@ -81,43 +81,43 @@ function it uses to do this is available: .. function:: detect_encoding(readline) - The :func:`detect_encoding` function is used to detect the encoding that - should be used to decode a Python source file. It requires one argment, + The :func:`detect_encoding` function is used to detect the encoding that + should be used to decode a Python source file. It requires one argment, readline, in the same way as the :func:`tokenize` generator. - + It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (not decoded from bytes) it has read in. - + It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. - - If no encoding is specified, then the default of 'utf-8' will be returned. - + If no encoding is specified, then the default of 'utf-8' will be returned. + + Example of a script re-writer that transforms float literals into Decimal objects:: def decistmt(s): """Substitute Decimals for floats in a string of statements. - + >>> from decimal import Decimal >>> s = 'print(+21.3e-5*-.1234/81.7)' >>> decistmt(s) "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))" - + The format of the exponent is inherited from the platform C library. Known cases are "e-007" (Windows) and "e-07" (not Windows). Since we're only showing 12 digits, and the 13th isn't close to 5, the rest of the output should be platform-independent. - + >>> exec(s) #doctest: +ELLIPSIS -3.21716034272e-0...7 - + Output from calculations with Decimal should be identical across all platforms. - + >>> exec(decistmt(s)) -3.217160342717258261933904529E-7 """ diff --git a/Doc/library/trace.rst b/Doc/library/trace.rst index 05d5d66..f79d7e5 100644 --- a/Doc/library/trace.rst +++ b/Doc/library/trace.rst @@ -65,13 +65,13 @@ The following command-line arguments are supported: :option:`--ignore-module` Accepts comma separated list of module names. Ignore each of the named - module and its submodules (if it is a package). May be given + module and its submodules (if it is a package). May be given multiple times. :option:`--ignore-dir` Ignore all modules and packages in the named directory and subdirectories (multiple directories can be joined by os.pathsep). May be given multiple - times. + times. .. _trace-api: diff --git a/Doc/library/traceback.rst b/Doc/library/traceback.rst index dd3ae69..1129745 100644 --- a/Doc/library/traceback.rst +++ b/Doc/library/traceback.rst @@ -163,10 +163,10 @@ exception and traceback:: def lumberjack(): bright_side_of_death() - + def bright_side_of_death(): return tuple()[0] - + try: lumberjack() except: @@ -245,12 +245,12 @@ The following example shows the different ways to print and format the stack:: >>> import traceback >>> def another_function(): ... lumberstack() - ... + ... >>> def lumberstack(): ... traceback.print_stack() ... print(repr(traceback.extract_stack())) ... print(repr(traceback.format_stack())) - ... + ... >>> another_function() File "<doctest>", line 10, in <module> another_function() diff --git a/Doc/library/turtle.rst b/Doc/library/turtle.rst index 64df742..0a7acea 100644 --- a/Doc/library/turtle.rst +++ b/Doc/library/turtle.rst @@ -1563,7 +1563,7 @@ The public classes of the module :mod:`turtle` Subclass of TurtleScreen, with :ref:`four methods added <screenspecific>`. - + .. class:: ScrolledCavas(master) :param master: some Tkinter widget to contain the ScrolledCanvas, i.e. @@ -1588,13 +1588,13 @@ The public classes of the module :mod:`turtle` "compound" ``None`` (a compund shape has to be constructed using the :meth:`addcomponent` method) =========== =========== - + .. method:: addcomponent(poly, fill, outline=None) :param poly: a polygon, i.e. a tuple of pairs of numbers :param fill: a color the *poly* will be filled with :param outline: a color for the poly's outline (if given) - + Example: >>> poly = ((0,0),(10,-5),(0,10),(-10,-5)) @@ -1638,31 +1638,31 @@ facilities: >>> help(Screen.bgcolor) Help on method bgcolor in module turtle: - + bgcolor(self, *args) unbound turtle.Screen method Set or return backgroundcolor of the TurtleScreen. - + Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. - - + + >>> screen.bgcolor("orange") >>> screen.bgcolor() "orange" >>> screen.bgcolor(0.5,0,0.5) >>> screen.bgcolor() "#800080" - + >>> help(Turtle.penup) Help on method penup in module turtle: - + penup(self) unbound turtle.Turtle method Pull the pen up -- no drawing when moving. - + Aliases: penup | pu | up - + No argument - + >>> turtle.penup() - The docstrings of the functions which are derived from methods have a modified @@ -1670,32 +1670,32 @@ facilities: >>> help(bgcolor) Help on function bgcolor in module turtle: - + bgcolor(*args) Set or return backgroundcolor of the TurtleScreen. - + Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. - + Example:: - + >>> bgcolor("orange") >>> bgcolor() "orange" >>> bgcolor(0.5,0,0.5) >>> bgcolor() "#800080" - + >>> help(penup) Help on function penup in module turtle: - + penup() Pull the pen up -- no drawing when moving. - + Aliases: penup | pu | up - + No argument - + Example: >>> penup() @@ -1871,19 +1871,19 @@ Have fun! Changes since Python 2.6 ======================== -- The methods :meth:`Turtle.tracer`, :meth:`Turtle.window_width` and - :meth:`Turtle.window_height` have been eliminated. - Methods with these names and functionality are now available only +- The methods :meth:`Turtle.tracer`, :meth:`Turtle.window_width` and + :meth:`Turtle.window_height` have been eliminated. + Methods with these names and functionality are now available only as methods of :class:`Screen`. The functions derived from these remain - available. (In fact already in Python 2.6 these methods were merely - duplications of the corresponding + available. (In fact already in Python 2.6 these methods were merely + duplications of the corresponding :class:`TurtleScreen`/:class:`Screen`-methods.) -- The method :meth:`Turtle.fill` has been eliminated. - The behaviour of :meth:`begin_fill` and :meth:`end_fill` - have changed slightly: now every filling-process must be completed with an +- The method :meth:`Turtle.fill` has been eliminated. + The behaviour of :meth:`begin_fill` and :meth:`end_fill` + have changed slightly: now every filling-process must be completed with an ``end_fill()`` call. - + - A method :meth:`Turtle.filling` has been added. It returns a boolean value: ``True`` if a filling process is under way, ``False`` otherwise. This behaviour corresponds to a ``fill()`` call without arguments in diff --git a/Doc/library/unicodedata.rst b/Doc/library/unicodedata.rst index e8f5569..d8428a5 100644 --- a/Doc/library/unicodedata.rst +++ b/Doc/library/unicodedata.rst @@ -156,7 +156,7 @@ Examples: File "<stdin>", line 1, in ? ValueError: not a decimal >>> unicodedata.category('A') # 'L'etter, 'u'ppercase - 'Lu' + 'Lu' >>> unicodedata.bidirectional('\u0660') # 'A'rabic, 'N'umber 'AN' diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst index 95ba1c4..8c078bc 100644 --- a/Doc/library/unittest.rst +++ b/Doc/library/unittest.rst @@ -591,7 +591,7 @@ failures. TestCase.failUnlessAlmostEqual(first, second[, places[, msg]]) Test that *first* and *second* are approximately equal by computing the - difference, rounding to the given number of decimal *places* (default 7), + difference, rounding to the given number of decimal *places* (default 7), and comparing to zero. Note that comparing a given number of decimal places is not the same as comparing a given number of significant digits. If the values do not compare @@ -602,7 +602,7 @@ failures. TestCase.failIfAlmostEqual(first, second[, places[, msg]]) Test that *first* and *second* are not approximately equal by computing the - difference, rounding to the given number of decimal *places* (default 7), + difference, rounding to the given number of decimal *places* (default 7), and comparing to zero. Note that comparing a given number of decimal places is not the same as comparing a given number of significant digits. If the values do not compare diff --git a/Doc/library/warnings.rst b/Doc/library/warnings.rst index 6a1b0df..f6b3db5 100644 --- a/Doc/library/warnings.rst +++ b/Doc/library/warnings.rst @@ -279,15 +279,15 @@ Available Functions this function with an alternative implementation by assigning to ``warnings.showwarning``. *line* is a line of source code to be included in the warning - message; if *line* is not supplied, :func:`showwarning` will + message; if *line* is not supplied, :func:`showwarning` will try to read the line specified by *filename* and *lineno*. .. 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, + 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*. diff --git a/Doc/library/webbrowser.rst b/Doc/library/webbrowser.rst index 410fa48..ed56741 100644 --- a/Doc/library/webbrowser.rst +++ b/Doc/library/webbrowser.rst @@ -155,7 +155,7 @@ Here are some simple examples:: url = 'http://www.python.org' - # Open URL in a new tab, if a browser window is already open. + # Open URL in a new tab, if a browser window is already open. webbrowser.open_new_tab(url + '/doc') # Open URL in new window, raising the window if possible. diff --git a/Doc/library/wsgiref.rst b/Doc/library/wsgiref.rst index e2eb3b6..de2eb37 100644 --- a/Doc/library/wsgiref.rst +++ b/Doc/library/wsgiref.rst @@ -168,7 +168,7 @@ also provides these miscellaneous utilities: filelike = StringIO("This is an example file-like object"*10) wrapper = FileWrapper(filelike, blksize=5) - for chunk in wrapper: + for chunk in wrapper: print(chunk) @@ -413,7 +413,7 @@ Paste" library. from wsgiref.validate import validator from wsgiref.simple_server import make_server - # Our callable object which is intentionally not compliant to the + # Our callable object which is intentionally not compliant to the # standard, so the validator is going to break def simple_app(environ, start_response): status = b'200 OK' # HTTP Status diff --git a/Doc/library/xml.etree.elementtree.rst b/Doc/library/xml.etree.elementtree.rst index d411c24..623df5a 100644 --- a/Doc/library/xml.etree.elementtree.rst +++ b/Doc/library/xml.etree.elementtree.rst @@ -32,7 +32,7 @@ convert it from and to XML. A C implementation of this API is available as :mod:`xml.etree.cElementTree`. See http://effbot.org/zone/element-index.htm for tutorials and links to other -docs. Fredrik Lundh's page is also the location of the development version of the +docs. Fredrik Lundh's page is also the location of the development version of the xml.etree.ElementTree. .. _elementtree-functions: @@ -379,7 +379,7 @@ This is the XML file that is going to be manipulated:: <title>Example page</title> </head> <body> - <p>Moved to <a href="http://example.org/">example.org</a> + <p>Moved to <a href="http://example.org/">example.org</a> or <a href="http://example.com/">example.com</a>.</p> </body> </html> @@ -486,9 +486,9 @@ XMLTreeBuilder Objects :meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method for each opening tag, its :meth:`end` method for each closing tag, -and data is processed by method :meth:`data`. :meth:`XMLTreeBuilder.close` -calls *target*\'s method :meth:`close`. -:class:`XMLTreeBuilder` can be used not only for building a tree structure. +and data is processed by method :meth:`data`. :meth:`XMLTreeBuilder.close` +calls *target*\'s method :meth:`close`. +:class:`XMLTreeBuilder` can be used not only for building a tree structure. This is an example of counting the maximum depth of an XML file:: >>> from xml.etree.ElementTree import XMLTreeBuilder @@ -496,16 +496,16 @@ This is an example of counting the maximum depth of an XML file:: ... maxDepth = 0 ... depth = 0 ... def start(self, tag, attrib): # Called for each opening tag. - ... self.depth += 1 + ... self.depth += 1 ... if self.depth > self.maxDepth: ... self.maxDepth = self.depth ... def end(self, tag): # Called for each closing tag. ... self.depth -= 1 - ... def data(self, data): + ... def data(self, data): ... pass # We do not need to do anything with data. ... def close(self): # Called when all data has been parsed. ... return self.maxDepth - ... + ... >>> target = MaxDepth() >>> parser = XMLTreeBuilder(target=target) >>> exampleXml = """ diff --git a/Doc/library/xmlrpc.server.rst b/Doc/library/xmlrpc.server.rst index 1a9c757..0d75206 100644 --- a/Doc/library/xmlrpc.server.rst +++ b/Doc/library/xmlrpc.server.rst @@ -126,7 +126,7 @@ Server code:: requestHandler=RequestHandler) server.register_introspection_functions() - # Register pow() function; this will use the value of + # Register pow() function; this will use the value of # pow.__name__ as the name, which is just 'pow'. server.register_function(pow) @@ -135,10 +135,10 @@ Server code:: return x + y server.register_function(adder_function, 'add') - # Register an instance; all the methods of the instance are + # Register an instance; all the methods of the instance are # published as XML-RPC methods (in this case, just 'div'). class MyFuncs: - def div(self, x, y): + def div(self, x, y): return x // y server.register_instance(MyFuncs()) diff --git a/Doc/library/zipfile.rst b/Doc/library/zipfile.rst index 75860cc..3583856 100644 --- a/Doc/library/zipfile.rst +++ b/Doc/library/zipfile.rst @@ -193,7 +193,7 @@ ZipFile Objects .. method:: ZipFile.extractall([path[, members[, pwd]]]) - Extract all members from the archive to the current working directory. *path* + Extract all members from the archive to the current working directory. *path* specifies a different directory to extract to. *members* is optional and must be a subset of the list returned by :meth:`namelist`. *pwd* is the password used for encrypted files. @@ -266,9 +266,9 @@ ZipFile Objects .. note:: - When passing a :class:`ZipInfo` instance as the *zinfo_or_acrname* parameter, - the compression method used will be that specified in the *compress_type* - member of the given :class:`ZipInfo` instance. By default, the + When passing a :class:`ZipInfo` instance as the *zinfo_or_acrname* parameter, + the compression method used will be that specified in the *compress_type* + member of the given :class:`ZipInfo` instance. By default, the :class:`ZipInfo` constructor sets this member to :const:`ZIP_STORED`. The following data attributes are also available: @@ -282,9 +282,9 @@ The following data attributes are also available: .. attribute:: ZipFile.comment - The comment text associated with the ZIP file. If assigning a comment to a - :class:`ZipFile` instance created with mode 'a' or 'w', this should be a - string no longer than 65535 bytes. Comments longer than this will be + The comment text associated with the ZIP file. If assigning a comment to a + :class:`ZipFile` instance created with mode 'a' or 'w', this should be a + string no longer than 65535 bytes. Comments longer than this will be truncated in the written archive when :meth:`ZipFile.close` is called. .. _pyzipfile-objects: @@ -313,10 +313,10 @@ The :class:`PyZipFile` constructor takes the same parameters as the internal use only. The :meth:`writepy` method makes archives with file names like this:: - string.pyc # Top level name - test/__init__.pyc # Package directory + string.pyc # Top level name + test/__init__.pyc # Package directory test/testall.pyc # Module test.testall - test/bogus/__init__.pyc # Subpackage directory + test/bogus/__init__.pyc # Subpackage directory test/bogus/myfile.pyc # Submodule test.bogus.myfile diff --git a/Doc/library/zipimport.rst b/Doc/library/zipimport.rst index 82383bf..912378e 100644 --- a/Doc/library/zipimport.rst +++ b/Doc/library/zipimport.rst @@ -142,7 +142,7 @@ Here is an example that imports a module from a ZIP archive - note that the -------- ------- 8467 1 file $ ./python - Python 2.3 (#1, Aug 1 2003, 19:54:32) + Python 2.3 (#1, Aug 1 2003, 19:54:32) >>> import sys >>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path >>> import jwzthreading diff --git a/Doc/license.rst b/Doc/license.rst index d15cae8..ac29d16 100644 --- a/Doc/license.rst +++ b/Doc/license.rst @@ -386,8 +386,8 @@ Floating point exception control The source for the :mod:`fpectl` module includes the following notice:: - --------------------------------------------------------------------- - / Copyright (c) 1996. \ + --------------------------------------------------------------------- + / Copyright (c) 1996. \ | The Regents of the University of California. | | All rights reserved. | | | @@ -419,7 +419,7 @@ The source for the :mod:`fpectl` module includes the following notice:: | opinions of authors expressed herein do not necessarily state or | | reflect those of the United States Government or the University | | of California, and shall not be used for advertising or product | - \ endorsement purposes. / + \ endorsement purposes. / --------------------------------------------------------------------- diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 3200ed8..57fd63b 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1152,7 +1152,7 @@ Basic customization implementing :meth:`__format__`, however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax. - + See :ref:`formatspec` for a description of the standard formatting syntax. The return value must be a string object. diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst index 52299be..100d81c 100644 --- a/Doc/reference/expressions.rst +++ b/Doc/reference/expressions.rst @@ -552,7 +552,7 @@ or list). Slicings may be used as expressions or as targets in assignment or :keyword:`del` statements. The syntax for a slicing: .. productionlist:: - slicing: `primary` "[" `slice_list` "]" + slicing: `primary` "[" `slice_list` "]" slice_list: `slice_item` ("," `slice_item`)* [","] slice_item: `expression` | `proper_slice` proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ] @@ -640,7 +640,7 @@ raised. Otherwise, the list of filled slots is used as the argument list for the call. .. note:: - + An implementation may provide builtin functions whose positional parameters do not have names, even if they are 'named' for the purpose of documentation, and which therefore cannot be supplied by keyword. In CPython, this is the case for @@ -1045,7 +1045,7 @@ Comparison of objects of the same type depends on the type: Comparison of objects of the differing types depends on whether either of the types provide explicit support for the comparison. Most numeric types can be compared with one another, but comparisons of :class:`float` and -:class:`Decimal` are not supported to avoid the inevitable confusion arising +:class:`Decimal` are not supported to avoid the inevitable confusion arising from representation issues such as ``float('1.1')`` being inexactly represented and therefore not exactly equal to ``Decimal('1.1')`` which is. When cross-type comparison is not supported, the comparison method returns @@ -1323,7 +1323,7 @@ groups from right to left). identity only, but this caused surprises because people expected to be able to test a dictionary for emptiness by comparing it to ``{}``. -.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of +.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of descriptors, you may notice seemingly unusual behaviour in certain uses of the :keyword:`is` operator, like those involving comparisons between instance methods, or constants. Check their documentation for more info. diff --git a/Doc/reference/lexical_analysis.rst b/Doc/reference/lexical_analysis.rst index 83d3b8b..826e692 100644 --- a/Doc/reference/lexical_analysis.rst +++ b/Doc/reference/lexical_analysis.rst @@ -608,7 +608,7 @@ Some examples of integer literals:: 7 2147483647 0o177 0b100110111 3 79228162514264337593543950336 0o377 0x100000000 - 79228162514264337593543950336 0xdeadbeef + 79228162514264337593543950336 0xdeadbeef .. _floating: @@ -654,7 +654,7 @@ restrictions on their range. To create a complex number with a nonzero real part, add a floating point number to it, e.g., ``(3+4j)``. Some examples of imaginary literals:: - 3.14j 10.j 10j .001j 1e100j 3.14e-10j + 3.14j 10.j 10j .001j 1e100j 3.14e-10j .. _operators: diff --git a/Doc/reference/simple_stmts.rst b/Doc/reference/simple_stmts.rst index a799301..611435a 100644 --- a/Doc/reference/simple_stmts.rst +++ b/Doc/reference/simple_stmts.rst @@ -507,7 +507,7 @@ instance, with its traceback set to its argument), like so:: .. index:: pair: exception; chaining __cause__ (exception attribute) __context__ (exception attribute) - + The ``from`` clause is used for exception chaining: if given, the second *expression* must be another exception class or instance, which will then be attached to the raised exception as the :attr:`__cause__` attribute (which is @@ -729,7 +729,7 @@ up to the last dot is used to find a "package"; the final identifier is then searched inside the package. A package is generally a subdirectory of a directory on ``sys.path`` that has a file :file:`__init__.py`. -.. +.. [XXX Can't be bothered to spell this out right now; see the URL http://www.python.org/doc/essays/packages.html for more details, also about how @@ -874,9 +874,9 @@ The :keyword:`nonlocal` statement : ["=" (`target_list` "=")+ `expression_list`] : | "nonlocal" `identifier` `augop` `expression_list` -The :keyword:`nonlocal` statement causes the listed identifiers to refer to -previously bound variables in the nearest enclosing scope. This is important -because the default behavior for binding is to search the local namespace +The :keyword:`nonlocal` statement causes the listed identifiers to refer to +previously bound variables in the nearest enclosing scope. This is important +because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope. @@ -889,7 +889,7 @@ Names listed in a :keyword:`nonlocal` statement, unlike to those listed in a enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously). -Names listed in a :keyword:`nonlocal` statement must not collide with +Names listed in a :keyword:`nonlocal` statement must not collide with pre-existing bindings in the local scope. .. seealso:: diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst index d6e8ca1..d6842e0 100644 --- a/Doc/tutorial/classes.rst +++ b/Doc/tutorial/classes.rst @@ -14,7 +14,7 @@ multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name. Objects can contain an arbitrary amount of private data. -In C++ terminology, normally class members (including the data members) are +In C++ terminology, normally class members (including the data members) are *public* (except see below :ref:`tut-private`), and all member functions are *virtual*. There are no special constructors or destructors. As in Modula-3, there are no shorthands for referencing the @@ -171,7 +171,7 @@ binding:: def do_global(): global spam spam = "global spam" - + spam = "test spam" do_local() print("After local assignment:", spam) @@ -302,7 +302,7 @@ are passed on to :meth:`__init__`. For example, :: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart - ... + ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5) @@ -532,7 +532,7 @@ Python has two builtin functions that work with inheritance: is ``True`` since :class:`bool` is a subclass of :class:`int`. However, ``issubclass(float, int)`` is ``False`` since :class:`float` is not a subclass of :class:`int`. - + .. _tut-multiple: diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst index b0b4478..98f76ff 100644 --- a/Doc/tutorial/controlflow.rst +++ b/Doc/tutorial/controlflow.rst @@ -61,7 +61,7 @@ they appear in the sequence. For example (no pun intended): ... a = ['cat', 'window', 'defenestrate'] >>> for x in a: ... print(x, len(x)) - ... + ... cat 3 window 6 defenestrate 12 @@ -74,7 +74,7 @@ convenient:: >>> for x in a[:]: # make a slice copy of the entire list ... if len(x) > 6: a.insert(0, x) - ... + ... >>> a ['defenestrate', 'cat', 'window', 'defenestrate'] @@ -96,7 +96,7 @@ If you do need to iterate over a sequence of numbers, the built-in function 2 3 4 - + The given end point is never part of the generated list; ``range(10)`` generates @@ -104,13 +104,13 @@ The given end point is never part of the generated list; ``range(10)`` generates is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the 'step'):: - range(5, 10) + range(5, 10) 5 through 9 - range(0, 10, 3) + range(0, 10, 3) 0, 3, 6, 9 - range(-10, -100, -30) + range(-10, -100, -30) -10, -40, -70 To iterate over the indices of a sequence, you can combine :func:`range` and @@ -119,7 +119,7 @@ To iterate over the indices of a sequence, you can combine :func:`range` and >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print(i, a[i]) - ... + ... 0 Mary 1 had 2 a @@ -135,12 +135,12 @@ A strange thing happens if you just print a range:: range(0, 10) In many ways the object returned by :func:`range` behaves as if it is a list, -but in fact it isn't. It is an object which returns the successive items of -the desired sequence when you iterate over it, but it doesn't really make -the list, thus saving space. +but in fact it isn't. It is an object which returns the successive items of +the desired sequence when you iterate over it, but it doesn't really make +the list, thus saving space. -We say such an object is *iterable*, that is, suitable as a target for -functions and constructs that expect something from which they can +We say such an object is *iterable*, that is, suitable as a target for +functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the :keyword:`for` statement is such an *iterator*. The function :func:`list` is another; it creates lists from iterables:: @@ -177,7 +177,7 @@ following loop, which searches for prime numbers:: ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') - ... + ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 @@ -198,7 +198,7 @@ required syntactically but the program requires no action. For example:: >>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) - ... + ... This is commonly used for creating minimal classes:: @@ -212,7 +212,7 @@ at a more abstract level. The :keyword:`pass` is silently ignored:: >>> def initlog(*args): ... pass # Remember to implement this! - ... + ... .. _tut-functions: @@ -229,7 +229,7 @@ boundary:: ... print(b, end=' ') ... a, b = b, a+b ... print() - ... + ... >>> # Now call the function we just defined: ... fib(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 @@ -300,7 +300,7 @@ Fibonacci series, instead of printing it:: ... result.append(b) # see below ... a, b = b, a+b ... return result - ... + ... >>> f100 = fib2(100) # call it >>> f100 # write the result [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] @@ -436,7 +436,7 @@ calls. Here's an example that fails due to this restriction:: >>> def function(a): ... pass - ... + ... >>> function(0, a=0) Traceback (most recent call last): File "<stdin>", line 1, in ? @@ -487,7 +487,7 @@ Arbitrary Argument Lists ------------------------ .. index:: - statement: * + statement: * Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped @@ -497,13 +497,13 @@ zero or more normal arguments may occur. :: def write_multiple_items(file, separator, *args): file.write(separator.join(args)) - + Normally, these ``variadic`` arguments will be last in the list of formal -parameters, because they scoop up all remaining input arguments that are +parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the ``*args`` -parameter are 'keyword-only' arguments, meaning that they can only be used as +parameter are 'keyword-only' arguments, meaning that they can only be used as keywords rather than positional arguments. :: - + >>> def concat(*args, sep="/"): ... return sep.join(args) ... @@ -581,7 +581,7 @@ Documentation Strings single: strings, documentation Here are some conventions about the content and formatting of documentation -strings. +strings. The first line should always be a short, concise summary of the object's purpose. For brevity, it should not explicitly state the object's name or type, @@ -610,11 +610,11 @@ Here is an example of a multi-line docstring:: >>> def my_function(): ... """Do nothing, but document it. - ... + ... ... No, really, it doesn't do anything. ... """ ... pass - ... + ... >>> print(my_function.__doc__) Do nothing, but document it. diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst index ca6de17..95497b4 100644 --- a/Doc/tutorial/datastructures.rst +++ b/Doc/tutorial/datastructures.rst @@ -159,7 +159,7 @@ List Comprehensions List comprehensions provide a concise way to create lists from sequences. Common applications are to make lists where each element is the result of -some operations applied to each member of the sequence, or to create a +some operations applied to each member of the sequence, or to create a subsequence of those elements that satisfy a certain condition. @@ -167,7 +167,7 @@ Each list comprehension consists of an expression followed by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result will be a list resulting from evaluating the expression in the context of the :keyword:`for` and :keyword:`if` clauses which follow it. If the expression -would evaluate to a tuple, it must be parenthesized. +would evaluate to a tuple, it must be parenthesized. Here we take a list of numbers and return a list of three times each number:: @@ -227,7 +227,7 @@ If you've got the stomach for it, list comprehensions can be nested. They are a powerful tool but -- like all powerful tools -- they need to be used carefully, if at all. -Consider the following example of a 3x3 matrix held as a list containing three +Consider the following example of a 3x3 matrix held as a list containing three lists, one list per row:: >>> mat = [ @@ -236,7 +236,7 @@ lists, one list per row:: ... [7, 8, 9], ... ] -Now, if you wanted to swap rows and columns, you could use a list +Now, if you wanted to swap rows and columns, you could use a list comprehension:: >>> print([[row[i] for row in mat] for i in [0, 1, 2]]) @@ -254,7 +254,7 @@ A more verbose version of this snippet shows the flow explicitly:: print(row[i], end="") print() -In real world, you should prefer builtin functions to complex flow statements. +In real world, you should prefer builtin functions to complex flow statements. The :func:`zip` function would do a great job for this use case:: >>> list(zip(*mat)) diff --git a/Doc/tutorial/errors.rst b/Doc/tutorial/errors.rst index ca70f89..e78947c 100644 --- a/Doc/tutorial/errors.rst +++ b/Doc/tutorial/errors.rst @@ -91,7 +91,7 @@ is signalled by raising the :exc:`KeyboardInterrupt` exception. :: ... break ... except ValueError: ... print("Oops! That was no valid number. Try again...") - ... + ... The :keyword:`try` statement works as follows. @@ -195,12 +195,12 @@ indirectly) in the try clause. For example:: >>> def this_fails(): ... x = 1/0 - ... + ... >>> try: ... this_fails() ... except ZeroDivisionError as err: ... print('Handling run-time error:', err) - ... + ... Handling run-time error: int division or modulo by zero @@ -251,12 +251,12 @@ directly or indirectly. For example:: ... self.value = value ... def __str__(self): ... return repr(self.value) - ... + ... >>> try: ... raise MyError(2*2) ... except MyError as e: ... print('My exception occurred, value:', e.value) - ... + ... My exception occurred, value: 4 >>> raise MyError('oops!') Traceback (most recent call last): @@ -326,7 +326,7 @@ example:: ... raise KeyboardInterrupt ... finally: ... print('Goodbye, world!') - ... + ... Goodbye, world! Traceback (most recent call last): File "<stdin>", line 2, in ? @@ -389,9 +389,9 @@ and print its contents to the screen. :: print(line) The problem with this code is that it leaves the file open for an indeterminate -amount of time after this part of the code has finished executing. -This is not an issue in simple scripts, but can be a problem for larger -applications. The :keyword:`with` statement allows objects like files to be +amount of time after this part of the code has finished executing. +This is not an issue in simple scripts, but can be a problem for larger +applications. The :keyword:`with` statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly. :: with open("myfile.txt") as f: diff --git a/Doc/tutorial/index.rst b/Doc/tutorial/index.rst index 3c0d91d..dfc6ac0 100644 --- a/Doc/tutorial/index.rst +++ b/Doc/tutorial/index.rst @@ -1,7 +1,7 @@ .. _tutorial-index: ###################### - The Python Tutorial + The Python Tutorial ###################### :Release: |version| diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst index 3252bbe..1fd779f 100644 --- a/Doc/tutorial/inputoutput.rst +++ b/Doc/tutorial/inputoutput.rst @@ -90,7 +90,7 @@ Here are two ways to write a table of squares and cubes:: >>> for x in range(1, 11): ... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) - ... + ... 1 1 1 2 4 8 3 9 27 @@ -165,7 +165,7 @@ number of characters wide. This is useful for making tables pretty.:: >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> for name, phone in table.items(): ... print('{0:10} ==> {1:10d}'.format(name, phone)) - ... + ... Jack ==> 4098 Dcab ==> 7678 Sjoerd ==> 4127 @@ -343,7 +343,7 @@ beginning of the file as the reference point. :: 16 >>> f.seek(5) # Go to the 6th byte in the file 5 - >>> f.read(1) + >>> f.read(1) b'5' >>> f.seek(-3, 2) # Go to the 3rd byte before the end 13 @@ -353,7 +353,7 @@ beginning of the file as the reference point. :: In text files (those opened without a ``b`` in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with ``seek(0, 2)``). - + When you're done with a file, call ``f.close()`` to close it and free up any system resources taken up by the open file. After calling ``f.close()``, attempts to use the file object will automatically fail. :: diff --git a/Doc/tutorial/interpreter.rst b/Doc/tutorial/interpreter.rst index e93b567..72cbec9 100644 --- a/Doc/tutorial/interpreter.rst +++ b/Doc/tutorial/interpreter.rst @@ -115,7 +115,7 @@ example, take a look at this :keyword:`if` statement:: >>> the_world_is_flat = 1 >>> if the_world_is_flat: ... print("Be careful not to fall off!") - ... + ... Be careful not to fall off! @@ -191,7 +191,7 @@ It is also possible to specify a different encoding for source files. In order to do this, put one more special comment line right after the ``#!`` line to define the source file encoding:: - # -*- coding: encoding -*- + # -*- coding: encoding -*- With that declaration, everything in the source file will be treated as having the encoding *encoding* instead of UTF-8. The list of possible encodings can be diff --git a/Doc/tutorial/introduction.rst b/Doc/tutorial/introduction.rst index 57254db..10166a6 100644 --- a/Doc/tutorial/introduction.rst +++ b/Doc/tutorial/introduction.rst @@ -58,7 +58,7 @@ operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages >>> 8/5 # Fractions aren't lost when dividing integers 1.6000000000000001 -Note: You might not see exactly the same result; floating point results can +Note: You might not see exactly the same result; floating point results can differ from one machine to another. We will say more later about controlling the appearance of floating point output; what we see here is the most informative display but not as easy to read as we would get with:: @@ -71,9 +71,9 @@ unless we are specifically discussing output formatting, and explain later why these two ways of displaying floating point data come to be different. See :ref:`tut-fp-issues` for a full discussion. -To do integer division and get an integer result, +To do integer division and get an integer result, discarding any fractional result, there is another operator, ``//``:: - + >>> # Integer division returns the floor: ... 7//3 2 @@ -103,7 +103,7 @@ error will occur:: >>> # try to access an undefined variable ... n - Traceback (most recent call last): + Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'n' is not defined @@ -245,14 +245,14 @@ Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or they will be included in the string. :: print(""" - Usage: thingy [OPTIONS] + Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """) produces the following output:: - Usage: thingy [OPTIONS] + Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to @@ -371,10 +371,10 @@ One way to remember how slices work is to think of the indices as pointing Then the right edge of the last character of a string of *n* characters has index *n*, for example:: - +---+---+---+---+---+ + +---+---+---+---+---+ | H | e | l | p | A | - +---+---+---+---+---+ - 0 1 2 3 4 5 + +---+---+---+---+---+ + 0 1 2 3 4 5 -5 -4 -3 -2 -1 The first row of numbers gives the position of the indices 0...5 in the string; @@ -396,7 +396,7 @@ The built-in function :func:`len` returns the length of a string:: .. seealso:: :ref:`typesseq` - Strings are examples of *sequence types*, and support the common + Strings are examples of *sequence types*, and support the common operations supported by such types. :ref:`string-methods` @@ -565,7 +565,7 @@ series as follows:: >>> while b < 10: ... print(b) ... a, b = b, a+b - ... + ... 1 1 2 @@ -601,8 +601,8 @@ This example introduces several new features. * The :func:`print` function writes the value of the expression(s) it is given. It differs from just writing the expression you want to write (as we did - earlier in the calculator examples) in the way it handles multiple - expressions, floating point quantities, + earlier in the calculator examples) in the way it handles multiple + expressions, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:: @@ -617,5 +617,5 @@ This example introduces several new features. >>> while b < 1000: ... print(b, end=' ') ... a, b = b, a+b - ... + ... 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 diff --git a/Doc/tutorial/modules.rst b/Doc/tutorial/modules.rst index aca553d..113186e 100644 --- a/Doc/tutorial/modules.rst +++ b/Doc/tutorial/modules.rst @@ -103,8 +103,8 @@ There is even a variant to import all names that a module defines:: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 This imports all names except those beginning with an underscore (``_``). -In most cases Python programmers do not use this facility since it introduces -an unknown set of names into the interpreter, possibly hiding some things +In most cases Python programmers do not use this facility since it introduces +an unknown set of names into the interpreter, possibly hiding some things you have already defined. .. note:: @@ -287,7 +287,7 @@ defines. It returns a sorted list of strings:: ['__name__', 'fib', 'fib2'] >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', - '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', + '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'callstats', 'copyright', 'displayhook', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags', @@ -317,25 +317,25 @@ want a list of those, they are defined in the standard module >>> dir(builtins) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'Buffer - Error', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Excep - tion', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError - ', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', - 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImp - lemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecatio - nWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StopIteration', - 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', - 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', ' - UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueE - rror', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__' - , '__import__', '__name__', 'abs', 'all', 'any', 'basestring', 'bin', 'bool', 'b - uffer', 'bytes', 'chr', 'chr8', 'classmethod', 'cmp', 'compile', 'complex', 'cop - yright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'ex - ec', 'exit', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'h - ash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', ' - len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'o - bject', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr - ', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'st - r', 'str8', 'sum', 'super', 'trunc', 'tuple', 'type', 'vars', 'zip'] + Error', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Excep + tion', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError + ', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', + 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImp + lemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecatio + nWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StopIteration', + 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', + 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', ' + UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueE + rror', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__' + , '__import__', '__name__', 'abs', 'all', 'any', 'basestring', 'bin', 'bool', 'b + uffer', 'bytes', 'chr', 'chr8', 'classmethod', 'cmp', 'compile', 'complex', 'cop + yright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'ex + ec', 'exit', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'h + ash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', ' + len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'o + bject', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr + ', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'st + r', 'str8', 'sum', 'super', 'trunc', 'tuple', 'type', 'vars', 'zip'] .. _tut-packages: diff --git a/Doc/tutorial/stdlib.rst b/Doc/tutorial/stdlib.rst index 3b1f1fc..ebb5233 100644 --- a/Doc/tutorial/stdlib.rst +++ b/Doc/tutorial/stdlib.rst @@ -136,7 +136,7 @@ The :mod:`random` module provides tools for making random selections:: >>> random.random() # random float 0.17970987693706186 >>> random.randrange(6) # random integer chosen from range(6) - 4 + 4 The SciPy project <http://scipy.org> has many other modules for numerical computations. diff --git a/Doc/tutorial/stdlib2.rst b/Doc/tutorial/stdlib2.rst index a06a20b..f581972 100644 --- a/Doc/tutorial/stdlib2.rst +++ b/Doc/tutorial/stdlib2.rst @@ -174,7 +174,7 @@ tasks in background while the main program continues to run:: class AsyncZip(threading.Thread): def __init__(self, infile, outfile): - threading.Thread.__init__(self) + threading.Thread.__init__(self) self.infile = infile self.outfile = outfile def run(self): @@ -358,11 +358,11 @@ For example, calculating a 5% tax on a 70 cent phone charge gives different results in decimal floating point and binary floating point. The difference becomes significant if the results are rounded to the nearest cent:: - >>> from decimal import * + >>> from decimal import * >>> Decimal('0.70') * Decimal('1.05') Decimal("0.7350") >>> .70 * 1.05 - 0.73499999999999999 + 0.73499999999999999 The :class:`Decimal` result keeps a trailing zero, automatically inferring four place significance from multiplicands with two place significance. Decimal @@ -380,7 +380,7 @@ calculations and equality tests that are unsuitable for binary floating point:: >>> sum([Decimal('0.1')]*10) == Decimal('1.0') True >>> sum([0.1]*10) == 1.0 - False + False The :mod:`decimal` module provides arithmetic with as much precision as needed:: diff --git a/Doc/tutorial/whatnow.rst b/Doc/tutorial/whatnow.rst index b950cbc..541b183 100644 --- a/Doc/tutorial/whatnow.rst +++ b/Doc/tutorial/whatnow.rst @@ -49,8 +49,8 @@ More Python resources: Cookbook (O'Reilly & Associates, ISBN 0-596-00797-3.) * http://scipy.org: The Scientific Python project includes modules for fast - array computations and manipulations plus a host of packages for such - things as linear algebra, Fourier transforms, non-linear solvers, + array computations and manipulations plus a host of packages for such + things as linear algebra, Fourier transforms, non-linear solvers, random number distributions, statistical analysis and the like. For Python-related questions and problem reports, you can post to the newsgroup @@ -68,6 +68,6 @@ solution for your problem. .. Postings figure based on average of last six months activity as reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182 - days = 116.9 msgs / day and steadily increasing. (XXX up to date figures?) + days = 116.9 msgs / day and steadily increasing. (XXX up to date figures?) diff --git a/Doc/using/cmdline.rst b/Doc/using/cmdline.rst index f0e533c..bfebd9d 100644 --- a/Doc/using/cmdline.rst +++ b/Doc/using/cmdline.rst @@ -8,8 +8,8 @@ Command line and environment The CPython interpreter scans the command line and the environment for various settings. -.. note:: - +.. note:: + Other implementations' command line schemes may differ. See :ref:`implementations` for further resources. @@ -61,7 +61,7 @@ source. Execute the Python code in *command*. *command* can be one ore more statements separated by newlines, with significant leading whitespace as in normal module code. - + If this option is given, the first element of :data:`sys.argv` will be ``"-c"`` and the current directory will be added to the start of :data:`sys.path` (allowing modules in that directory to be imported as top @@ -72,7 +72,7 @@ source. Search :data:`sys.path` for the named module and execute its contents as the :mod:`__main__` module. - + Since the argument is a *module* name, you must not give a file extension (``.py``). The ``module-name`` should be a valid Python module name, but the implementation may not always enforce this (e.g. it may allow you to @@ -84,18 +84,18 @@ source. written in C, since they do not have Python module files. However, it can still be used for precompiled modules, even if the original source file is not available. - + If this option is given, the first element of :data:`sys.argv` will be the full path to the module file. As with the :option:`-c` option, the current directory will be added to the start of :data:`sys.path`. - + Many standard library modules contain code that is invoked on their execution as a script. An example is the :mod:`timeit` module:: python -mtimeit -s 'setup here' 'benchmarked code here' python -mtimeit -h # for details - .. seealso:: + .. seealso:: :func:`runpy.run_module` The actual implementation of this feature. @@ -152,7 +152,7 @@ Generic options --version Print the Python version number and exit. Example output could be:: - + Python 3.0 @@ -189,7 +189,7 @@ Miscellaneous options enter interactive mode after executing the script or the command, even when :data:`sys.stdin` does not appear to be a terminal. The :envvar:`PYTHONSTARTUP` file is not read. - + This can be useful to inspect global variables or a stack trace when a script raises an exception. See also :envvar:`PYTHONINSPECT`. @@ -222,10 +222,10 @@ Miscellaneous options .. cmdoption:: -u - + Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. - + Note that there is internal buffering in :meth:`file.readlines` and :ref:`bltin-file-objects` (``for line in sys.stdin``) which is not influenced by this option. To work around this, you will want to use @@ -237,7 +237,7 @@ Miscellaneous options .. XXX should the -U option be documented? .. cmdoption:: -v - + Print a message each time a module is initialized, showing the place (filename or built-in module) from which it is loaded. When given twice (:option:`-vv`), print a message for each file that is checked for when @@ -246,13 +246,13 @@ Miscellaneous options .. cmdoption:: -W arg - + Warning control. Python's warning machinery by default prints warning messages to :data:`sys.stderr`. A typical warning message has the following form:: file:line: category: message - + By default, each warning is printed once for each source line where it occurs. This option controls how often warnings are printed. @@ -260,13 +260,13 @@ Miscellaneous options one option, the action for the last matching option is performed. Invalid :option:`-W` options are ignored (though, a warning message is printed about invalid options when the first warning is issued). - + Warnings can also be controlled from within a Python program using the :mod:`warnings` module. The simplest form of argument is one of the following action strings (or a unique abbreviation): - + ``ignore`` Ignore all warnings. ``default`` @@ -282,9 +282,9 @@ Miscellaneous options Print each warning only the first time it occurs in the program. ``error`` Raise an exception instead of printing a warning message. - - The full form of argument is:: - + + The full form of argument is:: + action:message:category:module:line Here, *action* is as explained above but only applies to messages that match @@ -305,10 +305,10 @@ Miscellaneous options .. cmdoption:: -x - + Skip the first line of the source, allowing use of non-Unix forms of ``#!cmd``. This is intended for a DOS specific hack only. - + .. warning:: The line numbers in error messages will be off by one! .. _using-on-envvars: @@ -319,13 +319,13 @@ Environment variables These environment variables influence Python's behavior. .. envvar:: PYTHONHOME - + Change the location of the standard Python libraries. By default, the libraries are searched in :file:`{prefix}/lib/python{version}` and :file:`{exec_prefix}/lib/python{version}`, where :file:`{prefix}` and :file:`{exec_prefix}` are installation-dependent directories, both defaulting to :file:`/usr/local`. - + When :envvar:`PYTHONHOME` is set to a single directory, its value replaces both :file:`{prefix}` and :file:`{exec_prefix}`. To specify different values for these, set :envvar:`PYTHONHOME` to :file:`{prefix}:{exec_prefix}`. @@ -341,11 +341,11 @@ These environment variables influence Python's behavior. In addition to normal directories, individual :envvar:`PYTHONPATH` entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles. - + The default search path is installation dependent, but generally begins with :file:`{prefix}/lib/python{version}`` (see :envvar:`PYTHONHOME` above). It is *always* appended to :envvar:`PYTHONPATH`. - + An additional directory will be inserted in the search path in front of :envvar:`PYTHONPATH` as described above under :ref:`using-on-interface-options`. The search path can be manipulated from @@ -353,7 +353,7 @@ These environment variables influence Python's behavior. .. envvar:: PYTHONSTARTUP - + If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so @@ -363,7 +363,7 @@ These environment variables influence Python's behavior. .. envvar:: PYTHONY2K - + Set this to a non-empty string to cause the :mod:`time` module to require dates specified as strings to include 4-digit years, otherwise 2-digit years are converted based on rules described in the :mod:`time` module @@ -371,21 +371,21 @@ These environment variables influence Python's behavior. .. envvar:: PYTHONOPTIMIZE - + If this is set to a non-empty string it is equivalent to specifying the :option:`-O` option. If set to an integer, it is equivalent to specifying :option:`-O` multiple times. .. envvar:: PYTHONDEBUG - + If this is set to a non-empty string it is equivalent to specifying the :option:`-d` option. If set to an integer, it is equivalent to specifying :option:`-d` multiple times. .. envvar:: PYTHONINSPECT - + If this is set to a non-empty string it is equivalent to specifying the :option:`-i` option. @@ -394,20 +394,20 @@ These environment variables influence Python's behavior. .. envvar:: PYTHONUNBUFFERED - + If this is set to a non-empty string it is equivalent to specifying the :option:`-u` option. .. envvar:: PYTHONVERBOSE - + If this is set to a non-empty string it is equivalent to specifying the :option:`-v` option. If set to an integer, it is equivalent to specifying :option:`-v` multiple times. .. envvar:: PYTHONCASEOK - + If this is set, Python ignores case in :keyword:`import` statements. This only works on Windows. diff --git a/Doc/using/unix.rst b/Doc/using/unix.rst index 2ab5ee1..d56d422 100644 --- a/Doc/using/unix.rst +++ b/Doc/using/unix.rst @@ -45,7 +45,7 @@ On FreeBSD and OpenBSD * OpenBSD users use:: - pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz + pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz For example i386 users get the 2.5.1 version of Python using:: @@ -87,7 +87,7 @@ source tree. Python-related paths and files ============================== - + These are subject to difference depending on local installation conventions; :envvar:`prefix` (``${prefix}``) and :envvar:`exec_prefix` (``${exec_prefix}``) are installation-dependent and should be interpreted as for GNU software; they @@ -112,7 +112,7 @@ For example, on most Linux systems, the default for both is :file:`/usr`. | | by the user module; not used by default | | | or by most applications. | +-----------------------------------------------+------------------------------------------+ - + Miscellaneous ============= diff --git a/Doc/using/windows.rst b/Doc/using/windows.rst index aa24933..99fc674 100644 --- a/Doc/using/windows.rst +++ b/Doc/using/windows.rst @@ -86,9 +86,9 @@ Excursus: Setting environment variables --------------------------------------- Windows has a built-in dialog for changing environment variables (following -guide applies to XP classical view): Right-click the icon for your machine -(usually located on your Desktop and called "My Computer") and choose -:menuselection:`Properties` there. Then, open the :guilabel:`Advanced` tab +guide applies to XP classical view): Right-click the icon for your machine +(usually located on your Desktop and called "My Computer") and choose +:menuselection:`Properties` there. Then, open the :guilabel:`Advanced` tab and click the :guilabel:`Environment Variables` button. In short, your path is: @@ -191,11 +191,11 @@ administrative rights): #. Launch a command prompt. #. Associate the correct file group with ``.py`` scripts:: - + assoc .py=Python.File #. Redirect all Python files to the new executable:: - + ftype Python.File=C:\Path\to\pythonw.exe "%1" %* diff --git a/Doc/whatsnew/2.0.rst b/Doc/whatsnew/2.0.rst index 9ea5dc1..75205d4 100644 --- a/Doc/whatsnew/2.0.rst +++ b/Doc/whatsnew/2.0.rst @@ -1,5 +1,5 @@ **************************** - What's New in Python 2.0 + What's New in Python 2.0 **************************** :Author: A.M. Kuchling and Moshe Zadka @@ -277,9 +277,9 @@ additional information. Take the first example in the previous paragraph, finding all the strings in the list containing a given substring. You could write the following to do it:: - # Given the list L, make a list of all strings + # Given the list L, make a list of all strings # containing the substring S. - sublist = filter( lambda s, substring=S: + sublist = filter( lambda s, substring=S: string.find(s, substring) != -1, L) @@ -291,7 +291,7 @@ substring is being searched for. List comprehensions make this cleaner:: List comprehensions have the form:: - [ expression for expr in sequence1 + [ expression for expr in sequence1 for expr2 in sequence2 ... for exprN in sequenceN if condition ] @@ -312,8 +312,8 @@ following Python code:: ... for exprN in sequenceN: if (condition): - # Append the value of - # the expression to the + # Append the value of + # the expression to the # resulting list. This means that when there are multiple :keyword:`for`...\ :keyword:`in` @@ -590,7 +590,7 @@ raised should still work. :: def f(): print "i=",i - i = i + 1 + i = i + 1 f() Two new exceptions, :exc:`TabError` and :exc:`IndentationError`, have been @@ -627,7 +627,7 @@ would do, and also inserts it into the dictionary as the value for *key*. Thus, the following lines of code:: if dict.has_key( key ): return dict[key] - else: + else: dict[key] = [] return dict[key] @@ -836,14 +836,14 @@ the simple case, when the software contains only .py files, a minimal :file:`setup.py` can be just a few lines long:: from distutils.core import setup - setup (name = "foo", version = "1.0", + setup (name = "foo", version = "1.0", py_modules = ["module1", "module2"]) The :file:`setup.py` file isn't much more complicated if the software consists of a few packages:: from distutils.core import setup - setup (name = "foo", version = "1.0", + setup (name = "foo", version = "1.0", packages = ["package", "package.subpackage"]) A C extension can be the most complicated case; here's an example taken from @@ -860,7 +860,7 @@ the PyXML package:: 'extensions/expat/xmltok/xmlrole.c', ] ) - setup (name = "PyXML", version = "0.5.4", + setup (name = "PyXML", version = "0.5.4", ext_modules =[ expat_extension ] ) The Distutils can also take care of creating source and binary distributions. diff --git a/Doc/whatsnew/2.1.rst b/Doc/whatsnew/2.1.rst index c3f1280..6b2ce3f 100644 --- a/Doc/whatsnew/2.1.rst +++ b/Doc/whatsnew/2.1.rst @@ -1,5 +1,5 @@ **************************** - What's New in Python 2.1 + What's New in Python 2.1 **************************** :Author: A.M. Kuchling @@ -98,7 +98,7 @@ To make the preceding explanation a bit clearer, here's an example:: x = 1 def f(): # The next line is a syntax error - exec 'x=2' + exec 'x=2' def g(): return x diff --git a/Doc/whatsnew/2.2.rst b/Doc/whatsnew/2.2.rst index 1383298..28ecb81 100644 --- a/Doc/whatsnew/2.2.rst +++ b/Doc/whatsnew/2.2.rst @@ -1,5 +1,5 @@ **************************** - What's New in Python 2.2 + What's New in Python 2.2 **************************** :Author: A.M. Kuchling @@ -473,7 +473,7 @@ there are no more values to be returned, calling :meth:`next` should raise the Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration - >>> + >>> In 2.2, Python's :keyword:`for` statement no longer expects a sequence; it expects something for which :func:`iter` will return an iterator. For backward @@ -909,7 +909,7 @@ To make the preceding explanation a bit clearer, here's an example:: x = 1 def f(): # The next line is a syntax error - exec 'x=2' + exec 'x=2' def g(): return x @@ -952,8 +952,8 @@ New and Improved Modules items = s.meerkat.getItems( {'channel': 4} ) # 'items' is another list of dictionaries, like this: - # [{'link': 'http://freshmeat.net/releases/52719/', - # 'description': 'A utility which converts HTML to XSL FO.', + # [{'link': 'http://freshmeat.net/releases/52719/', + # 'description': 'A utility which converts HTML to XSL FO.', # 'title': 'html2fo 0.3 (Default)'}, ... ] The :mod:`SimpleXMLRPCServer` module makes it easy to create straightforward diff --git a/Doc/whatsnew/2.3.rst b/Doc/whatsnew/2.3.rst index 810aa25..fd0f77f 100644 --- a/Doc/whatsnew/2.3.rst +++ b/Doc/whatsnew/2.3.rst @@ -1,5 +1,5 @@ **************************** - What's New in Python 2.3 + What's New in Python 2.3 **************************** :Author: A.M. Kuchling @@ -301,7 +301,7 @@ For example:: -------- ------- 8467 1 file amk@nyman:~/src/python$ ./python - Python 2.3 (#1, Aug 1 2003, 19:54:32) + Python 2.3 (#1, Aug 1 2003, 19:54:32) >>> import sys >>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path >>> import jwzthreading @@ -671,7 +671,7 @@ with older versions of the Distutils:: # ... } - if (hasattr(core, 'setup_keywords') and + if (hasattr(core, 'setup_keywords') and 'classifiers' in core.setup_keywords): kw['classifiers'] = \ ['Topic :: Internet :: WWW/HTTP :: Dynamic Content', @@ -1027,7 +1027,7 @@ Here are all of the changes that Python 2.3 makes to the core Python language. creating small dictionaries:: >>> dict(red=1, blue=2, green=3, black=4) - {'blue': 2, 'black': 4, 'green': 3, 'red': 1} + {'blue': 2, 'black': 4, 'green': 3, 'red': 1} (Contributed by Just van Rossum.) @@ -1622,7 +1622,7 @@ complete list of changes, or look through the CVS logs for all the details. ... self.valuelist.pop(i) ... def keys(self): ... return list(self.keylist) - ... + ... >>> s = SeqDict() >>> dir(s) # See that other dictionary methods are implemented ['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__', @@ -1779,7 +1779,7 @@ The help message is automatically generated for you:: set input filename -lLENGTH, --length=LENGTH set maximum length of output - $ + $ See the module's documentation for more details. diff --git a/Doc/whatsnew/2.4.rst b/Doc/whatsnew/2.4.rst index 59788ba..d608c2b 100644 --- a/Doc/whatsnew/2.4.rst +++ b/Doc/whatsnew/2.4.rst @@ -1,5 +1,5 @@ **************************** - What's New in Python 2.4 + What's New in Python 2.4 **************************** :Author: A.M. Kuchling @@ -63,10 +63,10 @@ symmetric differences. :: >>> a.add('z') # add a new element >>> a.update('wxy') # add multiple new elements >>> a - set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z']) + set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z']) >>> a.remove('x') # take one element out >>> a - set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z']) + set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z']) The :func:`frozenset` type is an immutable version of :func:`set`. Since it is immutable and hashable, it may be used as a dictionary key or as a member of @@ -351,7 +351,7 @@ iterator that loops over the elements of the sequence in reverse order. :: >>> for i in reversed(xrange(1,4)): ... print i - ... + ... 3 2 1 @@ -366,7 +366,7 @@ you want to reverse an iterator, first convert it to a list with :func:`list`. >>> input = open('/etc/passwd', 'r') >>> for line in reversed(list(input)): ... print line - ... + ... root:*:0:0:System Administrator:/var/root:/bin/tcsh ... @@ -650,7 +650,7 @@ the precision of the default context:: 28 >>> decimal.Decimal(1) / decimal.Decimal(7) Decimal("0.1428571428571428571428571429") - >>> decimal.getcontext().prec = 9 + >>> decimal.getcontext().prec = 9 >>> decimal.Decimal(1) / decimal.Decimal(7) Decimal("0.142857143") @@ -665,7 +665,7 @@ raised:: >>> decimal.getcontext().traps[decimal.DivisionByZero] = False >>> decimal.Decimal(1) / decimal.Decimal(0) Decimal("Infinity") - >>> + >>> The :class:`Context` instance also has various methods for formatting numbers such as :meth:`to_eng_string` and :meth:`to_sci_string`. @@ -803,7 +803,7 @@ Here are all of the changes that Python 2.4 makes to the core Python language. >>> 'www.python.org'.split('.', 1) ['www', 'python.org'] 'www.python.org'.rsplit('.', 1) - ['www.python', 'org'] + ['www.python', 'org'] * Three keyword parameters, *cmp*, *key*, and *reverse*, were added to the :meth:`sort` method of lists. These parameters make some common usages of @@ -1045,7 +1045,7 @@ complete list of changes, or look through the CVS logs for all the details. >>> list(d) # list the contents of the deque ['g', 'h', 'i'] >>> 'h' in d # search the deque - True + True Several modules, such as the :mod:`Queue` and :mod:`threading` modules, now take advantage of :class:`collections.deque` for improved performance. (Contributed @@ -1106,13 +1106,13 @@ complete list of changes, or look through the CVS logs for all the details. >>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14] >>> for key_val, it in itertools.groupby(L, lambda x: x % 2): ... print key_val, list(it) - ... + ... 0 [2, 4, 6] 1 [7] 0 [8] 1 [9, 11] 0 [12, 14] - >>> + >>> :func:`groupby` is typically used with sorted input. The logic for :func:`groupby` is similar to the Unix ``uniq`` filter which makes it handy for @@ -1120,21 +1120,21 @@ complete list of changes, or look through the CVS logs for all the details. >>> word = 'abracadabra' >>> letters = sorted(word) # Turn string into a sorted list of letters - >>> letters + >>> letters ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r'] >>> for k, g in itertools.groupby(letters): ... print k, list(g) - ... + ... a ['a', 'a', 'a', 'a', 'a'] b ['b', 'b'] c ['c'] d ['d'] r ['r', 'r'] >>> # List unique letters - >>> [k for k, g in groupby(letters)] + >>> [k for k, g in groupby(letters)] ['a', 'b', 'c', 'd', 'r'] >>> # Count letter occurrences - >>> [(k, len(list(g))) for k, g in groupby(letters)] + >>> [(k, len(list(g))) for k, g in groupby(letters)] [('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)] (Contributed by Hye-Shik Chang.) @@ -1175,7 +1175,7 @@ complete list of changes, or look through the CVS logs for all the details. import logging logging.basicConfig(filename='/var/log/application.log', level=0, # Log all messages - format='%(levelname):%(process):%(thread):%(message)') + format='%(levelname):%(process):%(thread):%(message)') Other additions to the :mod:`logging` package include a :meth:`log(level, msg)` convenience method, as well as a :class:`TimedRotatingFileHandler` class that diff --git a/Doc/whatsnew/2.5.rst b/Doc/whatsnew/2.5.rst index 43ba6e5..16350ac 100644 --- a/Doc/whatsnew/2.5.rst +++ b/Doc/whatsnew/2.5.rst @@ -1,5 +1,5 @@ **************************** - What's New in Python 2.5 + What's New in Python 2.5 **************************** :Author: A.M. Kuchling @@ -220,7 +220,7 @@ in the package index, determine the dependencies for a package, and download the required packages. :: VERSION = '1.0' - setup(name='PyPackage', + setup(name='PyPackage', version=VERSION, requires=['numarray', 'zlib (>=1.1.4)'], obsoletes=['OldPackage'] @@ -388,7 +388,7 @@ write:: else: else-block finally: - final-block + final-block The code in *block-1* is executed. If the code raises an exception, the various :keyword:`except` blocks are tested: if the exception is of class @@ -835,8 +835,8 @@ catch all exceptions, so you commonly need to list :exc:`KeyboardInterrupt` and ... except (KeyboardInterrupt, SystemExit): raise - except: - # Log error... + except: + # Log error... # Continue running program... In Python 2.5, you can now write ``except Exception`` to achieve the same @@ -947,7 +947,7 @@ arguments and returns an integer giving the slice index to use. For example:: class C: def __index__ (self): - return self.value + return self.value The return value must be either a Python integer or long integer. The interpreter will check that the type returned is correct, and raises a @@ -1035,9 +1035,9 @@ Here are all of the changes that Python 2.5 makes to the core Python language. L = ['medium', 'longest', 'short'] # Prints 'longest' - print max(L, key=len) + print max(L, key=len) # Prints 'short', because lexicographically 'short' has the largest value - print max(L) + print max(L) (Contributed by Steven Bethard and Raymond Hettinger.) @@ -1070,8 +1070,8 @@ Here are all of the changes that Python 2.5 makes to the core Python language. using the default ASCII encoding. The result of the comparison is false:: >>> chr(128) == unichr(128) # Can't convert chr(128) to Unicode - __main__:1: UnicodeWarning: Unicode equal comparison failed - to convert both arguments to Unicode - interpreting them + __main__:1: UnicodeWarning: Unicode equal comparison failed + to convert both arguments to Unicode - interpreting them as being unequal False >>> chr(127) == unichr(127) # chr(127) can be converted @@ -1259,10 +1259,10 @@ complete list of changes, or look through the SVN logs for all the details. Printing ``index`` results in the following output:: - defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'], - 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'], - 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'], - 'p': ['per'], 's': ['selva', 'smarrita'], + defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'], + 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'], + 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'], + 'p': ['per'], 's': ['selva', 'smarrita'], 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']} (Contributed by Guido van Rossum.) @@ -1884,17 +1884,17 @@ is that the constructor functions for creating new hashing objects are named differently. :: # Old versions - h = md5.md5() - h = md5.new() + h = md5.md5() + h = md5.new() - # New version + # New version h = hashlib.md5() # Old versions - h = sha.sha() - h = sha.new() + h = sha.sha() + h = sha.new() - # New version + # New version h = hashlib.sha1() # Hash that weren't previously available @@ -2191,7 +2191,7 @@ Changes to Python's build process and to the C API include: case that your extensions were using it, you can replace it by something like the following:: - range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll", + range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll", start, stop, step); .. ====================================================================== diff --git a/Doc/whatsnew/2.6.rst b/Doc/whatsnew/2.6.rst index d9a1993..750f7db 100644 --- a/Doc/whatsnew/2.6.rst +++ b/Doc/whatsnew/2.6.rst @@ -748,7 +748,7 @@ supply compound field names that read attributes or access dictionary keys:: >>> import sys >>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys) Platform: darwin - Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41) + Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41) [GCC 4.0.1 (Apple Computer, Inc. build 5367)]' >>> import mimetypes @@ -962,8 +962,8 @@ representing ``ABC``; in 2.6, ``bytes([65, 66, 67])`` returns the The primary use of :class:`bytes` in 2.6 will be to write tests of object type such as ``isinstance(x, bytes)``. This will help the 2to3 converter, which can't tell whether 2.x code intends strings to -contain either characters or 8-bit bytes; you can now -use either :class:`bytes` or :class:`str` to represent your intention +contain either characters or 8-bit bytes; you can now +use either :class:`bytes` or :class:`str` to represent your intention exactly, and the resulting code will also be correct in Python 3.0. There's also a ``__future__`` import that causes all string literals @@ -1838,9 +1838,9 @@ changes, or look through the Subversion logs for all the details. "/cgi-bin/add.py?category=1". (Contributed by Alexandre Fiori and Nubis; :issue:`1817`.) - The :func:`parse_qs` and :func:`parse_qsl` functions have been + The :func:`parse_qs` and :func:`parse_qsl` functions have been relocated from the :mod:`cgi` module to the :mod:`urlparse` module. - The versions still available in the :mod:`cgi` module will + The versions still available in the :mod:`cgi` module will trigger :exc:`PendingDeprecationWarning` messages in 2.6 (:issue:`600362`). @@ -1935,7 +1935,7 @@ changes, or look through the Subversion logs for all the details. * A new window method in the :mod:`curses` module, :meth:`chgat`, changes the display attributes for a certain number of characters on a single line. (Contributed by Fabian Kreutz.) - + :: # Boldface text starting at y=0,x=21 @@ -2432,9 +2432,9 @@ changes, or look through the Subversion logs for all the details. :issue:`742598`, :issue:`1193577`.) * The :mod:`sqlite3` module, maintained by Gerhard Haering, - has been updated from version 2.3.2 in Python 2.5 to + has been updated from version 2.3.2 in Python 2.5 to version 2.4.1. - + * The :mod:`struct` module now supports the C99 :ctype:`_Bool` type, using the format character ``'?'``. (Contributed by David Remahl.) @@ -2529,9 +2529,9 @@ changes, or look through the Subversion logs for all the details. ``with tempfile.NamedTemporaryFile() as tmp: ...``. (Contributed by Alexander Belopolsky; :issue:`2021`.) -* The :mod:`test.test_support` module gained a number - of context managers useful for writing tests. - :func:`EnvironmentVarGuard` is a +* The :mod:`test.test_support` module gained a number + of context managers useful for writing tests. + :func:`EnvironmentVarGuard` is a context manager that temporarily changes environment variables and automatically restores them to their old values. @@ -2546,7 +2546,7 @@ changes, or look through the Subversion logs for all the details. f = urllib.urlopen('https://sf.net') ... - Finally, :func:`check_warnings` resets the :mod:`warning` module's + Finally, :func:`check_warnings` resets the :mod:`warning` module's warning filters and returns an object that will record all warning messages triggered (:issue:`3781`):: @@ -2586,7 +2586,7 @@ changes, or look through the Subversion logs for all the details. :meth:`activeCount` method is renamed to :meth:`active_count`. Both the 2.6 and 3.0 versions of the module support the same properties and renamed methods, but don't remove the old methods. No date has been set - for the deprecation of the old APIs in Python 3.x; the old APIs won't + for the deprecation of the old APIs in Python 3.x; the old APIs won't be removed in any 2.x version. (Carried out by several people, most notably Benjamin Peterson.) @@ -2643,7 +2643,7 @@ changes, or look through the Subversion logs for all the details. (Added by Facundo Batista.) * The Unicode database provided by the :mod:`unicodedata` module - has been updated to version 5.1.0. (Updated by + has been updated to version 5.1.0. (Updated by Martin von Loewis; :issue:`3811`.) * The :mod:`warnings` module's :func:`formatwarning` and :func:`showwarning` @@ -2654,7 +2654,7 @@ changes, or look through the Subversion logs for all the details. A new function, :func:`catch_warnings`, is a context manager intended for testing purposes that lets you temporarily modify the warning filters and then restore their original values (:issue:`3781`). - + * The XML-RPC :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer` classes can now be prevented from immediately opening and binding to their socket by passing True as the ``bind_and_activate`` @@ -3224,8 +3224,8 @@ that may require changes to your code: * :meth:`object.__init__` previously accepted arbitrary arguments and keyword arguments, ignoring them. In Python 2.6, this is no longer - allowed and will result in a :exc:`TypeError`. This will affect - :meth:`__init__` methods that end up calling the corresponding + allowed and will result in a :exc:`TypeError`. This will affect + :meth:`__init__` methods that end up calling the corresponding method on :class:`object` (perhaps through using :func:`super`). See :issue:`1683368` for discussion. @@ -3285,7 +3285,7 @@ Acknowledgements The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this -article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy, -Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr, +article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy, +Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr, Antoine Pitrou, Brian Warner. diff --git a/Doc/whatsnew/3.0.rst b/Doc/whatsnew/3.0.rst index 678ad80..fcdca04 100644 --- a/Doc/whatsnew/3.0.rst +++ b/Doc/whatsnew/3.0.rst @@ -1,5 +1,5 @@ **************************** - What's New In Python 3.0 + What's New In Python 3.0 **************************** .. XXX Add trademark info for Apple, Microsoft. @@ -10,45 +10,45 @@ .. $Id$ Rules for maintenance: - + * Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree. - + * The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file. (Note: I didn't get to this for 3.0. GvR.) - + * This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.) - + * If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section. - + * It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text. - + * You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away). - + * Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary. (Due to time constraints I haven't managed to do this for 3.0. GvR.) - + * It's helpful to add the bug/patch number as a comment: - + % Patch 12345 XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer.) - + This saves the maintainer the effort of going through the SVN log when researching a change. (Again, I didn't get to this for 3.0. GvR.) @@ -819,7 +819,7 @@ Builtins need it; however, 99 percent of the time an explicit :keyword:`for` loop is more readable. -* Removed :func:`reload`. Use :func:`imp.reload`. +* Removed :func:`reload`. Use :func:`imp.reload`. * Removed. :meth:`dict.has_key` -- use the :keyword:`in` operator instead. diff --git a/Doc/whatsnew/3.1.rst b/Doc/whatsnew/3.1.rst index 7df4d1e..68a76f3 100644 --- a/Doc/whatsnew/3.1.rst +++ b/Doc/whatsnew/3.1.rst @@ -1,5 +1,5 @@ **************************** - What's New In Python 3.1 + What's New In Python 3.1 **************************** .. XXX Add trademark info for Apple, Microsoft. @@ -10,45 +10,45 @@ .. $Id$ Rules for maintenance: - + * Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree. - + * The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file. (Note: I didn't get to this for 3.0. GvR.) - + * This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.) - + * If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section. - + * It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text. - + * You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away). - + * Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary. (Due to time constraints I haven't managed to do this for 3.0. GvR.) - + * It's helpful to add the bug/patch number as a comment: - + % Patch 12345 XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer.) - + This saves the maintainer the effort of going through the SVN log when researching a change. (Again, I didn't get to this for 3.0. GvR.) |