diff --git a/cpython_2/environment/repo/Doc/library/filecmp.rst b/cpython_2/environment/repo/Doc/library/filecmp.rst new file mode 100644 index 0000000000000000000000000000000000000000..31b9b4afab93489527f893ec0b3de5dd61951410 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/filecmp.rst @@ -0,0 +1,198 @@ +:mod:`filecmp` --- File and Directory Comparisons +================================================= + +.. module:: filecmp + :synopsis: Compare files efficiently. + +.. sectionauthor:: Moshe Zadka + +**Source code:** :source:`Lib/filecmp.py` + +-------------- + +The :mod:`filecmp` module defines functions to compare files and directories, +with various optional time/correctness trade-offs. For comparing files, +see also the :mod:`difflib` module. + +The :mod:`filecmp` module defines the following functions: + + +.. function:: cmp(f1, f2, shallow=True) + + Compare the files named *f1* and *f2*, returning ``True`` if they seem equal, + ``False`` otherwise. + + If *shallow* is true, files with identical :func:`os.stat` signatures are + taken to be equal. Otherwise, the contents of the files are compared. + + Note that no external programs are called from this function, giving it + portability and efficiency. + + This function uses a cache for past comparisons and the results, + with cache entries invalidated if the :func:`os.stat` information for the + file changes. The entire cache may be cleared using :func:`clear_cache`. + + +.. function:: cmpfiles(dir1, dir2, common, shallow=True) + + Compare the files in the two directories *dir1* and *dir2* whose names are + given by *common*. + + Returns three lists of file names: *match*, *mismatch*, + *errors*. *match* contains the list of files that match, *mismatch* contains + the names of those that don't, and *errors* lists the names of files which + could not be compared. Files are listed in *errors* if they don't exist in + one of the directories, the user lacks permission to read them or if the + comparison could not be done for some other reason. + + The *shallow* parameter has the same meaning and default value as for + :func:`filecmp.cmp`. + + For example, ``cmpfiles('a', 'b', ['c', 'd/e'])`` will compare ``a/c`` with + ``b/c`` and ``a/d/e`` with ``b/d/e``. ``'c'`` and ``'d/e'`` will each be in + one of the three returned lists. + + +.. function:: clear_cache() + + Clear the filecmp cache. This may be useful if a file is compared so quickly + after it is modified that it is within the mtime resolution of + the underlying filesystem. + + .. versionadded:: 3.4 + + +.. _dircmp-objects: + +The :class:`dircmp` class +------------------------- + +.. class:: dircmp(a, b, ignore=None, hide=None) + + Construct a new directory comparison object, to compare the directories *a* + and *b*. *ignore* is a list of names to ignore, and defaults to + :attr:`filecmp.DEFAULT_IGNORES`. *hide* is a list of names to hide, and + defaults to ``[os.curdir, os.pardir]``. + + The :class:`dircmp` class compares files by doing *shallow* comparisons + as described for :func:`filecmp.cmp`. + + The :class:`dircmp` class provides the following methods: + + .. method:: report() + + Print (to :data:`sys.stdout`) a comparison between *a* and *b*. + + .. method:: report_partial_closure() + + Print a comparison between *a* and *b* and common immediate + subdirectories. + + .. method:: report_full_closure() + + Print a comparison between *a* and *b* and common subdirectories + (recursively). + + The :class:`dircmp` class offers a number of interesting attributes that may be + used to get various bits of information about the directory trees being + compared. + + Note that via :meth:`__getattr__` hooks, all attributes are computed lazily, + so there is no speed penalty if only those attributes which are lightweight + to compute are used. + + + .. attribute:: left + + The directory *a*. + + + .. attribute:: right + + The directory *b*. + + + .. attribute:: left_list + + Files and subdirectories in *a*, filtered by *hide* and *ignore*. + + + .. attribute:: right_list + + Files and subdirectories in *b*, filtered by *hide* and *ignore*. + + + .. attribute:: common + + Files and subdirectories in both *a* and *b*. + + + .. attribute:: left_only + + Files and subdirectories only in *a*. + + + .. attribute:: right_only + + Files and subdirectories only in *b*. + + + .. attribute:: common_dirs + + Subdirectories in both *a* and *b*. + + + .. attribute:: common_files + + Files in both *a* and *b*. + + + .. attribute:: common_funny + + Names in both *a* and *b*, such that the type differs between the + directories, or names for which :func:`os.stat` reports an error. + + + .. attribute:: same_files + + Files which are identical in both *a* and *b*, using the class's + file comparison operator. + + + .. attribute:: diff_files + + Files which are in both *a* and *b*, whose contents differ according + to the class's file comparison operator. + + + .. attribute:: funny_files + + Files which are in both *a* and *b*, but could not be compared. + + + .. attribute:: subdirs + + A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` + objects. + +.. attribute:: DEFAULT_IGNORES + + .. versionadded:: 3.4 + + List of directories ignored by :class:`dircmp` by default. + + +Here is a simplified example of using the ``subdirs`` attribute to search +recursively through two directories to show common different files:: + + >>> from filecmp import dircmp + >>> def print_diff_files(dcmp): + ... for name in dcmp.diff_files: + ... print("diff_file %s found in %s and %s" % (name, dcmp.left, + ... dcmp.right)) + ... for sub_dcmp in dcmp.subdirs.values(): + ... print_diff_files(sub_dcmp) + ... + >>> dcmp = dircmp('dir1', 'dir2') # doctest: +SKIP + >>> print_diff_files(dcmp) # doctest: +SKIP + diff --git a/cpython_2/environment/repo/Doc/library/fileformats.rst b/cpython_2/environment/repo/Doc/library/fileformats.rst new file mode 100644 index 0000000000000000000000000000000000000000..e9c2e1fbbdf3e8975400c8f1bb67f36e11f822df --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/fileformats.rst @@ -0,0 +1,17 @@ +.. _fileformats: + +************ +File Formats +************ + +The modules described in this chapter parse various miscellaneous file formats +that aren't markup languages and are not related to e-mail. + + +.. toctree:: + + csv.rst + configparser.rst + netrc.rst + xdrlib.rst + plistlib.rst diff --git a/cpython_2/environment/repo/Doc/library/fileinput.rst b/cpython_2/environment/repo/Doc/library/fileinput.rst new file mode 100644 index 0000000000000000000000000000000000000000..cc4039a30e38ae45c3bacff1cae9c77bc851261f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/fileinput.rst @@ -0,0 +1,214 @@ +:mod:`fileinput` --- Iterate over lines from multiple input streams +=================================================================== + +.. module:: fileinput + :synopsis: Loop over standard input or a list of files. + +.. moduleauthor:: Guido van Rossum +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/fileinput.py` + +-------------- + +This module implements a helper class and functions to quickly write a +loop over standard input or a list of files. If you just want to read or +write one file see :func:`open`. + +The typical use is:: + + import fileinput + for line in fileinput.input(): + process(line) + +This iterates over the lines of all files listed in ``sys.argv[1:]``, defaulting +to ``sys.stdin`` if the list is empty. If a filename is ``'-'``, it is also +replaced by ``sys.stdin`` and the optional arguments *mode* and *openhook* +are ignored. To specify an alternative list of filenames, pass it as the +first argument to :func:`.input`. A single file name is also allowed. + +All files are opened in text mode by default, but you can override this by +specifying the *mode* parameter in the call to :func:`.input` or +:class:`FileInput`. If an I/O error occurs during opening or reading a file, +:exc:`OSError` is raised. + +.. versionchanged:: 3.3 + :exc:`IOError` used to be raised; it is now an alias of :exc:`OSError`. + +If ``sys.stdin`` is used more than once, the second and further use will return +no lines, except perhaps for interactive use, or if it has been explicitly reset +(e.g. using ``sys.stdin.seek(0)``). + +Empty files are opened and immediately closed; the only time their presence in +the list of filenames is noticeable at all is when the last file opened is +empty. + +Lines are returned with any newlines intact, which means that the last line in +a file may not have one. + +You can control how files are opened by providing an opening hook via the +*openhook* parameter to :func:`fileinput.input` or :class:`FileInput()`. The +hook must be a function that takes two arguments, *filename* and *mode*, and +returns an accordingly opened file-like object. Two useful hooks are already +provided by this module. + +The following function is the primary interface of this module: + + +.. function:: input(files=None, inplace=False, backup='', *, mode='r', openhook=None) + + Create an instance of the :class:`FileInput` class. The instance will be used + as global state for the functions of this module, and is also returned to use + during iteration. The parameters to this function will be passed along to the + constructor of the :class:`FileInput` class. + + The :class:`FileInput` instance can be used as a context manager in the + :keyword:`with` statement. In this example, *input* is closed after the + :keyword:`!with` statement is exited, even if an exception occurs:: + + with fileinput.input(files=('spam.txt', 'eggs.txt')) as f: + for line in f: + process(line) + + .. versionchanged:: 3.2 + Can be used as a context manager. + + .. versionchanged:: 3.8 + The keyword parameters *mode* and *openhook* are now keyword-only. + + +The following functions use the global state created by :func:`fileinput.input`; +if there is no active state, :exc:`RuntimeError` is raised. + + +.. function:: filename() + + Return the name of the file currently being read. Before the first line has + been read, returns ``None``. + + +.. function:: fileno() + + Return the integer "file descriptor" for the current file. When no file is + opened (before the first line and between files), returns ``-1``. + + +.. function:: lineno() + + Return the cumulative line number of the line that has just been read. Before + the first line has been read, returns ``0``. After the last line of the last + file has been read, returns the line number of that line. + + +.. function:: filelineno() + + Return the line number in the current file. Before the first line has been + read, returns ``0``. After the last line of the last file has been read, + returns the line number of that line within the file. + + +.. function:: isfirstline() + + Return ``True`` if the line just read is the first line of its file, otherwise + return ``False``. + + +.. function:: isstdin() + + Return ``True`` if the last line was read from ``sys.stdin``, otherwise return + ``False``. + + +.. function:: nextfile() + + Close the current file so that the next iteration will read the first line from + the next file (if any); lines not read from the file will not count towards the + cumulative line count. The filename is not changed until after the first line + of the next file has been read. Before the first line has been read, this + function has no effect; it cannot be used to skip the first file. After the + last line of the last file has been read, this function has no effect. + + +.. function:: close() + + Close the sequence. + +The class which implements the sequence behavior provided by the module is +available for subclassing as well: + + +.. class:: FileInput(files=None, inplace=False, backup='', *, mode='r', openhook=None) + + Class :class:`FileInput` is the implementation; its methods :meth:`filename`, + :meth:`fileno`, :meth:`lineno`, :meth:`filelineno`, :meth:`isfirstline`, + :meth:`isstdin`, :meth:`nextfile` and :meth:`close` correspond to the + functions of the same name in the module. In addition it has a + :meth:`~io.TextIOBase.readline` method which returns the next input line, + and a :meth:`__getitem__` method which implements the sequence behavior. + The sequence must be accessed in strictly sequential order; random access + and :meth:`~io.TextIOBase.readline` cannot be mixed. + + With *mode* you can specify which file mode will be passed to :func:`open`. It + must be one of ``'r'``, ``'rU'``, ``'U'`` and ``'rb'``. + + The *openhook*, when given, must be a function that takes two arguments, + *filename* and *mode*, and returns an accordingly opened file-like object. You + cannot use *inplace* and *openhook* together. + + A :class:`FileInput` instance can be used as a context manager in the + :keyword:`with` statement. In this example, *input* is closed after the + :keyword:`!with` statement is exited, even if an exception occurs:: + + with FileInput(files=('spam.txt', 'eggs.txt')) as input: + process(input) + + + .. versionchanged:: 3.2 + Can be used as a context manager. + + .. deprecated:: 3.4 + The ``'rU'`` and ``'U'`` modes. + + .. deprecated:: 3.8 + Support for :meth:`__getitem__` method is deprecated. + + .. versionchanged:: 3.8 + The keyword parameter *mode* and *openhook* are now keyword-only. + + + +**Optional in-place filtering:** if the keyword argument ``inplace=True`` is +passed to :func:`fileinput.input` or to the :class:`FileInput` constructor, the +file is moved to a backup file and standard output is directed to the input file +(if a file of the same name as the backup file already exists, it will be +replaced silently). This makes it possible to write a filter that rewrites its +input file in place. If the *backup* parameter is given (typically as +``backup='.'``), it specifies the extension for the backup file, +and the backup file remains around; by default, the extension is ``'.bak'`` and +it is deleted when the output file is closed. In-place filtering is disabled +when standard input is read. + + +The two following opening hooks are provided by this module: + +.. function:: hook_compressed(filename, mode) + + Transparently opens files compressed with gzip and bzip2 (recognized by the + extensions ``'.gz'`` and ``'.bz2'``) using the :mod:`gzip` and :mod:`bz2` + modules. If the filename extension is not ``'.gz'`` or ``'.bz2'``, the file is + opened normally (ie, using :func:`open` without any decompression). + + Usage example: ``fi = fileinput.FileInput(openhook=fileinput.hook_compressed)`` + + +.. function:: hook_encoded(encoding, errors=None) + + Returns a hook which opens each file with :func:`open`, using the given + *encoding* and *errors* to read the file. + + Usage example: ``fi = + fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8", + "surrogateescape"))`` + + .. versionchanged:: 3.6 + Added the optional *errors* parameter. diff --git a/cpython_2/environment/repo/Doc/library/filesys.rst b/cpython_2/environment/repo/Doc/library/filesys.rst new file mode 100644 index 0000000000000000000000000000000000000000..0ccf2b7bf59a0fb5b1801c6f85db051997faccff --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/filesys.rst @@ -0,0 +1,38 @@ +.. _filesys: + +************************* +File and Directory Access +************************* + +The modules described in this chapter deal with disk files and directories. For +example, there are modules for reading the properties of files, manipulating +paths in a portable way, and creating temporary files. The full list of modules +in this chapter is: + + +.. toctree:: + + pathlib.rst + os.path.rst + fileinput.rst + stat.rst + filecmp.rst + tempfile.rst + glob.rst + fnmatch.rst + linecache.rst + shutil.rst + + +.. seealso:: + + Module :mod:`os` + Operating system interfaces, including functions to work with files at a + lower level than Python :term:`file objects `. + + Module :mod:`io` + Python's built-in I/O library, including both abstract classes and + some concrete classes such as file I/O. + + Built-in function :func:`open` + The standard way to open files for reading and writing with Python. diff --git a/cpython_2/environment/repo/Doc/library/fnmatch.rst b/cpython_2/environment/repo/Doc/library/fnmatch.rst new file mode 100644 index 0000000000000000000000000000000000000000..ce07d326b395d80605e4b712343a6b79feb5a37e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/fnmatch.rst @@ -0,0 +1,102 @@ +:mod:`fnmatch` --- Unix filename pattern matching +================================================= + +.. module:: fnmatch + :synopsis: Unix shell style filename pattern matching. + +**Source code:** :source:`Lib/fnmatch.py` + +.. index:: single: filenames; wildcard expansion + +.. index:: module: re + +-------------- + +This module provides support for Unix shell-style wildcards, which are *not* the +same as regular expressions (which are documented in the :mod:`re` module). The +special characters used in shell-style wildcards are: + +.. index:: + single: * (asterisk); in glob-style wildcards + single: ? (question mark); in glob-style wildcards + single: [] (square brackets); in glob-style wildcards + single: ! (exclamation); in glob-style wildcards + single: - (minus); in glob-style wildcards + ++------------+------------------------------------+ +| Pattern | Meaning | ++============+====================================+ +| ``*`` | matches everything | ++------------+------------------------------------+ +| ``?`` | matches any single character | ++------------+------------------------------------+ +| ``[seq]`` | matches any character in *seq* | ++------------+------------------------------------+ +| ``[!seq]`` | matches any character not in *seq* | ++------------+------------------------------------+ + +For a literal match, wrap the meta-characters in brackets. +For example, ``'[?]'`` matches the character ``'?'``. + +.. index:: module: glob + +Note that the filename separator (``'/'`` on Unix) is *not* special to this +module. See module :mod:`glob` for pathname expansion (:mod:`glob` uses +:func:`.filter` to match pathname segments). Similarly, filenames starting with +a period are not special for this module, and are matched by the ``*`` and ``?`` +patterns. + + +.. function:: fnmatch(filename, pattern) + + Test whether the *filename* string matches the *pattern* string, returning + :const:`True` or :const:`False`. Both parameters are case-normalized + using :func:`os.path.normcase`. :func:`fnmatchcase` can be used to perform a + case-sensitive comparison, regardless of whether that's standard for the + operating system. + + This example will print all file names in the current directory with the + extension ``.txt``:: + + import fnmatch + import os + + for file in os.listdir('.'): + if fnmatch.fnmatch(file, '*.txt'): + print(file) + + +.. function:: fnmatchcase(filename, pattern) + + Test whether *filename* matches *pattern*, returning :const:`True` or + :const:`False`; the comparison is case-sensitive and does not apply + :func:`os.path.normcase`. + + +.. function:: filter(names, pattern) + + Return the subset of the list of *names* that match *pattern*. It is the same as + ``[n for n in names if fnmatch(n, pattern)]``, but implemented more efficiently. + + +.. function:: translate(pattern) + + Return the shell-style *pattern* converted to a regular expression for + using with :func:`re.match`. + + Example: + + >>> import fnmatch, re + >>> + >>> regex = fnmatch.translate('*.txt') + >>> regex + '(?s:.*\\.txt)\\Z' + >>> reobj = re.compile(regex) + >>> reobj.match('foobar.txt') + + + +.. seealso:: + + Module :mod:`glob` + Unix shell-style path expansion. diff --git a/cpython_2/environment/repo/Doc/library/formatter.rst b/cpython_2/environment/repo/Doc/library/formatter.rst new file mode 100644 index 0000000000000000000000000000000000000000..6c10ac6fab50e47db0e903510ad2ea575a0b5050 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/formatter.rst @@ -0,0 +1,351 @@ +:mod:`formatter` --- Generic output formatting +============================================== + +.. module:: formatter + :synopsis: Generic output formatter and device interface. + :deprecated: + +.. deprecated:: 3.4 + Due to lack of usage, the formatter module has been deprecated. + +-------------- + +This module supports two interface definitions, each with multiple +implementations: The *formatter* interface, and the *writer* interface which is +required by the formatter interface. + +Formatter objects transform an abstract flow of formatting events into specific +output events on writer objects. Formatters manage several stack structures to +allow various properties of a writer object to be changed and restored; writers +need not be able to handle relative changes nor any sort of "change back" +operation. Specific writer properties which may be controlled via formatter +objects are horizontal alignment, font, and left margin indentations. A +mechanism is provided which supports providing arbitrary, non-exclusive style +settings to a writer as well. Additional interfaces facilitate formatting +events which are not reversible, such as paragraph separation. + +Writer objects encapsulate device interfaces. Abstract devices, such as file +formats, are supported as well as physical devices. The provided +implementations all work with abstract devices. The interface makes available +mechanisms for setting the properties which formatter objects manage and +inserting data into the output. + + +.. _formatter-interface: + +The Formatter Interface +----------------------- + +Interfaces to create formatters are dependent on the specific formatter class +being instantiated. The interfaces described below are the required interfaces +which all formatters must support once initialized. + +One data element is defined at the module level: + + +.. data:: AS_IS + + Value which can be used in the font specification passed to the ``push_font()`` + method described below, or as the new value to any other ``push_property()`` + method. Pushing the ``AS_IS`` value allows the corresponding ``pop_property()`` + method to be called without having to track whether the property was changed. + +The following attributes are defined for formatter instance objects: + + +.. attribute:: formatter.writer + + The writer instance with which the formatter interacts. + + +.. method:: formatter.end_paragraph(blanklines) + + Close any open paragraphs and insert at least *blanklines* before the next + paragraph. + + +.. method:: formatter.add_line_break() + + Add a hard line break if one does not already exist. This does not break the + logical paragraph. + + +.. method:: formatter.add_hor_rule(*args, **kw) + + Insert a horizontal rule in the output. A hard break is inserted if there is + data in the current paragraph, but the logical paragraph is not broken. The + arguments and keywords are passed on to the writer's :meth:`send_line_break` + method. + + +.. method:: formatter.add_flowing_data(data) + + Provide data which should be formatted with collapsed whitespace. Whitespace + from preceding and successive calls to :meth:`add_flowing_data` is considered as + well when the whitespace collapse is performed. The data which is passed to + this method is expected to be word-wrapped by the output device. Note that any + word-wrapping still must be performed by the writer object due to the need to + rely on device and font information. + + +.. method:: formatter.add_literal_data(data) + + Provide data which should be passed to the writer unchanged. Whitespace, + including newline and tab characters, are considered legal in the value of + *data*. + + +.. method:: formatter.add_label_data(format, counter) + + Insert a label which should be placed to the left of the current left margin. + This should be used for constructing bulleted or numbered lists. If the + *format* value is a string, it is interpreted as a format specification for + *counter*, which should be an integer. The result of this formatting becomes the + value of the label; if *format* is not a string it is used as the label value + directly. The label value is passed as the only argument to the writer's + :meth:`send_label_data` method. Interpretation of non-string label values is + dependent on the associated writer. + + Format specifications are strings which, in combination with a counter value, + are used to compute label values. Each character in the format string is copied + to the label value, with some characters recognized to indicate a transform on + the counter value. Specifically, the character ``'1'`` represents the counter + value formatter as an Arabic number, the characters ``'A'`` and ``'a'`` + represent alphabetic representations of the counter value in upper and lower + case, respectively, and ``'I'`` and ``'i'`` represent the counter value in Roman + numerals, in upper and lower case. Note that the alphabetic and roman + transforms require that the counter value be greater than zero. + + +.. method:: formatter.flush_softspace() + + Send any pending whitespace buffered from a previous call to + :meth:`add_flowing_data` to the associated writer object. This should be called + before any direct manipulation of the writer object. + + +.. method:: formatter.push_alignment(align) + + Push a new alignment setting onto the alignment stack. This may be + :const:`AS_IS` if no change is desired. If the alignment value is changed from + the previous setting, the writer's :meth:`new_alignment` method is called with + the *align* value. + + +.. method:: formatter.pop_alignment() + + Restore the previous alignment. + + +.. method:: formatter.push_font((size, italic, bold, teletype)) + + Change some or all font properties of the writer object. Properties which are + not set to :const:`AS_IS` are set to the values passed in while others are + maintained at their current settings. The writer's :meth:`new_font` method is + called with the fully resolved font specification. + + +.. method:: formatter.pop_font() + + Restore the previous font. + + +.. method:: formatter.push_margin(margin) + + Increase the number of left margin indentations by one, associating the logical + tag *margin* with the new indentation. The initial margin level is ``0``. + Changed values of the logical tag must be true values; false values other than + :const:`AS_IS` are not sufficient to change the margin. + + +.. method:: formatter.pop_margin() + + Restore the previous margin. + + +.. method:: formatter.push_style(*styles) + + Push any number of arbitrary style specifications. All styles are pushed onto + the styles stack in order. A tuple representing the entire stack, including + :const:`AS_IS` values, is passed to the writer's :meth:`new_styles` method. + + +.. method:: formatter.pop_style(n=1) + + Pop the last *n* style specifications passed to :meth:`push_style`. A tuple + representing the revised stack, including :const:`AS_IS` values, is passed to + the writer's :meth:`new_styles` method. + + +.. method:: formatter.set_spacing(spacing) + + Set the spacing style for the writer. + + +.. method:: formatter.assert_line_data(flag=1) + + Inform the formatter that data has been added to the current paragraph + out-of-band. This should be used when the writer has been manipulated + directly. The optional *flag* argument can be set to false if the writer + manipulations produced a hard line break at the end of the output. + + +.. _formatter-impls: + +Formatter Implementations +------------------------- + +Two implementations of formatter objects are provided by this module. Most +applications may use one of these classes without modification or subclassing. + + +.. class:: NullFormatter(writer=None) + + A formatter which does nothing. If *writer* is omitted, a :class:`NullWriter` + instance is created. No methods of the writer are called by + :class:`NullFormatter` instances. Implementations should inherit from this + class if implementing a writer interface but don't need to inherit any + implementation. + + +.. class:: AbstractFormatter(writer) + + The standard formatter. This implementation has demonstrated wide applicability + to many writers, and may be used directly in most circumstances. It has been + used to implement a full-featured World Wide Web browser. + + +.. _writer-interface: + +The Writer Interface +-------------------- + +Interfaces to create writers are dependent on the specific writer class being +instantiated. The interfaces described below are the required interfaces which +all writers must support once initialized. Note that while most applications can +use the :class:`AbstractFormatter` class as a formatter, the writer must +typically be provided by the application. + + +.. method:: writer.flush() + + Flush any buffered output or device control events. + + +.. method:: writer.new_alignment(align) + + Set the alignment style. The *align* value can be any object, but by convention + is a string or ``None``, where ``None`` indicates that the writer's "preferred" + alignment should be used. Conventional *align* values are ``'left'``, + ``'center'``, ``'right'``, and ``'justify'``. + + +.. method:: writer.new_font(font) + + Set the font style. The value of *font* will be ``None``, indicating that the + device's default font should be used, or a tuple of the form ``(size, + italic, bold, teletype)``. Size will be a string indicating the size of + font that should be used; specific strings and their interpretation must be + defined by the application. The *italic*, *bold*, and *teletype* values are + Boolean values specifying which of those font attributes should be used. + + +.. method:: writer.new_margin(margin, level) + + Set the margin level to the integer *level* and the logical tag to *margin*. + Interpretation of the logical tag is at the writer's discretion; the only + restriction on the value of the logical tag is that it not be a false value for + non-zero values of *level*. + + +.. method:: writer.new_spacing(spacing) + + Set the spacing style to *spacing*. + + +.. method:: writer.new_styles(styles) + + Set additional styles. The *styles* value is a tuple of arbitrary values; the + value :const:`AS_IS` should be ignored. The *styles* tuple may be interpreted + either as a set or as a stack depending on the requirements of the application + and writer implementation. + + +.. method:: writer.send_line_break() + + Break the current line. + + +.. method:: writer.send_paragraph(blankline) + + Produce a paragraph separation of at least *blankline* blank lines, or the + equivalent. The *blankline* value will be an integer. Note that the + implementation will receive a call to :meth:`send_line_break` before this call + if a line break is needed; this method should not include ending the last line + of the paragraph. It is only responsible for vertical spacing between + paragraphs. + + +.. method:: writer.send_hor_rule(*args, **kw) + + Display a horizontal rule on the output device. The arguments to this method + are entirely application- and writer-specific, and should be interpreted with + care. The method implementation may assume that a line break has already been + issued via :meth:`send_line_break`. + + +.. method:: writer.send_flowing_data(data) + + Output character data which may be word-wrapped and re-flowed as needed. Within + any sequence of calls to this method, the writer may assume that spans of + multiple whitespace characters have been collapsed to single space characters. + + +.. method:: writer.send_literal_data(data) + + Output character data which has already been formatted for display. Generally, + this should be interpreted to mean that line breaks indicated by newline + characters should be preserved and no new line breaks should be introduced. The + data may contain embedded newline and tab characters, unlike data provided to + the :meth:`send_formatted_data` interface. + + +.. method:: writer.send_label_data(data) + + Set *data* to the left of the current left margin, if possible. The value of + *data* is not restricted; treatment of non-string values is entirely + application- and writer-dependent. This method will only be called at the + beginning of a line. + + +.. _writer-impls: + +Writer Implementations +---------------------- + +Three implementations of the writer object interface are provided as examples by +this module. Most applications will need to derive new writer classes from the +:class:`NullWriter` class. + + +.. class:: NullWriter() + + A writer which only provides the interface definition; no actions are taken on + any methods. This should be the base class for all writers which do not need to + inherit any implementation methods. + + +.. class:: AbstractWriter() + + A writer which can be used in debugging formatters, but not much else. Each + method simply announces itself by printing its name and arguments on standard + output. + + +.. class:: DumbWriter(file=None, maxcol=72) + + Simple writer class which writes output on the :term:`file object` passed + in as *file* or, if *file* is omitted, on standard output. The output is + simply word-wrapped to the number of columns specified by *maxcol*. This + class is suitable for reflowing a sequence of paragraphs. + diff --git a/cpython_2/environment/repo/Doc/library/fractions.rst b/cpython_2/environment/repo/Doc/library/fractions.rst new file mode 100644 index 0000000000000000000000000000000000000000..a4d006eb58ffeb487aba0d1688fa6911dceb4f74 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/fractions.rst @@ -0,0 +1,182 @@ +:mod:`fractions` --- Rational numbers +===================================== + +.. module:: fractions + :synopsis: Rational numbers. + +.. moduleauthor:: Jeffrey Yasskin +.. sectionauthor:: Jeffrey Yasskin + +**Source code:** :source:`Lib/fractions.py` + +-------------- + +The :mod:`fractions` module provides support for rational number arithmetic. + + +A Fraction instance can be constructed from a pair of integers, from +another rational number, or from a string. + +.. class:: Fraction(numerator=0, denominator=1) + Fraction(other_fraction) + Fraction(float) + Fraction(decimal) + Fraction(string) + + The first version requires that *numerator* and *denominator* are instances + of :class:`numbers.Rational` and returns a new :class:`Fraction` instance + with value ``numerator/denominator``. If *denominator* is :const:`0`, it + raises a :exc:`ZeroDivisionError`. The second version requires that + *other_fraction* is an instance of :class:`numbers.Rational` and returns a + :class:`Fraction` instance with the same value. The next two versions accept + either a :class:`float` or a :class:`decimal.Decimal` instance, and return a + :class:`Fraction` instance with exactly the same value. Note that due to the + usual issues with binary floating-point (see :ref:`tut-fp-issues`), the + argument to ``Fraction(1.1)`` is not exactly equal to 11/10, and so + ``Fraction(1.1)`` does *not* return ``Fraction(11, 10)`` as one might expect. + (But see the documentation for the :meth:`limit_denominator` method below.) + The last version of the constructor expects a string or unicode instance. + The usual form for this instance is:: + + [sign] numerator ['/' denominator] + + where the optional ``sign`` may be either '+' or '-' and + ``numerator`` and ``denominator`` (if present) are strings of + decimal digits. In addition, any string that represents a finite + value and is accepted by the :class:`float` constructor is also + accepted by the :class:`Fraction` constructor. In either form the + input string may also have leading and/or trailing whitespace. + Here are some examples:: + + >>> from fractions import Fraction + >>> Fraction(16, -10) + Fraction(-8, 5) + >>> Fraction(123) + Fraction(123, 1) + >>> Fraction() + Fraction(0, 1) + >>> Fraction('3/7') + Fraction(3, 7) + >>> Fraction(' -3/7 ') + Fraction(-3, 7) + >>> Fraction('1.414213 \t\n') + Fraction(1414213, 1000000) + >>> Fraction('-.125') + Fraction(-1, 8) + >>> Fraction('7e-6') + Fraction(7, 1000000) + >>> Fraction(2.25) + Fraction(9, 4) + >>> Fraction(1.1) + Fraction(2476979795053773, 2251799813685248) + >>> from decimal import Decimal + >>> Fraction(Decimal('1.1')) + Fraction(11, 10) + + + The :class:`Fraction` class inherits from the abstract base class + :class:`numbers.Rational`, and implements all of the methods and + operations from that class. :class:`Fraction` instances are hashable, + and should be treated as immutable. In addition, + :class:`Fraction` has the following properties and methods: + + .. versionchanged:: 3.2 + The :class:`Fraction` constructor now accepts :class:`float` and + :class:`decimal.Decimal` instances. + + .. versionchanged:: 3.9 + The :func:`math.gcd` function is now used to normalize the *numerator* + and *denominator*. :func:`math.gcd` always return a :class:`int` type. + Previously, the GCD type depended on *numerator* and *denominator*. + + .. attribute:: numerator + + Numerator of the Fraction in lowest term. + + .. attribute:: denominator + + Denominator of the Fraction in lowest term. + + + .. method:: as_integer_ratio() + + Return a tuple of two integers, whose ratio is equal + to the Fraction and with a positive denominator. + + .. versionadded:: 3.8 + + .. method:: from_float(flt) + + This class method constructs a :class:`Fraction` representing the exact + value of *flt*, which must be a :class:`float`. Beware that + ``Fraction.from_float(0.3)`` is not the same value as ``Fraction(3, 10)``. + + .. note:: + + From Python 3.2 onwards, you can also construct a + :class:`Fraction` instance directly from a :class:`float`. + + + .. method:: from_decimal(dec) + + This class method constructs a :class:`Fraction` representing the exact + value of *dec*, which must be a :class:`decimal.Decimal` instance. + + .. note:: + + From Python 3.2 onwards, you can also construct a + :class:`Fraction` instance directly from a :class:`decimal.Decimal` + instance. + + + .. method:: limit_denominator(max_denominator=1000000) + + Finds and returns the closest :class:`Fraction` to ``self`` that has + denominator at most max_denominator. This method is useful for finding + rational approximations to a given floating-point number: + + >>> from fractions import Fraction + >>> Fraction('3.1415926535897932').limit_denominator(1000) + Fraction(355, 113) + + or for recovering a rational number that's represented as a float: + + >>> from math import pi, cos + >>> Fraction(cos(pi/3)) + Fraction(4503599627370497, 9007199254740992) + >>> Fraction(cos(pi/3)).limit_denominator() + Fraction(1, 2) + >>> Fraction(1.1).limit_denominator() + Fraction(11, 10) + + + .. method:: __floor__() + + Returns the greatest :class:`int` ``<= self``. This method can + also be accessed through the :func:`math.floor` function: + + >>> from math import floor + >>> floor(Fraction(355, 113)) + 3 + + + .. method:: __ceil__() + + Returns the least :class:`int` ``>= self``. This method can + also be accessed through the :func:`math.ceil` function. + + + .. method:: __round__() + __round__(ndigits) + + The first version returns the nearest :class:`int` to ``self``, + rounding half to even. The second version rounds ``self`` to the + nearest multiple of ``Fraction(1, 10**ndigits)`` (logically, if + ``ndigits`` is negative), again rounding half toward even. This + method can also be accessed through the :func:`round` function. + + +.. seealso:: + + Module :mod:`numbers` + The abstract base classes making up the numeric tower. diff --git a/cpython_2/environment/repo/Doc/library/frameworks.rst b/cpython_2/environment/repo/Doc/library/frameworks.rst new file mode 100644 index 0000000000000000000000000000000000000000..15ceeec9c255edb1854119ce96ee23dcd4b1110c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/frameworks.rst @@ -0,0 +1,18 @@ +.. _frameworks: + +****************** +Program Frameworks +****************** + +The modules described in this chapter are frameworks that will largely dictate +the structure of your program. Currently the modules described here are all +oriented toward writing command-line interfaces. + +The full list of modules described in this chapter is: + + +.. toctree:: + + turtle.rst + cmd.rst + shlex.rst diff --git a/cpython_2/environment/repo/Doc/library/ftplib.rst b/cpython_2/environment/repo/Doc/library/ftplib.rst new file mode 100644 index 0000000000000000000000000000000000000000..f4d4cdf9ada9d98403b15a9ac7ffd475ec28311d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/ftplib.rst @@ -0,0 +1,463 @@ +:mod:`ftplib` --- FTP protocol client +===================================== + +.. module:: ftplib + :synopsis: FTP protocol client (requires sockets). + +**Source code:** :source:`Lib/ftplib.py` + +.. index:: + pair: FTP; protocol + single: FTP; ftplib (standard module) + +-------------- + +This module defines the class :class:`FTP` and a few related items. The +:class:`FTP` class implements the client side of the FTP protocol. You can use +this to write Python programs that perform a variety of automated FTP jobs, such +as mirroring other FTP servers. It is also used by the module +:mod:`urllib.request` to handle URLs that use FTP. For more information on FTP +(File Transfer Protocol), see Internet :rfc:`959`. + +The default encoding is UTF-8, following :rfc:`2640`. + +Here's a sample session using the :mod:`ftplib` module:: + + >>> from ftplib import FTP + >>> ftp = FTP('ftp.us.debian.org') # connect to host, default port + >>> ftp.login() # user anonymous, passwd anonymous@ + '230 Login successful.' + >>> ftp.cwd('debian') # change into "debian" directory + >>> ftp.retrlines('LIST') # list directory contents + -rw-rw-r-- 1 1176 1176 1063 Jun 15 10:18 README + ... + drwxr-sr-x 5 1176 1176 4096 Dec 19 2000 pool + drwxr-sr-x 4 1176 1176 4096 Nov 17 2008 project + drwxr-xr-x 3 1176 1176 4096 Oct 10 2012 tools + '226 Directory send OK.' + >>> with open('README', 'wb') as fp: + >>> ftp.retrbinary('RETR README', fp.write) + '226 Transfer complete.' + >>> ftp.quit() + + +The module defines the following items: + +.. class:: FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None, *, encoding='utf-8') + + Return a new instance of the :class:`FTP` class. When *host* is given, the + method call ``connect(host)`` is made. When *user* is given, additionally + the method call ``login(user, passwd, acct)`` is made (where *passwd* and + *acct* default to the empty string when not given). The optional *timeout* + parameter specifies a timeout in seconds for blocking operations like the + connection attempt (if is not specified, the global default timeout setting + will be used). *source_address* is a 2-tuple ``(host, port)`` for the socket + to bind to as its source address before connecting. The *encoding* parameter + specifies the encoding for directories and filenames. + + The :class:`FTP` class supports the :keyword:`with` statement, e.g.: + + >>> from ftplib import FTP + >>> with FTP("ftp1.at.proftpd.org") as ftp: + ... ftp.login() + ... ftp.dir() + ... # doctest: +SKIP + '230 Anonymous login ok, restrictions apply.' + dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 . + dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 .. + dr-xr-xr-x 5 ftp ftp 4096 May 6 10:43 CentOS + dr-xr-xr-x 3 ftp ftp 18 Jul 10 2008 Fedora + >>> + + .. versionchanged:: 3.2 + Support for the :keyword:`with` statement was added. + + .. versionchanged:: 3.3 + *source_address* parameter was added. + + .. versionchanged:: 3.9 + If the *timeout* parameter is set to be zero, it will raise a + :class:`ValueError` to prevent the creation of a non-blocking socket. + The *encoding* parameter was added, and the default was changed from + Latin-1 to UTF-8 to follow :rfc:`2640`. + +.. class:: FTP_TLS(host='', user='', passwd='', acct='', keyfile=None, certfile=None, context=None, timeout=None, source_address=None, *, encoding='utf-8') + + A :class:`FTP` subclass which adds TLS support to FTP as described in + :rfc:`4217`. + Connect as usual to port 21 implicitly securing the FTP control connection + before authenticating. Securing the data connection requires the user to + explicitly ask for it by calling the :meth:`prot_p` method. *context* + is a :class:`ssl.SSLContext` object which allows bundling SSL configuration + options, certificates and private keys into a single (potentially + long-lived) structure. Please read :ref:`ssl-security` for best practices. + + *keyfile* and *certfile* are a legacy alternative to *context* -- they + can point to PEM-formatted private key and certificate chain files + (respectively) for the SSL connection. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.3 + *source_address* parameter was added. + + .. versionchanged:: 3.4 + The class now supports hostname check with + :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see + :data:`ssl.HAS_SNI`). + + .. deprecated:: 3.6 + + *keyfile* and *certfile* are deprecated in favor of *context*. + Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let + :func:`ssl.create_default_context` select the system's trusted CA + certificates for you. + + .. versionchanged:: 3.9 + If the *timeout* parameter is set to be zero, it will raise a + :class:`ValueError` to prevent the creation of a non-blocking socket. + The *encoding* parameter was added, and the default was changed from + Latin-1 to UTF-8 to follow :rfc:`2640`. + + Here's a sample session using the :class:`FTP_TLS` class:: + + >>> ftps = FTP_TLS('ftp.pureftpd.org') + >>> ftps.login() + '230 Anonymous user logged in' + >>> ftps.prot_p() + '200 Data protection level set to "private"' + >>> ftps.nlst() + ['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', 'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', 'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', 'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', 'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', 'sound', 'tmp', 'ucarp'] + + +.. exception:: error_reply + + Exception raised when an unexpected reply is received from the server. + + +.. exception:: error_temp + + Exception raised when an error code signifying a temporary error (response + codes in the range 400--499) is received. + + +.. exception:: error_perm + + Exception raised when an error code signifying a permanent error (response + codes in the range 500--599) is received. + + +.. exception:: error_proto + + Exception raised when a reply is received from the server that does not fit + the response specifications of the File Transfer Protocol, i.e. begin with a + digit in the range 1--5. + + +.. data:: all_errors + + The set of all exceptions (as a tuple) that methods of :class:`FTP` + instances may raise as a result of problems with the FTP connection (as + opposed to programming errors made by the caller). This set includes the + four exceptions listed above as well as :exc:`OSError` and :exc:`EOFError`. + + +.. seealso:: + + Module :mod:`netrc` + Parser for the :file:`.netrc` file format. The file :file:`.netrc` is + typically used by FTP clients to load user authentication information + before prompting the user. + + +.. _ftp-objects: + +FTP Objects +----------- + +Several methods are available in two flavors: one for handling text files and +another for binary files. These are named for the command which is used +followed by ``lines`` for the text version or ``binary`` for the binary version. + +:class:`FTP` instances have the following methods: + + +.. method:: FTP.set_debuglevel(level) + + Set the instance's debugging level. This controls the amount of debugging + output printed. The default, ``0``, produces no debugging output. A value of + ``1`` produces a moderate amount of debugging output, generally a single line + per request. A value of ``2`` or higher produces the maximum amount of + debugging output, logging each line sent and received on the control connection. + + +.. method:: FTP.connect(host='', port=0, timeout=None, source_address=None) + + Connect to the given host and port. The default port number is ``21``, as + specified by the FTP protocol specification. It is rarely needed to specify a + different port number. This function should be called only once for each + instance; it should not be called at all if a host was given when the instance + was created. All other methods can only be used after a connection has been + made. + The optional *timeout* parameter specifies a timeout in seconds for the + connection attempt. If no *timeout* is passed, the global default timeout + setting will be used. + *source_address* is a 2-tuple ``(host, port)`` for the socket to bind to as + its source address before connecting. + + .. audit-event:: ftplib.connect self,host,port ftplib.FTP.connect + + .. versionchanged:: 3.3 + *source_address* parameter was added. + + +.. method:: FTP.getwelcome() + + Return the welcome message sent by the server in reply to the initial + connection. (This message sometimes contains disclaimers or help information + that may be relevant to the user.) + + +.. method:: FTP.login(user='anonymous', passwd='', acct='') + + Log in as the given *user*. The *passwd* and *acct* parameters are optional and + default to the empty string. If no *user* is specified, it defaults to + ``'anonymous'``. If *user* is ``'anonymous'``, the default *passwd* is + ``'anonymous@'``. This function should be called only once for each instance, + after a connection has been established; it should not be called at all if a + host and user were given when the instance was created. Most FTP commands are + only allowed after the client has logged in. The *acct* parameter supplies + "accounting information"; few systems implement this. + + +.. method:: FTP.abort() + + Abort a file transfer that is in progress. Using this does not always work, but + it's worth a try. + + +.. method:: FTP.sendcmd(cmd) + + Send a simple command string to the server and return the response string. + + .. audit-event:: ftplib.sendcmd self,cmd ftplib.FTP.sendcmd + + +.. method:: FTP.voidcmd(cmd) + + Send a simple command string to the server and handle the response. Return + nothing if a response code corresponding to success (codes in the range + 200--299) is received. Raise :exc:`error_reply` otherwise. + + .. audit-event:: ftplib.sendcmd self,cmd ftplib.FTP.voidcmd + + +.. method:: FTP.retrbinary(cmd, callback, blocksize=8192, rest=None) + + Retrieve a file in binary transfer mode. *cmd* should be an appropriate + ``RETR`` command: ``'RETR filename'``. The *callback* function is called for + each block of data received, with a single bytes argument giving the data + block. The optional *blocksize* argument specifies the maximum chunk size to + read on the low-level socket object created to do the actual transfer (which + will also be the largest size of the data blocks passed to *callback*). A + reasonable default is chosen. *rest* means the same thing as in the + :meth:`transfercmd` method. + + +.. method:: FTP.retrlines(cmd, callback=None) + + Retrieve a file or directory listing in the encoding specified by the + *encoding* parameter at initialization. + *cmd* should be an appropriate ``RETR`` command (see :meth:`retrbinary`) or + a command such as ``LIST`` or ``NLST`` (usually just the string ``'LIST'``). + ``LIST`` retrieves a list of files and information about those files. + ``NLST`` retrieves a list of file names. + The *callback* function is called for each line with a string argument + containing the line with the trailing CRLF stripped. The default *callback* + prints the line to ``sys.stdout``. + + +.. method:: FTP.set_pasv(val) + + Enable "passive" mode if *val* is true, otherwise disable passive mode. + Passive mode is on by default. + + +.. method:: FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None) + + Store a file in binary transfer mode. *cmd* should be an appropriate + ``STOR`` command: ``"STOR filename"``. *fp* is a :term:`file object` + (opened in binary mode) which is read until EOF using its :meth:`~io.IOBase.read` + method in blocks of size *blocksize* to provide the data to be stored. + The *blocksize* argument defaults to 8192. *callback* is an optional single + parameter callable that is called on each block of data after it is sent. + *rest* means the same thing as in the :meth:`transfercmd` method. + + .. versionchanged:: 3.2 + *rest* parameter added. + + +.. method:: FTP.storlines(cmd, fp, callback=None) + + Store a file in line mode. *cmd* should be an appropriate + ``STOR`` command (see :meth:`storbinary`). Lines are read until EOF from the + :term:`file object` *fp* (opened in binary mode) using its :meth:`~io.IOBase.readline` + method to provide the data to be stored. *callback* is an optional single + parameter callable that is called on each line after it is sent. + + +.. method:: FTP.transfercmd(cmd, rest=None) + + Initiate a transfer over the data connection. If the transfer is active, send an + ``EPRT`` or ``PORT`` command and the transfer command specified by *cmd*, and + accept the connection. If the server is passive, send an ``EPSV`` or ``PASV`` + command, connect to it, and start the transfer command. Either way, return the + socket for the connection. + + If optional *rest* is given, a ``REST`` command is sent to the server, passing + *rest* as an argument. *rest* is usually a byte offset into the requested file, + telling the server to restart sending the file's bytes at the requested offset, + skipping over the initial bytes. Note however that the :meth:`transfercmd` + method converts *rest* to a string with the *encoding* parameter specified + at initialization, but no check is performed on the string's contents. If the + server does not recognize the ``REST`` command, an :exc:`error_reply` exception + will be raised. If this happens, simply call :meth:`transfercmd` without a + *rest* argument. + + +.. method:: FTP.ntransfercmd(cmd, rest=None) + + Like :meth:`transfercmd`, but returns a tuple of the data connection and the + expected size of the data. If the expected size could not be computed, ``None`` + will be returned as the expected size. *cmd* and *rest* means the same thing as + in :meth:`transfercmd`. + + +.. method:: FTP.mlsd(path="", facts=[]) + + List a directory in a standardized format by using ``MLSD`` command + (:rfc:`3659`). If *path* is omitted the current directory is assumed. + *facts* is a list of strings representing the type of information desired + (e.g. ``["type", "size", "perm"]``). Return a generator object yielding a + tuple of two elements for every file found in path. First element is the + file name, the second one is a dictionary containing facts about the file + name. Content of this dictionary might be limited by the *facts* argument + but server is not guaranteed to return all requested facts. + + .. versionadded:: 3.3 + + +.. method:: FTP.nlst(argument[, ...]) + + Return a list of file names as returned by the ``NLST`` command. The + optional *argument* is a directory to list (default is the current server + directory). Multiple arguments can be used to pass non-standard options to + the ``NLST`` command. + + .. note:: If your server supports the command, :meth:`mlsd` offers a better API. + + +.. method:: FTP.dir(argument[, ...]) + + Produce a directory listing as returned by the ``LIST`` command, printing it to + standard output. The optional *argument* is a directory to list (default is the + current server directory). Multiple arguments can be used to pass non-standard + options to the ``LIST`` command. If the last argument is a function, it is used + as a *callback* function as for :meth:`retrlines`; the default prints to + ``sys.stdout``. This method returns ``None``. + + .. note:: If your server supports the command, :meth:`mlsd` offers a better API. + + +.. method:: FTP.rename(fromname, toname) + + Rename file *fromname* on the server to *toname*. + + +.. method:: FTP.delete(filename) + + Remove the file named *filename* from the server. If successful, returns the + text of the response, otherwise raises :exc:`error_perm` on permission errors or + :exc:`error_reply` on other errors. + + +.. method:: FTP.cwd(pathname) + + Set the current directory on the server. + + +.. method:: FTP.mkd(pathname) + + Create a new directory on the server. + + +.. method:: FTP.pwd() + + Return the pathname of the current directory on the server. + + +.. method:: FTP.rmd(dirname) + + Remove the directory named *dirname* on the server. + + +.. method:: FTP.size(filename) + + Request the size of the file named *filename* on the server. On success, the + size of the file is returned as an integer, otherwise ``None`` is returned. + Note that the ``SIZE`` command is not standardized, but is supported by many + common server implementations. + + +.. method:: FTP.quit() + + Send a ``QUIT`` command to the server and close the connection. This is the + "polite" way to close a connection, but it may raise an exception if the server + responds with an error to the ``QUIT`` command. This implies a call to the + :meth:`close` method which renders the :class:`FTP` instance useless for + subsequent calls (see below). + + +.. method:: FTP.close() + + Close the connection unilaterally. This should not be applied to an already + closed connection such as after a successful call to :meth:`~FTP.quit`. + After this call the :class:`FTP` instance should not be used any more (after + a call to :meth:`close` or :meth:`~FTP.quit` you cannot reopen the + connection by issuing another :meth:`login` method). + + +FTP_TLS Objects +--------------- + +:class:`FTP_TLS` class inherits from :class:`FTP`, defining these additional objects: + +.. attribute:: FTP_TLS.ssl_version + + The SSL version to use (defaults to :attr:`ssl.PROTOCOL_SSLv23`). + +.. method:: FTP_TLS.auth() + + Set up a secure control connection by using TLS or SSL, depending on what + is specified in the :attr:`ssl_version` attribute. + + .. versionchanged:: 3.4 + The method now supports hostname check with + :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see + :data:`ssl.HAS_SNI`). + +.. method:: FTP_TLS.ccc() + + Revert control channel back to plaintext. This can be useful to take + advantage of firewalls that know how to handle NAT with non-secure FTP + without opening fixed ports. + + .. versionadded:: 3.3 + +.. method:: FTP_TLS.prot_p() + + Set up secure data connection. + +.. method:: FTP_TLS.prot_c() + + Set up clear text data connection. diff --git a/cpython_2/environment/repo/Doc/library/functional.rst b/cpython_2/environment/repo/Doc/library/functional.rst new file mode 100644 index 0000000000000000000000000000000000000000..5b6185a65cd12cc437bf6d3b52ec71a13cae14ac --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/functional.rst @@ -0,0 +1,15 @@ +****************************** +Functional Programming Modules +****************************** + +The modules described in this chapter provide functions and classes that support +a functional programming style, and general operations on callables. + +The following modules are documented in this chapter: + + +.. toctree:: + + itertools.rst + functools.rst + operator.rst diff --git a/cpython_2/environment/repo/Doc/library/functions.rst b/cpython_2/environment/repo/Doc/library/functions.rst new file mode 100644 index 0000000000000000000000000000000000000000..90a2370c1793bb0635bccbe6b0f4184813c6a2dd --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/functions.rst @@ -0,0 +1,1846 @@ +.. XXX document all delegations to __special__ methods +.. _built-in-funcs: + +Built-in Functions +================== + +The Python interpreter has a number of functions and types built into it that +are always available. They are listed here in alphabetical order. + +=================== ================= ================== ================== ==================== +.. .. Built-in Functions .. .. +=================== ================= ================== ================== ==================== +:func:`abs` :func:`delattr` :func:`hash` |func-memoryview|_ |func-set|_ +:func:`all` |func-dict|_ :func:`help` :func:`min` :func:`setattr` +:func:`any` :func:`dir` :func:`hex` :func:`next` :func:`slice` +:func:`ascii` :func:`divmod` :func:`id` :func:`object` :func:`sorted` +:func:`bin` :func:`enumerate` :func:`input` :func:`oct` :func:`staticmethod` +:func:`bool` :func:`eval` :func:`int` :func:`open` |func-str|_ +:func:`breakpoint` :func:`exec` :func:`isinstance` :func:`ord` :func:`sum` +|func-bytearray|_ :func:`filter` :func:`issubclass` :func:`pow` :func:`super` +|func-bytes|_ :func:`float` :func:`iter` :func:`print` |func-tuple|_ +:func:`callable` :func:`format` :func:`len` :func:`property` :func:`type` +:func:`chr` |func-frozenset|_ |func-list|_ |func-range|_ :func:`vars` +:func:`classmethod` :func:`getattr` :func:`locals` :func:`repr` :func:`zip` +:func:`compile` :func:`globals` :func:`map` :func:`reversed` :func:`__import__` +:func:`complex` :func:`hasattr` :func:`max` :func:`round` +=================== ================= ================== ================== ==================== + +.. using :func:`dict` would create a link to another page, so local targets are + used, with replacement texts to make the output in the table consistent + +.. |func-dict| replace:: ``dict()`` +.. |func-frozenset| replace:: ``frozenset()`` +.. |func-memoryview| replace:: ``memoryview()`` +.. |func-set| replace:: ``set()`` +.. |func-list| replace:: ``list()`` +.. |func-str| replace:: ``str()`` +.. |func-tuple| replace:: ``tuple()`` +.. |func-range| replace:: ``range()`` +.. |func-bytearray| replace:: ``bytearray()`` +.. |func-bytes| replace:: ``bytes()`` + +.. function:: abs(x) + + Return the absolute value of a number. The argument may be an + integer or a floating point number. If the argument is a complex number, its + magnitude is returned. If *x* defines :meth:`__abs__`, + ``abs(x)`` returns ``x.__abs__()``. + + +.. function:: all(iterable) + + Return ``True`` if all elements of the *iterable* are true (or if the iterable + is empty). Equivalent to:: + + def all(iterable): + for element in iterable: + if not element: + return False + return True + + +.. function:: any(iterable) + + Return ``True`` if any element of the *iterable* is true. If the iterable + is empty, return ``False``. Equivalent to:: + + def any(iterable): + for element in iterable: + if element: + return True + return False + + +.. function:: ascii(object) + + As :func:`repr`, return a string containing a printable representation of an + object, but escape the non-ASCII characters in the string returned by + :func:`repr` using ``\x``, ``\u`` or ``\U`` escapes. This generates a string + similar to that returned by :func:`repr` in Python 2. + + +.. function:: bin(x) + + Convert an integer number to a binary string prefixed with "0b". The result + is a valid Python expression. If *x* is not a Python :class:`int` object, it + has to define an :meth:`__index__` method that returns an integer. Some + examples: + + >>> bin(3) + '0b11' + >>> bin(-10) + '-0b1010' + + If prefix "0b" is desired or not, you can use either of the following ways. + + >>> format(14, '#b'), format(14, 'b') + ('0b1110', '1110') + >>> f'{14:#b}', f'{14:b}' + ('0b1110', '1110') + + See also :func:`format` for more information. + + +.. class:: bool([x]) + + Return a Boolean value, i.e. one of ``True`` or ``False``. *x* is converted + using the standard :ref:`truth testing procedure `. If *x* is false + or omitted, this returns ``False``; otherwise it returns ``True``. The + :class:`bool` class is a subclass of :class:`int` (see :ref:`typesnumeric`). + It cannot be subclassed further. Its only instances are ``False`` and + ``True`` (see :ref:`bltin-boolean-values`). + + .. index:: pair: Boolean; type + + .. versionchanged:: 3.7 + *x* is now a positional-only parameter. + +.. function:: breakpoint(*args, **kws) + + This function drops you into the debugger at the call site. Specifically, + it calls :func:`sys.breakpointhook`, passing ``args`` and ``kws`` straight + through. By default, ``sys.breakpointhook()`` calls + :func:`pdb.set_trace()` expecting no arguments. In this case, it is + purely a convenience function so you don't have to explicitly import + :mod:`pdb` or type as much code to enter the debugger. However, + :func:`sys.breakpointhook` can be set to some other function and + :func:`breakpoint` will automatically call that, allowing you to drop into + the debugger of choice. + + .. audit-event:: builtins.breakpoint breakpointhook breakpoint + + .. versionadded:: 3.7 + +.. _func-bytearray: +.. class:: bytearray([source[, encoding[, errors]]]) + :noindex: + + Return a new array of bytes. The :class:`bytearray` class is a mutable + sequence of integers in the range 0 <= x < 256. It has most of the usual + methods of mutable sequences, described in :ref:`typesseq-mutable`, as well + as most methods that the :class:`bytes` type has, see :ref:`bytes-methods`. + + The optional *source* parameter can be used to initialize the array in a few + different ways: + + * If it is a *string*, you must also give the *encoding* (and optionally, + *errors*) parameters; :func:`bytearray` then converts the string to + bytes using :meth:`str.encode`. + + * If it is an *integer*, the array will have that size and will be + initialized with null bytes. + + * If it is an object conforming to the *buffer* interface, a read-only buffer + of the object will be used to initialize the bytes array. + + * If it is an *iterable*, it must be an iterable of integers in the range + ``0 <= x < 256``, which are used as the initial contents of the array. + + Without an argument, an array of size 0 is created. + + See also :ref:`binaryseq` and :ref:`typebytearray`. + + +.. _func-bytes: +.. class:: bytes([source[, encoding[, errors]]]) + :noindex: + + Return a new "bytes" object, which is an immutable sequence of integers in + 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:`bytearray`. + + Bytes objects can also be created with literals, see :ref:`strings`. + + See also :ref:`binaryseq`, :ref:`typebytes`, and :ref:`bytes-methods`. + + +.. function:: callable(object) + + Return :const:`True` if the *object* argument appears callable, + :const:`False` if not. If this returns ``True``, it is still possible that a + call fails, but if it is ``False``, calling *object* will never succeed. + Note that classes are callable (calling a class returns a new instance); + instances are callable if their class has a :meth:`__call__` method. + + .. versionadded:: 3.2 + This function was first removed in Python 3.0 and then brought back + in Python 3.2. + + +.. function:: chr(i) + + Return the string representing a character whose Unicode code point is the + integer *i*. For example, ``chr(97)`` returns the string ``'a'``, while + ``chr(8364)`` returns the string ``'€'``. This is the inverse of :func:`ord`. + + The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in + base 16). :exc:`ValueError` will be raised if *i* is outside that range. + + +.. decorator:: classmethod + + Transform a method into a class method. + + A class method receives the class as implicit first argument, just like an + instance method receives the instance. To declare a class method, use this + idiom:: + + class C: + @classmethod + def f(cls, arg1, arg2, ...): ... + + The ``@classmethod`` form is a function :term:`decorator` -- see + :ref:`function` for details. + + A class method can be called either on the class (such as ``C.f()``) or on an instance (such + as ``C().f()``). The instance is ignored except for its class. If a class + method is called for a derived class, the derived class object is passed as the + implied first argument. + + Class methods are different than C++ or Java static methods. If you want those, + see :func:`staticmethod` in this section. + For more information on class methods, see :ref:`types`. + + .. versionchanged:: 3.9 + Class methods can now wrap other :term:`descriptors ` such as + :func:`property`. + +.. function:: compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) + + Compile the *source* into a code or AST object. Code objects can be executed + by :func:`exec` or :func:`eval`. *source* can either be a normal string, a + byte string, or an AST object. Refer to the :mod:`ast` module documentation + for information on how to work with AST objects. + + The *filename* argument should give the file from which the code was read; + pass some recognizable value if it wasn't read from a file (``''`` is + commonly used). + + The *mode* argument specifies what kind of code must be compiled; it can be + ``'exec'`` if *source* consists of a sequence of statements, ``'eval'`` if it + consists of a single expression, or ``'single'`` if it consists of a single + interactive statement (in the latter case, expression statements that + evaluate to something other than ``None`` will be printed). + + The optional arguments *flags* and *dont_inherit* control which :ref:`future + statements ` affect the compilation of *source*. If neither + is present (or both are zero) the code is compiled with those future + statements that are in effect in the code that is calling :func:`compile`. If the + *flags* argument is given and *dont_inherit* is not (or is zero) then the + future statements specified by the *flags* argument are used in addition to + those that would be used anyway. If *dont_inherit* is a non-zero integer then + the *flags* argument is it -- the future statements in effect around the call + to compile are ignored. + + Future statements are specified by bits which can be bitwise ORed together to + specify multiple statements. The bitfield required to specify a given feature + can be found as the :attr:`~__future__._Feature.compiler_flag` attribute on + the :class:`~__future__._Feature` instance in the :mod:`__future__` module. + + The optional argument *flags* also controls whether the compiled source is + allowed to contain top-level ``await``, ``async for`` and ``async with``. + When the bit ``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` is set, the return code + object has ``CO_COROUTINE`` set in ``co_code``, and can be interactively + executed via ``await eval(code_object)``. + + The argument *optimize* specifies the optimization level of the compiler; the + default value of ``-1`` selects the optimization level of the interpreter as + given by :option:`-O` options. Explicit levels are ``0`` (no optimization; + ``__debug__`` is true), ``1`` (asserts are removed, ``__debug__`` is false) + or ``2`` (docstrings are removed too). + + This function raises :exc:`SyntaxError` if the compiled source is invalid, + and :exc:`ValueError` if the source contains null bytes. + + If you want to parse Python code into its AST representation, see + :func:`ast.parse`. + + .. audit-event:: compile source,filename compile + + Raises an :ref:`auditing event ` ``compile`` with arguments + ``source`` and ``filename``. This event may also be raised by implicit + compilation. + + .. note:: + + When compiling a string with multi-line code in ``'single'`` or + ``'eval'`` mode, input must be terminated by at least one newline + character. This is to facilitate detection of incomplete and complete + statements in the :mod:`code` module. + + .. warning:: + + It is possible to crash the Python interpreter with a + sufficiently large/complex string when compiling to an AST + object due to stack depth limitations in Python's AST compiler. + + .. versionchanged:: 3.2 + Allowed use of Windows and Mac newlines. Also input in ``'exec'`` mode + does not have to end in a newline anymore. Added the *optimize* parameter. + + .. versionchanged:: 3.5 + Previously, :exc:`TypeError` was raised when null bytes were encountered + in *source*. + + .. versionadded:: 3.8 + ``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` can now be passed in flags to enable + support for top-level ``await``, ``async for``, and ``async with``. + + +.. class:: complex([real[, imag]]) + + Return a complex number with the value *real* + *imag*\*1j or convert a string + or number to a complex number. If the first parameter is a string, it will + be interpreted as a complex number and the function must be called without a + second parameter. The second parameter can never be a string. Each argument + may be any numeric type (including complex). If *imag* is omitted, it + defaults to zero and the constructor serves as a numeric conversion like + :class:`int` and :class:`float`. If both arguments are omitted, returns + ``0j``. + + For a general Python object ``x``, ``complex(x)`` delegates to + ``x.__complex__()``. If ``__complex__()`` is not defined then it falls back + to :meth:`__float__`. If ``__float__()`` is not defined then it falls back + to :meth:`__index__`. + + .. note:: + + When converting from a string, the string must not contain whitespace + around the central ``+`` or ``-`` operator. For example, + ``complex('1+2j')`` is fine, but ``complex('1 + 2j')`` raises + :exc:`ValueError`. + + The complex type is described in :ref:`typesnumeric`. + + .. versionchanged:: 3.6 + Grouping digits with underscores as in code literals is allowed. + + .. versionchanged:: 3.8 + Falls back to :meth:`__index__` if :meth:`__complex__` and + :meth:`__float__` are not defined. + + +.. function:: delattr(object, name) + + This is a relative of :func:`setattr`. The arguments are an object and a + string. The string must be the name of one of the object's attributes. The + function deletes the named attribute, provided the object allows it. For + example, ``delattr(x, 'foobar')`` is equivalent to ``del x.foobar``. + + +.. _func-dict: +.. class:: dict(**kwarg) + dict(mapping, **kwarg) + dict(iterable, **kwarg) + :noindex: + + Create a new dictionary. The :class:`dict` object is the dictionary class. + See :class:`dict` and :ref:`typesmapping` for documentation about this class. + + For other containers see the built-in :class:`list`, :class:`set`, and + :class:`tuple` classes, as well as the :mod:`collections` module. + + +.. function:: dir([object]) + + Without arguments, return the list of names in the current local scope. With an + argument, attempt to return a list of valid attributes for that object. + + If the object has a method named :meth:`__dir__`, this method will be called and + must return the list of attributes. This allows objects that implement a custom + :func:`__getattr__` or :func:`__getattribute__` function to customize the way + :func:`dir` reports their attributes. + + If the object does not provide :meth:`__dir__`, the function tries its best to + gather information from the object's :attr:`~object.__dict__` attribute, if defined, and + from its type object. The resulting list is not necessarily complete, and may + be inaccurate when the object has a custom :func:`__getattr__`. + + The default :func:`dir` mechanism behaves differently with different types of + objects, as it attempts to produce the most relevant, rather than complete, + information: + + * If the object is a module object, the list contains the names of the module's + attributes. + + * If the object is a type or class object, the list contains the names of its + attributes, and recursively of the attributes of its bases. + + * Otherwise, the list contains the object's attributes' names, the names of its + class's attributes, and recursively of the attributes of its class's base + classes. + + The resulting list is sorted alphabetically. For example: + + >>> import struct + >>> dir() # show the names in the module namespace # doctest: +SKIP + ['__builtins__', '__name__', 'struct'] + >>> dir(struct) # show the names in the struct module # doctest: +SKIP + ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', + '__initializing__', '__loader__', '__name__', '__package__', + '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', + 'unpack', 'unpack_from'] + >>> class Shape: + ... def __dir__(self): + ... return ['area', 'perimeter', 'location'] + >>> s = Shape() + >>> dir(s) + ['area', 'location', 'perimeter'] + + .. note:: + + Because :func:`dir` is supplied primarily as a convenience for use at an + interactive prompt, it tries to supply an interesting set of names more + than it tries to supply a rigorously or consistently defined set of names, + and its detailed behavior may change across releases. For example, + metaclass attributes are not in the result list when the argument is a + class. + + +.. function:: divmod(a, b) + + 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, 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 *a*, if ``a % b`` is non-zero it has the same sign as *b*, and ``0 + <= abs(a % b) < abs(b)``. + + +.. function:: enumerate(iterable, start=0) + + Return an enumerate object. *iterable* must be a sequence, an + :term:`iterator`, or some other object which supports iteration. + The :meth:`~iterator.__next__` method of the iterator returned by + :func:`enumerate` returns a tuple containing a count (from *start* which + defaults to 0) and the values obtained from iterating over *iterable*. + + >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] + >>> list(enumerate(seasons)) + [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] + >>> list(enumerate(seasons, start=1)) + [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] + + Equivalent to:: + + def enumerate(sequence, start=0): + n = start + for elem in sequence: + yield n, elem + n += 1 + + +.. function:: eval(expression[, globals[, locals]]) + + The arguments are a string and optional globals and locals. If provided, + *globals* must be a dictionary. If provided, *locals* can be any mapping + object. + + The *expression* argument is parsed and evaluated as a Python expression + (technically speaking, a condition list) using the *globals* and *locals* + dictionaries as global and local namespace. If the *globals* dictionary is + present and does not contain a value for the key ``__builtins__``, a + reference to the dictionary of the built-in module :mod:`builtins` is + inserted under that key before *expression* is parsed. This means that + *expression* normally has full access to the standard :mod:`builtins` + module and restricted environments are propagated. If the *locals* + dictionary is omitted it defaults to the *globals* dictionary. If both + dictionaries are omitted, the expression is executed with the *globals* and + *locals* in the environment where :func:`eval` is called. Note, *eval()* + does not have access to the :term:`nested scopes ` (non-locals) in the + enclosing environment. + + The return value is the result of + the evaluated expression. Syntax errors are reported as exceptions. Example: + + >>> x = 1 + >>> eval('x+1') + 2 + + This function can also be used to execute arbitrary code objects (such as + those created by :func:`compile`). In this case pass a code object instead + of a string. If the code object has been compiled with ``'exec'`` as the + *mode* argument, :func:`eval`\'s return value will be ``None``. + + Hints: dynamic execution of statements is supported by the :func:`exec` + function. The :func:`globals` and :func:`locals` functions + returns the current global and local dictionary, respectively, which may be + useful to pass around for use by :func:`eval` or :func:`exec`. + + See :func:`ast.literal_eval` for a function that can safely evaluate strings + with expressions containing only literals. + + .. audit-event:: exec code_object eval + + Raises an :ref:`auditing event ` ``exec`` with the code object + as the argument. Code compilation events may also be raised. + +.. index:: builtin: exec + +.. function:: exec(object[, globals[, locals]]) + + This function supports dynamic execution of Python code. *object* must be + either a string or a code object. If it is a string, the string is parsed as + a suite of Python statements which is then executed (unless a syntax error + occurs). [#]_ If it is a code object, it is simply executed. In all cases, + the code that's executed is expected to be valid as file input (see the + section "File input" in the Reference Manual). Be aware that the + :keyword:`return` and :keyword:`yield` statements may not be used outside of + function definitions even within the context of code passed to the + :func:`exec` function. The return value is ``None``. + + In all cases, if the optional parts are omitted, the code is executed in the + current scope. If only *globals* is provided, it must be a dictionary + (and not a subclass of dictionary), which + will be used for both the global and the local variables. If *globals* and + *locals* are given, they are used for the global and local variables, + respectively. If provided, *locals* can be any mapping object. Remember + that at module level, globals and locals are the same dictionary. If exec + gets two separate objects as *globals* and *locals*, the code will be + executed as if it were embedded in a class definition. + + If the *globals* dictionary does not contain a value for the key + ``__builtins__``, a reference to the dictionary of the built-in module + :mod:`builtins` is inserted under that key. That way you can control what + builtins are available to the executed code by inserting your own + ``__builtins__`` dictionary into *globals* before passing it to :func:`exec`. + + .. audit-event:: exec code_object exec + + Raises an :ref:`auditing event ` ``exec`` with the code object + as the argument. Code compilation events may also be raised. + + .. note:: + + The built-in functions :func:`globals` and :func:`locals` return the current + global and local dictionary, respectively, which may be useful to pass around + for use as the second and third argument to :func:`exec`. + + .. note:: + + The default *locals* act as described for function :func:`locals` below: + modifications to the default *locals* dictionary should not be attempted. + Pass an explicit *locals* dictionary if you need to see effects of the + code on *locals* after function :func:`exec` returns. + + +.. function:: filter(function, iterable) + + Construct an iterator from those elements of *iterable* for which *function* + returns true. *iterable* may be either a sequence, a container which + supports iteration, or an iterator. If *function* is ``None``, the identity + function is assumed, that is, all elements of *iterable* that are false are + removed. + + Note that ``filter(function, iterable)`` is equivalent to the generator + expression ``(item for item in iterable if function(item))`` if function is + not ``None`` and ``(item for item in iterable if item)`` if function is + ``None``. + + See :func:`itertools.filterfalse` for the complementary function that returns + elements of *iterable* for which *function* returns false. + + +.. class:: float([x]) + + .. index:: + single: NaN + single: Infinity + + Return a floating point number constructed from a number or string *x*. + + If the argument is a string, it should contain a decimal number, optionally + preceded by a sign, and optionally embedded in whitespace. The optional + sign may be ``'+'`` or ``'-'``; a ``'+'`` sign has no effect on the value + produced. The argument may also be a string representing a NaN + (not-a-number), or a positive or negative infinity. More precisely, the + input must conform to the following grammar after leading and trailing + whitespace characters are removed: + + .. productionlist:: + sign: "+" | "-" + infinity: "Infinity" | "inf" + nan: "nan" + numeric_value: `floatnumber` | `infinity` | `nan` + numeric_string: [`sign`] `numeric_value` + + Here ``floatnumber`` is the form of a Python floating-point literal, + described in :ref:`floating`. Case is not significant, so, for example, + "inf", "Inf", "INFINITY" and "iNfINity" are all acceptable spellings for + positive infinity. + + Otherwise, if the argument is an integer or a floating point number, a + floating point number with the same value (within Python's floating point + precision) is returned. If the argument is outside the range of a Python + float, an :exc:`OverflowError` will be raised. + + For a general Python object ``x``, ``float(x)`` delegates to + ``x.__float__()``. If ``__float__()`` is not defined then it falls back + to :meth:`__index__`. + + If no argument is given, ``0.0`` is returned. + + Examples:: + + >>> float('+1.23') + 1.23 + >>> float(' -12345\n') + -12345.0 + >>> float('1e-003') + 0.001 + >>> float('+1E6') + 1000000.0 + >>> float('-Infinity') + -inf + + The float type is described in :ref:`typesnumeric`. + + .. versionchanged:: 3.6 + Grouping digits with underscores as in code literals is allowed. + + .. versionchanged:: 3.7 + *x* is now a positional-only parameter. + + .. versionchanged:: 3.8 + Falls back to :meth:`__index__` if :meth:`__float__` is not defined. + + +.. index:: + single: __format__ + single: string; format() (built-in function) + +.. function:: format(value[, format_spec]) + + Convert a *value* 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`. + + The default *format_spec* is an empty string which usually gives the same + effect as calling :func:`str(value) `. + + A call to ``format(value, format_spec)`` is translated to + ``type(value).__format__(value, format_spec)`` which bypasses the instance + dictionary when searching for the value's :meth:`__format__` method. A + :exc:`TypeError` exception is raised if the method search reaches + :mod:`object` and the *format_spec* is non-empty, or if either the + *format_spec* or the return value are not strings. + + .. versionchanged:: 3.4 + ``object().__format__(format_spec)`` raises :exc:`TypeError` + if *format_spec* is not an empty string. + + +.. _func-frozenset: +.. class:: frozenset([iterable]) + :noindex: + + Return a new :class:`frozenset` object, optionally with elements taken from + *iterable*. ``frozenset`` is a built-in class. See :class:`frozenset` and + :ref:`types-set` for documentation about this class. + + For other containers see the built-in :class:`set`, :class:`list`, + :class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections` + module. + + +.. function:: getattr(object, name[, default]) + + Return the value of the named attribute of *object*. *name* must be a string. + If the string is the name of one of the object's attributes, the result is the + value of that attribute. For example, ``getattr(x, 'foobar')`` is equivalent to + ``x.foobar``. If the named attribute does not exist, *default* is returned if + provided, otherwise :exc:`AttributeError` is raised. + + +.. function:: globals() + + Return a dictionary representing the current global symbol table. This is always + the dictionary of the current module (inside a function or method, this is the + module where it is defined, not the module from which it is called). + + +.. function:: hasattr(object, name) + + The arguments are an object and a string. The result is ``True`` if the + string is the name of one of the object's attributes, ``False`` if not. (This + is implemented by calling ``getattr(object, name)`` and seeing whether it + raises an :exc:`AttributeError` or not.) + + +.. function:: hash(object) + + Return the hash value of the object (if it has one). Hash values are + integers. They are used to quickly compare dictionary keys during a + dictionary lookup. Numeric values that compare equal have the same hash + value (even if they are of different types, as is the case for 1 and 1.0). + + .. note:: + + For objects with custom :meth:`__hash__` methods, note that :func:`hash` + truncates the return value based on the bit width of the host machine. + See :meth:`__hash__` for details. + +.. function:: help([object]) + + Invoke the built-in help system. (This function is intended for interactive + use.) If no argument is given, the interactive help system starts on the + interpreter console. If the argument is a string, then the string is looked up + as the name of a module, function, class, method, keyword, or documentation + topic, and a help page is printed on the console. If the argument is any other + kind of object, a help page on the object is generated. + + Note that if a slash(/) appears in the parameter list of a function, when + invoking :func:`help`, it means that the parameters prior to the slash are + positional-only. For more info, see + :ref:`the FAQ entry on positional-only parameters `. + + This function is added to the built-in namespace by the :mod:`site` module. + + .. versionchanged:: 3.4 + Changes to :mod:`pydoc` and :mod:`inspect` mean that the reported + signatures for callables are now more comprehensive and consistent. + + +.. function:: hex(x) + + Convert an integer number to a lowercase hexadecimal string prefixed with + "0x". If *x* is not a Python :class:`int` object, it has to define an + :meth:`__index__` method that returns an integer. Some examples: + + >>> hex(255) + '0xff' + >>> hex(-42) + '-0x2a' + + If you want to convert an integer number to an uppercase or lower hexadecimal + string with prefix or not, you can use either of the following ways: + + >>> '%#x' % 255, '%x' % 255, '%X' % 255 + ('0xff', 'ff', 'FF') + >>> format(255, '#x'), format(255, 'x'), format(255, 'X') + ('0xff', 'ff', 'FF') + >>> f'{255:#x}', f'{255:x}', f'{255:X}' + ('0xff', 'ff', 'FF') + + See also :func:`format` for more information. + + See also :func:`int` for converting a hexadecimal string to an + integer using a base of 16. + + .. note:: + + To obtain a hexadecimal string representation for a float, use the + :meth:`float.hex` method. + + +.. function:: id(object) + + Return the "identity" of an object. This is an integer which + is guaranteed to be unique and constant for this object during its lifetime. + Two objects with non-overlapping lifetimes may have the same :func:`id` + value. + + .. impl-detail:: This is the address of the object in memory. + + +.. function:: input([prompt]) + + If the *prompt* argument is present, it is written to standard output without + a trailing newline. The function then reads a line from input, converts it + to a string (stripping a trailing newline), and returns that. When EOF is + read, :exc:`EOFError` is raised. Example:: + + >>> s = input('--> ') # doctest: +SKIP + --> Monty Python's Flying Circus + >>> s # doctest: +SKIP + "Monty Python's Flying Circus" + + If the :mod:`readline` module was loaded, then :func:`input` will use it + to provide elaborate line editing and history features. + + .. audit-event:: builtins.input prompt input + + Raises an :ref:`auditing event ` ``builtins.input`` with + argument ``prompt`` before reading input + + .. audit-event:: builtins.input/result result input + + Raises an auditing event ``builtins.input/result`` with the result after + successfully reading input. + + +.. class:: int([x]) + int(x, base=10) + + Return an integer object constructed from a number or string *x*, or return + ``0`` if no arguments are given. If *x* defines :meth:`__int__`, + ``int(x)`` returns ``x.__int__()``. If *x* defines :meth:`__index__`, + it returns ``x.__index__()``. If *x* defines :meth:`__trunc__`, + it returns ``x.__trunc__()``. + For floating point numbers, this truncates towards zero. + + If *x* is not a number or if *base* is given, then *x* must be a string, + :class:`bytes`, or :class:`bytearray` instance representing an :ref:`integer + literal ` in radix *base*. Optionally, the literal can be + preceded by ``+`` or ``-`` (with no space in between) and surrounded by + whitespace. A base-n literal consists of the digits 0 to n-1, with ``a`` + to ``z`` (or ``A`` to ``Z``) having + values 10 to 35. The default *base* is 10. The allowed values are 0 and 2--36. + Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``, + ``0o``/``0O``, or ``0x``/``0X``, as with integer literals in code. Base 0 + means to interpret exactly as a code literal, so that the actual base is 2, + 8, 10, or 16, and so that ``int('010', 0)`` is not legal, while + ``int('010')`` is, as well as ``int('010', 8)``. + + The integer type is described in :ref:`typesnumeric`. + + .. versionchanged:: 3.4 + If *base* is not an instance of :class:`int` and the *base* object has a + :meth:`base.__index__ ` method, that method is called + to obtain an integer for the base. Previous versions used + :meth:`base.__int__ ` instead of :meth:`base.__index__ + `. + + .. versionchanged:: 3.6 + Grouping digits with underscores as in code literals is allowed. + + .. versionchanged:: 3.7 + *x* is now a positional-only parameter. + + .. versionchanged:: 3.8 + Falls back to :meth:`__index__` if :meth:`__int__` is not defined. + + +.. function:: isinstance(object, classinfo) + + Return ``True`` if the *object* argument is an instance of the *classinfo* + argument, or of a (direct, indirect or :term:`virtual `) subclass thereof. If *object* is not + an object of the given type, the function always returns ``False``. + If *classinfo* is a tuple of type objects (or recursively, other such + tuples), return ``True`` if *object* is an instance of any of the types. + If *classinfo* is not a type or tuple of types and such tuples, + a :exc:`TypeError` exception is raised. + + +.. function:: issubclass(class, classinfo) + + Return ``True`` if *class* is a subclass (direct, indirect or :term:`virtual + `) of *classinfo*. A + class is considered a subclass of itself. *classinfo* may be a tuple of class + objects, in which case every entry in *classinfo* will be checked. In any other + case, a :exc:`TypeError` exception is raised. + + +.. function:: iter(object[, sentinel]) + + Return an :term:`iterator` object. The first argument is interpreted very + differently depending on the presence of the second argument. Without a + second argument, *object* must be a collection object which supports the + iteration protocol (the :meth:`__iter__` method), or it must support the + sequence protocol (the :meth:`__getitem__` method with integer arguments + starting at ``0``). If it does not support either of those protocols, + :exc:`TypeError` is raised. If the second argument, *sentinel*, is given, + then *object* must be a callable object. The iterator created in this case + will call *object* with no arguments for each call to its + :meth:`~iterator.__next__` method; if the value returned is equal to + *sentinel*, :exc:`StopIteration` will be raised, otherwise the value will + be returned. + + See also :ref:`typeiter`. + + One useful application of the second form of :func:`iter` is to build a + block-reader. For example, reading fixed-width blocks from a binary + database file until the end of file is reached:: + + from functools import partial + with open('mydata.db', 'rb') as f: + for block in iter(partial(f.read, 64), b''): + process_block(block) + + +.. function:: len(s) + + Return the length (the number of items) of an object. The argument may be a + sequence (such as a string, bytes, tuple, list, or range) or a collection + (such as a dictionary, set, or frozen set). + + .. impl-detail:: + + ``len`` raises :exc:`OverflowError` on lengths larger than + :data:`sys.maxsize`, such as :class:`range(2 ** 100) `. + + +.. _func-list: +.. class:: list([iterable]) + :noindex: + + Rather than being a function, :class:`list` is actually a mutable + sequence type, as documented in :ref:`typesseq-list` and :ref:`typesseq`. + + +.. function:: locals() + + Update and return a dictionary representing the current local symbol table. + Free variables are returned by :func:`locals` when it is called in function + blocks, but not in class blocks. Note that at the module level, :func:`locals` + and :func:`globals` are the same dictionary. + + .. note:: + The contents of this dictionary should not be modified; changes may not + affect the values of local and free variables used by the interpreter. + +.. function:: map(function, iterable, ...) + + Return an iterator that applies *function* to every item of *iterable*, + yielding the results. If additional *iterable* arguments are passed, + *function* must take that many arguments and is applied to the items from all + iterables in parallel. With multiple iterables, the iterator stops when the + shortest iterable is exhausted. For cases where the function inputs are + already arranged into argument tuples, see :func:`itertools.starmap`\. + + +.. function:: max(iterable, *[, key, default]) + max(arg1, arg2, *args[, key]) + + Return the largest item in an iterable or the largest of two or more + arguments. + + If one positional argument is provided, it should be an :term:`iterable`. + The largest item in the iterable is returned. If two or more positional + arguments are provided, the largest of the positional arguments is + returned. + + There are two optional keyword-only arguments. The *key* argument specifies + a one-argument ordering function like that used for :meth:`list.sort`. The + *default* argument specifies an object to return if the provided iterable is + empty. If the iterable is empty and *default* is not provided, a + :exc:`ValueError` is raised. + + If multiple items are maximal, the function returns the first one + encountered. This is consistent with other sort-stability preserving tools + such as ``sorted(iterable, key=keyfunc, reverse=True)[0]`` and + ``heapq.nlargest(1, iterable, key=keyfunc)``. + + .. versionadded:: 3.4 + The *default* keyword-only argument. + + .. versionchanged:: 3.8 + The *key* can be ``None``. + + +.. _func-memoryview: +.. class:: memoryview(obj) + :noindex: + + Return a "memory view" object created from the given argument. See + :ref:`typememoryview` for more information. + + +.. function:: min(iterable, *[, key, default]) + min(arg1, arg2, *args[, key]) + + Return the smallest item in an iterable or the smallest of two or more + arguments. + + If one positional argument is provided, it should be an :term:`iterable`. + The smallest item in the iterable is returned. If two or more positional + arguments are provided, the smallest of the positional arguments is + returned. + + There are two optional keyword-only arguments. The *key* argument specifies + a one-argument ordering function like that used for :meth:`list.sort`. The + *default* argument specifies an object to return if the provided iterable is + empty. If the iterable is empty and *default* is not provided, a + :exc:`ValueError` is raised. + + If multiple items are minimal, the function returns the first one + encountered. This is consistent with other sort-stability preserving tools + such as ``sorted(iterable, key=keyfunc)[0]`` and ``heapq.nsmallest(1, + iterable, key=keyfunc)``. + + .. versionadded:: 3.4 + The *default* keyword-only argument. + + .. versionchanged:: 3.8 + The *key* can be ``None``. + + +.. function:: next(iterator[, default]) + + Retrieve the next item from the *iterator* by calling its + :meth:`~iterator.__next__` method. If *default* is given, it is returned + if the iterator is exhausted, otherwise :exc:`StopIteration` is raised. + + +.. class:: object() + + Return a new featureless object. :class:`object` is a base for all classes. + It has the methods that are common to all instances of Python classes. This + function does not accept any arguments. + + .. note:: + + :class:`object` does *not* have a :attr:`~object.__dict__`, so you can't + assign arbitrary attributes to an instance of the :class:`object` class. + + +.. function:: oct(x) + + Convert an integer number to an octal string prefixed with "0o". The result + is a valid Python expression. If *x* is not a Python :class:`int` object, it + has to define an :meth:`__index__` method that returns an integer. For + example: + + >>> oct(8) + '0o10' + >>> oct(-56) + '-0o70' + + If you want to convert an integer number to octal string either with prefix + "0o" or not, you can use either of the following ways. + + >>> '%#o' % 10, '%o' % 10 + ('0o12', '12') + >>> format(10, '#o'), format(10, 'o') + ('0o12', '12') + >>> f'{10:#o}', f'{10:o}' + ('0o12', '12') + + See also :func:`format` for more information. + + .. index:: + single: file object; open() built-in function + +.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) + + Open *file* and return a corresponding :term:`file object`. If the file + cannot be opened, an :exc:`OSError` is raised. + + *file* is a :term:`path-like object` giving the pathname (absolute or + relative to 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 is + given, it is closed when the returned I/O object is closed, unless *closefd* + is set to ``False``.) + + *mode* is an optional string that specifies the mode in which the file is + opened. It defaults to ``'r'`` which means open for reading in text mode. + Other common values are ``'w'`` for writing (truncating the file if it + already exists), ``'x'`` for exclusive creation and ``'a'`` for appending + (which on *some* Unix systems, means that *all* writes append to the end of + the file regardless of the current seek position). In text mode, if + *encoding* is not specified the encoding used is platform dependent: + ``locale.getpreferredencoding(False)`` is called to get the current locale + encoding. (For reading and writing raw bytes use binary mode and leave + *encoding* unspecified.) The available modes are: + + .. _filemodes: + + .. index:: + pair: file; modes + + ========= =============================================================== + Character Meaning + ========= =============================================================== + ``'r'`` open for reading (default) + ``'w'`` open for writing, truncating the file first + ``'x'`` open for exclusive creation, failing if the file already exists + ``'a'`` open for writing, appending to the end of the file if it exists + ``'b'`` binary mode + ``'t'`` text mode (default) + ``'+'`` open for updating (reading and writing) + ========= =============================================================== + + The default mode is ``'r'`` (open for reading text, synonym of ``'rt'``). + Modes ``'w+'`` and ``'w+b'`` open and truncate the file. Modes ``'r+'`` + and ``'r+b'`` open the file with no truncation. + + As mentioned in the :ref:`io-overview`, Python distinguishes between binary + and text I/O. Files opened in binary mode (including ``'b'`` in the *mode* + argument) return contents as :class:`bytes` objects without any decoding. In + text mode (the default, or when ``'t'`` is included in the *mode* argument), + the contents of the file are returned as :class:`str`, the bytes having been + first decoded using a platform-dependent encoding or using the specified + *encoding* if given. + + There is an additional mode character permitted, ``'U'``, which no longer + has any effect, and is considered deprecated. It previously enabled + :term:`universal newlines` in text mode, which became the default behaviour + in Python 3.0. Refer to the documentation of the + :ref:`newline ` parameter for further details. + + .. note:: + + Python doesn't depend on the underlying operating system's notion of text + files; all the processing is done by Python itself, and is therefore + platform-independent. + + *buffering* is an optional integer used to set the buffering policy. Pass 0 + to switch buffering off (only allowed in binary mode), 1 to select line + buffering (only usable in text mode), and an integer > 1 to indicate the size + in bytes of a fixed-size chunk buffer. When no *buffering* argument is + given, the default buffering policy works as follows: + + * Binary files are buffered in fixed-size chunks; the size of the buffer is + chosen using a heuristic trying to determine the underlying device's "block + size" and falling back on :attr:`io.DEFAULT_BUFFER_SIZE`. On many systems, + the buffer will typically be 4096 or 8192 bytes long. + + * "Interactive" text files (files for which :meth:`~io.IOBase.isatty` + returns ``True``) use line buffering. Other text files use the policy + described above for binary files. + + *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 (whatever :func:`locale.getpreferredencoding` returns), but any + :term:`text encoding` supported by Python + can be used. See the :mod:`codecs` module for + the list of supported encodings. + + *errors* is an optional string that specifies how encoding and decoding + errors are to be handled—this cannot be used in binary mode. + A variety of standard error handlers are available + (listed under :ref:`error-handlers`), though any + error handling name that has been registered with + :func:`codecs.register_error` is also valid. The standard names + include: + + * ``'strict'`` to raise a :exc:`ValueError` exception if there is + an encoding error. The default value of ``None`` has the same + effect. + + * ``'ignore'`` ignores errors. Note that ignoring encoding errors + can lead to data loss. + + * ``'replace'`` causes a replacement marker (such as ``'?'``) to be inserted + where there is malformed data. + + * ``'surrogateescape'`` will represent any incorrect bytes as code + points in the Unicode Private Use Area ranging from U+DC80 to + U+DCFF. These private code points will then be turned back into + the same bytes when the ``surrogateescape`` error handler is used + when writing data. This is useful for processing files in an + unknown encoding. + + * ``'xmlcharrefreplace'`` is only supported when writing to a file. + Characters not supported by the encoding are replaced with the + appropriate XML character reference ``&#nnn;``. + + * ``'backslashreplace'`` replaces malformed data by Python's backslashed + escape sequences. + + * ``'namereplace'`` (also only supported when writing) + replaces unsupported characters with ``\N{...}`` escape sequences. + + .. index:: + single: universal newlines; open() built-in function + + .. _open-newline-parameter: + + *newline* controls how :term:`universal newlines` mode works (it only + applies to text mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and + ``'\r\n'``. It works as follows: + + * When reading input from the stream, if *newline* is ``None``, universal + newlines mode is enabled. Lines in the input can end in ``'\n'``, + ``'\r'``, or ``'\r\n'``, and these are translated into ``'\n'`` before + being returned to the caller. If it is ``''``, universal newlines mode is + enabled, but line endings are returned to the caller untranslated. If it + has any of the other legal values, input lines are only terminated by the + given string, and the line ending is returned to the caller untranslated. + + * When writing output to the stream, if *newline* is ``None``, any ``'\n'`` + characters written are translated to the system default line separator, + :data:`os.linesep`. If *newline* is ``''`` or ``'\n'``, no translation + takes place. If *newline* is any of the other legal values, any ``'\n'`` + characters written are translated to the given string. + + If *closefd* is ``False`` and a file descriptor rather than a filename was + given, the underlying file descriptor will be kept open when the file is + closed. If a filename is given *closefd* must be ``True`` (the default) + otherwise an error will be raised. + + A custom opener can be used by passing a callable as *opener*. The underlying + file descriptor for the file object is then obtained by calling *opener* with + (*file*, *flags*). *opener* must return an open file descriptor (passing + :mod:`os.open` as *opener* results in functionality similar to passing + ``None``). + + The newly created file is :ref:`non-inheritable `. + + The following example uses the :ref:`dir_fd ` parameter of the + :func:`os.open` function to open a file relative to a given directory:: + + >>> import os + >>> dir_fd = os.open('somedir', os.O_RDONLY) + >>> def opener(path, flags): + ... return os.open(path, flags, dir_fd=dir_fd) + ... + >>> with open('spamspam.txt', 'w', opener=opener) as f: + ... print('This will be written to somedir/spamspam.txt', file=f) + ... + >>> os.close(dir_fd) # don't leak a file descriptor + + The type of :term:`file object` returned by the :func:`open` function + depends on the mode. When :func:`open` is used to open a file in a text + mode (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of + :class:`io.TextIOBase` (specifically :class:`io.TextIOWrapper`). When used + to open a file in a binary mode with buffering, the returned class is a + subclass of :class:`io.BufferedIOBase`. The exact class varies: in read + binary mode, it returns an :class:`io.BufferedReader`; in write binary and + append binary modes, it returns an :class:`io.BufferedWriter`, and in + read/write mode, it returns an :class:`io.BufferedRandom`. When buffering is + disabled, the raw stream, a subclass of :class:`io.RawIOBase`, + :class:`io.FileIO`, is returned. + + .. index:: + single: line-buffered I/O + single: unbuffered I/O + single: buffer size, I/O + single: I/O control; buffering + single: binary mode + single: text mode + module: sys + + See also the file handling modules, such as, :mod:`fileinput`, :mod:`io` + (where :func:`open` is declared), :mod:`os`, :mod:`os.path`, :mod:`tempfile`, + and :mod:`shutil`. + + .. audit-event:: open file,mode,flags open + + The ``mode`` and ``flags`` arguments may have been modified or inferred from + the original call. + + .. versionchanged:: + 3.3 + + * The *opener* parameter was added. + * The ``'x'`` mode was added. + * :exc:`IOError` used to be raised, it is now an alias of :exc:`OSError`. + * :exc:`FileExistsError` is now raised if the file opened in exclusive + creation mode (``'x'``) already exists. + + .. versionchanged:: + 3.4 + + * The file is now non-inheritable. + + .. deprecated-removed:: 3.4 3.10 + + The ``'U'`` mode. + + .. versionchanged:: + 3.5 + + * If the system call is interrupted and the signal handler does not raise an + exception, the function now retries the system call instead of raising an + :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + * The ``'namereplace'`` error handler was added. + + .. versionchanged:: + 3.6 + + * Support added to accept objects implementing :class:`os.PathLike`. + * On Windows, opening a console buffer may return a subclass of + :class:`io.RawIOBase` other than :class:`io.FileIO`. + +.. function:: ord(c) + + Given a string representing one Unicode character, return an integer + representing the Unicode code point of that character. For example, + ``ord('a')`` returns the integer ``97`` and ``ord('€')`` (Euro sign) + returns ``8364``. This is the inverse of :func:`chr`. + + +.. function:: pow(base, exp[, mod]) + + Return *base* to the power *exp*; if *mod* is present, return *base* to the + power *exp*, modulo *mod* (computed more efficiently than + ``pow(base, exp) % mod``). The two-argument form ``pow(base, exp)`` is + equivalent to using the power operator: ``base**exp``. + + The arguments must have numeric types. With mixed operand types, the + coercion rules for binary arithmetic operators apply. For :class:`int` + operands, the result has the same type as the operands (after coercion) + unless the second argument is negative; in that case, all arguments are + converted to float and a float result is delivered. For example, ``10**2`` + returns ``100``, but ``10**-2`` returns ``0.01``. + + For :class:`int` operands *base* and *exp*, if *mod* is present, *mod* must + also be of integer type and *mod* must be nonzero. If *mod* is present and + *exp* is negative, *base* must be relatively prime to *mod*. In that case, + ``pow(inv_base, -exp, mod)`` is returned, where *inv_base* is an inverse to + *base* modulo *mod*. + + Here's an example of computing an inverse for ``38`` modulo ``97``:: + + >>> pow(38, -1, mod=97) + 23 + >>> 23 * 38 % 97 == 1 + True + + .. versionchanged:: 3.8 + For :class:`int` operands, the three-argument form of ``pow`` now allows + the second argument to be negative, permitting computation of modular + inverses. + + .. versionchanged:: 3.8 + Allow keyword arguments. Formerly, only positional arguments were + supported. + + +.. function:: print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False) + + Print *objects* to the text stream *file*, separated by *sep* and followed + by *end*. *sep*, *end*, *file* and *flush*, if present, must be given as keyword + arguments. + + All non-keyword arguments are converted to strings like :func:`str` does and + written to the stream, separated by *sep* and followed by *end*. Both *sep* + and *end* must be strings; they can also be ``None``, which means to use the + default values. If no *objects* are given, :func:`print` will just write + *end*. + + The *file* argument must be an object with a ``write(string)`` method; if it + is not present or ``None``, :data:`sys.stdout` will be used. Since printed + arguments are converted to text strings, :func:`print` cannot be used with + binary mode file objects. For these, use ``file.write(...)`` instead. + + Whether output is buffered is usually determined by *file*, but if the + *flush* keyword argument is true, the stream is forcibly flushed. + + .. versionchanged:: 3.3 + Added the *flush* keyword argument. + + +.. class:: property(fget=None, fset=None, fdel=None, doc=None) + + Return a property attribute. + + *fget* is a function for getting an attribute value. *fset* is a function + for setting an attribute value. *fdel* is a function for deleting an attribute + value. And *doc* creates a docstring for the attribute. + + A typical use is to define a managed attribute ``x``:: + + class C: + def __init__(self): + self._x = None + + def getx(self): + return self._x + + def setx(self, value): + self._x = value + + def delx(self): + del self._x + + x = property(getx, setx, delx, "I'm the 'x' property.") + + If *c* is an instance of *C*, ``c.x`` will invoke the getter, + ``c.x = value`` will invoke the setter and ``del c.x`` the deleter. + + If given, *doc* will be the docstring of the property attribute. Otherwise, the + property will copy *fget*'s docstring (if it exists). This makes it possible to + create read-only properties easily using :func:`property` as a :term:`decorator`:: + + class Parrot: + def __init__(self): + self._voltage = 100000 + + @property + def voltage(self): + """Get the current voltage.""" + return self._voltage + + The ``@property`` decorator turns the :meth:`voltage` method into a "getter" + for a read-only attribute with the same name, and it sets the docstring for + *voltage* to "Get the current voltage." + + A property object has :attr:`~property.getter`, :attr:`~property.setter`, + and :attr:`~property.deleter` methods usable as decorators that create a + copy of the property with the corresponding accessor function set to the + decorated function. This is best explained with an example:: + + class C: + def __init__(self): + self._x = None + + @property + def x(self): + """I'm the 'x' property.""" + return self._x + + @x.setter + def x(self, value): + self._x = value + + @x.deleter + def x(self): + del self._x + + This code is exactly equivalent to the first example. Be sure to give the + additional functions the same name as the original property (``x`` in this + case.) + + The returned property object also has the attributes ``fget``, ``fset``, and + ``fdel`` corresponding to the constructor arguments. + + .. versionchanged:: 3.5 + The docstrings of property objects are now writeable. + + +.. _func-range: +.. class:: range(stop) + range(start, stop[, step]) + :noindex: + + Rather than being a function, :class:`range` is actually an immutable + sequence type, as documented in :ref:`typesseq-range` and :ref:`typesseq`. + + +.. function:: repr(object) + + Return a string containing a printable representation of an object. For many + types, this function makes an attempt to return a string that would yield an + object with the same value when passed to :func:`eval`, otherwise the + representation is a string enclosed in angle brackets that contains the name + of the type of the object together with additional information often + including the name and address of the object. A class can control what this + function returns for its instances by defining a :meth:`__repr__` method. + + +.. function:: reversed(seq) + + Return a reverse :term:`iterator`. *seq* must be an object which has + a :meth:`__reversed__` method or supports the sequence protocol (the + :meth:`__len__` method and the :meth:`__getitem__` method with integer + arguments starting at ``0``). + + +.. function:: round(number[, ndigits]) + + Return *number* rounded to *ndigits* precision after the decimal + point. If *ndigits* is omitted or is ``None``, it returns the + nearest integer to its input. + + For the built-in types supporting :func:`round`, values are rounded to the + closest multiple of 10 to the power minus *ndigits*; if two multiples are + equally close, rounding is done toward the even choice (so, for example, + both ``round(0.5)`` and ``round(-0.5)`` are ``0``, and ``round(1.5)`` is + ``2``). Any integer value is valid for *ndigits* (positive, zero, or + negative). The return value is an integer if *ndigits* is omitted or + ``None``. + Otherwise the return value has the same type as *number*. + + For a general Python object ``number``, ``round`` delegates to + ``number.__round__``. + + .. note:: + + The behavior of :func:`round` for floats can be surprising: for example, + ``round(2.675, 2)`` gives ``2.67`` instead of the expected ``2.68``. + This is not a bug: it's a result of the fact that most decimal fractions + can't be represented exactly as a float. See :ref:`tut-fp-issues` for + more information. + + +.. _func-set: +.. class:: set([iterable]) + :noindex: + + Return a new :class:`set` object, optionally with elements taken from + *iterable*. ``set`` is a built-in class. See :class:`set` and + :ref:`types-set` for documentation about this class. + + For other containers see the built-in :class:`frozenset`, :class:`list`, + :class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections` + module. + + +.. function:: setattr(object, name, value) + + This is the counterpart of :func:`getattr`. The arguments are an object, a + string and an arbitrary value. The string may name an existing attribute or a + new attribute. The function assigns the value to the attribute, provided the + object allows it. For example, ``setattr(x, 'foobar', 123)`` is equivalent to + ``x.foobar = 123``. + + +.. class:: slice(stop) + slice(start, stop[, step]) + + .. index:: single: Numerical Python + + Return a :term:`slice` object representing the set of indices specified by + ``range(start, stop, step)``. The *start* and *step* arguments default to + ``None``. Slice objects have read-only data attributes :attr:`~slice.start`, + :attr:`~slice.stop` and :attr:`~slice.step` which merely return the argument + values (or their default). They have no other explicit functionality; + however they are used by Numerical Python and other third party extensions. + Slice objects are also generated when extended indexing syntax is used. For + example: ``a[start:stop:step]`` or ``a[start:stop, i]``. See + :func:`itertools.islice` for an alternate version that returns an iterator. + + +.. function:: sorted(iterable, *, key=None, reverse=False) + + Return a new sorted list from the items in *iterable*. + + Has two optional arguments which must be specified as keyword arguments. + + *key* specifies a function of one argument that is used to extract a comparison + key from each element in *iterable* (for example, ``key=str.lower``). The + default value is ``None`` (compare the elements directly). + + *reverse* is a boolean value. If set to ``True``, then the list elements are + sorted as if each comparison were reversed. + + Use :func:`functools.cmp_to_key` to convert an old-style *cmp* function to a + *key* function. + + The built-in :func:`sorted` function is guaranteed to be stable. A sort is + stable if it guarantees not to change the relative order of elements that + compare equal --- this is helpful for sorting in multiple passes (for + example, sort by department, then by salary grade). + + For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`. + +.. decorator:: staticmethod + + Transform a method into a static method. + + A static method does not receive an implicit first argument. To declare a static + method, use this idiom:: + + class C: + @staticmethod + def f(arg1, arg2, ...): ... + + The ``@staticmethod`` form is a function :term:`decorator` -- see + :ref:`function` for details. + + A static method can be called either on the class (such as ``C.f()``) or on an instance (such + as ``C().f()``). + + Static methods in Python are similar to those found in Java or C++. Also see + :func:`classmethod` for a variant that is useful for creating alternate class + constructors. + + Like all decorators, it is also possible to call ``staticmethod`` as + a regular function and do something with its result. This is needed + in some cases where you need a reference to a function from a class + body and you want to avoid the automatic transformation to instance + method. For these cases, use this idiom:: + + class C: + builtin_open = staticmethod(open) + + For more information on static methods, see :ref:`types`. + + +.. index:: + single: string; str() (built-in function) + +.. _func-str: +.. class:: str(object='') + str(object=b'', encoding='utf-8', errors='strict') + :noindex: + + Return a :class:`str` version of *object*. See :func:`str` for details. + + ``str`` is the built-in string :term:`class`. For general information + about strings, see :ref:`textseq`. + + +.. function:: sum(iterable, /, start=0) + + Sums *start* and the items of an *iterable* from left to right and returns the + total. The *iterable*'s items are normally numbers, and the start value is not + allowed to be a string. + + For some use cases, there are good alternatives to :func:`sum`. + The preferred, fast way to concatenate a sequence of strings is by calling + ``''.join(sequence)``. To add floating point values with extended precision, + see :func:`math.fsum`\. To concatenate a series of iterables, consider using + :func:`itertools.chain`. + + .. versionchanged:: 3.8 + The *start* parameter can be specified as a keyword argument. + +.. function:: super([type[, object-or-type]]) + + Return a proxy object that delegates method calls to a parent or sibling + class of *type*. This is useful for accessing inherited methods that have + been overridden in a class. + + The *object-or-type* determines the :term:`method resolution order` + to be searched. The search starts from the class right after the + *type*. + + For example, if :attr:`~class.__mro__` of *object-or-type* is + ``D -> B -> C -> A -> object`` and the value of *type* is ``B``, + then :func:`super` searches ``C -> A -> object``. + + The :attr:`~class.__mro__` attribute of the *object-or-type* lists the method + resolution search order used by both :func:`getattr` and :func:`super`. The + attribute is dynamic and can change whenever the inheritance hierarchy is + updated. + + If the second argument is omitted, the super object returned is unbound. If + the second argument is an object, ``isinstance(obj, type)`` must be true. If + the second argument is a type, ``issubclass(type2, type)`` must be true (this + is useful for classmethods). + + There are two typical use cases for *super*. In a class hierarchy with + single inheritance, *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 inheritance 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 + single inheritance. This makes it 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 + order of calls is determined at runtime, because that order adapts + to changes in the class hierarchy, and because that order can include + sibling classes that are unknown prior to runtime). + + For both use cases, a typical superclass call looks like this:: + + class C(B): + def method(self, arg): + super().method(arg) # This does the same thing as: + # super(C, self).method(arg) + + In addition to method lookups, :func:`super` also works for attribute + lookups. One possible use case for this is calling :term:`descriptors ` + in a parent or sibling class. + + Note that :func:`super` is implemented as part of the binding process for + explicit dotted attribute lookups such as ``super().__getitem__(name)``. + It does so by implementing its own :meth:`__getattribute__` method for searching + classes in a predictable order that supports cooperative multiple inheritance. + Accordingly, :func:`super` is undefined for implicit lookups using statements or + operators such as ``super()[name]``. + + Also note that, aside from the zero argument form, :func:`super` is not + limited to use inside methods. The two argument form specifies the + arguments exactly and makes the appropriate references. The zero + argument form only works inside a class definition, as the compiler fills + in the necessary details to correctly retrieve the class being defined, + as well as accessing the current instance for ordinary methods. + + For practical suggestions on how to design cooperative classes using + :func:`super`, see `guide to using super() + `_. + + +.. _func-tuple: +.. class:: tuple([iterable]) + :noindex: + + Rather than being a function, :class:`tuple` is actually an immutable + sequence type, as documented in :ref:`typesseq-tuple` and :ref:`typesseq`. + + +.. class:: type(object) + type(name, bases, dict) + + .. index:: object: type + + With one argument, return the type of an *object*. The return value is a + type object and generally the same object as returned by + :attr:`object.__class__ `. + + The :func:`isinstance` built-in function is recommended for testing the type + of an object, because it takes subclasses into account. + + + With three arguments, return a new type object. This is essentially a + dynamic form of the :keyword:`class` statement. The *name* string is the + class name and becomes the :attr:`~definition.__name__` attribute; the *bases* + tuple itemizes the base classes and becomes the :attr:`~class.__bases__` + attribute; and the *dict* dictionary is the namespace containing definitions + for class body and is copied to a standard dictionary to become the + :attr:`~object.__dict__` attribute. For example, the following two + statements create identical :class:`type` objects: + + >>> class X: + ... a = 1 + ... + >>> X = type('X', (object,), dict(a=1)) + + See also :ref:`bltin-type-objects`. + + .. versionchanged:: 3.6 + Subclasses of :class:`type` which don't override ``type.__new__`` may no + longer use the one-argument form to get the type of an object. + +.. function:: vars([object]) + + Return the :attr:`~object.__dict__` attribute for a module, class, instance, + or any other object with a :attr:`~object.__dict__` attribute. + + Objects such as modules and instances have an updateable :attr:`~object.__dict__` + attribute; however, other objects may have write restrictions on their + :attr:`~object.__dict__` attributes (for example, classes use a + :class:`types.MappingProxyType` to prevent direct dictionary updates). + + Without an argument, :func:`vars` acts like :func:`locals`. Note, the + locals dictionary is only useful for reads since updates to the locals + dictionary are ignored. + + +.. function:: zip(*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, + it returns an empty iterator. Equivalent to:: + + def zip(*iterables): + # zip('ABCD', 'xy') --> Ax By + sentinel = object() + iterators = [iter(it) for it in iterables] + while iterators: + result = [] + for it in iterators: + elem = next(it, sentinel) + if elem is sentinel: + return + result.append(elem) + yield tuple(result) + + The left-to-right evaluation order of the iterables is guaranteed. This + makes possible an idiom for clustering a data series into n-length groups + using ``zip(*[iter(s)]*n)``. This repeats the *same* iterator ``n`` times + so that each output tuple has the result of ``n`` calls to the iterator. + This has the effect of dividing the input into n-length chunks. + + :func:`zip` should only be used with unequal length inputs when you don't + care about trailing, unmatched values from the longer iterables. If those + values are important, use :func:`itertools.zip_longest` instead. + + :func:`zip` in conjunction with the ``*`` operator can be used to unzip a + list:: + + >>> x = [1, 2, 3] + >>> y = [4, 5, 6] + >>> zipped = zip(x, y) + >>> list(zipped) + [(1, 4), (2, 5), (3, 6)] + >>> x2, y2 = zip(*zip(x, y)) + >>> x == list(x2) and y == list(y2) + True + + +.. function:: __import__(name, globals=None, locals=None, fromlist=(), level=0) + + .. index:: + statement: import + module: imp + + .. note:: + + This is an advanced function that is not needed in everyday Python + programming, unlike :func:`importlib.import_module`. + + This function is invoked by the :keyword:`import` statement. It can be + replaced (by importing the :mod:`builtins` module and assigning to + ``builtins.__import__``) in order to change semantics of the + :keyword:`!import` statement, but doing so is **strongly** discouraged as it + is usually simpler to use import hooks (see :pep:`302`) to attain the same + goals and does not cause issues with code which assumes the default import + implementation is in use. Direct use of :func:`__import__` is also + discouraged in favor of :func:`importlib.import_module`. + + The function imports the module *name*, potentially using the given *globals* + and *locals* to determine how to interpret the name in a package context. + The *fromlist* gives the names of objects or submodules that should be + imported from the module given by *name*. The standard implementation does + not use its *locals* argument at all, and uses its *globals* only to + determine the package context of the :keyword:`import` statement. + + *level* specifies whether to use absolute or relative imports. ``0`` (the + default) means only perform absolute imports. Positive values for + *level* indicate the number of parent directories to search relative to the + directory of the module calling :func:`__import__` (see :pep:`328` for the + details). + + When the *name* variable is of the form ``package.module``, normally, the + top-level package (the name up till the first dot) is returned, *not* the + module named by *name*. However, when a non-empty *fromlist* argument is + given, the module named by *name* is returned. + + For example, the statement ``import spam`` results in bytecode resembling the + following code:: + + spam = __import__('spam', globals(), locals(), [], 0) + + The statement ``import spam.ham`` results in this call:: + + spam = __import__('spam.ham', globals(), locals(), [], 0) + + Note how :func:`__import__` returns the toplevel module here because this is + the object that is bound to a name by the :keyword:`import` statement. + + On the other hand, the statement ``from spam.ham import eggs, sausage as + saus`` results in :: + + _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) + eggs = _temp.eggs + saus = _temp.sausage + + Here, the ``spam.ham`` module is returned from :func:`__import__`. From this + object, the names to import are retrieved and assigned to their respective + names. + + If you simply want to import a module (potentially within a package) by name, + use :func:`importlib.import_module`. + + .. versionchanged:: 3.3 + Negative values for *level* are no longer supported (which also changes + the default value to 0). + + .. versionchanged:: 3.9 + When the command line options :option:`-E` or :option:`-I` are being used, + the environment variable :envvar:`PYTHONCASEOK` is now ignored. + +.. rubric:: Footnotes + +.. [#] Note that the parser only accepts the Unix-style end of line convention. + If you are reading the code from a file, make sure to use newline conversion + mode to convert Windows or Mac-style newlines. diff --git a/cpython_2/environment/repo/Doc/library/functools.rst b/cpython_2/environment/repo/Doc/library/functools.rst new file mode 100644 index 0000000000000000000000000000000000000000..a44eb85b27dbab6712f6dc4199a76625426f1290 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/functools.rst @@ -0,0 +1,848 @@ +:mod:`functools` --- Higher-order functions and operations on callable objects +============================================================================== + +.. module:: functools + :synopsis: Higher-order functions and operations on callable objects. + +.. moduleauthor:: Peter Harris +.. moduleauthor:: Raymond Hettinger +.. moduleauthor:: Nick Coghlan +.. moduleauthor:: Łukasz Langa +.. moduleauthor:: Pablo Galindo +.. sectionauthor:: Peter Harris + +**Source code:** :source:`Lib/functools.py` + +.. testsetup:: default + + import functools + from functools import * + +-------------- + +The :mod:`functools` module is for higher-order functions: functions that act on +or return other functions. In general, any callable object can be treated as a +function for the purposes of this module. + +The :mod:`functools` module defines the following functions: + +.. decorator:: cache(user_function) + + Simple lightweight unbounded function cache. Sometimes called + `"memoize" `_. + + Returns the same as ``lru_cache(maxsize=None)``, creating a thin + wrapper around a dictionary lookup for the function arguments. Because it + never needs to evict old values, this is smaller and faster than + :func:`lru_cache()` with a size limit. + + For example:: + + @cache + def factorial(n): + return n * factorial(n-1) if n else 1 + + >>> factorial(10) # no previously cached result, makes 11 recursive calls + 3628800 + >>> factorial(5) # just looks up cached value result + 120 + >>> factorial(12) # makes two new recursive calls, the other 10 are cached + 479001600 + + .. versionadded:: 3.9 + + +.. decorator:: cached_property(func) + + Transform a method of a class into a property whose value is computed once + and then cached as a normal attribute for the life of the instance. Similar + to :func:`property`, with the addition of caching. Useful for expensive + computed properties of instances that are otherwise effectively immutable. + + Example:: + + class DataSet: + def __init__(self, sequence_of_numbers): + self._data = sequence_of_numbers + + @cached_property + def stdev(self): + return statistics.stdev(self._data) + + @cached_property + def variance(self): + return statistics.variance(self._data) + + .. versionadded:: 3.8 + + .. note:: + + This decorator requires that the ``__dict__`` attribute on each instance + be a mutable mapping. This means it will not work with some types, such as + metaclasses (since the ``__dict__`` attributes on type instances are + read-only proxies for the class namespace), and those that specify + ``__slots__`` without including ``__dict__`` as one of the defined slots + (as such classes don't provide a ``__dict__`` attribute at all). + + +.. function:: cmp_to_key(func) + + Transform an old-style comparison function to a :term:`key function`. Used + with tools that accept key functions (such as :func:`sorted`, :func:`min`, + :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`, + :func:`itertools.groupby`). This function is primarily used as a transition + tool for programs being converted from Python 2 which supported the use of + comparison functions. + + A comparison function is any callable that accept two arguments, compares them, + and returns a negative number for less-than, zero for equality, or a positive + number for greater-than. A key function is a callable that accepts one + argument and returns another value to be used as the sort key. + + Example:: + + sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order + + For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`. + + .. versionadded:: 3.2 + + +.. decorator:: lru_cache(user_function) + lru_cache(maxsize=128, typed=False) + + Decorator to wrap a function with a memoizing callable that saves up to the + *maxsize* most recent calls. It can save time when an expensive or I/O bound + function is periodically called with the same arguments. + + Since a dictionary is used to cache results, the positional and keyword + arguments to the function must be hashable. + + Distinct argument patterns may be considered to be distinct calls with + separate cache entries. For example, `f(a=1, b=2)` and `f(b=2, a=1)` + differ in their keyword argument order and may have two separate cache + entries. + + If *user_function* is specified, it must be a callable. This allows the + *lru_cache* decorator to be applied directly to a user function, leaving + the *maxsize* at its default value of 128:: + + @lru_cache + def count_vowels(sentence): + sentence = sentence.casefold() + return sum(sentence.count(vowel) for vowel in 'aeiou') + + If *maxsize* is set to ``None``, the LRU feature is disabled and the cache can + grow without bound. + + If *typed* is set to true, function arguments of different types will be + cached separately. For example, ``f(3)`` and ``f(3.0)`` will be treated + as distinct calls with distinct results. + + The wrapped function is instrumented with a :func:`cache_parameters` + function that returns a new :class:`dict` showing the values for *maxsize* + and *typed*. This is for information purposes only. Mutating the values + has no effect. + + To help measure the effectiveness of the cache and tune the *maxsize* + parameter, the wrapped function is instrumented with a :func:`cache_info` + function that returns a :term:`named tuple` showing *hits*, *misses*, + *maxsize* and *currsize*. In a multi-threaded environment, the hits + and misses are approximate. + + The decorator also provides a :func:`cache_clear` function for clearing or + invalidating the cache. + + The original underlying function is accessible through the + :attr:`__wrapped__` attribute. This is useful for introspection, for + bypassing the cache, or for rewrapping the function with a different cache. + + An `LRU (least recently used) cache + `_ + works best when the most recent calls are the best predictors of upcoming + calls (for example, the most popular articles on a news server tend to + change each day). The cache's size limit assures that the cache does not + grow without bound on long-running processes such as web servers. + + In general, the LRU cache should only be used when you want to reuse + previously computed values. Accordingly, it doesn't make sense to cache + functions with side-effects, functions that need to create distinct mutable + objects on each call, or impure functions such as time() or random(). + + Example of an LRU cache for static web content:: + + @lru_cache(maxsize=32) + def get_pep(num): + 'Retrieve text of a Python Enhancement Proposal' + resource = 'http://www.python.org/dev/peps/pep-%04d/' % num + try: + with urllib.request.urlopen(resource) as s: + return s.read() + except urllib.error.HTTPError: + return 'Not Found' + + >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991: + ... pep = get_pep(n) + ... print(n, len(pep)) + + >>> get_pep.cache_info() + CacheInfo(hits=3, misses=8, maxsize=32, currsize=8) + + Example of efficiently computing + `Fibonacci numbers `_ + using a cache to implement a + `dynamic programming `_ + technique:: + + @lru_cache(maxsize=None) + def fib(n): + if n < 2: + return n + return fib(n-1) + fib(n-2) + + >>> [fib(n) for n in range(16)] + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] + + >>> fib.cache_info() + CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) + + .. versionadded:: 3.2 + + .. versionchanged:: 3.3 + Added the *typed* option. + + .. versionchanged:: 3.8 + Added the *user_function* option. + + .. versionadded:: 3.9 + Added the function :func:`cache_parameters` + +.. decorator:: total_ordering + + Given a class defining one or more rich comparison ordering methods, this + class decorator supplies the rest. This simplifies the effort involved + in specifying all of the possible rich comparison operations: + + The class must define one of :meth:`__lt__`, :meth:`__le__`, + :meth:`__gt__`, or :meth:`__ge__`. + In addition, the class should supply an :meth:`__eq__` method. + + For example:: + + @total_ordering + class Student: + def _is_valid_operand(self, other): + return (hasattr(other, "lastname") and + hasattr(other, "firstname")) + def __eq__(self, other): + if not self._is_valid_operand(other): + return NotImplemented + return ((self.lastname.lower(), self.firstname.lower()) == + (other.lastname.lower(), other.firstname.lower())) + def __lt__(self, other): + if not self._is_valid_operand(other): + return NotImplemented + return ((self.lastname.lower(), self.firstname.lower()) < + (other.lastname.lower(), other.firstname.lower())) + + .. note:: + + While this decorator makes it easy to create well behaved totally + ordered types, it *does* come at the cost of slower execution and + more complex stack traces for the derived comparison methods. If + performance benchmarking indicates this is a bottleneck for a given + application, implementing all six rich comparison methods instead is + likely to provide an easy speed boost. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.4 + Returning NotImplemented from the underlying comparison function for + unrecognised types is now supported. + +.. function:: partial(func, /, *args, **keywords) + + Return a new :ref:`partial object` which when called + will behave like *func* called with the positional arguments *args* + and keyword arguments *keywords*. If more arguments are supplied to the + call, they are appended to *args*. If additional keyword arguments are + supplied, they extend and override *keywords*. + Roughly equivalent to:: + + def partial(func, /, *args, **keywords): + def newfunc(*fargs, **fkeywords): + newkeywords = {**keywords, **fkeywords} + return func(*args, *fargs, **newkeywords) + newfunc.func = func + newfunc.args = args + newfunc.keywords = keywords + return newfunc + + The :func:`partial` is used for partial function application which "freezes" + some portion of a function's arguments and/or keywords resulting in a new object + with a simplified signature. For example, :func:`partial` can be used to create + a callable that behaves like the :func:`int` function where the *base* argument + defaults to two: + + >>> from functools import partial + >>> basetwo = partial(int, base=2) + >>> basetwo.__doc__ = 'Convert base 2 string to an int.' + >>> basetwo('10010') + 18 + + +.. class:: partialmethod(func, /, *args, **keywords) + + Return a new :class:`partialmethod` descriptor which behaves + like :class:`partial` except that it is designed to be used as a method + definition rather than being directly callable. + + *func* must be a :term:`descriptor` or a callable (objects which are both, + like normal functions, are handled as descriptors). + + When *func* is a descriptor (such as a normal Python function, + :func:`classmethod`, :func:`staticmethod`, :func:`abstractmethod` or + another instance of :class:`partialmethod`), calls to ``__get__`` are + delegated to the underlying descriptor, and an appropriate + :ref:`partial object` returned as the result. + + When *func* is a non-descriptor callable, an appropriate bound method is + created dynamically. This behaves like a normal Python function when + used as a method: the *self* argument will be inserted as the first + positional argument, even before the *args* and *keywords* supplied to + the :class:`partialmethod` constructor. + + Example:: + + >>> class Cell: + ... def __init__(self): + ... self._alive = False + ... @property + ... def alive(self): + ... return self._alive + ... def set_state(self, state): + ... self._alive = bool(state) + ... set_alive = partialmethod(set_state, True) + ... set_dead = partialmethod(set_state, False) + ... + >>> c = Cell() + >>> c.alive + False + >>> c.set_alive() + >>> c.alive + True + + .. versionadded:: 3.4 + + +.. function:: reduce(function, iterable[, initializer]) + + Apply *function* of two arguments cumulatively to the items of *iterable*, from + left to right, so as to reduce the iterable to a single value. For example, + ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``. + The left argument, *x*, is the accumulated value and the right argument, *y*, is + the update value from the *iterable*. If the optional *initializer* is present, + it is placed before the items of the iterable in the calculation, and serves as + a default when the iterable is empty. If *initializer* is not given and + *iterable* contains only one item, the first item is returned. + + Roughly equivalent to:: + + def reduce(function, iterable, initializer=None): + it = iter(iterable) + if initializer is None: + value = next(it) + else: + value = initializer + for element in it: + value = function(value, element) + return value + + See :func:`itertools.accumulate` for an iterator that yields all intermediate + values. + +.. decorator:: singledispatch + + Transform a function into a :term:`single-dispatch ` :term:`generic function`. + + To define a generic function, decorate it with the ``@singledispatch`` + decorator. Note that the dispatch happens on the type of the first argument, + create your function accordingly:: + + >>> from functools import singledispatch + >>> @singledispatch + ... def fun(arg, verbose=False): + ... if verbose: + ... print("Let me just say,", end=" ") + ... print(arg) + + To add overloaded implementations to the function, use the :func:`register` + attribute of the generic function. It is a decorator. For functions + annotated with types, the decorator will infer the type of the first + argument automatically:: + + >>> @fun.register + ... def _(arg: int, verbose=False): + ... if verbose: + ... print("Strength in numbers, eh?", end=" ") + ... print(arg) + ... + >>> @fun.register + ... def _(arg: list, verbose=False): + ... if verbose: + ... print("Enumerate this:") + ... for i, elem in enumerate(arg): + ... print(i, elem) + + For code which doesn't use type annotations, the appropriate type + argument can be passed explicitly to the decorator itself:: + + >>> @fun.register(complex) + ... def _(arg, verbose=False): + ... if verbose: + ... print("Better than complicated.", end=" ") + ... print(arg.real, arg.imag) + ... + + + To enable registering lambdas and pre-existing functions, the + :func:`register` attribute can be used in a functional form:: + + >>> def nothing(arg, verbose=False): + ... print("Nothing.") + ... + >>> fun.register(type(None), nothing) + + The :func:`register` attribute returns the undecorated function which + enables decorator stacking, pickling, as well as creating unit tests for + each variant independently:: + + >>> @fun.register(float) + ... @fun.register(Decimal) + ... def fun_num(arg, verbose=False): + ... if verbose: + ... print("Half of your number:", end=" ") + ... print(arg / 2) + ... + >>> fun_num is fun + False + + When called, the generic function dispatches on the type of the first + argument:: + + >>> fun("Hello, world.") + Hello, world. + >>> fun("test.", verbose=True) + Let me just say, test. + >>> fun(42, verbose=True) + Strength in numbers, eh? 42 + >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True) + Enumerate this: + 0 spam + 1 spam + 2 eggs + 3 spam + >>> fun(None) + Nothing. + >>> fun(1.23) + 0.615 + + Where there is no registered implementation for a specific type, its + method resolution order is used to find a more generic implementation. + The original function decorated with ``@singledispatch`` is registered + for the base ``object`` type, which means it is used if no better + implementation is found. + + If an implementation registered to :term:`abstract base class`, virtual + subclasses will be dispatched to that implementation:: + + >>> from collections.abc import Mapping + >>> @fun.register + ... def _(arg: Mapping, verbose=False): + ... if verbose: + ... print("Keys & Values") + ... for key, value in arg.items(): + ... print(key, "=>", value) + ... + >>> fun({"a": "b"}) + a => b + + To check which implementation will the generic function choose for + a given type, use the ``dispatch()`` attribute:: + + >>> fun.dispatch(float) + + >>> fun.dispatch(dict) # note: default implementation + + + To access all registered implementations, use the read-only ``registry`` + attribute:: + + >>> fun.registry.keys() + dict_keys([, , , + , , + ]) + >>> fun.registry[float] + + >>> fun.registry[object] + + + .. versionadded:: 3.4 + + .. versionchanged:: 3.7 + The :func:`register` attribute supports using type annotations. + + +.. class:: singledispatchmethod(func) + + Transform a method into a :term:`single-dispatch ` :term:`generic function`. + + To define a generic method, decorate it with the ``@singledispatchmethod`` + decorator. Note that the dispatch happens on the type of the first non-self + or non-cls argument, create your function accordingly:: + + class Negator: + @singledispatchmethod + def neg(self, arg): + raise NotImplementedError("Cannot negate a") + + @neg.register + def _(self, arg: int): + return -arg + + @neg.register + def _(self, arg: bool): + return not arg + + ``@singledispatchmethod`` supports nesting with other decorators such as + ``@classmethod``. Note that to allow for ``dispatcher.register``, + ``singledispatchmethod`` must be the *outer most* decorator. Here is the + ``Negator`` class with the ``neg`` methods being class bound:: + + class Negator: + @singledispatchmethod + @classmethod + def neg(cls, arg): + raise NotImplementedError("Cannot negate a") + + @neg.register + @classmethod + def _(cls, arg: int): + return -arg + + @neg.register + @classmethod + def _(cls, arg: bool): + return not arg + + The same pattern can be used for other similar decorators: ``staticmethod``, + ``abstractmethod``, and others. + + .. versionadded:: 3.8 + + +.. class:: TopologicalSorter(graph=None) + + Provides functionality to topologically sort a graph of hashable nodes. + + A topological order is a linear ordering of the vertices in a graph such that + for every directed edge u -> v from vertex u to vertex v, vertex u comes + before vertex v in the ordering. For instance, the vertices of the graph may + represent tasks to be performed, and the edges may represent constraints that + one task must be performed before another; in this example, a topological + ordering is just a valid sequence for the tasks. A complete topological + ordering is possible if and only if the graph has no directed cycles, that + is, if it is a directed acyclic graph. + + If the optional *graph* argument is provided it must be a dictionary + representing a directed acyclic graph where the keys are nodes and the values + are iterables of all predecessors of that node in the graph (the nodes that + have edges that point to the value in the key). Additional nodes can be added + to the graph using the :meth:`~TopologicalSorter.add` method. + + In the general case, the steps required to perform the sorting of a given + graph are as follows: + + * Create an instance of the :class:`TopologicalSorter` with an optional + initial graph. + * Add additional nodes to the graph. + * Call :meth:`~TopologicalSorter.prepare` on the graph. + * While :meth:`~TopologicalSorter.is_active` is ``True``, iterate over + the nodes returned by :meth:`~TopologicalSorter.get_ready` and + process them. Call :meth:`~TopologicalSorter.done` on each node as it + finishes processing. + + In case just an immediate sorting of the nodes in the graph is required and + no parallelism is involved, the convenience method + :meth:`TopologicalSorter.static_order` can be used directly: + + .. doctest:: + + >>> graph = {"D": {"B", "C"}, "C": {"A"}, "B": {"A"}} + >>> ts = TopologicalSorter(graph) + >>> tuple(ts.static_order()) + ('A', 'C', 'B', 'D') + + The class is designed to easily support parallel processing of the nodes as + they become ready. For instance:: + + topological_sorter = TopologicalSorter() + + # Add nodes to 'topological_sorter'... + + topological_sorter.prepare() + while topological_sorter.is_active(): + for node in topological_sorter.get_ready(): + # Worker threads or processes take nodes to work on off the + # 'task_queue' queue. + task_queue.put(node) + + # When the work for a node is done, workers put the node in + # 'finalized_tasks_queue' so we can get more nodes to work on. + # The definition of 'is_active()' guarantees that, at this point, at + # least one node has been placed on 'task_queue' that hasn't yet + # been passed to 'done()', so this blocking 'get()' must (eventually) + # succeed. After calling 'done()', we loop back to call 'get_ready()' + # again, so put newly freed nodes on 'task_queue' as soon as + # logically possible. + node = finalized_tasks_queue.get() + topological_sorter.done(node) + + .. method:: add(node, *predecessors) + + Add a new node and its predecessors to the graph. Both the *node* and all + elements in *predecessors* must be hashable. + + If called multiple times with the same node argument, the set of + dependencies will be the union of all dependencies passed in. + + It is possible to add a node with no dependencies (*predecessors* is not + provided) or to provide a dependency twice. If a node that has not been + provided before is included among *predecessors* it will be automatically + added to the graph with no predecessors of its own. + + Raises :exc:`ValueError` if called after :meth:`~TopologicalSorter.prepare`. + + .. method:: prepare() + + Mark the graph as finished and check for cycles in the graph. If any cycle + is detected, :exc:`CycleError` will be raised, but + :meth:`~TopologicalSorter.get_ready` can still be used to obtain as many + nodes as possible until cycles block more progress. After a call to this + function, the graph cannot be modified, and therefore no more nodes can be + added using :meth:`~TopologicalSorter.add`. + + .. method:: is_active() + + Returns ``True`` if more progress can be made and ``False`` otherwise. + Progress can be made if cycles do not block the resolution and either + there are still nodes ready that haven't yet been returned by + :meth:`TopologicalSorter.get_ready` or the number of nodes marked + :meth:`TopologicalSorter.done` is less than the number that have been + returned by :meth:`TopologicalSorter.get_ready`. + + The :meth:`~TopologicalSorter.__bool__` method of this class defers to + this function, so instead of:: + + if ts.is_active(): + ... + + if possible to simply do:: + + if ts: + ... + + Raises :exc:`ValueError` if called without calling + :meth:`~TopologicalSorter.prepare` previously. + + .. method:: done(*nodes) + + Marks a set of nodes returned by :meth:`TopologicalSorter.get_ready` as + processed, unblocking any successor of each node in *nodes* for being + returned in the future by a call to :meth:`TopologicalSorter.get_ready`. + + Raises :exc:`ValueError` if any node in *nodes* has already been marked as + processed by a previous call to this method or if a node was not added to + the graph by using :meth:`TopologicalSorter.add`, if called without + calling :meth:`~TopologicalSorter.prepare` or if node has not yet been + returned by :meth:`~TopologicalSorter.get_ready`. + + .. method:: get_ready() + + Returns a ``tuple`` with all the nodes that are ready. Initially it + returns all nodes with no predecessors, and once those are marked as + processed by calling :meth:`TopologicalSorter.done`, further calls will + return all new nodes that have all their predecessors already processed. + Once no more progress can be made, empty tuples are returned. + + Raises :exc:`ValueError` if called without calling + :meth:`~TopologicalSorter.prepare` previously. + + .. method:: static_order() + + Returns an iterable of nodes in a topological order. Using this method + does not require to call :meth:`TopologicalSorter.prepare` or + :meth:`TopologicalSorter.done`. This method is equivalent to:: + + def static_order(self): + self.prepare() + while self.is_active(): + node_group = self.get_ready() + yield from node_group + self.done(*node_group) + + The particular order that is returned may depend on the specific order in + which the items were inserted in the graph. For example: + + .. doctest:: + + >>> ts = TopologicalSorter() + >>> ts.add(3, 2, 1) + >>> ts.add(1, 0) + >>> print([*ts.static_order()]) + [2, 0, 1, 3] + + >>> ts2 = TopologicalSorter() + >>> ts2.add(1, 0) + >>> ts2.add(3, 2, 1) + >>> print([*ts2.static_order()]) + [0, 2, 1, 3] + + This is due to the fact that "0" and "2" are in the same level in the + graph (they would have been returned in the same call to + :meth:`~TopologicalSorter.get_ready`) and the order between them is + determined by the order of insertion. + + + If any cycle is detected, :exc:`CycleError` will be raised. + + .. versionadded:: 3.9 + + +.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) + + Update a *wrapper* function to look like the *wrapped* function. The optional + arguments are tuples to specify which attributes of the original function are + assigned directly to the matching attributes on the wrapper function and which + attributes of the wrapper function are updated with the corresponding attributes + from the original function. The default values for these arguments are the + module level constants ``WRAPPER_ASSIGNMENTS`` (which assigns to the wrapper + function's ``__module__``, ``__name__``, ``__qualname__``, ``__annotations__`` + and ``__doc__``, the documentation string) and ``WRAPPER_UPDATES`` (which + updates the wrapper function's ``__dict__``, i.e. the instance dictionary). + + To allow access to the original function for introspection and other purposes + (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function + automatically adds a ``__wrapped__`` attribute to the wrapper that refers to + the function being wrapped. + + The main intended use for this function is in :term:`decorator` functions which + wrap the decorated function and return the wrapper. If the wrapper function is + not updated, the metadata of the returned function will reflect the wrapper + definition rather than the original function definition, which is typically less + than helpful. + + :func:`update_wrapper` may be used with callables other than functions. Any + attributes named in *assigned* or *updated* that are missing from the object + being wrapped are ignored (i.e. this function will not attempt to set them + on the wrapper function). :exc:`AttributeError` is still raised if the + wrapper function itself is missing any attributes named in *updated*. + + .. versionadded:: 3.2 + Automatic addition of the ``__wrapped__`` attribute. + + .. versionadded:: 3.2 + Copying of the ``__annotations__`` attribute by default. + + .. versionchanged:: 3.2 + Missing attributes no longer trigger an :exc:`AttributeError`. + + .. versionchanged:: 3.4 + The ``__wrapped__`` attribute now always refers to the wrapped + function, even if that function defined a ``__wrapped__`` attribute. + (see :issue:`17482`) + + +.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) + + This is a convenience function for invoking :func:`update_wrapper` as a + function decorator when defining a wrapper function. It is equivalent to + ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``. + For example:: + + >>> from functools import wraps + >>> def my_decorator(f): + ... @wraps(f) + ... def wrapper(*args, **kwds): + ... print('Calling decorated function') + ... return f(*args, **kwds) + ... return wrapper + ... + >>> @my_decorator + ... def example(): + ... """Docstring""" + ... print('Called example function') + ... + >>> example() + Calling decorated function + Called example function + >>> example.__name__ + 'example' + >>> example.__doc__ + 'Docstring' + + Without the use of this decorator factory, the name of the example function + would have been ``'wrapper'``, and the docstring of the original :func:`example` + would have been lost. + + +.. _partial-objects: + +:class:`partial` Objects +------------------------ + +:class:`partial` objects are callable objects created by :func:`partial`. They +have three read-only attributes: + + +.. attribute:: partial.func + + A callable object or function. Calls to the :class:`partial` object will be + forwarded to :attr:`func` with new arguments and keywords. + + +.. attribute:: partial.args + + The leftmost positional arguments that will be prepended to the positional + arguments provided to a :class:`partial` object call. + + +.. attribute:: partial.keywords + + The keyword arguments that will be supplied when the :class:`partial` object is + called. + +:class:`partial` objects are like :class:`function` objects in that they are +callable, weak referencable, and can have attributes. There are some important +differences. For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes +are not created automatically. Also, :class:`partial` objects defined in +classes behave like static methods and do not transform into bound methods +during instance attribute look-up. + + +Exceptions +---------- +The :mod:`functools` module defines the following exception classes: + +.. exception:: CycleError + + Subclass of :exc:`ValueError` raised by :meth:`TopologicalSorter.prepare` if cycles exist + in the working graph. If multiple cycles exist, only one undefined choice among them will + be reported and included in the exception. + + The detected cycle can be accessed via the second element in the :attr:`~CycleError.args` + attribute of the exception instance and consists in a list of nodes, such that each node is, + in the graph, an immediate predecessor of the next node in the list. In the reported list, + the first and the last node will be the same, to make it clear that it is cyclic. diff --git a/cpython_2/environment/repo/Doc/library/gc.rst b/cpython_2/environment/repo/Doc/library/gc.rst new file mode 100644 index 0000000000000000000000000000000000000000..0c33c865304591ebb8d1e4b8ea6ea4d8309982f9 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/gc.rst @@ -0,0 +1,321 @@ +:mod:`gc` --- Garbage Collector interface +========================================= + +.. module:: gc + :synopsis: Interface to the cycle-detecting garbage collector. + +.. moduleauthor:: Neil Schemenauer +.. sectionauthor:: Neil Schemenauer + +-------------- + +This module provides an interface to the optional garbage collector. It +provides the ability to disable the collector, tune the collection frequency, +and set debugging options. It also provides access to unreachable objects that +the collector found but cannot free. Since the collector supplements the +reference counting already used in Python, you can disable the collector if you +are sure your program does not create reference cycles. Automatic collection +can be disabled by calling ``gc.disable()``. To debug a leaking program call +``gc.set_debug(gc.DEBUG_LEAK)``. Notice that this includes +``gc.DEBUG_SAVEALL``, causing garbage-collected objects to be saved in +gc.garbage for inspection. + +The :mod:`gc` module provides the following functions: + + +.. function:: enable() + + Enable automatic garbage collection. + + +.. function:: disable() + + Disable automatic garbage collection. + + +.. function:: isenabled() + + Return ``True`` if automatic collection is enabled. + + +.. function:: collect(generation=2) + + With no arguments, run a full collection. The optional argument *generation* + may be an integer specifying which generation to collect (from 0 to 2). A + :exc:`ValueError` is raised if the generation number is invalid. The number of + unreachable objects found is returned. + + The free lists maintained for a number of built-in types are cleared + whenever a full collection or collection of the highest generation (2) + is run. Not all items in some free lists may be freed due to the + particular implementation, in particular :class:`float`. + + +.. function:: set_debug(flags) + + Set the garbage collection debugging flags. Debugging information will be + written to ``sys.stderr``. See below for a list of debugging flags which can be + combined using bit operations to control debugging. + + +.. function:: get_debug() + + Return the debugging flags currently set. + + +.. function:: get_objects(generation=None) + + Returns a list of all objects tracked by the collector, excluding the list + returned. If *generation* is not None, return only the objects tracked by + the collector that are in that generation. + + .. versionchanged:: 3.8 + New *generation* parameter. + +.. function:: get_stats() + + Return a list of three per-generation dictionaries containing collection + statistics since interpreter start. The number of keys may change + in the future, but currently each dictionary will contain the following + items: + + * ``collections`` is the number of times this generation was collected; + + * ``collected`` is the total number of objects collected inside this + generation; + + * ``uncollectable`` is the total number of objects which were found + to be uncollectable (and were therefore moved to the :data:`garbage` + list) inside this generation. + + .. versionadded:: 3.4 + + +.. function:: set_threshold(threshold0[, threshold1[, threshold2]]) + + Set the garbage collection thresholds (the collection frequency). Setting + *threshold0* to zero disables collection. + + The GC classifies objects into three generations depending on how many + collection sweeps they have survived. New objects are placed in the youngest + generation (generation ``0``). If an object survives a collection it is moved + into the next older generation. Since generation ``2`` is the oldest + generation, objects in that generation remain there after a collection. In + order to decide when to run, the collector keeps track of the number object + allocations and deallocations since the last collection. When the number of + allocations minus the number of deallocations exceeds *threshold0*, collection + starts. Initially only generation ``0`` is examined. If generation ``0`` has + been examined more than *threshold1* times since generation ``1`` has been + examined, then generation ``1`` is examined as well. Similarly, *threshold2* + controls the number of collections of generation ``1`` before collecting + generation ``2``. + + +.. function:: get_count() + + Return the current collection counts as a tuple of ``(count0, count1, + count2)``. + + +.. function:: get_threshold() + + Return the current collection thresholds as a tuple of ``(threshold0, + threshold1, threshold2)``. + + +.. function:: get_referrers(*objs) + + Return the list of objects that directly refer to any of objs. This function + will only locate those containers which support garbage collection; extension + types which do refer to other objects but do not support garbage collection will + not be found. + + Note that objects which have already been dereferenced, but which live in cycles + and have not yet been collected by the garbage collector can be listed among the + resulting referrers. To get only currently live objects, call :func:`collect` + before calling :func:`get_referrers`. + + Care must be taken when using objects returned by :func:`get_referrers` because + some of them could still be under construction and hence in a temporarily + invalid state. Avoid using :func:`get_referrers` for any purpose other than + debugging. + + +.. function:: get_referents(*objs) + + Return a list of objects directly referred to by any of the arguments. The + referents returned are those objects visited by the arguments' C-level + :c:member:`~PyTypeObject.tp_traverse` methods (if any), and may not be all objects actually + directly reachable. :c:member:`~PyTypeObject.tp_traverse` methods are supported only by objects + that support garbage collection, and are only required to visit objects that may + be involved in a cycle. So, for example, if an integer is directly reachable + from an argument, that integer object may or may not appear in the result list. + + +.. function:: is_tracked(obj) + + Returns ``True`` if the object is currently tracked by the garbage collector, + ``False`` otherwise. As a general rule, instances of atomic types aren't + tracked and instances of non-atomic types (containers, user-defined + objects...) are. However, some type-specific optimizations can be present + in order to suppress the garbage collector footprint of simple instances + (e.g. dicts containing only atomic keys and values):: + + >>> gc.is_tracked(0) + False + >>> gc.is_tracked("a") + False + >>> gc.is_tracked([]) + True + >>> gc.is_tracked({}) + False + >>> gc.is_tracked({"a": 1}) + False + >>> gc.is_tracked({"a": []}) + True + + .. versionadded:: 3.1 + + +.. function:: is_finalized(obj) + + Returns ``True`` if the given object has been finalized by the + garbage collector, ``False`` otherwise. :: + + >>> x = None + >>> class Lazarus: + ... def __del__(self): + ... global x + ... x = self + ... + >>> lazarus = Lazarus() + >>> gc.is_finalized(lazarus) + False + >>> del lazarus + >>> gc.is_finalized(x) + True + + .. versionadded:: 3.9 + + +.. function:: freeze() + + Freeze all the objects tracked by gc - move them to a permanent generation + and ignore all the future collections. This can be used before a POSIX + fork() call to make the gc copy-on-write friendly or to speed up collection. + Also collection before a POSIX fork() call may free pages for future + allocation which can cause copy-on-write too so it's advised to disable gc + in parent process and freeze before fork and enable gc in child process. + + .. versionadded:: 3.7 + + +.. function:: unfreeze() + + Unfreeze the objects in the permanent generation, put them back into the + oldest generation. + + .. versionadded:: 3.7 + + +.. function:: get_freeze_count() + + Return the number of objects in the permanent generation. + + .. versionadded:: 3.7 + + +The following variables are provided for read-only access (you can mutate the +values but should not rebind them): + +.. data:: garbage + + A list of objects which the collector found to be unreachable but could + not be freed (uncollectable objects). Starting with Python 3.4, this + list should be empty most of the time, except when using instances of + C extension types with a non-``NULL`` ``tp_del`` slot. + + If :const:`DEBUG_SAVEALL` is set, then all unreachable objects will be + added to this list rather than freed. + + .. versionchanged:: 3.2 + If this list is non-empty at :term:`interpreter shutdown`, a + :exc:`ResourceWarning` is emitted, which is silent by default. If + :const:`DEBUG_UNCOLLECTABLE` is set, in addition all uncollectable objects + are printed. + + .. versionchanged:: 3.4 + Following :pep:`442`, objects with a :meth:`__del__` method don't end + up in :attr:`gc.garbage` anymore. + +.. data:: callbacks + + A list of callbacks that will be invoked by the garbage collector before and + after collection. The callbacks will be called with two arguments, + *phase* and *info*. + + *phase* can be one of two values: + + "start": The garbage collection is about to start. + + "stop": The garbage collection has finished. + + *info* is a dict providing more information for the callback. The following + keys are currently defined: + + "generation": The oldest generation being collected. + + "collected": When *phase* is "stop", the number of objects + successfully collected. + + "uncollectable": When *phase* is "stop", the number of objects + that could not be collected and were put in :data:`garbage`. + + Applications can add their own callbacks to this list. The primary + use cases are: + + Gathering statistics about garbage collection, such as how often + various generations are collected, and how long the collection + takes. + + Allowing applications to identify and clear their own uncollectable + types when they appear in :data:`garbage`. + + .. versionadded:: 3.3 + + +The following constants are provided for use with :func:`set_debug`: + + +.. data:: DEBUG_STATS + + Print statistics during collection. This information can be useful when tuning + the collection frequency. + + +.. data:: DEBUG_COLLECTABLE + + Print information on collectable objects found. + + +.. data:: DEBUG_UNCOLLECTABLE + + Print information of uncollectable objects found (objects which are not + reachable but cannot be freed by the collector). These objects will be added + to the ``garbage`` list. + + .. versionchanged:: 3.2 + Also print the contents of the :data:`garbage` list at + :term:`interpreter shutdown`, if it isn't empty. + +.. data:: DEBUG_SAVEALL + + When set, all unreachable objects found will be appended to *garbage* rather + than being freed. This can be useful for debugging a leaking program. + + +.. data:: DEBUG_LEAK + + The debugging flags necessary for the collector to print information about a + leaking program (equal to ``DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | + DEBUG_SAVEALL``). diff --git a/cpython_2/environment/repo/Doc/library/getopt.rst b/cpython_2/environment/repo/Doc/library/getopt.rst new file mode 100644 index 0000000000000000000000000000000000000000..336deab28cb8a46af63d78ba119354248c767c1f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/getopt.rst @@ -0,0 +1,164 @@ +:mod:`getopt` --- C-style parser for command line options +========================================================= + +.. module:: getopt + :synopsis: Portable parser for command line options; support both short and + long option names. + +**Source code:** :source:`Lib/getopt.py` + +.. note:: + + The :mod:`getopt` module is a parser for command line options whose API is + designed to be familiar to users of the C :c:func:`getopt` function. Users who + are unfamiliar with the C :c:func:`getopt` function or who would like to write + less code and get better help and error messages should consider using the + :mod:`argparse` module instead. + +-------------- + +This module helps scripts to parse the command line arguments in ``sys.argv``. +It supports the same conventions as the Unix :c:func:`getopt` function (including +the special meanings of arguments of the form '``-``' and '``--``'). Long +options similar to those supported by GNU software may be used as well via an +optional third argument. + +This module provides two functions and an +exception: + + +.. function:: getopt(args, shortopts, longopts=[]) + + Parses command line options and parameter list. *args* is the argument list to + be parsed, without the leading reference to the running program. Typically, this + means ``sys.argv[1:]``. *shortopts* is the string of option letters that the + script wants to recognize, with options that require an argument followed by a + colon (``':'``; i.e., the same format that Unix :c:func:`getopt` uses). + + .. note:: + + Unlike GNU :c:func:`getopt`, after a non-option argument, all further + arguments are considered also non-options. This is similar to the way + non-GNU Unix systems work. + + *longopts*, if specified, must be a list of strings with the names of the + long options which should be supported. The leading ``'--'`` characters + should not be included in the option name. Long options which require an + argument should be followed by an equal sign (``'='``). Optional arguments + are not supported. To accept only long options, *shortopts* should be an + empty string. Long options on the command line can be recognized so long as + they provide a prefix of the option name that matches exactly one of the + accepted options. For example, if *longopts* is ``['foo', 'frob']``, the + option ``--fo`` will match as ``--foo``, but ``--f`` will + not match uniquely, so :exc:`GetoptError` will be raised. + + The return value consists of two elements: the first is a list of ``(option, + value)`` pairs; the second is the list of program arguments left after the + option list was stripped (this is a trailing slice of *args*). Each + option-and-value pair returned has the option as its first element, prefixed + with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long + options (e.g., ``'--long-option'``), and the option argument as its + second element, or an empty string if the option has no argument. The + options occur in the list in the same order in which they were found, thus + allowing multiple occurrences. Long and short options may be mixed. + + +.. function:: gnu_getopt(args, shortopts, longopts=[]) + + This function works like :func:`getopt`, except that GNU style scanning mode is + used by default. This means that option and non-option arguments may be + intermixed. The :func:`getopt` function stops processing options as soon as a + non-option argument is encountered. + + If the first character of the option string is ``'+'``, or if the environment + variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as + soon as a non-option argument is encountered. + + +.. exception:: GetoptError + + This is raised when an unrecognized option is found in the argument list or when + an option requiring an argument is given none. The argument to the exception is + a string indicating the cause of the error. For long options, an argument given + to an option which does not require one will also cause this exception to be + raised. The attributes :attr:`msg` and :attr:`opt` give the error message and + related option; if there is no specific option to which the exception relates, + :attr:`opt` is an empty string. + +.. XXX deprecated? +.. exception:: error + + Alias for :exc:`GetoptError`; for backward compatibility. + +An example using only Unix style options: + + >>> import getopt + >>> args = '-a -b -cfoo -d bar a1 a2'.split() + >>> args + ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] + >>> optlist, args = getopt.getopt(args, 'abc:d:') + >>> optlist + [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] + >>> args + ['a1', 'a2'] + +Using long option names is equally easy: + + >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' + >>> args = s.split() + >>> args + ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2'] + >>> optlist, args = getopt.getopt(args, 'x', [ + ... 'condition=', 'output-file=', 'testing']) + >>> optlist + [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')] + >>> args + ['a1', 'a2'] + +In a script, typical usage is something like this:: + + import getopt, sys + + def main(): + try: + opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) + except getopt.GetoptError as err: + # print help information and exit: + print(err) # will print something like "option -a not recognized" + usage() + sys.exit(2) + output = None + verbose = False + for o, a in opts: + if o == "-v": + verbose = True + elif o in ("-h", "--help"): + usage() + sys.exit() + elif o in ("-o", "--output"): + output = a + else: + assert False, "unhandled option" + # ... + + if __name__ == "__main__": + main() + +Note that an equivalent command line interface could be produced with less code +and more informative help and error messages by using the :mod:`argparse` module:: + + import argparse + + if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-o', '--output') + parser.add_argument('-v', dest='verbose', action='store_true') + args = parser.parse_args() + # ... do something with args.output ... + # ... do something with args.verbose .. + +.. seealso:: + + Module :mod:`argparse` + Alternative command line option and argument parsing library. + diff --git a/cpython_2/environment/repo/Doc/library/getpass.rst b/cpython_2/environment/repo/Doc/library/getpass.rst new file mode 100644 index 0000000000000000000000000000000000000000..82b11919a3d2bf67eeb7ef40e80d51b93f96a4bb --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/getpass.rst @@ -0,0 +1,51 @@ +:mod:`getpass` --- Portable password input +========================================== + +.. module:: getpass + :synopsis: Portable reading of passwords and retrieval of the userid. + +.. moduleauthor:: Piers Lauder +.. sectionauthor:: Fred L. Drake, Jr. +.. Windows (& Mac?) support by Guido van Rossum. + +**Source code:** :source:`Lib/getpass.py` + +-------------- + +The :mod:`getpass` module provides two functions: + + +.. function:: getpass(prompt='Password: ', stream=None) + + Prompt the user for a password without echoing. The user is prompted using + the string *prompt*, which defaults to ``'Password: '``. On Unix, the + prompt is written to the file-like object *stream* using the replace error + handler if needed. *stream* defaults to the controlling terminal + (:file:`/dev/tty`) or if that is unavailable to ``sys.stderr`` (this + argument is ignored on Windows). + + If echo free input is unavailable getpass() falls back to printing + a warning message to *stream* and reading from ``sys.stdin`` and + issuing a :exc:`GetPassWarning`. + + .. note:: + If you call getpass from within IDLE, the input may be done in the + terminal you launched IDLE from rather than the idle window itself. + +.. exception:: GetPassWarning + + A :exc:`UserWarning` subclass issued when password input may be echoed. + + +.. function:: getuser() + + Return the "login name" of the user. + + This function checks the environment variables :envvar:`LOGNAME`, + :envvar:`USER`, :envvar:`LNAME` and :envvar:`USERNAME`, in order, and + returns the value of the first one which is set to a non-empty string. If + none are set, the login name from the password database is returned on + systems which support the :mod:`pwd` module, otherwise, an exception is + raised. + + In general, this function should be preferred over :func:`os.getlogin()`. diff --git a/cpython_2/environment/repo/Doc/library/gettext.rst b/cpython_2/environment/repo/Doc/library/gettext.rst new file mode 100644 index 0000000000000000000000000000000000000000..ec2c12806b41608cc26388610ccea41e459f5b6e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/gettext.rst @@ -0,0 +1,732 @@ +:mod:`gettext` --- Multilingual internationalization services +============================================================= + +.. module:: gettext + :synopsis: Multilingual internationalization services. + +.. moduleauthor:: Barry A. Warsaw +.. sectionauthor:: Barry A. Warsaw + +**Source code:** :source:`Lib/gettext.py` + +-------------- + +The :mod:`gettext` module provides internationalization (I18N) and localization +(L10N) services for your Python modules and applications. It supports both the +GNU :program:`gettext` message catalog API and a higher level, class-based API that may +be more appropriate for Python files. The interface described below allows you +to write your module and application messages in one natural language, and +provide a catalog of translated messages for running under different natural +languages. + +Some hints on localizing your Python modules and applications are also given. + + +GNU :program:`gettext` API +-------------------------- + +The :mod:`gettext` module defines the following API, which is very similar to +the GNU :program:`gettext` API. If you use this API you will affect the +translation of your entire application globally. Often this is what you want if +your application is monolingual, with the choice of language dependent on the +locale of your user. If you are localizing a Python module, or if your +application needs to switch languages on the fly, you probably want to use the +class-based API instead. + + +.. function:: bindtextdomain(domain, localedir=None) + + Bind the *domain* to the locale directory *localedir*. More concretely, + :mod:`gettext` will look for binary :file:`.mo` files for the given domain using + the path (on Unix): :file:`{localedir}/{language}/LC_MESSAGES/{domain}.mo`, where + *language* is searched for in the environment variables :envvar:`LANGUAGE`, + :envvar:`LC_ALL`, :envvar:`LC_MESSAGES`, and :envvar:`LANG` respectively. + + If *localedir* is omitted or ``None``, then the current binding for *domain* is + returned. [#]_ + + +.. function:: bind_textdomain_codeset(domain, codeset=None) + + Bind the *domain* to *codeset*, changing the encoding of byte strings + returned by the :func:`lgettext`, :func:`ldgettext`, :func:`lngettext` + and :func:`ldngettext` functions. + If *codeset* is omitted, then the current binding is returned. + + .. deprecated-removed:: 3.8 3.10 + + +.. function:: textdomain(domain=None) + + Change or query the current global domain. If *domain* is ``None``, then the + current global domain is returned, otherwise the global domain is set to + *domain*, which is returned. + + +.. index:: single: _ (underscore); gettext +.. function:: gettext(message) + + Return the localized translation of *message*, based on the current global + domain, language, and locale directory. This function is usually aliased as + :func:`_` in the local namespace (see examples below). + + +.. function:: dgettext(domain, message) + + Like :func:`.gettext`, but look the message up in the specified *domain*. + + +.. function:: ngettext(singular, plural, n) + + Like :func:`.gettext`, but consider plural forms. If a translation is found, + apply the plural formula to *n*, and return the resulting message (some + languages have more than two plural forms). If no translation is found, return + *singular* if *n* is 1; return *plural* otherwise. + + The Plural formula is taken from the catalog header. It is a C or Python + expression that has a free variable *n*; the expression evaluates to the index + of the plural in the catalog. See + `the GNU gettext documentation `__ + for the precise syntax to be used in :file:`.po` files and the + formulas for a variety of languages. + + +.. function:: dngettext(domain, singular, plural, n) + + Like :func:`ngettext`, but look the message up in the specified *domain*. + + +.. function:: pgettext(context, message) +.. function:: dpgettext(domain, context, message) +.. function:: npgettext(context, singular, plural, n) +.. function:: dnpgettext(domain, context, singular, plural, n) + + Similar to the corresponding functions without the ``p`` in the prefix (that + is, :func:`gettext`, :func:`dgettext`, :func:`ngettext`, :func:`dngettext`), + but the translation is restricted to the given message *context*. + + .. versionadded:: 3.8 + + +.. function:: lgettext(message) +.. function:: ldgettext(domain, message) +.. function:: lngettext(singular, plural, n) +.. function:: ldngettext(domain, singular, plural, n) + + Equivalent to the corresponding functions without the ``l`` prefix + (:func:`.gettext`, :func:`dgettext`, :func:`ngettext` and :func:`dngettext`), + but the translation is returned as a byte string encoded in the preferred + system encoding if no other encoding was explicitly set with + :func:`bind_textdomain_codeset`. + + .. warning:: + + These functions should be avoided in Python 3, because they return + encoded bytes. It's much better to use alternatives which return + Unicode strings instead, since most Python applications will want to + manipulate human readable text as strings instead of bytes. Further, + it's possible that you may get unexpected Unicode-related exceptions + if there are encoding problems with the translated strings. + + .. deprecated-removed:: 3.8 3.10 + + +Note that GNU :program:`gettext` also defines a :func:`dcgettext` method, but +this was deemed not useful and so it is currently unimplemented. + +Here's an example of typical usage for this API:: + + import gettext + gettext.bindtextdomain('myapplication', '/path/to/my/language/directory') + gettext.textdomain('myapplication') + _ = gettext.gettext + # ... + print(_('This is a translatable string.')) + + +Class-based API +--------------- + +The class-based API of the :mod:`gettext` module gives you more flexibility and +greater convenience than the GNU :program:`gettext` API. It is the recommended +way of localizing your Python applications and modules. :mod:`!gettext` defines +a :class:`GNUTranslations` class which implements the parsing of GNU :file:`.mo` format +files, and has methods for returning strings. Instances of this class can also +install themselves in the built-in namespace as the function :func:`_`. + + +.. function:: find(domain, localedir=None, languages=None, all=False) + + This function implements the standard :file:`.mo` file search algorithm. It + takes a *domain*, identical to what :func:`textdomain` takes. Optional + *localedir* is as in :func:`bindtextdomain`. Optional *languages* is a list of + strings, where each string is a language code. + + If *localedir* is not given, then the default system locale directory is used. + [#]_ If *languages* is not given, then the following environment variables are + searched: :envvar:`LANGUAGE`, :envvar:`LC_ALL`, :envvar:`LC_MESSAGES`, and + :envvar:`LANG`. The first one returning a non-empty value is used for the + *languages* variable. The environment variables should contain a colon separated + list of languages, which will be split on the colon to produce the expected list + of language code strings. + + :func:`find` then expands and normalizes the languages, and then iterates + through them, searching for an existing file built of these components: + + :file:`{localedir}/{language}/LC_MESSAGES/{domain}.mo` + + The first such file name that exists is returned by :func:`find`. If no such + file is found, then ``None`` is returned. If *all* is given, it returns a list + of all file names, in the order in which they appear in the languages list or + the environment variables. + + +.. function:: translation(domain, localedir=None, languages=None, class_=None, fallback=False, codeset=None) + + Return a :class:`*Translations` instance based on the *domain*, *localedir*, + and *languages*, which are first passed to :func:`find` to get a list of the + associated :file:`.mo` file paths. Instances with identical :file:`.mo` file + names are cached. The actual class instantiated is *class_* if + provided, otherwise :class:`GNUTranslations`. The class's constructor must + take a single :term:`file object` argument. If provided, *codeset* will change + the charset used to encode translated strings in the + :meth:`~NullTranslations.lgettext` and :meth:`~NullTranslations.lngettext` + methods. + + If multiple files are found, later files are used as fallbacks for earlier ones. + To allow setting the fallback, :func:`copy.copy` is used to clone each + translation object from the cache; the actual instance data is still shared with + the cache. + + If no :file:`.mo` file is found, this function raises :exc:`OSError` if + *fallback* is false (which is the default), and returns a + :class:`NullTranslations` instance if *fallback* is true. + + .. versionchanged:: 3.3 + :exc:`IOError` used to be raised instead of :exc:`OSError`. + + .. deprecated-removed:: 3.8 3.10 + The *codeset* parameter. + + +.. function:: install(domain, localedir=None, codeset=None, names=None) + + This installs the function :func:`_` in Python's builtins namespace, based on + *domain*, *localedir*, and *codeset* which are passed to the function + :func:`translation`. + + For the *names* parameter, please see the description of the translation + object's :meth:`~NullTranslations.install` method. + + As seen below, you usually mark the strings in your application that are + candidates for translation, by wrapping them in a call to the :func:`_` + function, like this:: + + print(_('This string will be translated.')) + + For convenience, you want the :func:`_` function to be installed in Python's + builtins namespace, so it is easily accessible in all modules of your + application. + + .. deprecated-removed:: 3.8 3.10 + The *codeset* parameter. + + +The :class:`NullTranslations` class +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Translation classes are what actually implement the translation of original +source file message strings to translated message strings. The base class used +by all translation classes is :class:`NullTranslations`; this provides the basic +interface you can use to write your own specialized translation classes. Here +are the methods of :class:`!NullTranslations`: + + +.. class:: NullTranslations(fp=None) + + Takes an optional :term:`file object` *fp*, which is ignored by the base class. + Initializes "protected" instance variables *_info* and *_charset* which are set + by derived classes, as well as *_fallback*, which is set through + :meth:`add_fallback`. It then calls ``self._parse(fp)`` if *fp* is not + ``None``. + + .. method:: _parse(fp) + + No-op in the base class, this method takes file object *fp*, and reads + the data from the file, initializing its message catalog. If you have an + unsupported message catalog file format, you should override this method + to parse your format. + + + .. method:: add_fallback(fallback) + + Add *fallback* as the fallback object for the current translation object. + A translation object should consult the fallback if it cannot provide a + translation for a given message. + + + .. method:: gettext(message) + + If a fallback has been set, forward :meth:`!gettext` to the fallback. + Otherwise, return *message*. Overridden in derived classes. + + + .. method:: ngettext(singular, plural, n) + + If a fallback has been set, forward :meth:`!ngettext` to the fallback. + Otherwise, return *singular* if *n* is 1; return *plural* otherwise. + Overridden in derived classes. + + + .. method:: pgettext(context, message) + + If a fallback has been set, forward :meth:`pgettext` to the fallback. + Otherwise, return the translated message. Overridden in derived classes. + + .. versionadded:: 3.8 + + + .. method:: npgettext(context, singular, plural, n) + + If a fallback has been set, forward :meth:`npgettext` to the fallback. + Otherwise, return the translated message. Overridden in derived classes. + + .. versionadded:: 3.8 + + + .. method:: lgettext(message) + .. method:: lngettext(singular, plural, n) + + Equivalent to :meth:`.gettext` and :meth:`.ngettext`, but the translation + is returned as a byte string encoded in the preferred system encoding + if no encoding was explicitly set with :meth:`set_output_charset`. + Overridden in derived classes. + + .. warning:: + + These methods should be avoided in Python 3. See the warning for the + :func:`lgettext` function. + + .. deprecated-removed:: 3.8 3.10 + + + .. method:: info() + + Return the "protected" :attr:`_info` variable, a dictionary containing + the metadata found in the message catalog file. + + + .. method:: charset() + + Return the encoding of the message catalog file. + + + .. method:: output_charset() + + Return the encoding used to return translated messages in :meth:`.lgettext` + and :meth:`.lngettext`. + + .. deprecated-removed:: 3.8 3.10 + + + .. method:: set_output_charset(charset) + + Change the encoding used to return translated messages. + + .. deprecated-removed:: 3.8 3.10 + + + .. method:: install(names=None) + + This method installs :meth:`.gettext` into the built-in namespace, + binding it to ``_``. + + If the *names* parameter is given, it must be a sequence containing the + names of functions you want to install in the builtins namespace in + addition to :func:`_`. Supported names are ``'gettext'``, ``'ngettext'``, + ``'pgettext'``, ``'npgettext'``, ``'lgettext'``, and ``'lngettext'``. + + Note that this is only one way, albeit the most convenient way, to make + the :func:`_` function available to your application. Because it affects + the entire application globally, and specifically the built-in namespace, + localized modules should never install :func:`_`. Instead, they should use + this code to make :func:`_` available to their module:: + + import gettext + t = gettext.translation('mymodule', ...) + _ = t.gettext + + This puts :func:`_` only in the module's global namespace and so only + affects calls within this module. + + .. versionchanged:: 3.8 + Added ``'pgettext'`` and ``'npgettext'``. + + +The :class:`GNUTranslations` class +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The :mod:`gettext` module provides one additional class derived from +:class:`NullTranslations`: :class:`GNUTranslations`. This class overrides +:meth:`_parse` to enable reading GNU :program:`gettext` format :file:`.mo` files +in both big-endian and little-endian format. + +:class:`GNUTranslations` parses optional metadata out of the translation +catalog. It is convention with GNU :program:`gettext` to include metadata as +the translation for the empty string. This metadata is in :rfc:`822`\ -style +``key: value`` pairs, and should contain the ``Project-Id-Version`` key. If the +key ``Content-Type`` is found, then the ``charset`` property is used to +initialize the "protected" :attr:`_charset` instance variable, defaulting to +``None`` if not found. If the charset encoding is specified, then all message +ids and message strings read from the catalog are converted to Unicode using +this encoding, else ASCII is assumed. + +Since message ids are read as Unicode strings too, all :meth:`*gettext` methods +will assume message ids as Unicode strings, not byte strings. + +The entire set of key/value pairs are placed into a dictionary and set as the +"protected" :attr:`_info` instance variable. + +If the :file:`.mo` file's magic number is invalid, the major version number is +unexpected, or if other problems occur while reading the file, instantiating a +:class:`GNUTranslations` class can raise :exc:`OSError`. + +.. class:: GNUTranslations + + The following methods are overridden from the base class implementation: + + .. method:: gettext(message) + + Look up the *message* id in the catalog and return the corresponding message + string, as a Unicode string. If there is no entry in the catalog for the + *message* id, and a fallback has been set, the look up is forwarded to the + fallback's :meth:`~NullTranslations.gettext` method. Otherwise, the + *message* id is returned. + + + .. method:: ngettext(singular, plural, n) + + Do a plural-forms lookup of a message id. *singular* is used as the message id + for purposes of lookup in the catalog, while *n* is used to determine which + plural form to use. The returned message string is a Unicode string. + + If the message id is not found in the catalog, and a fallback is specified, + the request is forwarded to the fallback's :meth:`~NullTranslations.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('.')) + cat = GNUTranslations(somefile) + message = cat.ngettext( + 'There is %(num)d file in this directory', + 'There are %(num)d files in this directory', + n) % {'num': n} + + + .. method:: pgettext(context, message) + + Look up the *context* and *message* id in the catalog and return the + corresponding message string, as a Unicode string. If there is no + entry in the catalog for the *message* id and *context*, and a fallback + has been set, the look up is forwarded to the fallback's + :meth:`pgettext` method. Otherwise, the *message* id is returned. + + .. versionadded:: 3.8 + + + .. method:: npgettext(context, singular, plural, n) + + Do a plural-forms lookup of a message id. *singular* is used as the + message id for purposes of lookup in the catalog, while *n* is used to + determine which plural form to use. + + If the message id for *context* is not found in the catalog, and a + fallback is specified, the request is forwarded to the fallback's + :meth:`npgettext` method. Otherwise, when *n* is 1 *singular* is + returned, and *plural* is returned in all other cases. + + .. versionadded:: 3.8 + + + .. method:: lgettext(message) + .. method:: lngettext(singular, plural, n) + + Equivalent to :meth:`.gettext` and :meth:`.ngettext`, but the translation + is returned as a byte string encoded in the preferred system encoding + if no encoding was explicitly set with + :meth:`~NullTranslations.set_output_charset`. + + .. warning:: + + These methods should be avoided in Python 3. See the warning for the + :func:`lgettext` function. + + .. deprecated-removed:: 3.8 3.10 + + +Solaris message catalog support +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The Solaris operating system defines its own binary :file:`.mo` file format, but +since no documentation can be found on this format, it is not supported at this +time. + + +The Catalog constructor +^^^^^^^^^^^^^^^^^^^^^^^ + +.. index:: single: GNOME + +GNOME uses a version of the :mod:`gettext` module by James Henstridge, but this +version has a slightly different API. Its documented usage was:: + + import gettext + cat = gettext.Catalog(domain, localedir) + _ = cat.gettext + print(_('hello world')) + +For compatibility with this older module, the function :func:`Catalog` is an +alias for the :func:`translation` function described above. + +One difference between this module and Henstridge's: his catalog objects +supported access through a mapping API, but this appears to be unused and so is +not currently supported. + + +Internationalizing your programs and modules +-------------------------------------------- + +Internationalization (I18N) refers to the operation by which a program is made +aware of multiple languages. Localization (L10N) refers to the adaptation of +your program, once internationalized, to the local language and cultural habits. +In order to provide multilingual messages for your Python programs, you need to +take the following steps: + +#. prepare your program or module by specially marking translatable strings + +#. run a suite of tools over your marked files to generate raw messages catalogs + +#. create language-specific translations of the message catalogs + +#. use the :mod:`gettext` module so that message strings are properly translated + +In order to prepare your code for I18N, you need to look at all the strings in +your files. Any string that needs to be translated should be marked by wrapping +it in ``_('...')`` --- that is, a call to the function :func:`_`. For example:: + + filename = 'mylog.txt' + message = _('writing a log message') + with open(filename, 'w') as fp: + fp.write(message) + +In this example, the string ``'writing a log message'`` is marked as a candidate +for translation, while the strings ``'mylog.txt'`` and ``'w'`` are not. + +There are a few tools to extract the strings meant for translation. +The original GNU :program:`gettext` only supported C or C++ source +code but its extended version :program:`xgettext` scans code written +in a number of languages, including Python, to find strings marked as +translatable. `Babel `__ is a Python +internationalization library that includes a :file:`pybabel` script to +extract and compile message catalogs. François Pinard's program +called :program:`xpot` does a similar job and is available as part of +his `po-utils package `__. + +(Python also includes pure-Python versions of these programs, called +:program:`pygettext.py` and :program:`msgfmt.py`; some Python distributions +will install them for you. :program:`pygettext.py` is similar to +:program:`xgettext`, but only understands Python source code and +cannot handle other programming languages such as C or C++. +:program:`pygettext.py` supports a command-line interface similar to +:program:`xgettext`; for details on its use, run ``pygettext.py +--help``. :program:`msgfmt.py` is binary compatible with GNU +:program:`msgfmt`. With these two programs, you may not need the GNU +:program:`gettext` package to internationalize your Python +applications.) + +:program:`xgettext`, :program:`pygettext`, and similar tools generate +:file:`.po` files that are message catalogs. They are structured +human-readable files that contain every marked string in the source +code, along with a placeholder for the translated versions of these +strings. + +Copies of these :file:`.po` files are then handed over to the +individual human translators who write translations for every +supported natural language. They send back the completed +language-specific versions as a :file:`.po` file that's +compiled into a machine-readable :file:`.mo` binary catalog file using +the :program:`msgfmt` program. The :file:`.mo` files are used by the +:mod:`gettext` module for the actual translation processing at +run-time. + +How you use the :mod:`gettext` module in your code depends on whether you are +internationalizing a single module or your entire application. The next two +sections will discuss each case. + + +Localizing your module +^^^^^^^^^^^^^^^^^^^^^^ + +If you are localizing your module, you must take care not to make global +changes, e.g. to the built-in namespace. You should not use the GNU :program:`gettext` +API but instead the class-based API. + +Let's say your module is called "spam" and the module's various natural language +translation :file:`.mo` files reside in :file:`/usr/share/locale` in GNU +:program:`gettext` format. Here's what you would put at the top of your +module:: + + import gettext + t = gettext.translation('spam', '/usr/share/locale') + _ = t.gettext + + +Localizing your application +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If you are localizing your application, you can install the :func:`_` function +globally into the built-in namespace, usually in the main driver file of your +application. This will let all your application-specific files just use +``_('...')`` without having to explicitly install it in each file. + +In the simple case then, you need only add the following bit of code to the main +driver file of your application:: + + import gettext + gettext.install('myapplication') + +If you need to set the locale directory, you can pass it into the +:func:`install` function:: + + import gettext + gettext.install('myapplication', '/usr/share/locale') + + +Changing languages on the fly +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If your program needs to support many languages at the same time, you may want +to create multiple translation instances and then switch between them +explicitly, like so:: + + import gettext + + lang1 = gettext.translation('myapplication', languages=['en']) + lang2 = gettext.translation('myapplication', languages=['fr']) + lang3 = gettext.translation('myapplication', languages=['de']) + + # start by using language1 + lang1.install() + + # ... time goes by, user selects language 2 + lang2.install() + + # ... more time goes by, user selects language 3 + lang3.install() + + +Deferred translations +^^^^^^^^^^^^^^^^^^^^^ + +In most coding situations, strings are translated where they are coded. +Occasionally however, you need to mark strings for translation, but defer actual +translation until later. A classic example is:: + + animals = ['mollusk', + 'albatross', + 'rat', + 'penguin', + 'python', ] + # ... + for a in animals: + print(a) + +Here, you want to mark the strings in the ``animals`` list as being +translatable, but you don't actually want to translate them until they are +printed. + +Here is one way you can handle this situation:: + + def _(message): return message + + animals = [_('mollusk'), + _('albatross'), + _('rat'), + _('penguin'), + _('python'), ] + + del _ + + # ... + for a in animals: + print(_(a)) + +This works because the dummy definition of :func:`_` simply returns the string +unchanged. And this dummy definition will temporarily override any definition +of :func:`_` in the built-in namespace (until the :keyword:`del` command). Take +care, though if you have a previous definition of :func:`_` in the local +namespace. + +Note that the second use of :func:`_` will not identify "a" as being +translatable to the :program:`gettext` program, because the parameter +is not a string literal. + +Another way to handle this is with the following example:: + + def N_(message): return message + + animals = [N_('mollusk'), + N_('albatross'), + N_('rat'), + N_('penguin'), + N_('python'), ] + + # ... + for a in animals: + print(_(a)) + +In this case, you are marking translatable strings with the function +:func:`N_`, which won't conflict with any definition of :func:`_`. +However, you will need to teach your message extraction program to +look for translatable strings marked with :func:`N_`. :program:`xgettext`, +:program:`pygettext`, ``pybabel extract``, and :program:`xpot` all +support this through the use of the :option:`!-k` command-line switch. +The choice of :func:`N_` here is totally arbitrary; it could have just +as easily been :func:`MarkThisStringForTranslation`. + + +Acknowledgements +---------------- + +The following people contributed code, feedback, design suggestions, previous +implementations, and valuable experience to the creation of this module: + +* Peter Funk + +* James Henstridge + +* Juan David Ibáñez Palomar + +* Marc-André Lemburg + +* Martin von Löwis + +* François Pinard + +* Barry Warsaw + +* Gustavo Niemeyer + +.. rubric:: Footnotes + +.. [#] The default locale directory is system dependent; for example, on RedHat Linux + it is :file:`/usr/share/locale`, but on Solaris it is :file:`/usr/lib/locale`. + The :mod:`gettext` module does not try to support these system dependent + defaults; instead its default is :file:`{sys.base_prefix}/share/locale` (see + :data:`sys.base_prefix`). For this reason, it is always best to call + :func:`bindtextdomain` with an explicit absolute path at the start of your + application. + +.. [#] See the footnote for :func:`bindtextdomain` above. diff --git a/cpython_2/environment/repo/Doc/library/glob.rst b/cpython_2/environment/repo/Doc/library/glob.rst new file mode 100644 index 0000000000000000000000000000000000000000..92a8c4d1eb871cfe8120dca583a63756cf8d07b2 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/glob.rst @@ -0,0 +1,117 @@ +:mod:`glob` --- Unix style pathname pattern expansion +===================================================== + +.. module:: glob + :synopsis: Unix shell style pathname pattern expansion. + +**Source code:** :source:`Lib/glob.py` + +.. index:: single: filenames; pathname expansion + +-------------- + +.. index:: + single: * (asterisk); in glob-style wildcards + single: ? (question mark); in glob-style wildcards + single: [] (square brackets); in glob-style wildcards + single: ! (exclamation); in glob-style wildcards + single: - (minus); in glob-style wildcards + single: . (dot); in glob-style wildcards + +The :mod:`glob` module finds all the pathnames matching a specified pattern +according to the rules used by the Unix shell, although results are returned in +arbitrary order. No tilde expansion is done, but ``*``, ``?``, and character +ranges expressed with ``[]`` will be correctly matched. This is done by using +the :func:`os.scandir` and :func:`fnmatch.fnmatch` functions in concert, and +not by actually invoking a subshell. Note that unlike :func:`fnmatch.fnmatch`, +:mod:`glob` treats filenames beginning with a dot (``.``) as special cases. +(For tilde and shell variable expansion, use :func:`os.path.expanduser` and +:func:`os.path.expandvars`.) + +For a literal match, wrap the meta-characters in brackets. +For example, ``'[?]'`` matches the character ``'?'``. + + +.. seealso:: + The :mod:`pathlib` module offers high-level path objects. + + +.. function:: glob(pathname, *, recursive=False) + + Return a possibly-empty list of path names that match *pathname*, which must be + a string containing a path specification. *pathname* can be either absolute + (like :file:`/usr/src/Python-1.5/Makefile`) or relative (like + :file:`../../Tools/\*/\*.gif`), and can contain shell-style wildcards. Broken + symlinks are included in the results (as in the shell). Whether or not the + results are sorted depends on the file system. + + .. index:: + single: **; in glob-style wildcards + + If *recursive* is true, the pattern "``**``" will match any files and zero or + more directories, subdirectories and symbolic links to directories. If the + pattern is followed by an :data:`os.sep` or :data:`os.altsep` then files will not + match. + + .. audit-event:: glob.glob pathname,recursive glob.glob + + .. note:: + Using the "``**``" pattern in large directory trees may consume + an inordinate amount of time. + + .. versionchanged:: 3.5 + Support for recursive globs using "``**``". + + +.. function:: iglob(pathname, *, recursive=False) + + Return an :term:`iterator` which yields the same values as :func:`glob` + without actually storing them all simultaneously. + + .. audit-event:: glob.glob pathname,recursive glob.iglob + + +.. function:: escape(pathname) + + Escape all special characters (``'?'``, ``'*'`` and ``'['``). + This is useful if you want to match an arbitrary literal string that may + have special characters in it. Special characters in drive/UNC + sharepoints are not escaped, e.g. on Windows + ``escape('//?/c:/Quo vadis?.txt')`` returns ``'//?/c:/Quo vadis[?].txt'``. + + .. versionadded:: 3.4 + + +For example, consider a directory containing the following files: +:file:`1.gif`, :file:`2.txt`, :file:`card.gif` and a subdirectory :file:`sub` +which contains only the file :file:`3.txt`. :func:`glob` will produce +the following results. Notice how any leading components of the path are +preserved. :: + + >>> import glob + >>> glob.glob('./[0-9].*') + ['./1.gif', './2.txt'] + >>> glob.glob('*.gif') + ['1.gif', 'card.gif'] + >>> glob.glob('?.gif') + ['1.gif'] + >>> glob.glob('**/*.txt', recursive=True) + ['2.txt', 'sub/3.txt'] + >>> glob.glob('./**/', recursive=True) + ['./', './sub/'] + +If the directory contains files starting with ``.`` they won't be matched by +default. For example, consider a directory containing :file:`card.gif` and +:file:`.card.gif`:: + + >>> import glob + >>> glob.glob('*.gif') + ['card.gif'] + >>> glob.glob('.c*') + ['.card.gif'] + +.. seealso:: + + Module :mod:`fnmatch` + Shell-style filename (not path) expansion + diff --git a/cpython_2/environment/repo/Doc/library/grp.rst b/cpython_2/environment/repo/Doc/library/grp.rst new file mode 100644 index 0000000000000000000000000000000000000000..74de3f952005fd7220a4e298d967a464faa6f47a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/grp.rst @@ -0,0 +1,68 @@ +:mod:`grp` --- The group database +================================= + +.. module:: grp + :platform: Unix + :synopsis: The group database (getgrnam() and friends). + +-------------- + +This module provides access to the Unix group database. It is available on all +Unix versions. + +Group database entries are reported as a tuple-like object, whose attributes +correspond to the members of the ``group`` structure (Attribute field below, see +````): + ++-------+-----------+---------------------------------+ +| Index | Attribute | Meaning | ++=======+===========+=================================+ +| 0 | gr_name | the name of the group | ++-------+-----------+---------------------------------+ +| 1 | gr_passwd | the (encrypted) group password; | +| | | often empty | ++-------+-----------+---------------------------------+ +| 2 | gr_gid | the numerical group ID | ++-------+-----------+---------------------------------+ +| 3 | gr_mem | all the group member's user | +| | | names | ++-------+-----------+---------------------------------+ + +The gid is an integer, name and password are strings, and the member list is a +list of strings. (Note that most users are not explicitly listed as members of +the group they are in according to the password database. Check both databases +to get complete membership information. Also note that a ``gr_name`` that +starts with a ``+`` or ``-`` is likely to be a YP/NIS reference and may not be +accessible via :func:`getgrnam` or :func:`getgrgid`.) + +It defines the following items: + + +.. function:: getgrgid(gid) + + Return the group database entry for the given numeric group ID. :exc:`KeyError` + is raised if the entry asked for cannot be found. + + .. deprecated:: 3.6 + Since Python 3.6 the support of non-integer arguments like floats or + strings in :func:`getgrgid` is deprecated. + +.. function:: getgrnam(name) + + Return the group database entry for the given group name. :exc:`KeyError` is + raised if the entry asked for cannot be found. + + +.. function:: getgrall() + + Return a list of all available group entries, in arbitrary order. + + +.. seealso:: + + Module :mod:`pwd` + An interface to the user database, similar to this. + + Module :mod:`spwd` + An interface to the shadow password database, similar to this. + diff --git a/cpython_2/environment/repo/Doc/library/gzip.rst b/cpython_2/environment/repo/Doc/library/gzip.rst new file mode 100644 index 0000000000000000000000000000000000000000..33c40676f747c57bdd494f17c7c5cf71ee28e956 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/gzip.rst @@ -0,0 +1,267 @@ +:mod:`gzip` --- Support for :program:`gzip` files +================================================= + +.. module:: gzip + :synopsis: Interfaces for gzip compression and decompression using file objects. + +**Source code:** :source:`Lib/gzip.py` + +-------------- + +This module provides a simple interface to compress and decompress files just +like the GNU programs :program:`gzip` and :program:`gunzip` would. + +The data compression is provided by the :mod:`zlib` module. + +The :mod:`gzip` module provides the :class:`GzipFile` class, as well as the +:func:`.open`, :func:`compress` and :func:`decompress` convenience functions. +The :class:`GzipFile` class reads and writes :program:`gzip`\ -format files, +automatically compressing or decompressing the data so that it looks like an +ordinary :term:`file object`. + +Note that additional file formats which can be decompressed by the +:program:`gzip` and :program:`gunzip` programs, such as those produced by +:program:`compress` and :program:`pack`, are not supported by this module. + +The module defines the following items: + + +.. function:: open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None) + + Open a gzip-compressed file in binary or text mode, returning a :term:`file + object`. + + The *filename* argument can be an actual filename (a :class:`str` or + :class:`bytes` object), or an existing file object to read from or write to. + + The *mode* argument can be any of ``'r'``, ``'rb'``, ``'a'``, ``'ab'``, + ``'w'``, ``'wb'``, ``'x'`` or ``'xb'`` for binary mode, or ``'rt'``, + ``'at'``, ``'wt'``, or ``'xt'`` for text mode. The default is ``'rb'``. + + The *compresslevel* argument is an integer from 0 to 9, as for the + :class:`GzipFile` constructor. + + For binary mode, this function is equivalent to the :class:`GzipFile` + constructor: ``GzipFile(filename, mode, compresslevel)``. In this case, the + *encoding*, *errors* and *newline* arguments must not be provided. + + For text mode, a :class:`GzipFile` object is created, and wrapped in an + :class:`io.TextIOWrapper` instance with the specified encoding, error + handling behavior, and line ending(s). + + .. versionchanged:: 3.3 + Added support for *filename* being a file object, support for text mode, + and the *encoding*, *errors* and *newline* arguments. + + .. versionchanged:: 3.4 + Added support for the ``'x'``, ``'xb'`` and ``'xt'`` modes. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + +.. exception:: BadGzipFile + + An exception raised for invalid gzip files. It inherits :exc:`OSError`. + :exc:`EOFError` and :exc:`zlib.error` can also be raised for invalid gzip + files. + + .. versionadded:: 3.8 + +.. class:: GzipFile(filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None) + + Constructor for the :class:`GzipFile` class, which simulates most of the + methods of a :term:`file object`, with the exception of the :meth:`truncate` + method. At least one of *fileobj* and *filename* must be given a non-trivial + value. + + The new class instance is based on *fileobj*, which can be a regular file, an + :class:`io.BytesIO` object, or any other object which simulates a file. It + defaults to ``None``, in which case *filename* is opened to provide a file + object. + + When *fileobj* is not ``None``, the *filename* argument is only used to be + included in the :program:`gzip` file header, which may include the original + filename of the uncompressed file. It defaults to the filename of *fileobj*, if + discernible; otherwise, it defaults to the empty string, and in this case the + original filename is not included in the header. + + The *mode* argument can be any of ``'r'``, ``'rb'``, ``'a'``, ``'ab'``, ``'w'``, + ``'wb'``, ``'x'``, or ``'xb'``, depending on whether the file will be read or + written. The default is the mode of *fileobj* if discernible; otherwise, the + default is ``'rb'``. In future Python releases the mode of *fileobj* will + not be used. It is better to always specify *mode* for writing. + + Note that the file is always opened in binary mode. To open a compressed file + in text mode, use :func:`.open` (or wrap your :class:`GzipFile` with an + :class:`io.TextIOWrapper`). + + The *compresslevel* argument is an integer from ``0`` to ``9`` controlling + the level of compression; ``1`` is fastest and produces the least + compression, and ``9`` is slowest and produces the most compression. ``0`` + is no compression. The default is ``9``. + + The *mtime* argument is an optional numeric timestamp to be written to + the last modification time field in the stream when compressing. It + should only be provided in compression mode. If omitted or ``None``, the + current time is used. See the :attr:`mtime` attribute for more details. + + Calling a :class:`GzipFile` object's :meth:`close` method does not close + *fileobj*, since you might wish to append more material after the compressed + data. This also allows you to pass an :class:`io.BytesIO` object opened for + writing as *fileobj*, and retrieve the resulting memory buffer using the + :class:`io.BytesIO` object's :meth:`~io.BytesIO.getvalue` method. + + :class:`GzipFile` supports the :class:`io.BufferedIOBase` interface, + including iteration and the :keyword:`with` statement. Only the + :meth:`truncate` method isn't implemented. + + :class:`GzipFile` also provides the following method and attribute: + + .. method:: peek(n) + + Read *n* uncompressed bytes without advancing the file position. + At most one single read on the compressed stream is done to satisfy + the call. The number of bytes returned may be more or less than + requested. + + .. note:: While calling :meth:`peek` does not change the file position of + the :class:`GzipFile`, it may change the position of the underlying + file object (e.g. if the :class:`GzipFile` was constructed with the + *fileobj* parameter). + + .. versionadded:: 3.2 + + .. attribute:: mtime + + When decompressing, the value of the last modification time field in + the most recently read header may be read from this attribute, as an + integer. The initial value before reading any headers is ``None``. + + All :program:`gzip` compressed streams are required to contain this + timestamp field. Some programs, such as :program:`gunzip`\ , make use + of the timestamp. The format is the same as the return value of + :func:`time.time` and the :attr:`~os.stat_result.st_mtime` attribute of + the object returned by :func:`os.stat`. + + .. versionchanged:: 3.1 + Support for the :keyword:`with` statement was added, along with the + *mtime* constructor argument and :attr:`mtime` attribute. + + .. versionchanged:: 3.2 + Support for zero-padded and unseekable files was added. + + .. versionchanged:: 3.3 + The :meth:`io.BufferedIOBase.read1` method is now implemented. + + .. versionchanged:: 3.4 + Added support for the ``'x'`` and ``'xb'`` modes. + + .. versionchanged:: 3.5 + Added support for writing arbitrary + :term:`bytes-like objects `. + The :meth:`~io.BufferedIOBase.read` method now accepts an argument of + ``None``. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + .. deprecated:: 3.9 + Opening :class:`GzipFile` for writing without specifying the *mode* + argument is deprecated. + + +.. function:: compress(data, compresslevel=9, *, mtime=None) + + Compress the *data*, returning a :class:`bytes` object containing + the compressed data. *compresslevel* and *mtime* have the same meaning as in + the :class:`GzipFile` constructor above. + + .. versionadded:: 3.2 + .. versionchanged:: 3.8 + Added the *mtime* parameter for reproducible output. + +.. function:: decompress(data) + + Decompress the *data*, returning a :class:`bytes` object containing the + uncompressed data. + + .. versionadded:: 3.2 + + +.. _gzip-usage-examples: + +Examples of usage +----------------- + +Example of how to read a compressed file:: + + import gzip + with gzip.open('/home/joe/file.txt.gz', 'rb') as f: + file_content = f.read() + +Example of how to create a compressed GZIP file:: + + import gzip + content = b"Lots of content here" + with gzip.open('/home/joe/file.txt.gz', 'wb') as f: + f.write(content) + +Example of how to GZIP compress an existing file:: + + import gzip + import shutil + with open('/home/joe/file.txt', 'rb') as f_in: + with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out: + shutil.copyfileobj(f_in, f_out) + +Example of how to GZIP compress a binary string:: + + import gzip + s_in = b"Lots of content here" + s_out = gzip.compress(s_in) + +.. seealso:: + + Module :mod:`zlib` + The basic data compression module needed to support the :program:`gzip` file + format. + + +.. program:: gzip + +Command Line Interface +---------------------- + +The :mod:`gzip` module provides a simple command line interface to compress or +decompress files. + +Once executed the :mod:`gzip` module keeps the input file(s). + +.. versionchanged:: 3.8 + + Add a new command line interface with a usage. + By default, when you will execute the CLI, the default compression level is 6. + +Command line options +^^^^^^^^^^^^^^^^^^^^ + +.. cmdoption:: file + + If *file* is not specified, read from :attr:`sys.stdin`. + +.. cmdoption:: --fast + + Indicates the fastest compression method (less compression). + +.. cmdoption:: --best + + Indicates the slowest compression method (best compression). + +.. cmdoption:: -d, --decompress + + Decompress the given file. + +.. cmdoption:: -h, --help + + Show the help message. + diff --git a/cpython_2/environment/repo/Doc/library/hashlib-blake2-tree.png b/cpython_2/environment/repo/Doc/library/hashlib-blake2-tree.png new file mode 100644 index 0000000000000000000000000000000000000000..f8692a130817c07027e398427ae048e90c9440ad Binary files /dev/null and b/cpython_2/environment/repo/Doc/library/hashlib-blake2-tree.png differ diff --git a/cpython_2/environment/repo/Doc/library/hashlib.rst b/cpython_2/environment/repo/Doc/library/hashlib.rst new file mode 100644 index 0000000000000000000000000000000000000000..b737d22d4100cdf2af0046fc40a9b8f2102eff42 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/hashlib.rst @@ -0,0 +1,748 @@ +:mod:`hashlib` --- Secure hashes and message digests +==================================================== + +.. module:: hashlib + :synopsis: Secure hash and message digest algorithms. + +.. moduleauthor:: Gregory P. Smith +.. sectionauthor:: Gregory P. Smith + +**Source code:** :source:`Lib/hashlib.py` + +.. index:: + single: message digest, MD5 + single: secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512 + +.. testsetup:: + + import hashlib + + +-------------- + +This module implements a common interface to many different secure hash and +message digest algorithms. Included are the FIPS secure hash algorithms SHA1, +SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5 +algorithm (defined in Internet :rfc:`1321`). The terms "secure hash" and +"message digest" are interchangeable. Older algorithms were called message +digests. The modern term is secure hash. + +.. note:: + + If you want the adler32 or crc32 hash functions, they are available in + the :mod:`zlib` module. + +.. warning:: + + Some algorithms have known hash collision weaknesses, refer to the "See + also" section at the end. + + +.. _hash-algorithms: + +Hash algorithms +--------------- + +There is one constructor method named for each type of :dfn:`hash`. All return +a hash object with the same simple interface. For example: use :func:`sha256` to +create a SHA-256 hash object. You can now feed this object with :term:`bytes-like +objects ` (normally :class:`bytes`) using the :meth:`update` method. +At any point you can ask it for the :dfn:`digest` of the +concatenation of the data fed to it so far using the :meth:`digest` or +:meth:`hexdigest` methods. + +.. note:: + + For better multithreading performance, the Python :term:`GIL` is released for + data larger than 2047 bytes at object creation or on update. + +.. note:: + + Feeding string objects into :meth:`update` is not supported, as hashes work + on bytes, not on characters. + +.. index:: single: OpenSSL; (use in module hashlib) + +Constructors for hash algorithms that are always present in this module are +:func:`sha1`, :func:`sha224`, :func:`sha256`, :func:`sha384`, +:func:`sha512`, :func:`blake2b`, and :func:`blake2s`. +:func:`md5` is normally available as well, though it +may be missing or blocked if you are using a rare "FIPS compliant" build of Python. +Additional algorithms may also be available depending upon the OpenSSL +library that Python uses on your platform. On most platforms the +:func:`sha3_224`, :func:`sha3_256`, :func:`sha3_384`, :func:`sha3_512`, +:func:`shake_128`, :func:`shake_256` are also available. + +.. versionadded:: 3.6 + SHA3 (Keccak) and SHAKE constructors :func:`sha3_224`, :func:`sha3_256`, + :func:`sha3_384`, :func:`sha3_512`, :func:`shake_128`, :func:`shake_256`. + +.. versionadded:: 3.6 + :func:`blake2b` and :func:`blake2s` were added. + +.. versionchanged:: 3.9 + All hashlib constructors take a keyword-only argument *usedforsecurity* + with default value ``True``. A false value allows the use of insecure and + blocked hashing algorithms in restricted environments. ``False`` indicates + that the hashing algorithm is not used in a security context, e.g. as a + non-cryptographic one-way compression function. + +For example, to obtain the digest of the byte string ``b'Nobody inspects the +spammish repetition'``:: + + >>> import hashlib + >>> m = hashlib.sha256() + >>> m.update(b"Nobody inspects") + >>> m.update(b" the spammish repetition") + >>> m.digest() + b'\x03\x1e\xdd}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7\xfd\xdf\xf7\xbcN\x84:\xa6\xaf\x0c\x95\x0fK\x94\x06' + >>> m.digest_size + 32 + >>> m.block_size + 64 + +More condensed: + + >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest() + 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' + +.. function:: new(name[, data], *, usedforsecurity=True) + + Is a generic constructor that takes the string *name* of the desired + algorithm as its first parameter. It also exists to allow access to the + above listed hashes as well as any other algorithms that your OpenSSL + library may offer. The named constructors are much faster than :func:`new` + and should be preferred. + +Using :func:`new` with an algorithm provided by OpenSSL: + + >>> h = hashlib.new('ripemd160') + >>> h.update(b"Nobody inspects the spammish repetition") + >>> h.hexdigest() + 'cc4a5ce1b3df48aec5d22d1f16b894a0b894eccc' + +Hashlib provides the following constant attributes: + +.. data:: algorithms_guaranteed + + A set containing the names of the hash algorithms guaranteed to be supported + by this module on all platforms. Note that 'md5' is in this list despite + some upstream vendors offering an odd "FIPS compliant" Python build that + excludes it. + + .. versionadded:: 3.2 + +.. data:: algorithms_available + + A set containing the names of the hash algorithms that are available in the + running Python interpreter. These names will be recognized when passed to + :func:`new`. :attr:`algorithms_guaranteed` will always be a subset. The + same algorithm may appear multiple times in this set under different names + (thanks to OpenSSL). + + .. versionadded:: 3.2 + +The following values are provided as constant attributes of the hash objects +returned by the constructors: + + +.. data:: hash.digest_size + + The size of the resulting hash in bytes. + +.. data:: hash.block_size + + The internal block size of the hash algorithm in bytes. + +A hash object has the following attributes: + +.. attribute:: hash.name + + The canonical name of this hash, always lowercase and always suitable as a + parameter to :func:`new` to create another hash of this type. + + .. versionchanged:: 3.4 + The name attribute has been present in CPython since its inception, but + until Python 3.4 was not formally specified, so may not exist on some + platforms. + +A hash object has the following methods: + + +.. method:: hash.update(data) + + Update the hash object with the :term:`bytes-like object`. + Repeated calls are equivalent to a single call with the + concatenation of all the arguments: ``m.update(a); m.update(b)`` is + equivalent to ``m.update(a+b)``. + + .. versionchanged:: 3.1 + The Python GIL is released to allow other threads to run while hash + updates on data larger than 2047 bytes is taking place when using hash + algorithms supplied by OpenSSL. + + +.. method:: hash.digest() + + Return the digest of the data passed to the :meth:`update` method so far. + This is a bytes object of size :attr:`digest_size` which may contain bytes in + the whole range from 0 to 255. + + +.. method:: hash.hexdigest() + + Like :meth:`digest` except the digest is returned as a string object of + double length, containing only hexadecimal digits. This may be used to + exchange the value safely in email or other non-binary environments. + + +.. method:: hash.copy() + + Return a copy ("clone") of the hash object. This can be used to efficiently + compute the digests of data sharing a common initial substring. + + +SHAKE variable length digests +----------------------------- + +The :func:`shake_128` and :func:`shake_256` algorithms provide variable +length digests with length_in_bits//2 up to 128 or 256 bits of security. +As such, their digest methods require a length. Maximum length is not limited +by the SHAKE algorithm. + +.. method:: shake.digest(length) + + Return the digest of the data passed to the :meth:`update` method so far. + This is a bytes object of size *length* which may contain bytes in + the whole range from 0 to 255. + + +.. method:: shake.hexdigest(length) + + Like :meth:`digest` except the digest is returned as a string object of + double length, containing only hexadecimal digits. This may be used to + exchange the value safely in email or other non-binary environments. + + +Key derivation +-------------- + +Key derivation and key stretching algorithms are designed for secure password +hashing. Naive algorithms such as ``sha1(password)`` are not resistant against +brute-force attacks. A good password hashing function must be tunable, slow, and +include a `salt `_. + + +.. function:: pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) + + The function provides PKCS#5 password-based key derivation function 2. It + uses HMAC as pseudorandom function. + + The string *hash_name* is the desired name of the hash digest algorithm for + HMAC, e.g. 'sha1' or 'sha256'. *password* and *salt* are interpreted as + buffers of bytes. Applications and libraries should limit *password* to + a sensible length (e.g. 1024). *salt* should be about 16 or more bytes from + a proper source, e.g. :func:`os.urandom`. + + The number of *iterations* should be chosen based on the hash algorithm and + computing power. As of 2013, at least 100,000 iterations of SHA-256 are + suggested. + + *dklen* is the length of the derived key. If *dklen* is ``None`` then the + digest size of the hash algorithm *hash_name* is used, e.g. 64 for SHA-512. + + >>> import hashlib + >>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000) + >>> dk.hex() + '0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5' + + .. versionadded:: 3.4 + + .. note:: + + A fast implementation of *pbkdf2_hmac* is available with OpenSSL. The + Python implementation uses an inline version of :mod:`hmac`. It is about + three times slower and doesn't release the GIL. + +.. function:: scrypt(password, *, salt, n, r, p, maxmem=0, dklen=64) + + The function provides scrypt password-based key derivation function as + defined in :rfc:`7914`. + + *password* and *salt* must be :term:`bytes-like objects + `. Applications and libraries should limit *password* + to a sensible length (e.g. 1024). *salt* should be about 16 or more + bytes from a proper source, e.g. :func:`os.urandom`. + + *n* is the CPU/Memory cost factor, *r* the block size, *p* parallelization + factor and *maxmem* limits memory (OpenSSL 1.1.0 defaults to 32 MiB). + *dklen* is the length of the derived key. + + .. availability:: OpenSSL 1.1+. + + .. versionadded:: 3.6 + + +BLAKE2 +------ + +.. sectionauthor:: Dmitry Chestnykh + +.. index:: + single: blake2b, blake2s + +BLAKE2_ is a cryptographic hash function defined in :rfc:`7693` that comes in two +flavors: + +* **BLAKE2b**, optimized for 64-bit platforms and produces digests of any size + between 1 and 64 bytes, + +* **BLAKE2s**, optimized for 8- to 32-bit platforms and produces digests of any + size between 1 and 32 bytes. + +BLAKE2 supports **keyed mode** (a faster and simpler replacement for HMAC_), +**salted hashing**, **personalization**, and **tree hashing**. + +Hash objects from this module follow the API of standard library's +:mod:`hashlib` objects. + + +Creating hash objects +^^^^^^^^^^^^^^^^^^^^^ + +New hash objects are created by calling constructor functions: + + +.. function:: blake2b(data=b'', *, digest_size=64, key=b'', salt=b'', \ + person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \ + node_depth=0, inner_size=0, last_node=False, \ + usedforsecurity=True) + +.. function:: blake2s(data=b'', *, digest_size=32, key=b'', salt=b'', \ + person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \ + node_depth=0, inner_size=0, last_node=False, \ + usedforsecurity=True) + + +These functions return the corresponding hash objects for calculating +BLAKE2b or BLAKE2s. They optionally take these general parameters: + +* *data*: initial chunk of data to hash, which must be + :term:`bytes-like object`. It can be passed only as positional argument. + +* *digest_size*: size of output digest in bytes. + +* *key*: key for keyed hashing (up to 64 bytes for BLAKE2b, up to 32 bytes for + BLAKE2s). + +* *salt*: salt for randomized hashing (up to 16 bytes for BLAKE2b, up to 8 + bytes for BLAKE2s). + +* *person*: personalization string (up to 16 bytes for BLAKE2b, up to 8 bytes + for BLAKE2s). + +The following table shows limits for general parameters (in bytes): + +======= =========== ======== ========= =========== +Hash digest_size len(key) len(salt) len(person) +======= =========== ======== ========= =========== +BLAKE2b 64 64 16 16 +BLAKE2s 32 32 8 8 +======= =========== ======== ========= =========== + +.. note:: + + BLAKE2 specification defines constant lengths for salt and personalization + parameters, however, for convenience, this implementation accepts byte + strings of any size up to the specified length. If the length of the + parameter is less than specified, it is padded with zeros, thus, for + example, ``b'salt'`` and ``b'salt\x00'`` is the same value. (This is not + the case for *key*.) + +These sizes are available as module `constants`_ described below. + +Constructor functions also accept the following tree hashing parameters: + +* *fanout*: fanout (0 to 255, 0 if unlimited, 1 in sequential mode). + +* *depth*: maximal depth of tree (1 to 255, 255 if unlimited, 1 in + sequential mode). + +* *leaf_size*: maximal byte length of leaf (0 to 2**32-1, 0 if unlimited or in + sequential mode). + +* *node_offset*: node offset (0 to 2**64-1 for BLAKE2b, 0 to 2**48-1 for + BLAKE2s, 0 for the first, leftmost, leaf, or in sequential mode). + +* *node_depth*: node depth (0 to 255, 0 for leaves, or in sequential mode). + +* *inner_size*: inner digest size (0 to 64 for BLAKE2b, 0 to 32 for + BLAKE2s, 0 in sequential mode). + +* *last_node*: boolean indicating whether the processed node is the last + one (`False` for sequential mode). + +.. figure:: hashlib-blake2-tree.png + :alt: Explanation of tree mode parameters. + +See section 2.10 in `BLAKE2 specification +`_ for comprehensive review of tree +hashing. + + +Constants +^^^^^^^^^ + +.. data:: blake2b.SALT_SIZE +.. data:: blake2s.SALT_SIZE + +Salt length (maximum length accepted by constructors). + + +.. data:: blake2b.PERSON_SIZE +.. data:: blake2s.PERSON_SIZE + +Personalization string length (maximum length accepted by constructors). + + +.. data:: blake2b.MAX_KEY_SIZE +.. data:: blake2s.MAX_KEY_SIZE + +Maximum key size. + + +.. data:: blake2b.MAX_DIGEST_SIZE +.. data:: blake2s.MAX_DIGEST_SIZE + +Maximum digest size that the hash function can output. + + +Examples +^^^^^^^^ + +Simple hashing +"""""""""""""" + +To calculate hash of some data, you should first construct a hash object by +calling the appropriate constructor function (:func:`blake2b` or +:func:`blake2s`), then update it with the data by calling :meth:`update` on the +object, and, finally, get the digest out of the object by calling +:meth:`digest` (or :meth:`hexdigest` for hex-encoded string). + + >>> from hashlib import blake2b + >>> h = blake2b() + >>> h.update(b'Hello world') + >>> h.hexdigest() + '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183' + + +As a shortcut, you can pass the first chunk of data to update directly to the +constructor as the positional argument: + + >>> from hashlib import blake2b + >>> blake2b(b'Hello world').hexdigest() + '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183' + +You can call :meth:`hash.update` as many times as you need to iteratively +update the hash: + + >>> from hashlib import blake2b + >>> items = [b'Hello', b' ', b'world'] + >>> h = blake2b() + >>> for item in items: + ... h.update(item) + >>> h.hexdigest() + '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183' + + +Using different digest sizes +"""""""""""""""""""""""""""" + +BLAKE2 has configurable size of digests up to 64 bytes for BLAKE2b and up to 32 +bytes for BLAKE2s. For example, to replace SHA-1 with BLAKE2b without changing +the size of output, we can tell BLAKE2b to produce 20-byte digests: + + >>> from hashlib import blake2b + >>> h = blake2b(digest_size=20) + >>> h.update(b'Replacing SHA1 with the more secure function') + >>> h.hexdigest() + 'd24f26cf8de66472d58d4e1b1774b4c9158b1f4c' + >>> h.digest_size + 20 + >>> len(h.digest()) + 20 + +Hash objects with different digest sizes have completely different outputs +(shorter hashes are *not* prefixes of longer hashes); BLAKE2b and BLAKE2s +produce different outputs even if the output length is the same: + + >>> from hashlib import blake2b, blake2s + >>> blake2b(digest_size=10).hexdigest() + '6fa1d8fcfd719046d762' + >>> blake2b(digest_size=11).hexdigest() + 'eb6ec15daf9546254f0809' + >>> blake2s(digest_size=10).hexdigest() + '1bf21a98c78a1c376ae9' + >>> blake2s(digest_size=11).hexdigest() + '567004bf96e4a25773ebf4' + + +Keyed hashing +""""""""""""" + +Keyed hashing can be used for authentication as a faster and simpler +replacement for `Hash-based message authentication code +`_ (HMAC). +BLAKE2 can be securely used in prefix-MAC mode thanks to the +indifferentiability property inherited from BLAKE. + +This example shows how to get a (hex-encoded) 128-bit authentication code for +message ``b'message data'`` with key ``b'pseudorandom key'``:: + + >>> from hashlib import blake2b + >>> h = blake2b(key=b'pseudorandom key', digest_size=16) + >>> h.update(b'message data') + >>> h.hexdigest() + '3d363ff7401e02026f4a4687d4863ced' + + +As a practical example, a web application can symmetrically sign cookies sent +to users and later verify them to make sure they weren't tampered with:: + + >>> from hashlib import blake2b + >>> from hmac import compare_digest + >>> + >>> SECRET_KEY = b'pseudorandomly generated server secret key' + >>> AUTH_SIZE = 16 + >>> + >>> def sign(cookie): + ... h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY) + ... h.update(cookie) + ... return h.hexdigest().encode('utf-8') + >>> + >>> def verify(cookie, sig): + ... good_sig = sign(cookie) + ... return compare_digest(good_sig, sig) + >>> + >>> cookie = b'user-alice' + >>> sig = sign(cookie) + >>> print("{0},{1}".format(cookie.decode('utf-8'), sig)) + user-alice,b'43b3c982cf697e0c5ab22172d1ca7421' + >>> verify(cookie, sig) + True + >>> verify(b'user-bob', sig) + False + >>> verify(cookie, b'0102030405060708090a0b0c0d0e0f00') + False + +Even though there's a native keyed hashing mode, BLAKE2 can, of course, be used +in HMAC construction with :mod:`hmac` module:: + + >>> import hmac, hashlib + >>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s) + >>> m.update(b'message') + >>> m.hexdigest() + 'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142' + + +Randomized hashing +"""""""""""""""""" + +By setting *salt* parameter users can introduce randomization to the hash +function. Randomized hashing is useful for protecting against collision attacks +on the hash function used in digital signatures. + + Randomized hashing is designed for situations where one party, the message + preparer, generates all or part of a message to be signed by a second + party, the message signer. If the message preparer is able to find + cryptographic hash function collisions (i.e., two messages producing the + same hash value), then they might prepare meaningful versions of the message + that would produce the same hash value and digital signature, but with + different results (e.g., transferring $1,000,000 to an account, rather than + $10). Cryptographic hash functions have been designed with collision + resistance as a major goal, but the current concentration on attacking + cryptographic hash functions may result in a given cryptographic hash + function providing less collision resistance than expected. Randomized + hashing offers the signer additional protection by reducing the likelihood + that a preparer can generate two or more messages that ultimately yield the + same hash value during the digital signature generation process --- even if + it is practical to find collisions for the hash function. However, the use + of randomized hashing may reduce the amount of security provided by a + digital signature when all portions of the message are prepared + by the signer. + + (`NIST SP-800-106 "Randomized Hashing for Digital Signatures" + `_) + +In BLAKE2 the salt is processed as a one-time input to the hash function during +initialization, rather than as an input to each compression function. + +.. warning:: + + *Salted hashing* (or just hashing) with BLAKE2 or any other general-purpose + cryptographic hash function, such as SHA-256, is not suitable for hashing + passwords. See `BLAKE2 FAQ `_ for more + information. +.. + + >>> import os + >>> from hashlib import blake2b + >>> msg = b'some message' + >>> # Calculate the first hash with a random salt. + >>> salt1 = os.urandom(blake2b.SALT_SIZE) + >>> h1 = blake2b(salt=salt1) + >>> h1.update(msg) + >>> # Calculate the second hash with a different random salt. + >>> salt2 = os.urandom(blake2b.SALT_SIZE) + >>> h2 = blake2b(salt=salt2) + >>> h2.update(msg) + >>> # The digests are different. + >>> h1.digest() != h2.digest() + True + + +Personalization +""""""""""""""" + +Sometimes it is useful to force hash function to produce different digests for +the same input for different purposes. Quoting the authors of the Skein hash +function: + + We recommend that all application designers seriously consider doing this; + we have seen many protocols where a hash that is computed in one part of + the protocol can be used in an entirely different part because two hash + computations were done on similar or related data, and the attacker can + force the application to make the hash inputs the same. Personalizing each + hash function used in the protocol summarily stops this type of attack. + + (`The Skein Hash Function Family + `_, + p. 21) + +BLAKE2 can be personalized by passing bytes to the *person* argument:: + + >>> from hashlib import blake2b + >>> FILES_HASH_PERSON = b'MyApp Files Hash' + >>> BLOCK_HASH_PERSON = b'MyApp Block Hash' + >>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON) + >>> h.update(b'the same content') + >>> h.hexdigest() + '20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4' + >>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON) + >>> h.update(b'the same content') + >>> h.hexdigest() + 'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3' + +Personalization together with the keyed mode can also be used to derive different +keys from a single one. + + >>> from hashlib import blake2s + >>> from base64 import b64decode, b64encode + >>> orig_key = b64decode(b'Rm5EPJai72qcK3RGBpW3vPNfZy5OZothY+kHY6h21KM=') + >>> enc_key = blake2s(key=orig_key, person=b'kEncrypt').digest() + >>> mac_key = blake2s(key=orig_key, person=b'kMAC').digest() + >>> print(b64encode(enc_key).decode('utf-8')) + rbPb15S/Z9t+agffno5wuhB77VbRi6F9Iv2qIxU7WHw= + >>> print(b64encode(mac_key).decode('utf-8')) + G9GtHFE1YluXY1zWPlYk1e/nWfu0WSEb0KRcjhDeP/o= + +Tree mode +""""""""" + +Here's an example of hashing a minimal tree with two leaf nodes:: + + 10 + / \ + 00 01 + +This example uses 64-byte internal digests, and returns the 32-byte final +digest:: + + >>> from hashlib import blake2b + >>> + >>> FANOUT = 2 + >>> DEPTH = 2 + >>> LEAF_SIZE = 4096 + >>> INNER_SIZE = 64 + >>> + >>> buf = bytearray(6000) + >>> + >>> # Left leaf + ... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH, + ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE, + ... node_offset=0, node_depth=0, last_node=False) + >>> # Right leaf + ... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH, + ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE, + ... node_offset=1, node_depth=0, last_node=True) + >>> # Root node + ... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH, + ... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE, + ... node_offset=0, node_depth=1, last_node=True) + >>> h10.update(h00.digest()) + >>> h10.update(h01.digest()) + >>> h10.hexdigest() + '3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa' + +Credits +^^^^^^^ + +BLAKE2_ was designed by *Jean-Philippe Aumasson*, *Samuel Neves*, *Zooko +Wilcox-O'Hearn*, and *Christian Winnerlein* based on SHA-3_ finalist BLAKE_ +created by *Jean-Philippe Aumasson*, *Luca Henzen*, *Willi Meier*, and +*Raphael C.-W. Phan*. + +It uses core algorithm from ChaCha_ cipher designed by *Daniel J. Bernstein*. + +The stdlib implementation is based on pyblake2_ module. It was written by +*Dmitry Chestnykh* based on C implementation written by *Samuel Neves*. The +documentation was copied from pyblake2_ and written by *Dmitry Chestnykh*. + +The C code was partly rewritten for Python by *Christian Heimes*. + +The following public domain dedication applies for both C hash function +implementation, extension code, and this documentation: + + To the extent possible under law, the author(s) have dedicated all copyright + and related and neighboring rights to this software to the public domain + worldwide. This software is distributed without any warranty. + + You should have received a copy of the CC0 Public Domain Dedication along + with this software. If not, see + https://creativecommons.org/publicdomain/zero/1.0/. + +The following people have helped with development or contributed their changes +to the project and the public domain according to the Creative Commons Public +Domain Dedication 1.0 Universal: + +* *Alexandr Sokolovskiy* + +.. _BLAKE2: https://blake2.net +.. _HMAC: https://en.wikipedia.org/wiki/Hash-based_message_authentication_code +.. _BLAKE: https://131002.net/blake/ +.. _SHA-3: https://en.wikipedia.org/wiki/NIST_hash_function_competition +.. _ChaCha: https://cr.yp.to/chacha.html +.. _pyblake2: https://pythonhosted.org/pyblake2/ + + + +.. seealso:: + + Module :mod:`hmac` + A module to generate message authentication codes using hashes. + + Module :mod:`base64` + Another way to encode binary hashes for non-binary environments. + + https://blake2.net + Official BLAKE2 website. + + https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2.pdf + The FIPS 180-2 publication on Secure Hash Algorithms. + + https://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms + Wikipedia article with information on which algorithms have known issues and + what that means regarding their use. + + https://www.ietf.org/rfc/rfc2898.txt + PKCS #5: Password-Based Cryptography Specification Version 2.0 diff --git a/cpython_2/environment/repo/Doc/library/heapq.rst b/cpython_2/environment/repo/Doc/library/heapq.rst new file mode 100644 index 0000000000000000000000000000000000000000..8b00f7b27959b68188a8cc9a5506b943ae6ae770 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/heapq.rst @@ -0,0 +1,322 @@ +:mod:`heapq` --- Heap queue algorithm +===================================== + +.. module:: heapq + :synopsis: Heap queue algorithm (a.k.a. priority queue). + +.. moduleauthor:: Kevin O'Connor +.. sectionauthor:: Guido van Rossum +.. sectionauthor:: François Pinard +.. sectionauthor:: Raymond Hettinger + +**Source code:** :source:`Lib/heapq.py` + +-------------- + +This module provides an implementation of the heap queue algorithm, also known +as the priority queue algorithm. + +Heaps are binary trees for which every parent node has a value less than or +equal to any of its children. This implementation uses arrays for which +``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting +elements from zero. For the sake of comparison, non-existing elements are +considered to be infinite. The interesting property of a heap is that its +smallest element is always the root, ``heap[0]``. + +The API below differs from textbook heap algorithms in two aspects: (a) We use +zero-based indexing. This makes the relationship between the index for a node +and the indexes for its children slightly less obvious, but is more suitable +since Python uses zero-based indexing. (b) Our pop method returns the smallest +item, not the largest (called a "min heap" in textbooks; a "max heap" is more +common in texts because of its suitability for in-place sorting). + +These two make it possible to view the heap as a regular Python list without +surprises: ``heap[0]`` is the smallest item, and ``heap.sort()`` maintains the +heap invariant! + +To create a heap, use a list initialized to ``[]``, or you can transform a +populated list into a heap via function :func:`heapify`. + +The following functions are provided: + + +.. function:: heappush(heap, item) + + Push the value *item* onto the *heap*, maintaining the heap invariant. + + +.. function:: heappop(heap) + + Pop and return the smallest item from the *heap*, maintaining the heap + invariant. If the heap is empty, :exc:`IndexError` is raised. To access the + smallest item without popping it, use ``heap[0]``. + + +.. function:: heappushpop(heap, item) + + Push *item* on the heap, then pop and return the smallest item from the + *heap*. The combined action runs more efficiently than :func:`heappush` + followed by a separate call to :func:`heappop`. + + +.. function:: heapify(x) + + Transform list *x* into a heap, in-place, in linear time. + + +.. function:: heapreplace(heap, item) + + Pop and return the smallest item from the *heap*, and also push the new *item*. + The heap size doesn't change. If the heap is empty, :exc:`IndexError` is raised. + + This one step operation is more efficient than a :func:`heappop` followed by + :func:`heappush` and can be more appropriate when using a fixed-size heap. + The pop/push combination always returns an element from the heap and replaces + it with *item*. + + The value returned may be larger than the *item* added. If that isn't + desired, consider using :func:`heappushpop` instead. Its push/pop + combination returns the smaller of the two values, leaving the larger value + on the heap. + + +The module also offers three general purpose functions based on heaps. + + +.. function:: merge(*iterables, key=None, reverse=False) + + Merge multiple sorted inputs into a single sorted output (for example, merge + timestamped entries from multiple log files). Returns an :term:`iterator` + over the sorted values. + + Similar to ``sorted(itertools.chain(*iterables))`` but returns an iterable, does + not pull the data into memory all at once, and assumes that each of the input + streams is already sorted (smallest to largest). + + Has two optional arguments which must be specified as keyword arguments. + + *key* specifies a :term:`key function` of one argument that is used to + extract a comparison key from each input element. The default value is + ``None`` (compare the elements directly). + + *reverse* is a boolean value. If set to ``True``, then the input elements + are merged as if each comparison were reversed. To achieve behavior similar + to ``sorted(itertools.chain(*iterables), reverse=True)``, all iterables must + be sorted from largest to smallest. + + .. versionchanged:: 3.5 + Added the optional *key* and *reverse* parameters. + + +.. function:: nlargest(n, iterable, key=None) + + Return a list with the *n* largest elements from the dataset defined by + *iterable*. *key*, if provided, specifies a function of one argument that is + used to extract a comparison key from each element in *iterable* (for example, + ``key=str.lower``). Equivalent to: ``sorted(iterable, key=key, + reverse=True)[:n]``. + + +.. function:: nsmallest(n, iterable, key=None) + + Return a list with the *n* smallest elements from the dataset defined by + *iterable*. *key*, if provided, specifies a function of one argument that is + used to extract a comparison key from each element in *iterable* (for example, + ``key=str.lower``). Equivalent to: ``sorted(iterable, key=key)[:n]``. + + +The latter two functions perform best for smaller values of *n*. For larger +values, it is more efficient to use the :func:`sorted` function. Also, when +``n==1``, it is more efficient to use the built-in :func:`min` and :func:`max` +functions. If repeated usage of these functions is required, consider turning +the iterable into an actual heap. + + +Basic Examples +-------------- + +A `heapsort `_ can be implemented by +pushing all values onto a heap and then popping off the smallest values one at a +time:: + + >>> def heapsort(iterable): + ... h = [] + ... for value in iterable: + ... heappush(h, value) + ... return [heappop(h) for i in range(len(h))] + ... + >>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + +This is similar to ``sorted(iterable)``, but unlike :func:`sorted`, this +implementation is not stable. + +Heap elements can be tuples. This is useful for assigning comparison values +(such as task priorities) alongside the main record being tracked:: + + >>> h = [] + >>> heappush(h, (5, 'write code')) + >>> heappush(h, (7, 'release product')) + >>> heappush(h, (1, 'write spec')) + >>> heappush(h, (3, 'create tests')) + >>> heappop(h) + (1, 'write spec') + + +Priority Queue Implementation Notes +----------------------------------- + +A `priority queue `_ is common use +for a heap, and it presents several implementation challenges: + +* Sort stability: how do you get two tasks with equal priorities to be returned + in the order they were originally added? + +* Tuple comparison breaks for (priority, task) pairs if the priorities are equal + and the tasks do not have a default comparison order. + +* If the priority of a task changes, how do you move it to a new position in + the heap? + +* Or if a pending task needs to be deleted, how do you find it and remove it + from the queue? + +A solution to the first two challenges is to store entries as 3-element list +including the priority, an entry count, and the task. The entry count serves as +a tie-breaker so that two tasks with the same priority are returned in the order +they were added. And since no two entry counts are the same, the tuple +comparison will never attempt to directly compare two tasks. + +Another solution to the problem of non-comparable tasks is to create a wrapper +class that ignores the task item and only compares the priority field:: + + from dataclasses import dataclass, field + from typing import Any + + @dataclass(order=True) + class PrioritizedItem: + priority: int + item: Any=field(compare=False) + +The remaining challenges revolve around finding a pending task and making +changes to its priority or removing it entirely. Finding a task can be done +with a dictionary pointing to an entry in the queue. + +Removing the entry or changing its priority is more difficult because it would +break the heap structure invariants. So, a possible solution is to mark the +entry as removed and add a new entry with the revised priority:: + + pq = [] # list of entries arranged in a heap + entry_finder = {} # mapping of tasks to entries + REMOVED = '' # placeholder for a removed task + counter = itertools.count() # unique sequence count + + def add_task(task, priority=0): + 'Add a new task or update the priority of an existing task' + if task in entry_finder: + remove_task(task) + count = next(counter) + entry = [priority, count, task] + entry_finder[task] = entry + heappush(pq, entry) + + def remove_task(task): + 'Mark an existing task as REMOVED. Raise KeyError if not found.' + entry = entry_finder.pop(task) + entry[-1] = REMOVED + + def pop_task(): + 'Remove and return the lowest priority task. Raise KeyError if empty.' + while pq: + priority, count, task = heappop(pq) + if task is not REMOVED: + del entry_finder[task] + return task + raise KeyError('pop from an empty priority queue') + + +Theory +------ + +Heaps are arrays for which ``a[k] <= a[2*k+1]`` and ``a[k] <= a[2*k+2]`` for all +*k*, counting elements from 0. For the sake of comparison, non-existing +elements are considered to be infinite. The interesting property of a heap is +that ``a[0]`` is always its smallest element. + +The strange invariant above is meant to be an efficient memory representation +for a tournament. The numbers below are *k*, not ``a[k]``:: + + 0 + + 1 2 + + 3 4 5 6 + + 7 8 9 10 11 12 13 14 + + 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 + +In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In a usual +binary tournament we see in sports, each cell is the winner over the two cells +it tops, and we can trace the winner down the tree to see all opponents s/he +had. However, in many computer applications of such tournaments, we do not need +to trace the history of a winner. To be more memory efficient, when a winner is +promoted, we try to replace it by something else at a lower level, and the rule +becomes that a cell and the two cells it tops contain three different items, but +the top cell "wins" over the two topped cells. + +If this heap invariant is protected at all time, index 0 is clearly the overall +winner. The simplest algorithmic way to remove it and find the "next" winner is +to move some loser (let's say cell 30 in the diagram above) into the 0 position, +and then percolate this new 0 down the tree, exchanging values, until the +invariant is re-established. This is clearly logarithmic on the total number of +items in the tree. By iterating over all items, you get an O(n log n) sort. + +A nice feature of this sort is that you can efficiently insert new items while +the sort is going on, provided that the inserted items are not "better" than the +last 0'th element you extracted. This is especially useful in simulation +contexts, where the tree holds all incoming events, and the "win" condition +means the smallest scheduled time. When an event schedules other events for +execution, they are scheduled into the future, so they can easily go into the +heap. So, a heap is a good structure for implementing schedulers (this is what +I used for my MIDI sequencer :-). + +Various structures for implementing schedulers have been extensively studied, +and heaps are good for this, as they are reasonably speedy, the speed is almost +constant, and the worst case is not much different than the average case. +However, there are other representations which are more efficient overall, yet +the worst cases might be terrible. + +Heaps are also very useful in big disk sorts. You most probably all know that a +big sort implies producing "runs" (which are pre-sorted sequences, whose size is +usually related to the amount of CPU memory), followed by a merging passes for +these runs, which merging is often very cleverly organised [#]_. It is very +important that the initial sort produces the longest runs possible. Tournaments +are a good way to achieve that. If, using all the memory available to hold a +tournament, you replace and percolate items that happen to fit the current run, +you'll produce runs which are twice the size of the memory for random input, and +much better for input fuzzily ordered. + +Moreover, if you output the 0'th item on disk and get an input which may not fit +in the current tournament (because the value "wins" over the last output value), +it cannot fit in the heap, so the size of the heap decreases. The freed memory +could be cleverly reused immediately for progressively building a second heap, +which grows at exactly the same rate the first heap is melting. When the first +heap completely vanishes, you switch heaps and start a new run. Clever and +quite effective! + +In a word, heaps are useful memory structures to know. I use them in a few +applications, and I think it is good to keep a 'heap' module around. :-) + +.. rubric:: Footnotes + +.. [#] The disk balancing algorithms which are current, nowadays, are more annoying + than clever, and this is a consequence of the seeking capabilities of the disks. + On devices which cannot seek, like big tape drives, the story was quite + different, and one had to be very clever to ensure (far in advance) that each + tape movement will be the most effective possible (that is, will best + participate at "progressing" the merge). Some tapes were even able to read + backwards, and this was also used to avoid the rewinding time. Believe me, real + good tape sorts were quite spectacular to watch! From all times, sorting has + always been a Great Art! :-) + diff --git a/cpython_2/environment/repo/Doc/library/hmac.rst b/cpython_2/environment/repo/Doc/library/hmac.rst new file mode 100644 index 0000000000000000000000000000000000000000..57ac8bb16120f5d75e44f168fe023a5809f3b6a4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/hmac.rst @@ -0,0 +1,139 @@ +:mod:`hmac` --- Keyed-Hashing for Message Authentication +======================================================== + +.. module:: hmac + :synopsis: Keyed-Hashing for Message Authentication (HMAC) implementation + +.. moduleauthor:: Gerhard Häring +.. sectionauthor:: Gerhard Häring + +**Source code:** :source:`Lib/hmac.py` + +-------------- + +This module implements the HMAC algorithm as described by :rfc:`2104`. + + +.. function:: new(key, msg=None, digestmod='') + + Return a new hmac object. *key* is a bytes or bytearray object giving the + secret key. If *msg* is present, the method call ``update(msg)`` is made. + *digestmod* is the digest name, digest constructor or module for the HMAC + object to use. It may be any name suitable to :func:`hashlib.new`. + Despite its argument position, it is required. + + .. versionchanged:: 3.4 + Parameter *key* can be a bytes or bytearray object. + Parameter *msg* can be of any type supported by :mod:`hashlib`. + Parameter *digestmod* can be the name of a hash algorithm. + + .. deprecated-removed:: 3.4 3.8 + MD5 as implicit default digest for *digestmod* is deprecated. + The digestmod parameter is now required. Pass it as a keyword + argument to avoid awkwardness when you do not have an initial msg. + + +.. function:: digest(key, msg, digest) + + Return digest of *msg* for given secret *key* and *digest*. The + function is equivalent to ``HMAC(key, msg, digest).digest()``, but + uses an optimized C or inline implementation, which is faster for messages + that fit into memory. The parameters *key*, *msg*, and *digest* have + the same meaning as in :func:`~hmac.new`. + + CPython implementation detail, the optimized C implementation is only used + when *digest* is a string and name of a digest algorithm, which is + supported by OpenSSL. + + .. versionadded:: 3.7 + + +An HMAC object has the following methods: + +.. method:: HMAC.update(msg) + + Update the hmac object with *msg*. Repeated calls are equivalent to a + single call with the concatenation of all the arguments: + ``m.update(a); m.update(b)`` is equivalent to ``m.update(a + b)``. + + .. versionchanged:: 3.4 + Parameter *msg* can be of any type supported by :mod:`hashlib`. + + +.. method:: HMAC.digest() + + Return the digest of the bytes passed to the :meth:`update` method so far. + This bytes object will be the same length as the *digest_size* of the digest + given to the constructor. It may contain non-ASCII bytes, including NUL + bytes. + + .. warning:: + + When comparing the output of :meth:`digest` to an externally-supplied + digest during a verification routine, it is recommended to use the + :func:`compare_digest` function instead of the ``==`` operator + to reduce the vulnerability to timing attacks. + + +.. method:: HMAC.hexdigest() + + Like :meth:`digest` except the digest is returned as a string twice the + length containing only hexadecimal digits. This may be used to exchange the + value safely in email or other non-binary environments. + + .. warning:: + + When comparing the output of :meth:`hexdigest` to an externally-supplied + digest during a verification routine, it is recommended to use the + :func:`compare_digest` function instead of the ``==`` operator + to reduce the vulnerability to timing attacks. + + +.. method:: HMAC.copy() + + Return a copy ("clone") of the hmac object. This can be used to efficiently + compute the digests of strings that share a common initial substring. + + +A hash object has the following attributes: + +.. attribute:: HMAC.digest_size + + The size of the resulting HMAC digest in bytes. + +.. attribute:: HMAC.block_size + + The internal block size of the hash algorithm in bytes. + + .. versionadded:: 3.4 + +.. attribute:: HMAC.name + + The canonical name of this HMAC, always lowercase, e.g. ``hmac-md5``. + + .. versionadded:: 3.4 + + +This module also provides the following helper function: + +.. function:: compare_digest(a, b) + + Return ``a == b``. This function uses an approach designed to prevent + timing analysis by avoiding content-based short circuiting behaviour, + making it appropriate for cryptography. *a* and *b* must both be of the + same type: either :class:`str` (ASCII only, as e.g. returned by + :meth:`HMAC.hexdigest`), or a :term:`bytes-like object`. + + .. note:: + + If *a* and *b* are of different lengths, or if an error occurs, + a timing attack could theoretically reveal information about the + types and lengths of *a* and *b*—but not their values. + + .. versionadded:: 3.3 + + +.. seealso:: + + Module :mod:`hashlib` + The Python module providing secure hash functions. diff --git a/cpython_2/environment/repo/Doc/library/html.entities.rst b/cpython_2/environment/repo/Doc/library/html.entities.rst new file mode 100644 index 0000000000000000000000000000000000000000..067e1b1e5adb3e29887a21bd7ffc7848db007e71 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/html.entities.rst @@ -0,0 +1,47 @@ +:mod:`html.entities` --- Definitions of HTML general entities +============================================================= + +.. module:: html.entities + :synopsis: Definitions of HTML general entities. + +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/html/entities.py` + +-------------- + +This module defines four dictionaries, :data:`html5`, +:data:`name2codepoint`, :data:`codepoint2name`, and :data:`entitydefs`. + + +.. data:: html5 + + A dictionary that maps HTML5 named character references [#]_ to the + equivalent Unicode character(s), e.g. ``html5['gt;'] == '>'``. + Note that the trailing semicolon is included in the name (e.g. ``'gt;'``), + however some of the names are accepted by the standard even without the + semicolon: in this case the name is present with and without the ``';'``. + See also :func:`html.unescape`. + + .. versionadded:: 3.3 + + +.. data:: entitydefs + + A dictionary mapping XHTML 1.0 entity definitions to their replacement text in + ISO Latin-1. + + +.. data:: name2codepoint + + A dictionary that maps HTML entity names to the Unicode code points. + + +.. data:: codepoint2name + + A dictionary that maps Unicode code points to HTML entity names. + + +.. rubric:: Footnotes + +.. [#] See https://www.w3.org/TR/html5/syntax.html#named-character-references diff --git a/cpython_2/environment/repo/Doc/library/html.parser.rst b/cpython_2/environment/repo/Doc/library/html.parser.rst new file mode 100644 index 0000000000000000000000000000000000000000..ac844a683bf7ac1b9cc9bdf873943647c8a3ee6d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/html.parser.rst @@ -0,0 +1,340 @@ +:mod:`html.parser` --- Simple HTML and XHTML parser +=================================================== + +.. module:: html.parser + :synopsis: A simple parser that can handle HTML and XHTML. + +**Source code:** :source:`Lib/html/parser.py` + +.. index:: + single: HTML + single: XHTML + +-------------- + +This module defines a class :class:`HTMLParser` which serves as the basis for +parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML. + +.. class:: HTMLParser(*, convert_charrefs=True) + + Create a parser instance able to parse invalid markup. + + If *convert_charrefs* is ``True`` (the default), all character + references (except the ones in ``script``/``style`` elements) are + automatically converted to the corresponding Unicode characters. + + An :class:`.HTMLParser` instance is fed HTML data and calls handler methods + when start tags, end tags, text, comments, and other markup elements are + encountered. The user should subclass :class:`.HTMLParser` and override its + methods to implement the desired behavior. + + This parser does not check that end tags match start tags or call the end-tag + handler for elements which are closed implicitly by closing an outer element. + + .. versionchanged:: 3.4 + *convert_charrefs* keyword argument added. + + .. versionchanged:: 3.5 + The default value for argument *convert_charrefs* is now ``True``. + + +Example HTML Parser Application +------------------------------- + +As a basic example, below is a simple HTML parser that uses the +:class:`HTMLParser` class to print out start tags, end tags, and data +as they are encountered:: + + from html.parser import HTMLParser + + class MyHTMLParser(HTMLParser): + def handle_starttag(self, tag, attrs): + print("Encountered a start tag:", tag) + + def handle_endtag(self, tag): + print("Encountered an end tag :", tag) + + def handle_data(self, data): + print("Encountered some data :", data) + + parser = MyHTMLParser() + parser.feed('Test' + '

Parse me!

') + +The output will then be: + +.. code-block:: none + + Encountered a start tag: html + Encountered a start tag: head + Encountered a start tag: title + Encountered some data : Test + Encountered an end tag : title + Encountered an end tag : head + Encountered a start tag: body + Encountered a start tag: h1 + Encountered some data : Parse me! + Encountered an end tag : h1 + Encountered an end tag : body + Encountered an end tag : html + + +:class:`.HTMLParser` Methods +---------------------------- + +:class:`HTMLParser` instances have the following methods: + + +.. method:: HTMLParser.feed(data) + + Feed some text to the parser. It is processed insofar as it consists of + complete elements; incomplete data is buffered until more data is fed or + :meth:`close` is called. *data* must be :class:`str`. + + +.. method:: HTMLParser.close() + + Force processing of all buffered data as if it were followed by an end-of-file + mark. This method may be redefined by a derived class to define additional + processing at the end of the input, but the redefined version should always call + the :class:`HTMLParser` base class method :meth:`close`. + + +.. method:: HTMLParser.reset() + + Reset the instance. Loses all unprocessed data. This is called implicitly at + instantiation time. + + +.. method:: HTMLParser.getpos() + + Return current line number and offset. + + +.. method:: HTMLParser.get_starttag_text() + + Return the text of the most recently opened start tag. This should not normally + be needed for structured processing, but may be useful in dealing with HTML "as + deployed" or for re-generating input with minimal changes (whitespace between + attributes can be preserved, etc.). + + +The following methods are called when data or markup elements are encountered +and they are meant to be overridden in a subclass. The base class +implementations do nothing (except for :meth:`~HTMLParser.handle_startendtag`): + + +.. method:: HTMLParser.handle_starttag(tag, attrs) + + This method is called to handle the start of a tag (e.g. ``
``). + + The *tag* argument is the name of the tag converted to lower case. The *attrs* + argument is a list of ``(name, value)`` pairs containing the attributes found + inside the tag's ``<>`` brackets. The *name* will be translated to lower case, + and quotes in the *value* have been removed, and character and entity references + have been replaced. + + For instance, for the tag ````, this method + would be called as ``handle_starttag('a', [('href', 'https://www.cwi.nl/')])``. + + All entity references from :mod:`html.entities` are replaced in the attribute + values. + + +.. method:: HTMLParser.handle_endtag(tag) + + This method is called to handle the end tag of an element (e.g. ``
``). + + The *tag* argument is the name of the tag converted to lower case. + + +.. method:: HTMLParser.handle_startendtag(tag, attrs) + + Similar to :meth:`handle_starttag`, but called when the parser encounters an + XHTML-style empty tag (````). This method may be overridden by + subclasses which require this particular lexical information; the default + implementation simply calls :meth:`handle_starttag` and :meth:`handle_endtag`. + + +.. method:: HTMLParser.handle_data(data) + + This method is called to process arbitrary data (e.g. text nodes and the + content of ```` and ````). + + +.. method:: HTMLParser.handle_entityref(name) + + This method is called to process a named character reference of the form + ``&name;`` (e.g. ``>``), where *name* is a general entity reference + (e.g. ``'gt'``). This method is never called if *convert_charrefs* is + ``True``. + + +.. method:: HTMLParser.handle_charref(name) + + This method is called to process decimal and hexadecimal numeric character + references of the form ``&#NNN;`` and ``&#xNNN;``. For example, the decimal + equivalent for ``>`` is ``>``, whereas the hexadecimal is ``>``; + in this case the method will receive ``'62'`` or ``'x3E'``. This method + is never called if *convert_charrefs* is ``True``. + + +.. method:: HTMLParser.handle_comment(data) + + This method is called when a comment is encountered (e.g. ````). + + For example, the comment ```` will cause this method to be + called with the argument ``' comment '``. + + The content of Internet Explorer conditional comments (condcoms) will also be + sent to this method, so, for ````, + this method will receive ``'[if IE 9]>IE9-specific content``). + + The *decl* parameter will be the entire contents of the declaration inside + the ```` markup (e.g. ``'DOCTYPE html'``). + + +.. method:: HTMLParser.handle_pi(data) + + Method called when a processing instruction is encountered. The *data* + parameter will contain the entire processing instruction. For example, for the + processing instruction ````, this method would be called as + ``handle_pi("proc color='red'")``. It is intended to be overridden by a derived + class; the base class implementation does nothing. + + .. note:: + + The :class:`HTMLParser` class uses the SGML syntactic rules for processing + instructions. An XHTML processing instruction using the trailing ``'?'`` will + cause the ``'?'`` to be included in *data*. + + +.. method:: HTMLParser.unknown_decl(data) + + This method is called when an unrecognized declaration is read by the parser. + + The *data* parameter will be the entire contents of the declaration inside + the ```` markup. It is sometimes useful to be overridden by a + derived class. The base class implementation does nothing. + + +.. _htmlparser-examples: + +Examples +-------- + +The following class implements a parser that will be used to illustrate more +examples:: + + from html.parser import HTMLParser + from html.entities import name2codepoint + + class MyHTMLParser(HTMLParser): + def handle_starttag(self, tag, attrs): + print("Start tag:", tag) + for attr in attrs: + print(" attr:", attr) + + def handle_endtag(self, tag): + print("End tag :", tag) + + def handle_data(self, data): + print("Data :", data) + + def handle_comment(self, data): + print("Comment :", data) + + def handle_entityref(self, name): + c = chr(name2codepoint[name]) + print("Named ent:", c) + + def handle_charref(self, name): + if name.startswith('x'): + c = chr(int(name[1:], 16)) + else: + c = chr(int(name)) + print("Num ent :", c) + + def handle_decl(self, data): + print("Decl :", data) + + parser = MyHTMLParser() + +Parsing a doctype:: + + >>> parser.feed('') + Decl : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" + +Parsing an element with a few attributes and a title:: + + >>> parser.feed('The Python logo') + Start tag: img + attr: ('src', 'python-logo.png') + attr: ('alt', 'The Python logo') + >>> + >>> parser.feed('

Python

') + Start tag: h1 + Data : Python + End tag : h1 + +The content of ``script`` and ``style`` elements is returned as is, without +further parsing:: + + >>> parser.feed('') + Start tag: style + attr: ('type', 'text/css') + Data : #python { color: green } + End tag : style + + >>> parser.feed('') + Start tag: script + attr: ('type', 'text/javascript') + Data : alert("hello!"); + End tag : script + +Parsing comments:: + + >>> parser.feed('' + ... '') + Comment : a comment + Comment : [if IE 9]>IE-specific content'``):: + + >>> parser.feed('>>>') + Named ent: > + Num ent : > + Num ent : > + +Feeding incomplete chunks to :meth:`~HTMLParser.feed` works, but +:meth:`~HTMLParser.handle_data` might be called more than once +(unless *convert_charrefs* is set to ``True``):: + + >>> for chunk in ['buff', 'ered ', 'text']: + ... parser.feed(chunk) + ... + Start tag: span + Data : buff + Data : ered + Data : text + End tag : span + +Parsing invalid HTML (e.g. unquoted attributes) also works:: + + >>> parser.feed('

tag soup

') + Start tag: p + Start tag: a + attr: ('class', 'link') + attr: ('href', '#main') + Data : tag soup + End tag : p + End tag : a diff --git a/cpython_2/environment/repo/Doc/library/html.rst b/cpython_2/environment/repo/Doc/library/html.rst new file mode 100644 index 0000000000000000000000000000000000000000..c2b01e14ea755569e1c78743e2b3fe21f5ba8272 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/html.rst @@ -0,0 +1,39 @@ +:mod:`html` --- HyperText Markup Language support +================================================= + +.. module:: html + :synopsis: Helpers for manipulating HTML. + +**Source code:** :source:`Lib/html/__init__.py` + +-------------- + +This module defines utilities to manipulate HTML. + +.. function:: escape(s, quote=True) + + Convert the characters ``&``, ``<`` and ``>`` in string *s* to HTML-safe + sequences. Use this if you need to display text that might contain such + characters in HTML. If the optional flag *quote* is true, the characters + (``"``) and (``'``) are also translated; this helps for inclusion in an HTML + attribute value delimited by quotes, as in ````. + + .. versionadded:: 3.2 + + +.. function:: unescape(s) + + Convert all named and numeric character references (e.g. ``>``, + ``>``, ``>``) in the string *s* to the corresponding Unicode + characters. This function uses the rules defined by the HTML 5 standard + for both valid and invalid character references, and the :data:`list of + HTML 5 named character references `. + + .. versionadded:: 3.4 + +-------------- + +Submodules in the ``html`` package are: + +* :mod:`html.parser` -- HTML/XHTML parser with lenient parsing mode +* :mod:`html.entities` -- HTML entity definitions diff --git a/cpython_2/environment/repo/Doc/library/http.client.rst b/cpython_2/environment/repo/Doc/library/http.client.rst new file mode 100644 index 0000000000000000000000000000000000000000..35997db2a9d27d29ac61e7f5ec78614c5bcb13fd --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/http.client.rst @@ -0,0 +1,613 @@ +:mod:`http.client` --- HTTP protocol client +=========================================== + +.. module:: http.client + :synopsis: HTTP and HTTPS protocol client (requires sockets). + +**Source code:** :source:`Lib/http/client.py` + +.. index:: + pair: HTTP; protocol + single: HTTP; http.client (standard module) + +.. index:: module: urllib.request + +-------------- + +This module defines classes which implement the client side of the HTTP and +HTTPS protocols. It is normally not used directly --- the module +:mod:`urllib.request` uses it to handle URLs that use HTTP and HTTPS. + +.. seealso:: + + The `Requests package `_ + is recommended for a higher-level HTTP client interface. + +.. note:: + + HTTPS support is only available if Python was compiled with SSL support + (through the :mod:`ssl` module). + +The module provides the following classes: + + +.. class:: HTTPConnection(host, port=None[, timeout], source_address=None, \ + blocksize=8192) + + An :class:`HTTPConnection` instance represents one transaction with an HTTP + server. It should be instantiated passing it a host and optional port + number. If no port number is passed, the port is extracted from the host + string if it has the form ``host:port``, else the default HTTP port (80) is + used. If the optional *timeout* parameter is given, blocking + operations (like connection attempts) will timeout after that many seconds + (if it is not given, the global default timeout setting is used). + The optional *source_address* parameter may be a tuple of a (host, port) + to use as the source address the HTTP connection is made from. + The optional *blocksize* parameter sets the buffer size in bytes for + sending a file-like message body. + + For example, the following calls all create instances that connect to the server + at the same host and port:: + + >>> h1 = http.client.HTTPConnection('www.python.org') + >>> h2 = http.client.HTTPConnection('www.python.org:80') + >>> h3 = http.client.HTTPConnection('www.python.org', 80) + >>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10) + + .. versionchanged:: 3.2 + *source_address* was added. + + .. versionchanged:: 3.4 + The *strict* parameter was removed. HTTP 0.9-style "Simple Responses" are + not longer supported. + + .. versionchanged:: 3.7 + *blocksize* parameter was added. + + +.. class:: HTTPSConnection(host, port=None, key_file=None, \ + cert_file=None[, timeout], \ + source_address=None, *, context=None, \ + check_hostname=None, blocksize=8192) + + A subclass of :class:`HTTPConnection` that uses SSL for communication with + secure servers. Default port is ``443``. If *context* is specified, it + must be a :class:`ssl.SSLContext` instance describing the various SSL + options. + + Please read :ref:`ssl-security` for more information on best practices. + + .. versionchanged:: 3.2 + *source_address*, *context* and *check_hostname* were added. + + .. versionchanged:: 3.2 + This class now supports HTTPS virtual hosts if possible (that is, + if :data:`ssl.HAS_SNI` is true). + + .. versionchanged:: 3.4 + The *strict* parameter was removed. HTTP 0.9-style "Simple Responses" are + no longer supported. + + .. versionchanged:: 3.4.3 + This class now performs all the necessary certificate and hostname checks + by default. To revert to the previous, unverified, behavior + :func:`ssl._create_unverified_context` can be passed to the *context* + parameter. + + .. versionchanged:: 3.8 + This class now enables TLS 1.3 + :attr:`ssl.SSLContext.post_handshake_auth` for the default *context* or + when *cert_file* is passed with a custom *context*. + + .. deprecated:: 3.6 + + *key_file* and *cert_file* are deprecated in favor of *context*. + Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let + :func:`ssl.create_default_context` select the system's trusted CA + certificates for you. + + The *check_hostname* parameter is also deprecated; the + :attr:`ssl.SSLContext.check_hostname` attribute of *context* should + be used instead. + + +.. class:: HTTPResponse(sock, debuglevel=0, method=None, url=None) + + Class whose instances are returned upon successful connection. Not + instantiated directly by user. + + .. versionchanged:: 3.4 + The *strict* parameter was removed. HTTP 0.9 style "Simple Responses" are + no longer supported. + +This module provides the following function: + +.. function:: parse_headers(fp) + + Parse the headers from a file pointer *fp* representing a HTTP + request/response. The file has to be a :class:`BufferedIOBase` reader + (i.e. not text) and must provide a valid :rfc:`2822` style header. + + This function returns an instance of :class:`http.client.HTTPMessage` + that holds the header fields, but no payload + (the same as :attr:`HTTPResponse.msg` + and :attr:`http.server.BaseHTTPRequestHandler.headers`). + After returning, the file pointer *fp* is ready to read the HTTP body. + + .. note:: + :meth:`parse_headers` does not parse the start-line of a HTTP message; + it only parses the ``Name: value`` lines. The file has to be ready to + read these field lines, so the first line should already be consumed + before calling the function. + +The following exceptions are raised as appropriate: + + +.. exception:: HTTPException + + The base class of the other exceptions in this module. It is a subclass of + :exc:`Exception`. + + +.. exception:: NotConnected + + A subclass of :exc:`HTTPException`. + + +.. exception:: InvalidURL + + A subclass of :exc:`HTTPException`, raised if a port is given and is either + non-numeric or empty. + + +.. exception:: UnknownProtocol + + A subclass of :exc:`HTTPException`. + + +.. exception:: UnknownTransferEncoding + + A subclass of :exc:`HTTPException`. + + +.. exception:: UnimplementedFileMode + + A subclass of :exc:`HTTPException`. + + +.. exception:: IncompleteRead + + A subclass of :exc:`HTTPException`. + + +.. exception:: ImproperConnectionState + + A subclass of :exc:`HTTPException`. + + +.. exception:: CannotSendRequest + + A subclass of :exc:`ImproperConnectionState`. + + +.. exception:: CannotSendHeader + + A subclass of :exc:`ImproperConnectionState`. + + +.. exception:: ResponseNotReady + + A subclass of :exc:`ImproperConnectionState`. + + +.. exception:: BadStatusLine + + A subclass of :exc:`HTTPException`. Raised if a server responds with a HTTP + status code that we don't understand. + + +.. exception:: LineTooLong + + A subclass of :exc:`HTTPException`. Raised if an excessively long line + is received in the HTTP protocol from the server. + + +.. exception:: RemoteDisconnected + + A subclass of :exc:`ConnectionResetError` and :exc:`BadStatusLine`. Raised + by :meth:`HTTPConnection.getresponse` when the attempt to read the response + results in no data read from the connection, indicating that the remote end + has closed the connection. + + .. versionadded:: 3.5 + Previously, :exc:`BadStatusLine`\ ``('')`` was raised. + + +The constants defined in this module are: + +.. data:: HTTP_PORT + + The default port for the HTTP protocol (always ``80``). + +.. data:: HTTPS_PORT + + The default port for the HTTPS protocol (always ``443``). + +.. data:: responses + + This dictionary maps the HTTP 1.1 status codes to the W3C names. + + Example: ``http.client.responses[http.client.NOT_FOUND]`` is ``'Not Found'``. + +See :ref:`http-status-codes` for a list of HTTP status codes that are +available in this module as constants. + + +.. _httpconnection-objects: + +HTTPConnection Objects +---------------------- + +:class:`HTTPConnection` instances have the following methods: + + +.. method:: HTTPConnection.request(method, url, body=None, headers={}, *, \ + encode_chunked=False) + + This will send a request to the server using the HTTP request + method *method* and the selector *url*. + + If *body* is specified, the specified data is sent after the headers are + finished. It may be a :class:`str`, a :term:`bytes-like object`, an + open :term:`file object`, or an iterable of :class:`bytes`. If *body* + is a string, it is encoded as ISO-8859-1, the default for HTTP. If it + is a bytes-like object, the bytes are sent as is. If it is a :term:`file + object`, the contents of the file is sent; this file object should + support at least the ``read()`` method. If the file object is an + instance of :class:`io.TextIOBase`, the data returned by the ``read()`` + method will be encoded as ISO-8859-1, otherwise the data returned by + ``read()`` is sent as is. If *body* is an iterable, the elements of the + iterable are sent as is until the iterable is exhausted. + + The *headers* argument should be a mapping of extra HTTP headers to send + with the request. + + If *headers* contains neither Content-Length nor Transfer-Encoding, + but there is a request body, one of those + header fields will be added automatically. If + *body* is ``None``, the Content-Length header is set to ``0`` for + methods that expect a body (``PUT``, ``POST``, and ``PATCH``). If + *body* is a string or a bytes-like object that is not also a + :term:`file `, the Content-Length header is + set to its length. Any other type of *body* (files + and iterables in general) will be chunk-encoded, and the + Transfer-Encoding header will automatically be set instead of + Content-Length. + + The *encode_chunked* argument is only relevant if Transfer-Encoding is + specified in *headers*. If *encode_chunked* is ``False``, the + HTTPConnection object assumes that all encoding is handled by the + calling code. If it is ``True``, the body will be chunk-encoded. + + .. note:: + Chunked transfer encoding has been added to the HTTP protocol + version 1.1. Unless the HTTP server is known to handle HTTP 1.1, + the caller must either specify the Content-Length, or must pass a + :class:`str` or bytes-like object that is not also a file as the + body representation. + + .. versionadded:: 3.2 + *body* can now be an iterable. + + .. versionchanged:: 3.6 + If neither Content-Length nor Transfer-Encoding are set in + *headers*, file and iterable *body* objects are now chunk-encoded. + The *encode_chunked* argument was added. + No attempt is made to determine the Content-Length for file + objects. + +.. method:: HTTPConnection.getresponse() + + Should be called after a request is sent to get the response from the server. + Returns an :class:`HTTPResponse` instance. + + .. note:: + + Note that you must have read the whole response before you can send a new + request to the server. + + .. versionchanged:: 3.5 + If a :exc:`ConnectionError` or subclass is raised, the + :class:`HTTPConnection` object will be ready to reconnect when + a new request is sent. + + +.. method:: HTTPConnection.set_debuglevel(level) + + Set the debugging level. The default debug level is ``0``, meaning no + debugging output is printed. Any value greater than ``0`` will cause all + currently defined debug output to be printed to stdout. The ``debuglevel`` + is passed to any new :class:`HTTPResponse` objects that are created. + + .. versionadded:: 3.1 + + +.. method:: HTTPConnection.set_tunnel(host, port=None, headers=None) + + Set the host and the port for HTTP Connect Tunnelling. This allows running + the connection through a proxy server. + + The host and port arguments specify the endpoint of the tunneled connection + (i.e. the address included in the CONNECT request, *not* the address of the + proxy server). + + The headers argument should be a mapping of extra HTTP headers to send with + the CONNECT request. + + For example, to tunnel through a HTTPS proxy server running locally on port + 8080, we would pass the address of the proxy to the :class:`HTTPSConnection` + constructor, and the address of the host that we eventually want to reach to + the :meth:`~HTTPConnection.set_tunnel` method:: + + >>> import http.client + >>> conn = http.client.HTTPSConnection("localhost", 8080) + >>> conn.set_tunnel("www.python.org") + >>> conn.request("HEAD","/index.html") + + .. versionadded:: 3.2 + + +.. method:: HTTPConnection.connect() + + Connect to the server specified when the object was created. By default, + this is called automatically when making a request if the client does not + already have a connection. + + +.. method:: HTTPConnection.close() + + Close the connection to the server. + + +.. attribute:: HTTPConnection.blocksize + + Buffer size in bytes for sending a file-like message body. + + .. versionadded:: 3.7 + + +As an alternative to using the :meth:`request` method described above, you can +also send your request step by step, by using the four functions below. + + +.. method:: HTTPConnection.putrequest(method, url, skip_host=False, \ + skip_accept_encoding=False) + + This should be the first call after the connection to the server has been + made. It sends a line to the server consisting of the *method* string, + the *url* string, and the HTTP version (``HTTP/1.1``). To disable automatic + sending of ``Host:`` or ``Accept-Encoding:`` headers (for example to accept + additional content encodings), specify *skip_host* or *skip_accept_encoding* + with non-False values. + + +.. method:: HTTPConnection.putheader(header, argument[, ...]) + + Send an :rfc:`822`\ -style header to the server. It sends a line to the server + consisting of the header, a colon and a space, and the first argument. If more + arguments are given, continuation lines are sent, each consisting of a tab and + an argument. + + +.. method:: HTTPConnection.endheaders(message_body=None, *, encode_chunked=False) + + Send a blank line to the server, signalling the end of the headers. The + optional *message_body* argument can be used to pass a message body + associated with the request. + + If *encode_chunked* is ``True``, the result of each iteration of + *message_body* will be chunk-encoded as specified in :rfc:`7230`, + Section 3.3.1. How the data is encoded is dependent on the type of + *message_body*. If *message_body* implements the :ref:`buffer interface + ` the encoding will result in a single chunk. + If *message_body* is a :class:`collections.abc.Iterable`, each iteration + of *message_body* will result in a chunk. If *message_body* is a + :term:`file object`, each call to ``.read()`` will result in a chunk. + The method automatically signals the end of the chunk-encoded data + immediately after *message_body*. + + .. note:: Due to the chunked encoding specification, empty chunks + yielded by an iterator body will be ignored by the chunk-encoder. + This is to avoid premature termination of the read of the request by + the target server due to malformed encoding. + + .. versionadded:: 3.6 + Chunked encoding support. The *encode_chunked* parameter was + added. + + +.. method:: HTTPConnection.send(data) + + Send data to the server. This should be used directly only after the + :meth:`endheaders` method has been called and before :meth:`getresponse` is + called. + + +.. _httpresponse-objects: + +HTTPResponse Objects +-------------------- + +An :class:`HTTPResponse` instance wraps the HTTP response from the +server. It provides access to the request headers and the entity +body. The response is an iterable object and can be used in a with +statement. + +.. versionchanged:: 3.5 + The :class:`io.BufferedIOBase` interface is now implemented and + all of its reader operations are supported. + + +.. method:: HTTPResponse.read([amt]) + + Reads and returns the response body, or up to the next *amt* bytes. + +.. method:: HTTPResponse.readinto(b) + + Reads up to the next len(b) bytes of the response body into the buffer *b*. + Returns the number of bytes read. + + .. versionadded:: 3.3 + +.. method:: HTTPResponse.getheader(name, default=None) + + Return the value of the header *name*, or *default* if there is no header + matching *name*. If there is more than one header with the name *name*, + return all of the values joined by ', '. If 'default' is any iterable other + than a single string, its elements are similarly returned joined by commas. + +.. method:: HTTPResponse.getheaders() + + Return a list of (header, value) tuples. + +.. method:: HTTPResponse.fileno() + + Return the ``fileno`` of the underlying socket. + +.. attribute:: HTTPResponse.msg + + A :class:`http.client.HTTPMessage` instance containing the response + headers. :class:`http.client.HTTPMessage` is a subclass of + :class:`email.message.Message`. + +.. attribute:: HTTPResponse.version + + HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. + +.. attribute:: HTTPResponse.url + + URL of the resource retrieved, commonly used to determine if a redirect was followed. + +.. attribute:: HTTPResponse.headers + + Headers of the response in the form of an :class:`email.message.EmailMessage` instance. + +.. attribute:: HTTPResponse.status + + Status code returned by server. + +.. attribute:: HTTPResponse.reason + + Reason phrase returned by server. + +.. attribute:: HTTPResponse.debuglevel + + A debugging hook. If :attr:`debuglevel` is greater than zero, messages + will be printed to stdout as the response is read and parsed. + +.. attribute:: HTTPResponse.closed + + Is ``True`` if the stream is closed. + +.. method:: HTTPResponse.geturl() + + .. deprecated:: 3.9 + Deprecated in favor of :attr:`~HTTPResponse.url`. + +.. method:: HTTPResponse.info() + + .. deprecated:: 3.9 + Deprecated in favor of :attr:`~HTTPResponse.headers`. + +.. method:: HTTPResponse.getstatus() + + .. deprecated:: 3.9 + Deprecated in favor of :attr:`~HTTPResponse.status`. + +Examples +-------- + +Here is an example session that uses the ``GET`` method:: + + >>> import http.client + >>> conn = http.client.HTTPSConnection("www.python.org") + >>> conn.request("GET", "/") + >>> r1 = conn.getresponse() + >>> print(r1.status, r1.reason) + 200 OK + >>> data1 = r1.read() # This will return entire content. + >>> # The following example demonstrates reading data in chunks. + >>> conn.request("GET", "/") + >>> r1 = conn.getresponse() + >>> while chunk := r1.read(200): + ... print(repr(chunk)) + b'\n 10 11 12 13 14 ...`` +:func:`cycle` p p0, p1, ... plast, p0, p1, ... ``cycle('ABCD') --> A B C D A B C D ...`` +:func:`repeat` elem [,n] elem, elem, elem, ... endlessly or up to n times ``repeat(10, 3) --> 10 10 10`` +================== ================= ================================================= ========================================= + +**Iterators terminating on the shortest input sequence:** + +============================ ============================ ================================================= ============================================================= +Iterator Arguments Results Example +============================ ============================ ================================================= ============================================================= +:func:`accumulate` p [,func] p0, p0+p1, p0+p1+p2, ... ``accumulate([1,2,3,4,5]) --> 1 3 6 10 15`` +:func:`chain` p, q, ... p0, p1, ... plast, q0, q1, ... ``chain('ABC', 'DEF') --> A B C D E F`` +:func:`chain.from_iterable` iterable p0, p1, ... plast, q0, q1, ... ``chain.from_iterable(['ABC', 'DEF']) --> A B C D E F`` +:func:`compress` data, selectors (d[0] if s[0]), (d[1] if s[1]), ... ``compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F`` +:func:`dropwhile` pred, seq seq[n], seq[n+1], starting when pred fails ``dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1`` +:func:`filterfalse` pred, seq elements of seq where pred(elem) is false ``filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8`` +:func:`groupby` iterable[, key] sub-iterators grouped by value of key(v) +:func:`islice` seq, [start,] stop [, step] elements from seq[start:stop:step] ``islice('ABCDEFG', 2, None) --> C D E F G`` +:func:`starmap` func, seq func(\*seq[0]), func(\*seq[1]), ... ``starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000`` +:func:`takewhile` pred, seq seq[0], seq[1], until pred fails ``takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4`` +:func:`tee` it, n it1, it2, ... itn splits one iterator into n +:func:`zip_longest` p, q, ... (p[0], q[0]), (p[1], q[1]), ... ``zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-`` +============================ ============================ ================================================= ============================================================= + +**Combinatoric iterators:** + +============================================== ==================== ============================================================= +Iterator Arguments Results +============================================== ==================== ============================================================= +:func:`product` p, q, ... [repeat=1] cartesian product, equivalent to a nested for-loop +:func:`permutations` p[, r] r-length tuples, all possible orderings, no repeated elements +:func:`combinations` p, r r-length tuples, in sorted order, no repeated elements +:func:`combinations_with_replacement` p, r r-length tuples, in sorted order, with repeated elements +============================================== ==================== ============================================================= + +============================================== ============================================================= +Examples Results +============================================== ============================================================= +``product('ABCD', repeat=2)`` ``AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD`` +``permutations('ABCD', 2)`` ``AB AC AD BA BC BD CA CB CD DA DB DC`` +``combinations('ABCD', 2)`` ``AB AC AD BC BD CD`` +``combinations_with_replacement('ABCD', 2)`` ``AA AB AC AD BB BC BD CC CD DD`` +============================================== ============================================================= + + +.. _itertools-functions: + +Itertool functions +------------------ + +The following module functions all construct and return iterators. Some provide +streams of infinite length, so they should only be accessed by functions or +loops that truncate the stream. + +.. function:: accumulate(iterable[, func, *, initial=None]) + + Make an iterator that returns accumulated sums, or accumulated + results of other binary functions (specified via the optional + *func* argument). + + If *func* is supplied, it should be a function + of two arguments. Elements of the input *iterable* may be any type + that can be accepted as arguments to *func*. (For example, with + the default operation of addition, elements may be any addable + type including :class:`~decimal.Decimal` or + :class:`~fractions.Fraction`.) + + Usually, the number of elements output matches the input iterable. + However, if the keyword argument *initial* is provided, the + accumulation leads off with the *initial* value so that the output + has one more element than the input iterable. + + Roughly equivalent to:: + + def accumulate(iterable, func=operator.add, *, initial=None): + 'Return running totals' + # accumulate([1,2,3,4,5]) --> 1 3 6 10 15 + # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115 + # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120 + it = iter(iterable) + total = initial + if initial is None: + try: + total = next(it) + except StopIteration: + return + yield total + for element in it: + total = func(total, element) + yield total + + There are a number of uses for the *func* argument. It can be set to + :func:`min` for a running minimum, :func:`max` for a running maximum, or + :func:`operator.mul` for a running product. Amortization tables can be + built by accumulating interest and applying payments. First-order + `recurrence relations `_ + can be modeled by supplying the initial value in the iterable and using only + the accumulated total in *func* argument:: + + >>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8] + >>> list(accumulate(data, operator.mul)) # running product + [3, 12, 72, 144, 144, 1296, 0, 0, 0, 0] + >>> list(accumulate(data, max)) # running maximum + [3, 4, 6, 6, 6, 9, 9, 9, 9, 9] + + # Amortize a 5% loan of 1000 with 4 annual payments of 90 + >>> cashflows = [1000, -90, -90, -90, -90] + >>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt)) + [1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001] + + # Chaotic recurrence relation https://en.wikipedia.org/wiki/Logistic_map + >>> logistic_map = lambda x, _: r * x * (1 - x) + >>> r = 3.8 + >>> x0 = 0.4 + >>> inputs = repeat(x0, 36) # only the initial value is used + >>> [format(x, '.2f') for x in accumulate(inputs, logistic_map)] + ['0.40', '0.91', '0.30', '0.81', '0.60', '0.92', '0.29', '0.79', '0.63', + '0.88', '0.39', '0.90', '0.33', '0.84', '0.52', '0.95', '0.18', '0.57', + '0.93', '0.25', '0.71', '0.79', '0.63', '0.88', '0.39', '0.91', '0.32', + '0.83', '0.54', '0.95', '0.20', '0.60', '0.91', '0.30', '0.80', '0.60'] + + See :func:`functools.reduce` for a similar function that returns only the + final accumulated value. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.3 + Added the optional *func* parameter. + + .. versionchanged:: 3.8 + Added the optional *initial* parameter. + +.. function:: chain(*iterables) + + Make an iterator that returns elements from the first iterable until it is + exhausted, then proceeds to the next iterable, until all of the iterables are + exhausted. Used for treating consecutive sequences as a single sequence. + Roughly equivalent to:: + + def chain(*iterables): + # chain('ABC', 'DEF') --> A B C D E F + for it in iterables: + for element in it: + yield element + + +.. classmethod:: chain.from_iterable(iterable) + + Alternate constructor for :func:`chain`. Gets chained inputs from a + single iterable argument that is evaluated lazily. Roughly equivalent to:: + + def from_iterable(iterables): + # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F + for it in iterables: + for element in it: + yield element + + +.. function:: combinations(iterable, r) + + Return *r* length subsequences of elements from the input *iterable*. + + Combinations are emitted in lexicographic sort order. So, if the + input *iterable* is sorted, the combination tuples will be produced + 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 + values in each combination. + + Roughly equivalent to:: + + def combinations(iterable, r): + # combinations('ABCD', 2) --> AB AC AD BC BD CD + # combinations(range(4), 3) --> 012 013 023 123 + pool = tuple(iterable) + n = len(pool) + if r > n: + return + indices = list(range(r)) + yield tuple(pool[i] for i in indices) + while True: + for i in reversed(range(r)): + if indices[i] != i + n - r: + break + else: + return + indices[i] += 1 + for j in range(i+1, r): + indices[j] = indices[j-1] + 1 + yield tuple(pool[i] for i in indices) + + The code for :func:`combinations` can be also expressed as a subsequence + of :func:`permutations` after filtering entries where the elements are not + in sorted order (according to their position in the input pool):: + + def combinations(iterable, r): + pool = tuple(iterable) + n = len(pool) + for indices in permutations(range(n), r): + if sorted(indices) == list(indices): + yield tuple(pool[i] for i in indices) + + The number of items returned is ``n! / r! / (n-r)!`` when ``0 <= r <= n`` + or zero when ``r > n``. + +.. function:: combinations_with_replacement(iterable, r) + + Return *r* length subsequences of elements from the input *iterable* + allowing individual elements to be repeated more than once. + + Combinations are emitted in lexicographic sort order. So, if the + input *iterable* is sorted, the combination tuples will be produced + in sorted order. + + Elements are treated as unique based on their position, not on their + value. So if the input elements are unique, the generated combinations + will also be unique. + + Roughly equivalent to:: + + def combinations_with_replacement(iterable, r): + # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC + pool = tuple(iterable) + n = len(pool) + if not n and r: + return + indices = [0] * r + yield tuple(pool[i] for i in indices) + while True: + for i in reversed(range(r)): + if indices[i] != n - 1: + break + else: + return + indices[i:] = [indices[i] + 1] * (r - i) + yield tuple(pool[i] for i in indices) + + The code for :func:`combinations_with_replacement` can be also expressed as + a subsequence of :func:`product` after filtering entries where the elements + are not in sorted order (according to their position in the input pool):: + + def combinations_with_replacement(iterable, r): + pool = tuple(iterable) + n = len(pool) + for indices in product(range(n), repeat=r): + if sorted(indices) == list(indices): + yield tuple(pool[i] for i in indices) + + The number of items returned is ``(n+r-1)! / r! / (n-1)!`` when ``n > 0``. + + .. versionadded:: 3.1 + + +.. function:: compress(data, selectors) + + Make an iterator that filters elements from *data* returning only those that + have a corresponding element in *selectors* that evaluates to ``True``. + Stops when either the *data* or *selectors* iterables has been exhausted. + Roughly equivalent to:: + + def compress(data, selectors): + # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F + return (d for d, s in zip(data, selectors) if s) + + .. versionadded:: 3.1 + + +.. function:: count(start=0, step=1) + + Make an iterator that returns evenly spaced values starting with number *start*. Often + used as an argument to :func:`map` to generate consecutive data points. + Also, used with :func:`zip` to add sequence numbers. Roughly equivalent to:: + + def count(start=0, step=1): + # count(10) --> 10 11 12 13 14 ... + # count(2.5, 0.5) -> 2.5 3.0 3.5 ... + n = start + while True: + yield n + n += step + + When counting with floating point numbers, better accuracy can sometimes be + achieved by substituting multiplicative code such as: ``(start + step * i + for i in count())``. + + .. versionchanged:: 3.1 + Added *step* argument and allowed non-integer arguments. + +.. function:: cycle(iterable) + + Make an iterator returning elements from the iterable and saving a copy of each. + When the iterable is exhausted, return elements from the saved copy. Repeats + indefinitely. Roughly equivalent to:: + + def cycle(iterable): + # cycle('ABCD') --> A B C D A B C D A B C D ... + saved = [] + for element in iterable: + yield element + saved.append(element) + while saved: + for element in saved: + yield element + + Note, this member of the toolkit may require significant auxiliary storage + (depending on the length of the iterable). + + +.. function:: dropwhile(predicate, iterable) + + Make an iterator that drops elements from the iterable as long as the predicate + is true; afterwards, returns every element. Note, the iterator does not produce + *any* output until the predicate first becomes false, so it may have a lengthy + start-up time. Roughly equivalent to:: + + def dropwhile(predicate, iterable): + # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1 + iterable = iter(iterable) + for x in iterable: + if not predicate(x): + yield x + break + for x in iterable: + yield x + +.. function:: filterfalse(predicate, iterable) + + Make an iterator that filters elements from iterable returning only those for + which the predicate is ``False``. If *predicate* is ``None``, return the items + that are false. Roughly equivalent to:: + + def filterfalse(predicate, iterable): + # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8 + if predicate is None: + predicate = bool + for x in iterable: + if not predicate(x): + yield x + + +.. function:: groupby(iterable, key=None) + + Make an iterator that returns consecutive keys and groups from the *iterable*. + The *key* is a function computing a key value for each element. If not + specified or is ``None``, *key* defaults to an identity function and returns + the element unchanged. Generally, the iterable needs to already be sorted on + the same key function. + + The operation of :func:`groupby` is similar to the ``uniq`` filter in Unix. It + generates a break or new group every time the value of the key function changes + (which is why it is usually necessary to have sorted the data using the same key + function). That behavior differs from SQL's GROUP BY which aggregates common + elements regardless of their input order. + + The returned group is itself an iterator that shares the underlying iterable + with :func:`groupby`. Because the source is shared, when the :func:`groupby` + object is advanced, the previous group is no longer visible. So, if that data + is needed later, it should be stored as a list:: + + groups = [] + uniquekeys = [] + data = sorted(data, key=keyfunc) + for k, g in groupby(data, keyfunc): + groups.append(list(g)) # Store group iterator as a list + uniquekeys.append(k) + + :func:`groupby` is roughly equivalent to:: + + class groupby: + # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B + # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D + def __init__(self, iterable, key=None): + if key is None: + key = lambda x: x + self.keyfunc = key + self.it = iter(iterable) + self.tgtkey = self.currkey = self.currvalue = object() + def __iter__(self): + return self + def __next__(self): + self.id = object() + while self.currkey == self.tgtkey: + self.currvalue = next(self.it) # Exit on StopIteration + self.currkey = self.keyfunc(self.currvalue) + self.tgtkey = self.currkey + return (self.currkey, self._grouper(self.tgtkey, self.id)) + def _grouper(self, tgtkey, id): + while self.id is id and self.currkey == tgtkey: + yield self.currvalue + try: + self.currvalue = next(self.it) + except StopIteration: + return + self.currkey = self.keyfunc(self.currvalue) + + +.. function:: islice(iterable, stop) + islice(iterable, start, stop[, step]) + + Make an iterator that returns selected elements from the iterable. If *start* is + non-zero, then elements from the iterable are skipped until start is reached. + Afterward, elements are returned consecutively unless *step* is set higher than + one which results in items being skipped. If *stop* is ``None``, then iteration + continues until the iterator is exhausted, if at all; otherwise, it stops at the + specified position. Unlike regular slicing, :func:`islice` does not support + negative values for *start*, *stop*, or *step*. Can be used to extract related + fields from data where the internal structure has been flattened (for example, a + multi-line report may list a name field on every third line). Roughly equivalent to:: + + def islice(iterable, *args): + # islice('ABCDEFG', 2) --> A B + # islice('ABCDEFG', 2, 4) --> C D + # islice('ABCDEFG', 2, None) --> C D E F G + # islice('ABCDEFG', 0, None, 2) --> A C E G + s = slice(*args) + start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1 + it = iter(range(start, stop, step)) + try: + nexti = next(it) + except StopIteration: + # Consume *iterable* up to the *start* position. + for i, element in zip(range(start), iterable): + pass + return + try: + for i, element in enumerate(iterable): + if i == nexti: + yield element + nexti = next(it) + except StopIteration: + # Consume to *stop*. + for i, element in zip(range(i + 1, stop), iterable): + pass + + If *start* is ``None``, then iteration starts at zero. If *step* is ``None``, + then the step defaults to one. + + +.. function:: permutations(iterable, r=None) + + 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 + are generated. + + Permutations are emitted in lexicographic sort order. So, if the + input *iterable* is sorted, the permutation tuples will be produced + 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 + values in each permutation. + + Roughly equivalent to:: + + def permutations(iterable, r=None): + # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC + # permutations(range(3)) --> 012 021 102 120 201 210 + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r + if r > n: + return + indices = list(range(n)) + cycles = list(range(n, n-r, -1)) + yield tuple(pool[i] for i in indices[:r]) + while n: + for i in reversed(range(r)): + cycles[i] -= 1 + if cycles[i] == 0: + indices[i:] = indices[i+1:] + indices[i:i+1] + cycles[i] = n - i + else: + j = cycles[i] + indices[i], indices[-j] = indices[-j], indices[i] + yield tuple(pool[i] for i in indices[:r]) + break + else: + return + + 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):: + + def permutations(iterable, r=None): + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r + for indices in product(range(n), repeat=r): + if len(set(indices)) == r: + yield tuple(pool[i] for i in indices) + + The number of items returned is ``n! / (n-r)!`` when ``0 <= r <= n`` + or zero when ``r > n``. + +.. function:: product(*iterables, repeat=1) + + Cartesian product of input iterables. + + Roughly equivalent to nested for-loops in a generator expression. For example, + ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``. + + The nested loops cycle like an odometer with the rightmost element advancing + on every iteration. This pattern creates a lexicographic ordering so that if + the input's iterables are sorted, the product tuples are emitted in sorted + order. + + To compute the product of an iterable with itself, specify the number of + repetitions with the optional *repeat* keyword argument. For example, + ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``. + + This function is roughly equivalent to the following code, except that the + actual implementation does not build up intermediate results in memory:: + + def product(*args, repeat=1): + # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy + # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 + pools = [tuple(pool) for pool in args] * repeat + result = [[]] + for pool in pools: + result = [x+[y] for x in result for y in pool] + for prod in result: + yield tuple(prod) + + +.. function:: repeat(object[, times]) + + Make an iterator that returns *object* over and over again. Runs indefinitely + unless the *times* argument is specified. Used as argument to :func:`map` for + invariant parameters to the called function. Also used with :func:`zip` to + create an invariant part of a tuple record. + + Roughly equivalent to:: + + def repeat(object, times=None): + # repeat(10, 3) --> 10 10 10 + if times is None: + while True: + yield object + else: + for i in range(times): + yield object + + A common use for *repeat* is to supply a stream of constant values to *map* + or *zip*:: + + >>> list(map(pow, range(10), repeat(2))) + [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + +.. function:: starmap(function, iterable) + + Make an iterator that computes the function using arguments obtained from + the iterable. Used instead of :func:`map` when argument parameters are already + grouped in tuples from a single iterable (the data has been "pre-zipped"). The + difference between :func:`map` and :func:`starmap` parallels the distinction + between ``function(a,b)`` and ``function(*c)``. Roughly equivalent to:: + + def starmap(function, iterable): + # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000 + for args in iterable: + yield function(*args) + + +.. function:: takewhile(predicate, iterable) + + Make an iterator that returns elements from the iterable as long as the + predicate is true. Roughly equivalent to:: + + def takewhile(predicate, iterable): + # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4 + for x in iterable: + if predicate(x): + yield x + else: + break + + +.. function:: tee(iterable, n=2) + + Return *n* independent iterators from a single iterable. + + The following Python code helps explain what *tee* does (although the actual + implementation is more complex and uses only a single underlying + :abbr:`FIFO (first-in, first-out)` queue). + + Roughly equivalent to:: + + def tee(iterable, n=2): + it = iter(iterable) + deques = [collections.deque() for i in range(n)] + def gen(mydeque): + while True: + if not mydeque: # when the local deque is empty + try: + newval = next(it) # fetch a new value and + except StopIteration: + return + for d in deques: # load it to all the deques + d.append(newval) + yield mydeque.popleft() + return tuple(gen(d) for d in deques) + + Once :func:`tee` has made a split, the original *iterable* should not be + used anywhere else; otherwise, the *iterable* could get advanced without + the tee objects being informed. + + ``tee`` iterators are not threadsafe. A :exc:`RuntimeError` may be + raised when using simultaneously iterators returned by the same :func:`tee` + call, even if the original *iterable* is threadsafe. + + This itertool may require significant auxiliary storage (depending on how + much temporary data needs to be stored). In general, if one iterator uses + most or all of the data before another iterator starts, it is faster to use + :func:`list` instead of :func:`tee`. + + +.. function:: zip_longest(*iterables, fillvalue=None) + + Make an iterator that aggregates elements from each of the iterables. If the + iterables are of uneven length, missing values are filled-in with *fillvalue*. + Iteration continues until the longest iterable is exhausted. Roughly equivalent to:: + + def zip_longest(*args, fillvalue=None): + # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- + iterators = [iter(it) for it in args] + num_active = len(iterators) + if not num_active: + return + while True: + values = [] + for i, it in enumerate(iterators): + try: + value = next(it) + except StopIteration: + num_active -= 1 + if not num_active: + return + iterators[i] = repeat(fillvalue) + value = fillvalue + values.append(value) + yield tuple(values) + + If one of the iterables is potentially infinite, then the :func:`zip_longest` + function should be wrapped with something that limits the number of calls + (for example :func:`islice` or :func:`takewhile`). If not specified, + *fillvalue* defaults to ``None``. + + +.. _itertools-recipes: + +Itertools Recipes +----------------- + +This section shows recipes for creating an extended toolset using the existing +itertools as building blocks. + +Substantially all of these recipes and many, many others can be installed from +the `more-itertools project `_ found +on the Python Package Index:: + + pip install more-itertools + +The extended tools offer the same high performance as the underlying toolset. +The superior memory performance is kept by processing elements one at a time +rather than bringing the whole iterable into memory all at once. Code volume is +kept small by linking the tools together in a functional style which helps +eliminate temporary variables. High speed is retained by preferring +"vectorized" building blocks over the use of for-loops and :term:`generator`\s +which incur interpreter overhead. + +.. testcode:: + + def take(n, iterable): + "Return first n items of the iterable as a list" + return list(islice(iterable, n)) + + def prepend(value, iterator): + "Prepend a single value in front of an iterator" + # prepend(1, [2, 3, 4]) -> 1 2 3 4 + return chain([value], iterator) + + def tabulate(function, start=0): + "Return function(0), function(1), ..." + return map(function, count(start)) + + def tail(n, iterable): + "Return an iterator over the last n items" + # tail(3, 'ABCDEFG') --> E F G + return iter(collections.deque(iterable, maxlen=n)) + + def consume(iterator, n=None): + "Advance the iterator n-steps ahead. If n is None, consume entirely." + # Use functions that consume iterators at C speed. + if n is None: + # feed the entire iterator into a zero-length deque + collections.deque(iterator, maxlen=0) + else: + # advance to the empty slice starting at position n + next(islice(iterator, n, n), None) + + def nth(iterable, n, default=None): + "Returns the nth item or a default value" + return next(islice(iterable, n, None), default) + + def all_equal(iterable): + "Returns True if all the elements are equal to each other" + g = groupby(iterable) + return next(g, True) and not next(g, False) + + def quantify(iterable, pred=bool): + "Count how many times the predicate is true" + return sum(map(pred, iterable)) + + def padnone(iterable): + """Returns the sequence elements and then returns None indefinitely. + + Useful for emulating the behavior of the built-in map() function. + """ + return chain(iterable, repeat(None)) + + def ncycles(iterable, n): + "Returns the sequence elements n times" + return chain.from_iterable(repeat(tuple(iterable), n)) + + def dotproduct(vec1, vec2): + return sum(map(operator.mul, vec1, vec2)) + + def flatten(list_of_lists): + "Flatten one level of nesting" + return chain.from_iterable(list_of_lists) + + def repeatfunc(func, times=None, *args): + """Repeat calls to func with specified arguments. + + Example: repeatfunc(random.random) + """ + if times is None: + return starmap(func, repeat(args)) + return starmap(func, repeat(args, times)) + + def pairwise(iterable): + "s -> (s0,s1), (s1,s2), (s2, s3), ..." + a, b = tee(iterable) + next(b, None) + return zip(a, b) + + def grouper(iterable, n, fillvalue=None): + "Collect data into fixed-length chunks or blocks" + # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" + args = [iter(iterable)] * n + return zip_longest(*args, fillvalue=fillvalue) + + def roundrobin(*iterables): + "roundrobin('ABC', 'D', 'EF') --> A D E B F C" + # Recipe credited to George Sakkis + num_active = len(iterables) + nexts = cycle(iter(it).__next__ for it in iterables) + while num_active: + try: + for next in nexts: + yield next() + except StopIteration: + # Remove the iterator we just exhausted from the cycle. + num_active -= 1 + nexts = cycle(islice(nexts, num_active)) + + def partition(pred, iterable): + 'Use a predicate to partition entries into false entries and true entries' + # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 + t1, t2 = tee(iterable) + return filterfalse(pred, t1), filter(pred, t2) + + def powerset(iterable): + "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" + s = list(iterable) + return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) + + 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 + seen = set() + seen_add = seen.add + if key is None: + for element in filterfalse(seen.__contains__, iterable): + seen_add(element) + yield element + else: + for element in iterable: + k = key(element) + if k not in seen: + seen_add(k) + yield element + + def unique_justseen(iterable, key=None): + "List unique elements, preserving order. Remember only the element just seen." + # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B + # unique_justseen('ABBCcAD', str.lower) --> A B C A D + return map(next, map(operator.itemgetter(1), groupby(iterable, key))) + + def iter_except(func, exception, first=None): + """ Call a function repeatedly until an exception is raised. + + Converts a call-until-exception interface to an iterator interface. + Like builtins.iter(func, sentinel) but uses an exception instead + of a sentinel to end the loop. + + Examples: + iter_except(functools.partial(heappop, h), IndexError) # priority queue iterator + iter_except(d.popitem, KeyError) # non-blocking dict iterator + iter_except(d.popleft, IndexError) # non-blocking deque iterator + iter_except(q.get_nowait, Queue.Empty) # loop over a producer Queue + iter_except(s.pop, KeyError) # non-blocking set iterator + + """ + try: + if first is not None: + yield first() # For database APIs needing an initial cast to db.first() + while True: + yield func() + except exception: + pass + + def first_true(iterable, default=False, pred=None): + """Returns the first true value in the iterable. + + If no true value is found, returns *default* + + If *pred* is not None, returns the first item + for which pred(item) is true. + + """ + # first_true([a,b,c], x) --> a or b or c or x + # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x + return next(filter(pred, iterable), default) + + def random_product(*args, repeat=1): + "Random selection from itertools.product(*args, **kwds)" + pools = [tuple(pool) for pool in args] * repeat + return tuple(random.choice(pool) for pool in pools) + + def random_permutation(iterable, r=None): + "Random selection from itertools.permutations(iterable, r)" + pool = tuple(iterable) + r = len(pool) if r is None else r + return tuple(random.sample(pool, r)) + + def random_combination(iterable, r): + "Random selection from itertools.combinations(iterable, r)" + pool = tuple(iterable) + n = len(pool) + indices = sorted(random.sample(range(n), r)) + return tuple(pool[i] for i in indices) + + def random_combination_with_replacement(iterable, r): + "Random selection from itertools.combinations_with_replacement(iterable, r)" + pool = tuple(iterable) + n = len(pool) + indices = sorted(random.randrange(n) for i in range(r)) + return tuple(pool[i] for i in indices) + + def nth_combination(iterable, r, index): + 'Equivalent to list(combinations(iterable, r))[index]' + pool = tuple(iterable) + n = len(pool) + if r < 0 or r > n: + raise ValueError + c = 1 + k = min(r, n-r) + for i in range(1, k+1): + c = c * (n - k + i) // i + if index < 0: + index += c + if index < 0 or index >= c: + raise IndexError + result = [] + while r: + c, n, r = c*r//n, n-1, r-1 + while index >= c: + index -= c + c, n = c*(n-r)//n, n-1 + result.append(pool[-1-n]) + return tuple(result) + diff --git a/cpython_2/environment/repo/Doc/library/json.rst b/cpython_2/environment/repo/Doc/library/json.rst new file mode 100644 index 0000000000000000000000000000000000000000..b923c8e1670529e19d2e32848d7e6d7a27179097 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/json.rst @@ -0,0 +1,763 @@ +:mod:`json` --- JSON encoder and decoder +======================================== + +.. module:: json + :synopsis: Encode and decode the JSON format. + +.. moduleauthor:: Bob Ippolito +.. sectionauthor:: Bob Ippolito + +**Source code:** :source:`Lib/json/__init__.py` + +-------------- + +`JSON (JavaScript Object Notation) `_, specified by +:rfc:`7159` (which obsoletes :rfc:`4627`) and by +`ECMA-404 `_, +is a lightweight data interchange format inspired by +`JavaScript `_ object literal syntax +(although it is not a strict subset of JavaScript [#rfc-errata]_ ). + +:mod:`json` exposes an API familiar to users of the standard library +: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]}]' + >>> print(json.dumps("\"foo\bar")) + "\"foo\bar" + >>> print(json.dumps('\u1234')) + "\u1234" + >>> print(json.dumps('\\')) + "\\" + >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)) + {"a": 0, "b": 0, "c": 0} + >>> from io import StringIO + >>> io = StringIO() + >>> json.dump(['streaming API'], io) + >>> io.getvalue() + '["streaming API"]' + +Compact encoding:: + + >>> import json + >>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':')) + '[1,2,3,{"4":5,"6":7}]' + +Pretty printing:: + + >>> import json + >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)) + { + "4": 5, + "6": 7 + } + +Decoding JSON:: + + >>> import json + >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') + ['foo', {'bar': ['baz', None, 1.0, 2]}] + >>> json.loads('"\\"foo\\bar"') + '"foo\x08ar' + >>> from io import StringIO + >>> io = StringIO('["streaming API"]') + >>> json.load(io) + ['streaming API'] + +Specializing JSON object decoding:: + + >>> import json + >>> def as_complex(dct): + ... if '__complex__' in dct: + ... return complex(dct['real'], dct['imag']) + ... return dct + ... + >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', + ... object_hook=as_complex) + (1+2j) + >>> import decimal + >>> json.loads('1.1', parse_float=decimal.Decimal) + Decimal('1.1') + +Extending :class:`JSONEncoder`:: + + >>> import json + >>> class ComplexEncoder(json.JSONEncoder): + ... def default(self, obj): + ... if isinstance(obj, complex): + ... return [obj.real, obj.imag] + ... # Let the base class default method raise the TypeError + ... return json.JSONEncoder.default(self, obj) + ... + >>> json.dumps(2 + 1j, cls=ComplexEncoder) + '[2.0, 1.0]' + >>> ComplexEncoder().encode(2 + 1j) + '[2.0, 1.0]' + >>> list(ComplexEncoder().iterencode(2 + 1j)) + ['[2.0', ', 1.0', ']'] + + +Using :mod:`json.tool` from the shell to validate and pretty-print: + +.. code-block:: shell-session + + $ echo '{"json":"obj"}' | python -m json.tool + { + "json": "obj" + } + $ echo '{1.2:3.4}' | python -m json.tool + Expecting property name enclosed in double quotes: line 1 column 2 (char 1) + +See :ref:`json-commandline` for detailed documentation. + +.. note:: + + JSON is a subset of `YAML `_ 1.2. The JSON produced by + this module's default settings (in particular, the default *separators* + value) is also a subset of YAML 1.0 and 1.1. This module can thus also be + used as a YAML serializer. + +.. note:: + + This module's encoders and decoders preserve input and output order by + default. Order is only lost if the underlying containers are unordered. + + Prior to Python 3.7, :class:`dict` was not guaranteed to be ordered, so + inputs and outputs were typically scrambled unless + :class:`collections.OrderedDict` was specifically requested. Starting + with Python 3.7, the regular :class:`dict` became order preserving, so + it is no longer necessary to specify :class:`collections.OrderedDict` for + JSON generation and parsing. + + +Basic Usage +----------- + +.. function:: dump(obj, fp, *, skipkeys=False, ensure_ascii=True, \ + check_circular=True, allow_nan=True, cls=None, \ + indent=None, separators=None, default=None, \ + sort_keys=False, **kw) + + Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting + :term:`file-like object`) using this :ref:`conversion table + `. + + If *skipkeys* is true (default: ``False``), then dict keys that are not + of a basic type (:class:`str`, :class:`int`, :class:`float`, :class:`bool`, + ``None``) will be skipped instead of raising a :exc:`TypeError`. + + The :mod:`json` module always produces :class:`str` objects, not + :class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str` + input. + + If *ensure_ascii* is true (the default), the output is guaranteed to + have all incoming non-ASCII characters escaped. If *ensure_ascii* is + false, these characters will be output as-is. + + If *check_circular* is false (default: ``True``), then the circular + reference check for container types will be skipped and a circular reference + will result in an :exc:`OverflowError` (or worse). + + If *allow_nan* is false (default: ``True``), then it will be a + :exc:`ValueError` to serialize out of range :class:`float` values (``nan``, + ``inf``, ``-inf``) in strict compliance of the JSON specification. + If *allow_nan* is true, their JavaScript equivalents (``NaN``, + ``Infinity``, ``-Infinity``) will be used. + + If *indent* is a non-negative integer or string, then JSON array elements and + object members will be pretty-printed with that indent level. An indent level + of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) + selects the most compact representation. Using a positive integer indent + indents that many spaces per level. If *indent* is a string (such as ``"\t"``), + that string is used to indent each level. + + .. versionchanged:: 3.2 + Allow strings for *indent* in addition to integers. + + If specified, *separators* should be an ``(item_separator, key_separator)`` + tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and + ``(',', ': ')`` otherwise. To get the most compact JSON representation, + you should specify ``(',', ':')`` to eliminate whitespace. + + .. versionchanged:: 3.4 + Use ``(',', ': ')`` as default if *indent* is not ``None``. + + If specified, *default* should be a function that gets called for objects that + can't otherwise be serialized. It should return a JSON encodable version of + the object or raise a :exc:`TypeError`. If not specified, :exc:`TypeError` + is raised. + + If *sort_keys* is true (default: ``False``), then the output of + dictionaries will be sorted by key. + + To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the + :meth:`default` method to serialize additional types), specify it with the + *cls* kwarg; otherwise :class:`JSONEncoder` is used. + + .. versionchanged:: 3.6 + All optional parameters are now :ref:`keyword-only `. + + .. note:: + + Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol, + so trying to serialize multiple objects with repeated calls to + :func:`dump` using the same *fp* will result in an invalid JSON file. + +.. function:: dumps(obj, *, skipkeys=False, ensure_ascii=True, \ + check_circular=True, allow_nan=True, cls=None, \ + indent=None, separators=None, default=None, \ + sort_keys=False, **kw) + + Serialize *obj* to a JSON formatted :class:`str` using this :ref:`conversion + table `. The arguments have the same meaning as in + :func:`dump`. + + .. note:: + + Keys in key/value pairs of JSON are always of the type :class:`str`. When + a dictionary is converted into JSON, all the keys of the dictionary are + coerced to strings. As a result of this, if a dictionary is converted + into JSON and then back into a dictionary, the dictionary may not equal + the original one. That is, ``loads(dumps(x)) != x`` if x has non-string + keys. + +.. function:: load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) + + Deserialize *fp* (a ``.read()``-supporting :term:`text file` or + :term:`binary file` containing a JSON document) to a Python object using + this :ref:`conversion table `. + + *object_hook* is an optional function that will be called with the result of + any object literal decoded (a :class:`dict`). The return value of + *object_hook* will be used instead of the :class:`dict`. This feature can be used + to implement custom decoders (e.g. `JSON-RPC `_ + class hinting). + + *object_pairs_hook* is an optional function that will be called with the + result of any object literal decoded with an ordered list of pairs. The + return value of *object_pairs_hook* will be used instead of the + :class:`dict`. This feature can be used to implement custom decoders. + If *object_hook* is also defined, the *object_pairs_hook* takes priority. + + .. versionchanged:: 3.1 + Added support for *object_pairs_hook*. + + *parse_float*, if specified, will be called with the string of every JSON + float to be decoded. By default, this is equivalent to ``float(num_str)``. + This can be used to use another datatype or parser for JSON floats + (e.g. :class:`decimal.Decimal`). + + *parse_int*, if specified, will be called with the string of every JSON int + to be decoded. By default, this is equivalent to ``int(num_str)``. This can + be used to use another datatype or parser for JSON integers + (e.g. :class:`float`). + + *parse_constant*, if specified, will be called with one of the following + strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. + This can be used to raise an exception if invalid JSON numbers + are encountered. + + .. versionchanged:: 3.1 + *parse_constant* doesn't get called on 'null', 'true', 'false' anymore. + + To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls`` + kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments + will be passed to the constructor of the class. + + If the data being deserialized is not a valid JSON document, a + :exc:`JSONDecodeError` will be raised. + + .. versionchanged:: 3.6 + All optional parameters are now :ref:`keyword-only `. + + .. versionchanged:: 3.6 + *fp* can now be a :term:`binary file`. The input encoding should be + UTF-8, UTF-16 or UTF-32. + +.. function:: loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) + + Deserialize *s* (a :class:`str`, :class:`bytes` or :class:`bytearray` + instance containing a JSON document) to a Python object using this + :ref:`conversion table `. + + The other arguments have the same meaning as in :func:`load`. + + If the data being deserialized is not a valid JSON document, a + :exc:`JSONDecodeError` will be raised. + + .. versionchanged:: 3.6 + *s* can now be of type :class:`bytes` or :class:`bytearray`. The + input encoding should be UTF-8, UTF-16 or UTF-32. + + .. versionchanged:: 3.9 + The keyword argument *encoding* has been removed. + + +Encoders and Decoders +--------------------- + +.. class:: JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None) + + Simple JSON decoder. + + Performs the following translations in decoding by default: + + .. _json-to-py-table: + + +---------------+-------------------+ + | JSON | Python | + +===============+===================+ + | object | dict | + +---------------+-------------------+ + | array | list | + +---------------+-------------------+ + | string | str | + +---------------+-------------------+ + | number (int) | int | + +---------------+-------------------+ + | number (real) | float | + +---------------+-------------------+ + | true | True | + +---------------+-------------------+ + | false | False | + +---------------+-------------------+ + | null | None | + +---------------+-------------------+ + + It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their + corresponding ``float`` values, which is outside the JSON spec. + + *object_hook*, if specified, will be called with the result of every JSON + object decoded and its return value will be used in place of the given + :class:`dict`. This can be used to provide custom deserializations (e.g. to + support JSON-RPC class hinting). + + *object_pairs_hook*, if specified will be called with the result of every + JSON object decoded with an ordered list of pairs. The return value of + *object_pairs_hook* will be used instead of the :class:`dict`. This + feature can be used to implement custom decoders. If *object_hook* is also + defined, the *object_pairs_hook* takes priority. + + .. versionchanged:: 3.1 + Added support for *object_pairs_hook*. + + *parse_float*, if specified, will be called with the string of every JSON + float to be decoded. By default, this is equivalent to ``float(num_str)``. + This can be used to use another datatype or parser for JSON floats + (e.g. :class:`decimal.Decimal`). + + *parse_int*, if specified, will be called with the string of every JSON int + to be decoded. By default, this is equivalent to ``int(num_str)``. This can + be used to use another datatype or parser for JSON integers + (e.g. :class:`float`). + + *parse_constant*, if specified, will be called with one of the following + strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. + This can be used to raise an exception if invalid JSON numbers + are encountered. + + If *strict* is false (``True`` is the default), then control characters + will be allowed inside strings. Control characters in this context are + those with character codes in the 0--31 range, including ``'\t'`` (tab), + ``'\n'``, ``'\r'`` and ``'\0'``. + + If the data being deserialized is not a valid JSON document, a + :exc:`JSONDecodeError` will be raised. + + .. versionchanged:: 3.6 + All parameters are now :ref:`keyword-only `. + + .. method:: decode(s) + + Return the Python representation of *s* (a :class:`str` instance + containing a JSON document). + + :exc:`JSONDecodeError` will be raised if the given JSON document is not + valid. + + .. method:: raw_decode(s) + + Decode a JSON document from *s* (a :class:`str` beginning with a + JSON document) and return a 2-tuple of the Python representation + and the index in *s* where the document ended. + + This can be used to decode a JSON document from a string that may have + extraneous data at the end. + + +.. class:: JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None) + + Extensible JSON encoder for Python data structures. + + Supports the following objects and types by default: + + .. _py-to-json-table: + + +----------------------------------------+---------------+ + | Python | JSON | + +========================================+===============+ + | dict | object | + +----------------------------------------+---------------+ + | list, tuple | array | + +----------------------------------------+---------------+ + | str | string | + +----------------------------------------+---------------+ + | int, float, int- & float-derived Enums | number | + +----------------------------------------+---------------+ + | True | true | + +----------------------------------------+---------------+ + | False | false | + +----------------------------------------+---------------+ + | None | null | + +----------------------------------------+---------------+ + + .. versionchanged:: 3.4 + Added support for int- and float-derived Enum classes. + + To extend this to recognize other objects, subclass and implement a + :meth:`default` method with another method that returns a serializable object + for ``o`` if possible, otherwise it should call the superclass implementation + (to raise :exc:`TypeError`). + + If *skipkeys* is false (the default), then it is a :exc:`TypeError` to + attempt encoding of keys that are not :class:`str`, :class:`int`, + :class:`float` or ``None``. If *skipkeys* is true, such items are simply + skipped. + + If *ensure_ascii* is true (the default), the output is guaranteed to + have all incoming non-ASCII characters escaped. If *ensure_ascii* is + false, these characters will be output as-is. + + If *check_circular* is true (the default), then lists, dicts, and custom + encoded objects will be checked for circular references during encoding to + prevent an infinite recursion (which would cause an :exc:`OverflowError`). + Otherwise, no such check takes place. + + If *allow_nan* is true (the default), then ``NaN``, ``Infinity``, and + ``-Infinity`` will be encoded as such. This behavior is not JSON + specification compliant, but is consistent with most JavaScript based + encoders and decoders. Otherwise, it will be a :exc:`ValueError` to encode + such floats. + + If *sort_keys* is true (default: ``False``), then the output of dictionaries + will be sorted by key; this is useful for regression tests to ensure that + JSON serializations can be compared on a day-to-day basis. + + If *indent* is a non-negative integer or string, then JSON array elements and + object members will be pretty-printed with that indent level. An indent level + of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) + selects the most compact representation. Using a positive integer indent + indents that many spaces per level. If *indent* is a string (such as ``"\t"``), + that string is used to indent each level. + + .. versionchanged:: 3.2 + Allow strings for *indent* in addition to integers. + + If specified, *separators* should be an ``(item_separator, key_separator)`` + tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and + ``(',', ': ')`` otherwise. To get the most compact JSON representation, + you should specify ``(',', ':')`` to eliminate whitespace. + + .. versionchanged:: 3.4 + Use ``(',', ': ')`` as default if *indent* is not ``None``. + + If specified, *default* should be a function that gets called for objects that + can't otherwise be serialized. It should return a JSON encodable version of + the object or raise a :exc:`TypeError`. If not specified, :exc:`TypeError` + is raised. + + .. versionchanged:: 3.6 + All parameters are now :ref:`keyword-only `. + + + .. method:: default(o) + + Implement this method in a subclass such that it returns a serializable + object for *o*, or calls the base implementation (to raise a + :exc:`TypeError`). + + For example, to support arbitrary iterators, you could implement default + like this:: + + def default(self, o): + try: + iterable = iter(o) + except TypeError: + pass + else: + return list(iterable) + # Let the base class default method raise the TypeError + return json.JSONEncoder.default(self, o) + + + .. method:: encode(o) + + Return a JSON string representation of a Python data structure, *o*. For + example:: + + >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]}) + '{"foo": ["bar", "baz"]}' + + + .. method:: iterencode(o) + + Encode the given object, *o*, and yield each string representation as + available. For example:: + + for chunk in json.JSONEncoder().iterencode(bigobject): + mysocket.write(chunk) + + +Exceptions +---------- + +.. exception:: JSONDecodeError(msg, doc, pos) + + Subclass of :exc:`ValueError` with the following additional attributes: + + .. attribute:: msg + + The unformatted error message. + + .. attribute:: doc + + The JSON document being parsed. + + .. attribute:: pos + + The start index of *doc* where parsing failed. + + .. attribute:: lineno + + The line corresponding to *pos*. + + .. attribute:: colno + + The column corresponding to *pos*. + + .. versionadded:: 3.5 + + +Standard Compliance and Interoperability +---------------------------------------- + +The JSON format is specified by :rfc:`7159` and by +`ECMA-404 `_. +This section details this module's level of compliance with the RFC. +For simplicity, :class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and +parameters other than those explicitly mentioned, are not considered. + +This module does not comply with the RFC in a strict fashion, implementing some +extensions that are valid JavaScript but not valid JSON. In particular: + +- Infinite and NaN number values are accepted and output; +- Repeated names within an object are accepted, and only the value of the last + name-value pair is used. + +Since the RFC permits RFC-compliant parsers to accept input texts that are not +RFC-compliant, this module's deserializer is technically RFC-compliant under +default settings. + +Character Encodings +^^^^^^^^^^^^^^^^^^^ + +The RFC requires that JSON be represented using either UTF-8, UTF-16, or +UTF-32, with UTF-8 being the recommended default for maximum interoperability. + +As permitted, though not required, by the RFC, this module's serializer sets +*ensure_ascii=True* by default, thus escaping the output so that the resulting +strings only contain ASCII characters. + +Other than the *ensure_ascii* parameter, this module is defined strictly in +terms of conversion between Python objects and +:class:`Unicode strings `, and thus does not otherwise directly address +the issue of character encodings. + +The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text, +and this module's serializer does not add a BOM to its output. +The RFC permits, but does not require, JSON deserializers to ignore an initial +BOM in their input. This module's deserializer raises a :exc:`ValueError` +when an initial BOM is present. + +The RFC does not explicitly forbid JSON strings which contain byte sequences +that don't correspond to valid Unicode characters (e.g. unpaired UTF-16 +surrogates), but it does note that they may cause interoperability problems. +By default, this module accepts and outputs (when present in the original +:class:`str`) code points for such sequences. + + +Infinite and NaN Number Values +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The RFC does not permit the representation of infinite or NaN number values. +Despite that, by default, this module accepts and outputs ``Infinity``, +``-Infinity``, and ``NaN`` as if they were valid JSON number literal values:: + + >>> # Neither of these calls raises an exception, but the results are not valid JSON + >>> json.dumps(float('-inf')) + '-Infinity' + >>> json.dumps(float('nan')) + 'NaN' + >>> # Same when deserializing + >>> json.loads('-Infinity') + -inf + >>> json.loads('NaN') + nan + +In the serializer, the *allow_nan* parameter can be used to alter this +behavior. In the deserializer, the *parse_constant* parameter can be used to +alter this behavior. + + +Repeated Names Within an Object +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The RFC specifies that the names within a JSON object should be unique, but +does not mandate how repeated names in JSON objects should be handled. By +default, this module does not raise an exception; instead, it ignores all but +the last name-value pair for a given name:: + + >>> weird_json = '{"x": 1, "x": 2, "x": 3}' + >>> json.loads(weird_json) + {'x': 3} + +The *object_pairs_hook* parameter can be used to alter this behavior. + + +Top-level Non-Object, Non-Array Values +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The old version of JSON specified by the obsolete :rfc:`4627` required that +the top-level value of a JSON text must be either a JSON object or array +(Python :class:`dict` or :class:`list`), and could not be a JSON null, +boolean, number, or string value. :rfc:`7159` removed that restriction, and +this module does not and has never implemented that restriction in either its +serializer or its deserializer. + +Regardless, for maximum interoperability, you may wish to voluntarily adhere +to the restriction yourself. + + +Implementation Limitations +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Some JSON deserializer implementations may set limits on: + +* the size of accepted JSON texts +* the maximum level of nesting of JSON objects and arrays +* the range and precision of JSON numbers +* the content and maximum length of JSON strings + +This module does not impose any such limits beyond those of the relevant +Python datatypes themselves or the Python interpreter itself. + +When serializing to JSON, beware any such limitations in applications that may +consume your JSON. In particular, it is common for JSON numbers to be +deserialized into IEEE 754 double precision numbers and thus subject to that +representation's range and precision limitations. This is especially relevant +when serializing Python :class:`int` values of extremely large magnitude, or +when serializing instances of "exotic" numerical types such as +:class:`decimal.Decimal`. + + +.. _json-commandline: +.. program:: json.tool + +Command Line Interface +---------------------- + +.. module:: json.tool + :synopsis: A command line to validate and pretty-print JSON. + +**Source code:** :source:`Lib/json/tool.py` + +-------------- + +The :mod:`json.tool` module provides a simple command line interface to validate +and pretty-print JSON objects. + +If the optional ``infile`` and ``outfile`` arguments are not +specified, :attr:`sys.stdin` and :attr:`sys.stdout` will be used respectively: + +.. code-block:: shell-session + + $ echo '{"json": "obj"}' | python -m json.tool + { + "json": "obj" + } + $ echo '{1.2:3.4}' | python -m json.tool + Expecting property name enclosed in double quotes: line 1 column 2 (char 1) + +.. versionchanged:: 3.5 + The output is now in the same order as the input. Use the + :option:`--sort-keys` option to sort the output of dictionaries + alphabetically by key. + + +Command line options +^^^^^^^^^^^^^^^^^^^^ + +.. cmdoption:: infile + + The JSON file to be validated or pretty-printed: + + .. code-block:: shell-session + + $ python -m json.tool mp_films.json + [ + { + "title": "And Now for Something Completely Different", + "year": 1971 + }, + { + "title": "Monty Python and the Holy Grail", + "year": 1975 + } + ] + + If *infile* is not specified, read from :attr:`sys.stdin`. + +.. cmdoption:: outfile + + Write the output of the *infile* to the given *outfile*. Otherwise, write it + to :attr:`sys.stdout`. + +.. cmdoption:: --sort-keys + + Sort the output of dictionaries alphabetically by key. + + .. versionadded:: 3.5 + +.. cmdoption:: --no-ensure-ascii + + Disable escaping of non-ascii characters, see :func:`json.dumps` for more information. + + .. versionadded:: 3.9 + +.. cmdoption:: --json-lines + + Parse every input line as separate JSON object. + + .. versionadded:: 3.8 + +.. cmdoption:: --indent, --tab, --no-indent, --compact + + Mutually exclusive options for whitespace control + + .. versionadded:: 3.9 + +.. cmdoption:: -h, --help + + Show the help message. + + +.. rubric:: Footnotes + +.. [#rfc-errata] As noted in `the errata for RFC 7159 + `_, + JSON permits literal U+2028 (LINE SEPARATOR) and + U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript + (as of ECMAScript Edition 5.1) does not. diff --git a/cpython_2/environment/repo/Doc/library/keyword.rst b/cpython_2/environment/repo/Doc/library/keyword.rst new file mode 100644 index 0000000000000000000000000000000000000000..acec45cdcd586e36a3ed65461dc513fd17d808ae --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/keyword.rst @@ -0,0 +1,24 @@ +:mod:`keyword` --- Testing for Python keywords +============================================== + +.. module:: keyword + :synopsis: Test whether a string is a keyword in Python. + +**Source code:** :source:`Lib/keyword.py` + +-------------- + +This module allows a Python program to determine if a string is a +:ref:`keyword `. + + +.. function:: iskeyword(s) + + Return ``True`` if *s* is a Python :ref:`keyword `. + + +.. data:: kwlist + + Sequence containing all the :ref:`keywords ` defined for the + interpreter. If any keywords are defined to only be active when particular + :mod:`__future__` statements are in effect, these will be included as well. diff --git a/cpython_2/environment/repo/Doc/library/language.rst b/cpython_2/environment/repo/Doc/library/language.rst new file mode 100644 index 0000000000000000000000000000000000000000..1eac32e459021666bb6c1fe6f009c3a95b4d79ca --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/language.rst @@ -0,0 +1,28 @@ +.. _language: + +************************ +Python Language Services +************************ + +Python provides a number of modules to assist in working with the Python +language. These modules support tokenizing, parsing, syntax analysis, bytecode +disassembly, and various other facilities. + +These modules include: + + +.. toctree:: + + parser.rst + ast.rst + symtable.rst + symbol.rst + token.rst + keyword.rst + tokenize.rst + tabnanny.rst + pyclbr.rst + py_compile.rst + compileall.rst + dis.rst + pickletools.rst diff --git a/cpython_2/environment/repo/Doc/library/linecache.rst b/cpython_2/environment/repo/Doc/library/linecache.rst new file mode 100644 index 0000000000000000000000000000000000000000..dd9f4ee45ba82eba0e8cb6b57302f2feaf3ab045 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/linecache.rst @@ -0,0 +1,67 @@ +:mod:`linecache` --- Random access to text lines +================================================ + +.. module:: linecache + :synopsis: Provides random access to individual lines from text files. + +.. sectionauthor:: Moshe Zadka + +**Source code:** :source:`Lib/linecache.py` + +-------------- + +The :mod:`linecache` module allows one to get any line from a Python source file, while +attempting to optimize internally, using a cache, the common case where many +lines are read from a single file. This is used by the :mod:`traceback` module +to retrieve source lines for inclusion in the formatted traceback. + +The :func:`tokenize.open` function is used to open files. This +function uses :func:`tokenize.detect_encoding` to get the encoding of the +file; in the absence of an encoding token, the file encoding defaults to UTF-8. + +The :mod:`linecache` module defines the following functions: + + +.. function:: getline(filename, lineno, module_globals=None) + + Get line *lineno* from file named *filename*. This function will never raise an + exception --- it will return ``''`` on errors (the terminating newline character + will be included for lines that are found). + + .. index:: triple: module; search; path + + If a file named *filename* is not found, the function first checks + for a :pep:`302` ``__loader__`` in *module_globals*. + If there is such a loader and it defines a ``get_source`` method, + then that determines the source lines + (if ``get_source()`` returns ``None``, then ``''`` is returned). + Finally, if *filename* is a relative filename, + it is looked up relative to the entries in the module search path, ``sys.path``. + + +.. function:: clearcache() + + Clear the cache. Use this function if you no longer need lines from files + previously read using :func:`getline`. + + +.. function:: checkcache(filename=None) + + Check the cache for validity. Use this function if files in the cache may have + changed on disk, and you require the updated version. If *filename* is omitted, + it will check all the entries in the cache. + +.. function:: lazycache(filename, module_globals) + + Capture enough detail about a non-file-based module to permit getting its + lines later via :func:`getline` even if *module_globals* is ``None`` in the later + call. This avoids doing I/O until a line is actually needed, without having + to carry the module globals around indefinitely. + + .. versionadded:: 3.5 + +Example:: + + >>> import linecache + >>> linecache.getline(linecache.__file__, 8) + 'import sys\n' diff --git a/cpython_2/environment/repo/Doc/library/locale.rst b/cpython_2/environment/repo/Doc/library/locale.rst new file mode 100644 index 0000000000000000000000000000000000000000..bf57a0835591682c2abb0402692ef93f59d7ce55 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/locale.rst @@ -0,0 +1,588 @@ +:mod:`locale` --- Internationalization services +=============================================== + +.. module:: locale + :synopsis: Internationalization services. + +.. moduleauthor:: Martin von Löwis +.. sectionauthor:: Martin von Löwis + +**Source code:** :source:`Lib/locale.py` + +-------------- + +The :mod:`locale` module opens access to the POSIX locale database and +functionality. The POSIX locale mechanism allows programmers to deal with +certain cultural issues in an application, without requiring the programmer to +know all the specifics of each country where the software is executed. + +.. index:: module: _locale + +The :mod:`locale` module is implemented on top of the :mod:`_locale` module, +which in turn uses an ANSI C locale implementation if available. + +The :mod:`locale` module defines the following exception and functions: + + +.. exception:: Error + + Exception raised when the locale passed to :func:`setlocale` is not + recognized. + + +.. function:: setlocale(category, locale=None) + + If *locale* is given and not ``None``, :func:`setlocale` modifies the locale + setting for the *category*. The available categories are listed in the data + description below. *locale* may be a string, or an iterable of two strings + (language code and encoding). If it's an iterable, it's converted to a locale + name using the locale aliasing engine. An empty string specifies the user's + default settings. If the modification of the locale fails, the exception + :exc:`Error` is raised. If successful, the new locale setting is returned. + + If *locale* is omitted or ``None``, the current setting for *category* is + returned. + + :func:`setlocale` is not thread-safe on most systems. Applications typically + start with a call of :: + + import locale + locale.setlocale(locale.LC_ALL, '') + + This sets the locale for all categories to the user's default setting (typically + specified in the :envvar:`LANG` environment variable). If the locale is not + changed thereafter, using multithreading should not cause problems. + + +.. function:: localeconv() + + Returns the database of the local conventions as a dictionary. This dictionary + has the following strings as keys: + + .. tabularcolumns:: |l|l|L| + + +----------------------+-------------------------------------+--------------------------------+ + | Category | Key | Meaning | + +======================+=====================================+================================+ + | :const:`LC_NUMERIC` | ``'decimal_point'`` | Decimal point character. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'grouping'`` | Sequence of numbers specifying | + | | | which relative positions the | + | | | ``'thousands_sep'`` is | + | | | expected. If the sequence is | + | | | terminated with | + | | | :const:`CHAR_MAX`, no further | + | | | grouping is performed. If the | + | | | sequence terminates with a | + | | | ``0``, the last group size is | + | | | repeatedly used. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'thousands_sep'`` | Character used between groups. | + +----------------------+-------------------------------------+--------------------------------+ + | :const:`LC_MONETARY` | ``'int_curr_symbol'`` | International currency symbol. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'currency_symbol'`` | Local currency symbol. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'p_cs_precedes/n_cs_precedes'`` | Whether the currency symbol | + | | | precedes the value (for | + | | | positive resp. negative | + | | | values). | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'p_sep_by_space/n_sep_by_space'`` | Whether the currency symbol is | + | | | separated from the value by a | + | | | space (for positive resp. | + | | | negative values). | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'mon_decimal_point'`` | Decimal point used for | + | | | monetary values. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'frac_digits'`` | Number of fractional digits | + | | | used in local formatting of | + | | | monetary values. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'int_frac_digits'`` | Number of fractional digits | + | | | used in international | + | | | formatting of monetary values. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'mon_thousands_sep'`` | Group separator used for | + | | | monetary values. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'mon_grouping'`` | Equivalent to ``'grouping'``, | + | | | used for monetary values. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'positive_sign'`` | Symbol used to annotate a | + | | | positive monetary value. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'negative_sign'`` | Symbol used to annotate a | + | | | negative monetary value. | + +----------------------+-------------------------------------+--------------------------------+ + | | ``'p_sign_posn/n_sign_posn'`` | The position of the sign (for | + | | | positive resp. negative | + | | | values), see below. | + +----------------------+-------------------------------------+--------------------------------+ + + All numeric values can be set to :const:`CHAR_MAX` to indicate that there is no + value specified in this locale. + + The possible values for ``'p_sign_posn'`` and ``'n_sign_posn'`` are given below. + + +--------------+-----------------------------------------+ + | Value | Explanation | + +==============+=========================================+ + | ``0`` | Currency and value are surrounded by | + | | parentheses. | + +--------------+-----------------------------------------+ + | ``1`` | The sign should precede the value and | + | | currency symbol. | + +--------------+-----------------------------------------+ + | ``2`` | The sign should follow the value and | + | | currency symbol. | + +--------------+-----------------------------------------+ + | ``3`` | The sign should immediately precede the | + | | value. | + +--------------+-----------------------------------------+ + | ``4`` | The sign should immediately follow the | + | | value. | + +--------------+-----------------------------------------+ + | ``CHAR_MAX`` | Nothing is specified in this locale. | + +--------------+-----------------------------------------+ + + The function sets temporarily the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` + locale or the ``LC_MONETARY`` locale if locales are different and numeric or + monetary strings are non-ASCII. This temporary change affects other threads. + + .. versionchanged:: 3.7 + The function now sets temporarily the ``LC_CTYPE`` locale to the + ``LC_NUMERIC`` locale in some cases. + + +.. function:: nl_langinfo(option) + + Return some locale-specific information as a string. This function is not + available on all systems, and the set of possible options might also vary + across platforms. The possible argument values are numbers, for which + symbolic constants are available in the locale module. + + The :func:`nl_langinfo` function accepts one of the following keys. Most + descriptions are taken from the corresponding description in the GNU C + library. + + .. data:: CODESET + + Get a string with the name of the character encoding used in the + selected locale. + + .. data:: D_T_FMT + + Get a string that can be used as a format string for :func:`time.strftime` to + represent date and time in a locale-specific way. + + .. data:: D_FMT + + Get a string that can be used as a format string for :func:`time.strftime` to + represent a date in a locale-specific way. + + .. data:: T_FMT + + Get a string that can be used as a format string for :func:`time.strftime` to + represent a time in a locale-specific way. + + .. data:: T_FMT_AMPM + + Get a format string for :func:`time.strftime` to represent time in the am/pm + format. + + .. data:: DAY_1 ... DAY_7 + + Get the name of the n-th day of the week. + + .. note:: + + This follows the US convention of :const:`DAY_1` being Sunday, not the + international convention (ISO 8601) that Monday is the first day of the + week. + + .. data:: ABDAY_1 ... ABDAY_7 + + Get the abbreviated name of the n-th day of the week. + + .. data:: MON_1 ... MON_12 + + Get the name of the n-th month. + + .. data:: ABMON_1 ... ABMON_12 + + Get the abbreviated name of the n-th month. + + .. data:: RADIXCHAR + + Get the radix character (decimal dot, decimal comma, etc.). + + .. data:: THOUSEP + + Get the separator character for thousands (groups of three digits). + + .. data:: YESEXPR + + Get a regular expression that can be used with the regex function to + recognize a positive response to a yes/no question. + + .. note:: + + The expression is in the syntax suitable for the :c:func:`regex` function + from the C library, which might differ from the syntax used in :mod:`re`. + + .. data:: NOEXPR + + Get a regular expression that can be used with the regex(3) function to + recognize a negative response to a yes/no question. + + .. data:: CRNCYSTR + + Get the currency symbol, preceded by "-" if the symbol should appear before + the value, "+" if the symbol should appear after the value, or "." if the + symbol should replace the radix character. + + .. data:: ERA + + Get a string that represents the era used in the current locale. + + Most locales do not define this value. An example of a locale which does + define this value is the Japanese one. In Japan, the traditional + representation of dates includes the name of the era corresponding to the + then-emperor's reign. + + Normally it should not be necessary to use this value directly. Specifying + the ``E`` modifier in their format strings causes the :func:`time.strftime` + function to use this information. The format of the returned string is not + specified, and therefore you should not assume knowledge of it on different + systems. + + .. data:: ERA_D_T_FMT + + Get a format string for :func:`time.strftime` to represent date and time in a + locale-specific era-based way. + + .. data:: ERA_D_FMT + + Get a format string for :func:`time.strftime` to represent a date in a + locale-specific era-based way. + + .. data:: ERA_T_FMT + + Get a format string for :func:`time.strftime` to represent a time in a + locale-specific era-based way. + + .. data:: ALT_DIGITS + + Get a representation of up to 100 values used to represent the values + 0 to 99. + + +.. function:: getdefaultlocale([envvars]) + + Tries to determine the default locale settings and returns them as a tuple of + the form ``(language code, encoding)``. + + According to POSIX, a program which has not called ``setlocale(LC_ALL, '')`` + runs using the portable ``'C'`` locale. Calling ``setlocale(LC_ALL, '')`` lets + it use the default locale as defined by the :envvar:`LANG` variable. Since we + do not want to interfere with the current locale setting we thus emulate the + behavior in the way described above. + + To maintain compatibility with other platforms, not only the :envvar:`LANG` + variable is tested, but a list of variables given as envvars parameter. The + first found to be defined will be used. *envvars* defaults to the search + path used in GNU gettext; it must always contain the variable name + ``'LANG'``. The GNU gettext search path contains ``'LC_ALL'``, + ``'LC_CTYPE'``, ``'LANG'`` and ``'LANGUAGE'``, in that order. + + Except for the code ``'C'``, the language code corresponds to :rfc:`1766`. + *language code* and *encoding* may be ``None`` if their values cannot be + determined. + + +.. function:: getlocale(category=LC_CTYPE) + + Returns the current setting for the given locale category as sequence containing + *language code*, *encoding*. *category* may be one of the :const:`LC_\*` values + except :const:`LC_ALL`. It defaults to :const:`LC_CTYPE`. + + Except for the code ``'C'``, the language code corresponds to :rfc:`1766`. + *language code* and *encoding* may be ``None`` if their values cannot be + determined. + + +.. function:: getpreferredencoding(do_setlocale=True) + + Return the encoding used for text data, according to user preferences. User + preferences are expressed differently on different systems, and might not be + available programmatically on some systems, so this function only returns a + guess. + + On some systems, it is necessary to invoke :func:`setlocale` to obtain the user + preferences, so this function is not thread-safe. If invoking setlocale is not + necessary or desired, *do_setlocale* should be set to ``False``. + + On Android or in the UTF-8 mode (:option:`-X` ``utf8`` option), always + return ``'UTF-8'``, the locale and the *do_setlocale* argument are ignored. + + .. versionchanged:: 3.7 + The function now always returns ``UTF-8`` on Android or if the UTF-8 mode + is enabled. + + +.. function:: normalize(localename) + + Returns a normalized locale code for the given locale name. The returned locale + code is formatted for use with :func:`setlocale`. If normalization fails, the + original name is returned unchanged. + + If the given encoding is not known, the function defaults to the default + encoding for the locale code just like :func:`setlocale`. + + +.. function:: resetlocale(category=LC_ALL) + + Sets the locale for *category* to the default setting. + + The default setting is determined by calling :func:`getdefaultlocale`. + *category* defaults to :const:`LC_ALL`. + + +.. function:: strcoll(string1, string2) + + Compares two strings according to the current :const:`LC_COLLATE` setting. As + any other compare function, returns a negative, or a positive value, or ``0``, + depending on whether *string1* collates before or after *string2* or is equal to + it. + + +.. function:: strxfrm(string) + + Transforms a string to one that can be used in locale-aware + comparisons. For example, ``strxfrm(s1) < strxfrm(s2)`` is + equivalent to ``strcoll(s1, s2) < 0``. This function can be used + when the same string is compared repeatedly, e.g. when collating a + sequence of strings. + + +.. function:: format_string(format, val, grouping=False, monetary=False) + + Formats a number *val* according to the current :const:`LC_NUMERIC` setting. + The format follows the conventions of the ``%`` operator. For floating point + values, the decimal point is modified if appropriate. If *grouping* is true, + also takes the grouping into account. + + If *monetary* is true, the conversion uses monetary thousands separator and + grouping strings. + + Processes formatting specifiers as in ``format % val``, but takes the current + locale settings into account. + + .. versionchanged:: 3.7 + The *monetary* keyword parameter was added. + + +.. function:: format(format, val, grouping=False, monetary=False) + + Please note that this function works like :meth:`format_string` but will + only work for exactly one ``%char`` specifier. For example, ``'%f'`` and + ``'%.0f'`` are both valid specifiers, but ``'%f KiB'`` is not. + + For whole format strings, use :func:`format_string`. + + .. deprecated:: 3.7 + Use :meth:`format_string` instead. + + +.. function:: currency(val, symbol=True, grouping=False, international=False) + + Formats a number *val* according to the current :const:`LC_MONETARY` settings. + + The returned string includes the currency symbol if *symbol* is true, which is + the default. If *grouping* is true (which is not the default), grouping is done + with the value. If *international* is true (which is not the default), the + international currency symbol is used. + + Note that this function will not work with the 'C' locale, so you have to set a + locale via :func:`setlocale` first. + + +.. function:: str(float) + + Formats a floating point number using the same format as the built-in function + ``str(float)``, but takes the decimal point into account. + + +.. function:: delocalize(string) + + Converts a string into a normalized number string, following the + :const:`LC_NUMERIC` settings. + + .. versionadded:: 3.5 + + +.. function:: atof(string) + + Converts a string to a floating point number, following the :const:`LC_NUMERIC` + settings. + + +.. function:: atoi(string) + + Converts a string to an integer, following the :const:`LC_NUMERIC` conventions. + + +.. data:: LC_CTYPE + + .. index:: module: string + + Locale category for the character type functions. Depending on the settings of + this category, the functions of module :mod:`string` dealing with case change + their behaviour. + + +.. data:: LC_COLLATE + + Locale category for sorting strings. The functions :func:`strcoll` and + :func:`strxfrm` of the :mod:`locale` module are affected. + + +.. data:: LC_TIME + + Locale category for the formatting of time. The function :func:`time.strftime` + follows these conventions. + + +.. data:: LC_MONETARY + + Locale category for formatting of monetary values. The available options are + available from the :func:`localeconv` function. + + +.. data:: LC_MESSAGES + + Locale category for message display. Python currently does not support + application specific locale-aware messages. Messages displayed by the operating + system, like those returned by :func:`os.strerror` might be affected by this + category. + + +.. data:: LC_NUMERIC + + Locale category for formatting numbers. The functions :func:`.format`, + :func:`atoi`, :func:`atof` and :func:`.str` of the :mod:`locale` module are + affected by that category. All other numeric formatting operations are not + affected. + + +.. data:: LC_ALL + + Combination of all locale settings. If this flag is used when the locale is + changed, setting the locale for all categories is attempted. If that fails for + any category, no category is changed at all. When the locale is retrieved using + this flag, a string indicating the setting for all categories is returned. This + string can be later used to restore the settings. + + +.. data:: CHAR_MAX + + This is a symbolic constant used for different values returned by + :func:`localeconv`. + + +Example:: + + >>> import locale + >>> loc = locale.getlocale() # get current locale + # use German locale; name might vary with platform + >>> locale.setlocale(locale.LC_ALL, 'de_DE') + >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut + >>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale + >>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale + >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale + + +Background, details, hints, tips and caveats +-------------------------------------------- + +The C standard defines the locale as a program-wide property that may be +relatively expensive to change. On top of that, some implementation are broken +in such a way that frequent locale changes may cause core dumps. This makes the +locale somewhat painful to use correctly. + +Initially, when a program is started, the locale is the ``C`` locale, no matter +what the user's preferred locale is. There is one exception: the +:data:`LC_CTYPE` category is changed at startup to set the current locale +encoding to the user's preferred locale encoding. The program must explicitly +say that it wants the user's preferred locale settings for other categories by +calling ``setlocale(LC_ALL, '')``. + +It is generally a bad idea to call :func:`setlocale` in some library routine, +since as a side effect it affects the entire program. Saving and restoring it +is almost as bad: it is expensive and affects other threads that happen to run +before the settings have been restored. + +If, when coding a module for general use, you need a locale independent version +of an operation that is affected by the locale (such as +certain formats used with :func:`time.strftime`), you will have to find a way to +do it without using the standard library routine. Even better is convincing +yourself that using locale settings is okay. Only as a last resort should you +document that your module is not compatible with non-\ ``C`` locale settings. + +The only way to perform numeric operations according to the locale is to use the +special functions defined by this module: :func:`atof`, :func:`atoi`, +:func:`.format`, :func:`.str`. + +There is no way to perform case conversions and character classifications +according to the locale. For (Unicode) text strings these are done according +to the character value only, while for byte strings, the conversions and +classifications are done according to the ASCII value of the byte, and bytes +whose high bit is set (i.e., non-ASCII bytes) are never converted or considered +part of a character class such as letter or whitespace. + + +.. _embedding-locale: + +For extension writers and programs that embed Python +---------------------------------------------------- + +Extension modules should never call :func:`setlocale`, except to find out what +the current locale is. But since the return value can only be used portably to +restore it, that is not very useful (except perhaps to find out whether or not +the locale is ``C``). + +When Python code uses the :mod:`locale` module to change the locale, this also +affects the embedding application. If the embedding application doesn't want +this to happen, it should remove the :mod:`_locale` extension module (which does +all the work) from the table of built-in modules in the :file:`config.c` file, +and make sure that the :mod:`_locale` module is not accessible as a shared +library. + + +.. _locale-gettext: + +Access to message catalogs +-------------------------- + +.. function:: gettext(msg) +.. function:: dgettext(domain, msg) +.. function:: dcgettext(domain, msg, category) +.. function:: textdomain(domain) +.. function:: bindtextdomain(domain, dir) + +The locale module exposes the C library's gettext interface on systems that +provide this interface. It consists of the functions :func:`!gettext`, +:func:`!dgettext`, :func:`!dcgettext`, :func:`!textdomain`, :func:`!bindtextdomain`, +and :func:`!bind_textdomain_codeset`. These are similar to the same functions in +the :mod:`gettext` module, but use the C library's binary format for message +catalogs, and the C library's search algorithms for locating message catalogs. + +Python applications should normally find no need to invoke these functions, and +should use :mod:`gettext` instead. A known exception to this rule are +applications that link with additional C libraries which internally invoke +:c:func:`gettext` or :c:func:`dcgettext`. For these applications, it may be +necessary to bind the text domain, so that the libraries can properly locate +their message catalogs. + diff --git a/cpython_2/environment/repo/Doc/library/logging.config.rst b/cpython_2/environment/repo/Doc/library/logging.config.rst new file mode 100644 index 0000000000000000000000000000000000000000..683d6ed5e8ba525739db836bb6f6aeca13ee8770 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/logging.config.rst @@ -0,0 +1,823 @@ +:mod:`logging.config` --- Logging configuration +=============================================== + +.. module:: logging.config + :synopsis: Configuration of the logging module. + +.. moduleauthor:: Vinay Sajip +.. sectionauthor:: Vinay Sajip + +**Source code:** :source:`Lib/logging/config.py` + +.. sidebar:: Important + + This page contains only reference information. For tutorials, + please see + + * :ref:`Basic Tutorial ` + * :ref:`Advanced Tutorial ` + * :ref:`Logging Cookbook ` + +-------------- + +This section describes the API for configuring the logging module. + +.. _logging-config-api: + +Configuration functions +^^^^^^^^^^^^^^^^^^^^^^^ + +The following functions configure the logging module. They are located in the +:mod:`logging.config` module. Their use is optional --- you can configure the +logging module using these functions or by making calls to the main API (defined +in :mod:`logging` itself) and defining handlers which are declared either in +:mod:`logging` or :mod:`logging.handlers`. + +.. function:: dictConfig(config) + + Takes the logging configuration from a dictionary. The contents of + this dictionary are described in :ref:`logging-config-dictschema` + below. + + If an error is encountered during configuration, this function will + raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError` + or :exc:`ImportError` with a suitably descriptive message. The + following is a (possibly incomplete) list of conditions which will + raise an error: + + * A ``level`` which is not a string or which is a string not + corresponding to an actual logging level. + * A ``propagate`` value which is not a boolean. + * An id which does not have a corresponding destination. + * A non-existent handler id found during an incremental call. + * An invalid logger name. + * Inability to resolve to an internal or external object. + + Parsing is performed by the :class:`DictConfigurator` class, whose + constructor is passed the dictionary used for configuration, and + has a :meth:`configure` method. The :mod:`logging.config` module + has a callable attribute :attr:`dictConfigClass` + which is initially set to :class:`DictConfigurator`. + You can replace the value of :attr:`dictConfigClass` with a + suitable implementation of your own. + + :func:`dictConfig` calls :attr:`dictConfigClass` passing + the specified dictionary, and then calls the :meth:`configure` method on + the returned object to put the configuration into effect:: + + def dictConfig(config): + dictConfigClass(config).configure() + + For example, a subclass of :class:`DictConfigurator` could call + ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then + set up custom prefixes which would be usable in the subsequent + :meth:`configure` call. :attr:`dictConfigClass` would be bound to + this new subclass, and then :func:`dictConfig` could be called exactly as + in the default, uncustomized state. + + .. versionadded:: 3.2 + +.. function:: fileConfig(fname, defaults=None, disable_existing_loggers=True) + + Reads the logging configuration from a :mod:`configparser`\-format file. The + format of the file should be as described in + :ref:`logging-config-fileformat`. + This function can be called several times from an application, allowing an + end user to select from various pre-canned configurations (if the developer + provides a mechanism to present the choices and load the chosen + configuration). + + :param fname: A filename, or a file-like object, or an instance derived + from :class:`~configparser.RawConfigParser`. If a + ``RawConfigParser``-derived instance is passed, it is used as + is. Otherwise, a :class:`~configparser.Configparser` is + instantiated, and the configuration read by it from the + object passed in ``fname``. If that has a :meth:`readline` + method, it is assumed to be a file-like object and read using + :meth:`~configparser.ConfigParser.read_file`; otherwise, + it is assumed to be a filename and passed to + :meth:`~configparser.ConfigParser.read`. + + + :param defaults: Defaults to be passed to the ConfigParser can be specified + in this argument. + + :param disable_existing_loggers: If specified as ``False``, loggers which + exist when this call is made are left + enabled. The default is ``True`` because this + enables old behaviour in a + backward-compatible way. This behaviour is to + disable any existing non-root loggers unless + they or their ancestors are explicitly named + in the logging configuration. + + .. versionchanged:: 3.4 + An instance of a subclass of :class:`~configparser.RawConfigParser` is + now accepted as a value for ``fname``. This facilitates: + + * Use of a configuration file where logging configuration is just part + of the overall application configuration. + * Use of a configuration read from a file, and then modified by the using + application (e.g. based on command-line parameters or other aspects + of the runtime environment) before being passed to ``fileConfig``. + +.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None) + + Starts up a socket server on the specified port, and listens for new + configurations. If no port is specified, the module's default + :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be + sent as a file suitable for processing by :func:`dictConfig` or + :func:`fileConfig`. Returns a :class:`~threading.Thread` instance on which + you can call :meth:`~threading.Thread.start` to start the server, and which + you can :meth:`~threading.Thread.join` when appropriate. To stop the server, + call :func:`stopListening`. + + The ``verify`` argument, if specified, should be a callable which should + verify whether bytes received across the socket are valid and should be + processed. This could be done by encrypting and/or signing what is sent + across the socket, such that the ``verify`` callable can perform + signature verification and/or decryption. The ``verify`` callable is called + with a single argument - the bytes received across the socket - and should + return the bytes to be processed, or ``None`` to indicate that the bytes should + be discarded. The returned bytes could be the same as the passed in bytes + (e.g. when only verification is done), or they could be completely different + (perhaps if decryption were performed). + + To send a configuration to the socket, read in the configuration file and + send it to the socket as a sequence of bytes preceded by a four-byte length + string packed in binary using ``struct.pack('>L', n)``. + + .. note:: + + Because portions of the configuration are passed through + :func:`eval`, use of this function may open its users to a security risk. + While the function only binds to a socket on ``localhost``, and so does + not accept connections from remote machines, there are scenarios where + untrusted code could be run under the account of the process which calls + :func:`listen`. Specifically, if the process calling :func:`listen` runs + on a multi-user machine where users cannot trust each other, then a + malicious user could arrange to run essentially arbitrary code in a + victim user's process, simply by connecting to the victim's + :func:`listen` socket and sending a configuration which runs whatever + code the attacker wants to have executed in the victim's process. This is + especially easy to do if the default port is used, but not hard even if a + different port is used). To avoid the risk of this happening, use the + ``verify`` argument to :func:`listen` to prevent unrecognised + configurations from being applied. + + .. versionchanged:: 3.4 + The ``verify`` argument was added. + + .. note:: + + If you want to send configurations to the listener which don't + disable existing loggers, you will need to use a JSON format for + the configuration, which will use :func:`dictConfig` for configuration. + This method allows you to specify ``disable_existing_loggers`` as + ``False`` in the configuration you send. + + +.. function:: stopListening() + + Stops the listening server which was created with a call to :func:`listen`. + This is typically called before calling :meth:`join` on the return value from + :func:`listen`. + + +.. _logging-config-dictschema: + +Configuration dictionary schema +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Describing a logging configuration requires listing the various +objects to create and the connections between them; for example, you +may create a handler named 'console' and then say that the logger +named 'startup' will send its messages to the 'console' handler. +These objects aren't limited to those provided by the :mod:`logging` +module because you might write your own formatter or handler class. +The parameters to these classes may also need to include external +objects such as ``sys.stderr``. The syntax for describing these +objects and connections is defined in :ref:`logging-config-dict-connections` +below. + +Dictionary Schema Details +""""""""""""""""""""""""" + +The dictionary passed to :func:`dictConfig` must contain the following +keys: + +* *version* - to be set to an integer value representing the schema + version. The only valid value at present is 1, but having this key + allows the schema to evolve while still preserving backwards + compatibility. + +All other keys are optional, but if present they will be interpreted +as described below. In all cases below where a 'configuring dict' is +mentioned, it will be checked for the special ``'()'`` key to see if a +custom instantiation is required. If so, the mechanism described in +:ref:`logging-config-dict-userdef` below is used to create an instance; +otherwise, the context is used to determine what to instantiate. + +* *formatters* - the corresponding value will be a dict in which each + key is a formatter id and each value is a dict describing how to + configure the corresponding :class:`~logging.Formatter` instance. + + The configuring dict is searched for keys ``format`` and ``datefmt`` + (with defaults of ``None``) and these are used to construct a + :class:`~logging.Formatter` instance. + + .. versionchanged:: 3.8 + a ``validate`` key (with default of ``True``) can be added into + the ``formatters`` section of the configuring dict, this is to + validate the format. + +* *filters* - the corresponding value will be a dict in which each key + is a filter id and each value is a dict describing how to configure + the corresponding Filter instance. + + The configuring dict is searched for the key ``name`` (defaulting to the + empty string) and this is used to construct a :class:`logging.Filter` + instance. + +* *handlers* - the corresponding value will be a dict in which each + key is a handler id and each value is a dict describing how to + configure the corresponding Handler instance. + + The configuring dict is searched for the following keys: + + * ``class`` (mandatory). This is the fully qualified name of the + handler class. + + * ``level`` (optional). The level of the handler. + + * ``formatter`` (optional). The id of the formatter for this + handler. + + * ``filters`` (optional). A list of ids of the filters for this + handler. + + All *other* keys are passed through as keyword arguments to the + handler's constructor. For example, given the snippet: + + .. code-block:: yaml + + handlers: + console: + class : logging.StreamHandler + formatter: brief + level : INFO + filters: [allow_foo] + stream : ext://sys.stdout + file: + class : logging.handlers.RotatingFileHandler + formatter: precise + filename: logconfig.log + maxBytes: 1024 + backupCount: 3 + + the handler with id ``console`` is instantiated as a + :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying + stream. The handler with id ``file`` is instantiated as a + :class:`logging.handlers.RotatingFileHandler` with the keyword arguments + ``filename='logconfig.log', maxBytes=1024, backupCount=3``. + +* *loggers* - the corresponding value will be a dict in which each key + is a logger name and each value is a dict describing how to + configure the corresponding Logger instance. + + The configuring dict is searched for the following keys: + + * ``level`` (optional). The level of the logger. + + * ``propagate`` (optional). The propagation setting of the logger. + + * ``filters`` (optional). A list of ids of the filters for this + logger. + + * ``handlers`` (optional). A list of ids of the handlers for this + logger. + + The specified loggers will be configured according to the level, + propagation, filters and handlers specified. + +* *root* - this will be the configuration for the root logger. + Processing of the configuration will be as for any logger, except + that the ``propagate`` setting will not be applicable. + +* *incremental* - whether the configuration is to be interpreted as + incremental to the existing configuration. This value defaults to + ``False``, which means that the specified configuration replaces the + existing configuration with the same semantics as used by the + existing :func:`fileConfig` API. + + If the specified value is ``True``, the configuration is processed + as described in the section on :ref:`logging-config-dict-incremental`. + +* *disable_existing_loggers* - whether any existing non-root loggers are + to be disabled. This setting mirrors the parameter of the same name in + :func:`fileConfig`. If absent, this parameter defaults to ``True``. + This value is ignored if *incremental* is ``True``. + +.. _logging-config-dict-incremental: + +Incremental Configuration +""""""""""""""""""""""""" + +It is difficult to provide complete flexibility for incremental +configuration. For example, because objects such as filters +and formatters are anonymous, once a configuration is set up, it is +not possible to refer to such anonymous objects when augmenting a +configuration. + +Furthermore, there is not a compelling case for arbitrarily altering +the object graph of loggers, handlers, filters, formatters at +run-time, once a configuration is set up; the verbosity of loggers and +handlers can be controlled just by setting levels (and, in the case of +loggers, propagation flags). Changing the object graph arbitrarily in +a safe way is problematic in a multi-threaded environment; while not +impossible, the benefits are not worth the complexity it adds to the +implementation. + +Thus, when the ``incremental`` key of a configuration dict is present +and is ``True``, the system will completely ignore any ``formatters`` and +``filters`` entries, and process only the ``level`` +settings in the ``handlers`` entries, and the ``level`` and +``propagate`` settings in the ``loggers`` and ``root`` entries. + +Using a value in the configuration dict lets configurations to be sent +over the wire as pickled dicts to a socket listener. Thus, the logging +verbosity of a long-running application can be altered over time with +no need to stop and restart the application. + +.. _logging-config-dict-connections: + +Object connections +"""""""""""""""""" + +The schema describes a set of logging objects - loggers, +handlers, formatters, filters - which are connected to each other in +an object graph. Thus, the schema needs to represent connections +between the objects. For example, say that, once configured, a +particular logger has attached to it a particular handler. For the +purposes of this discussion, we can say that the logger represents the +source, and the handler the destination, of a connection between the +two. Of course in the configured objects this is represented by the +logger holding a reference to the handler. In the configuration dict, +this is done by giving each destination object an id which identifies +it unambiguously, and then using the id in the source object's +configuration to indicate that a connection exists between the source +and the destination object with that id. + +So, for example, consider the following YAML snippet: + +.. code-block:: yaml + + formatters: + brief: + # configuration for formatter with id 'brief' goes here + precise: + # configuration for formatter with id 'precise' goes here + handlers: + h1: #This is an id + # configuration of handler with id 'h1' goes here + formatter: brief + h2: #This is another id + # configuration of handler with id 'h2' goes here + formatter: precise + loggers: + foo.bar.baz: + # other configuration for logger 'foo.bar.baz' + handlers: [h1, h2] + +(Note: YAML used here because it's a little more readable than the +equivalent Python source form for the dictionary.) + +The ids for loggers are the logger names which would be used +programmatically to obtain a reference to those loggers, e.g. +``foo.bar.baz``. The ids for Formatters and Filters can be any string +value (such as ``brief``, ``precise`` above) and they are transient, +in that they are only meaningful for processing the configuration +dictionary and used to determine connections between objects, and are +not persisted anywhere when the configuration call is complete. + +The above snippet indicates that logger named ``foo.bar.baz`` should +have two handlers attached to it, which are described by the handler +ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id +``brief``, and the formatter for ``h2`` is that described by id +``precise``. + + +.. _logging-config-dict-userdef: + +User-defined objects +"""""""""""""""""""" + +The schema supports user-defined objects for handlers, filters and +formatters. (Loggers do not need to have different types for +different instances, so there is no support in this configuration +schema for user-defined logger classes.) + +Objects to be configured are described by dictionaries +which detail their configuration. In some places, the logging system +will be able to infer from the context how an object is to be +instantiated, but when a user-defined object is to be instantiated, +the system will not know how to do this. In order to provide complete +flexibility for user-defined object instantiation, the user needs +to provide a 'factory' - a callable which is called with a +configuration dictionary and which returns the instantiated object. +This is signalled by an absolute import path to the factory being +made available under the special key ``'()'``. Here's a concrete +example: + +.. code-block:: yaml + + formatters: + brief: + format: '%(message)s' + default: + format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s' + datefmt: '%Y-%m-%d %H:%M:%S' + custom: + (): my.package.customFormatterFactory + bar: baz + spam: 99.9 + answer: 42 + +The above YAML snippet defines three formatters. The first, with id +``brief``, is a standard :class:`logging.Formatter` instance with the +specified format string. The second, with id ``default``, has a +longer format and also defines the time format explicitly, and will +result in a :class:`logging.Formatter` initialized with those two format +strings. Shown in Python source form, the ``brief`` and ``default`` +formatters have configuration sub-dictionaries:: + + { + 'format' : '%(message)s' + } + +and:: + + { + 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s', + 'datefmt' : '%Y-%m-%d %H:%M:%S' + } + +respectively, and as these dictionaries do not contain the special key +``'()'``, the instantiation is inferred from the context: as a result, +standard :class:`logging.Formatter` instances are created. The +configuration sub-dictionary for the third formatter, with id +``custom``, is:: + + { + '()' : 'my.package.customFormatterFactory', + 'bar' : 'baz', + 'spam' : 99.9, + 'answer' : 42 + } + +and this contains the special key ``'()'``, which means that +user-defined instantiation is wanted. In this case, the specified +factory callable will be used. If it is an actual callable it will be +used directly - otherwise, if you specify a string (as in the example) +the actual callable will be located using normal import mechanisms. +The callable will be called with the **remaining** items in the +configuration sub-dictionary as keyword arguments. In the above +example, the formatter with id ``custom`` will be assumed to be +returned by the call:: + + my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42) + +The key ``'()'`` has been used as the special key because it is not a +valid keyword parameter name, and so will not clash with the names of +the keyword arguments used in the call. The ``'()'`` also serves as a +mnemonic that the corresponding value is a callable. + + +.. _logging-config-dict-externalobj: + +Access to external objects +"""""""""""""""""""""""""" + +There are times where a configuration needs to refer to objects +external to the configuration, for example ``sys.stderr``. If the +configuration dict is constructed using Python code, this is +straightforward, but a problem arises when the configuration is +provided via a text file (e.g. JSON, YAML). In a text file, there is +no standard way to distinguish ``sys.stderr`` from the literal string +``'sys.stderr'``. To facilitate this distinction, the configuration +system looks for certain special prefixes in string values and +treat them specially. For example, if the literal string +``'ext://sys.stderr'`` is provided as a value in the configuration, +then the ``ext://`` will be stripped off and the remainder of the +value processed using normal import mechanisms. + +The handling of such prefixes is done in a way analogous to protocol +handling: there is a generic mechanism to look for prefixes which +match the regular expression ``^(?P[a-z]+)://(?P.*)$`` +whereby, if the ``prefix`` is recognised, the ``suffix`` is processed +in a prefix-dependent manner and the result of the processing replaces +the string value. If the prefix is not recognised, then the string +value will be left as-is. + + +.. _logging-config-dict-internalobj: + +Access to internal objects +"""""""""""""""""""""""""" + +As well as external objects, there is sometimes also a need to refer +to objects in the configuration. This will be done implicitly by the +configuration system for things that it knows about. For example, the +string value ``'DEBUG'`` for a ``level`` in a logger or handler will +automatically be converted to the value ``logging.DEBUG``, and the +``handlers``, ``filters`` and ``formatter`` entries will take an +object id and resolve to the appropriate destination object. + +However, a more generic mechanism is needed for user-defined +objects which are not known to the :mod:`logging` module. For +example, consider :class:`logging.handlers.MemoryHandler`, which takes +a ``target`` argument which is another handler to delegate to. Since +the system already knows about this class, then in the configuration, +the given ``target`` just needs to be the object id of the relevant +target handler, and the system will resolve to the handler from the +id. If, however, a user defines a ``my.package.MyHandler`` which has +an ``alternate`` handler, the configuration system would not know that +the ``alternate`` referred to a handler. To cater for this, a generic +resolution system allows the user to specify: + +.. code-block:: yaml + + handlers: + file: + # configuration of file handler goes here + + custom: + (): my.package.MyHandler + alternate: cfg://handlers.file + +The literal string ``'cfg://handlers.file'`` will be resolved in an +analogous way to strings with the ``ext://`` prefix, but looking +in the configuration itself rather than the import namespace. The +mechanism allows access by dot or by index, in a similar way to +that provided by ``str.format``. Thus, given the following snippet: + +.. code-block:: yaml + + handlers: + email: + class: logging.handlers.SMTPHandler + mailhost: localhost + fromaddr: my_app@domain.tld + toaddrs: + - support_team@domain.tld + - dev_team@domain.tld + subject: Houston, we have a problem. + +in the configuration, the string ``'cfg://handlers'`` would resolve to +the dict with key ``handlers``, the string ``'cfg://handlers.email`` +would resolve to the dict with key ``email`` in the ``handlers`` dict, +and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would +resolve to ``'dev_team.domain.tld'`` and the string +``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value +``'support_team@domain.tld'``. The ``subject`` value could be accessed +using either ``'cfg://handlers.email.subject'`` or, equivalently, +``'cfg://handlers.email[subject]'``. The latter form only needs to be +used if the key contains spaces or non-alphanumeric characters. If an +index value consists only of decimal digits, access will be attempted +using the corresponding integer value, falling back to the string +value if needed. + +Given a string ``cfg://handlers.myhandler.mykey.123``, this will +resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``. +If the string is specified as ``cfg://handlers.myhandler.mykey[123]``, +the system will attempt to retrieve the value from +``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back +to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that +fails. + + +.. _logging-import-resolution: + +Import resolution and custom importers +"""""""""""""""""""""""""""""""""""""" + +Import resolution, by default, uses the builtin :func:`__import__` function +to do its importing. You may want to replace this with your own importing +mechanism: if so, you can replace the :attr:`importer` attribute of the +:class:`DictConfigurator` or its superclass, the +:class:`BaseConfigurator` class. However, you need to be +careful because of the way functions are accessed from classes via +descriptors. If you are using a Python callable to do your imports, and you +want to define it at class level rather than instance level, you need to wrap +it with :func:`staticmethod`. For example:: + + from importlib import import_module + from logging.config import BaseConfigurator + + BaseConfigurator.importer = staticmethod(import_module) + +You don't need to wrap with :func:`staticmethod` if you're setting the import +callable on a configurator *instance*. + + +.. _logging-config-fileformat: + +Configuration file format +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The configuration file format understood by :func:`fileConfig` is based on +:mod:`configparser` functionality. The file must contain sections called +``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the +entities of each type which are defined in the file. For each such entity, there +is a separate section which identifies how that entity is configured. Thus, for +a logger named ``log01`` in the ``[loggers]`` section, the relevant +configuration details are held in a section ``[logger_log01]``. Similarly, a +handler called ``hand01`` in the ``[handlers]`` section will have its +configuration held in a section called ``[handler_hand01]``, while a formatter +called ``form01`` in the ``[formatters]`` section will have its configuration +specified in a section called ``[formatter_form01]``. The root logger +configuration must be specified in a section called ``[logger_root]``. + +.. note:: + + The :func:`fileConfig` API is older than the :func:`dictConfig` API and does + not provide functionality to cover certain aspects of logging. For example, + you cannot configure :class:`~logging.Filter` objects, which provide for + filtering of messages beyond simple integer levels, using :func:`fileConfig`. + If you need to have instances of :class:`~logging.Filter` in your logging + configuration, you will need to use :func:`dictConfig`. Note that future + enhancements to configuration functionality will be added to + :func:`dictConfig`, so it's worth considering transitioning to this newer + API when it's convenient to do so. + +Examples of these sections in the file are given below. + +.. code-block:: ini + + [loggers] + keys=root,log02,log03,log04,log05,log06,log07 + + [handlers] + keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09 + + [formatters] + keys=form01,form02,form03,form04,form05,form06,form07,form08,form09 + +The root logger must specify a level and a list of handlers. An example of a +root logger section is given below. + +.. code-block:: ini + + [logger_root] + level=NOTSET + handlers=hand01 + +The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or +``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be +logged. Level values are :func:`eval`\ uated in the context of the ``logging`` +package's namespace. + +The ``handlers`` entry is a comma-separated list of handler names, which must +appear in the ``[handlers]`` section. These names must appear in the +``[handlers]`` section and have corresponding sections in the configuration +file. + +For loggers other than the root logger, some additional information is required. +This is illustrated by the following example. + +.. code-block:: ini + + [logger_parser] + level=DEBUG + handlers=hand01 + propagate=1 + qualname=compiler.parser + +The ``level`` and ``handlers`` entries are interpreted as for the root logger, +except that if a non-root logger's level is specified as ``NOTSET``, the system +consults loggers higher up the hierarchy to determine the effective level of the +logger. The ``propagate`` entry is set to 1 to indicate that messages must +propagate to handlers higher up the logger hierarchy from this logger, or 0 to +indicate that messages are **not** propagated to handlers up the hierarchy. The +``qualname`` entry is the hierarchical channel name of the logger, that is to +say the name used by the application to get the logger. + +Sections which specify handler configuration are exemplified by the following. + +.. code-block:: ini + + [handler_hand01] + class=StreamHandler + level=NOTSET + formatter=form01 + args=(sys.stdout,) + +The ``class`` entry indicates the handler's class (as determined by :func:`eval` +in the ``logging`` package's namespace). The ``level`` is interpreted as for +loggers, and ``NOTSET`` is taken to mean 'log everything'. + +The ``formatter`` entry indicates the key name of the formatter for this +handler. If blank, a default formatter (``logging._defaultFormatter``) is used. +If a name is specified, it must appear in the ``[formatters]`` section and have +a corresponding section in the configuration file. + +The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging`` +package's namespace, is the list of arguments to the constructor for the handler +class. Refer to the constructors for the relevant handlers, or to the examples +below, to see how typical entries are constructed. If not provided, it defaults +to ``()``. + +The optional ``kwargs`` entry, when :func:`eval`\ uated in the context of the +``logging`` package's namespace, is the keyword argument dict to the constructor +for the handler class. If not provided, it defaults to ``{}``. + +.. code-block:: ini + + [handler_hand02] + class=FileHandler + level=DEBUG + formatter=form02 + args=('python.log', 'w') + + [handler_hand03] + class=handlers.SocketHandler + level=INFO + formatter=form03 + args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) + + [handler_hand04] + class=handlers.DatagramHandler + level=WARN + formatter=form04 + args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT) + + [handler_hand05] + class=handlers.SysLogHandler + level=ERROR + formatter=form05 + args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER) + + [handler_hand06] + class=handlers.NTEventLogHandler + level=CRITICAL + formatter=form06 + args=('Python Application', '', 'Application') + + [handler_hand07] + class=handlers.SMTPHandler + level=WARN + formatter=form07 + args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject') + kwargs={'timeout': 10.0} + + [handler_hand08] + class=handlers.MemoryHandler + level=NOTSET + formatter=form08 + target= + args=(10, ERROR) + + [handler_hand09] + class=handlers.HTTPHandler + level=NOTSET + formatter=form09 + args=('localhost:9022', '/log', 'GET') + kwargs={'secure': True} + +Sections which specify formatter configuration are typified by the following. + +.. code-block:: ini + + [formatter_form01] + format=F1 %(asctime)s %(levelname)s %(message)s + datefmt= + class=logging.Formatter + +The ``format`` entry is the overall format string, and the ``datefmt`` entry is +the :func:`strftime`\ -compatible date/time format string. If empty, the +package substitutes something which is almost equivalent to specifying the date +format string ``'%Y-%m-%d %H:%M:%S'``. This format also specifies milliseconds, +which are appended to the result of using the above format string, with a comma +separator. An example time in this format is ``2003-01-23 00:29:50,411``. + +The ``class`` entry is optional. It indicates the name of the formatter's class +(as a dotted module and class name.) This option is useful for instantiating a +:class:`~logging.Formatter` subclass. Subclasses of +:class:`~logging.Formatter` can present exception tracebacks in an expanded or +condensed format. + +.. note:: + + Due to the use of :func:`eval` as described above, there are + potential security risks which result from using the :func:`listen` to send + and receive configurations via sockets. The risks are limited to where + multiple users with no mutual trust run code on the same machine; see the + :func:`listen` documentation for more information. + +.. seealso:: + + Module :mod:`logging` + API reference for the logging module. + + Module :mod:`logging.handlers` + Useful handlers included with the logging module. diff --git a/cpython_2/environment/repo/Doc/library/logging.handlers.rst b/cpython_2/environment/repo/Doc/library/logging.handlers.rst new file mode 100644 index 0000000000000000000000000000000000000000..059ab3d3a34448d41a7ef4ef171b8bc5bc94361e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/logging.handlers.rst @@ -0,0 +1,1129 @@ +:mod:`logging.handlers` --- Logging handlers +============================================ + +.. module:: logging.handlers + :synopsis: Handlers for the logging module. + +.. moduleauthor:: Vinay Sajip +.. sectionauthor:: Vinay Sajip + +**Source code:** :source:`Lib/logging/handlers.py` + +.. sidebar:: Important + + This page contains only reference information. For tutorials, + please see + + * :ref:`Basic Tutorial ` + * :ref:`Advanced Tutorial ` + * :ref:`Logging Cookbook ` + +-------------- + +.. currentmodule:: logging + +The following useful handlers are provided in the package. Note that three of +the handlers (:class:`StreamHandler`, :class:`FileHandler` and +:class:`NullHandler`) are actually defined in the :mod:`logging` module itself, +but have been documented here along with the other handlers. + +.. _stream-handler: + +StreamHandler +^^^^^^^^^^^^^ + +The :class:`StreamHandler` class, located in the core :mod:`logging` package, +sends logging output to streams such as *sys.stdout*, *sys.stderr* or any +file-like object (or, more precisely, any object which supports :meth:`write` +and :meth:`flush` methods). + + +.. class:: StreamHandler(stream=None) + + Returns a new instance of the :class:`StreamHandler` class. If *stream* is + specified, the instance will use it for logging output; otherwise, *sys.stderr* + will be used. + + + .. method:: emit(record) + + If a formatter is specified, it is used to format the record. The record + is then written to the stream followed by :attr:`terminator`. If exception information + is present, it is formatted using :func:`traceback.print_exception` and + appended to the stream. + + + .. method:: flush() + + Flushes the stream by calling its :meth:`flush` method. Note that the + :meth:`close` method is inherited from :class:`~logging.Handler` and so + does no output, so an explicit :meth:`flush` call may be needed at times. + + .. method:: setStream(stream) + + Sets the instance's stream to the specified value, if it is different. + The old stream is flushed before the new stream is set. + + :param stream: The stream that the handler should use. + + :return: the old stream, if the stream was changed, or *None* if it wasn't. + + .. versionadded:: 3.7 + + .. attribute:: terminator + + String used as the terminator when writing a formatted record to a stream. + Default value is ``'\n'``. + + If you don't want a newline termination, you can set the handler instance's + ``terminator`` attribute to the empty string. + + In earlier versions, the terminator was hardcoded as ``'\n'``. + + .. versionadded:: 3.2 + + +.. _file-handler: + +FileHandler +^^^^^^^^^^^ + +The :class:`FileHandler` class, located in the core :mod:`logging` package, +sends logging output to a disk file. It inherits the output functionality from +:class:`StreamHandler`. + + +.. class:: FileHandler(filename, mode='a', encoding=None, delay=False, errors=None) + + Returns a new instance of the :class:`FileHandler` class. The specified file is + opened and used as the stream for logging. If *mode* is not specified, + :const:`'a'` is used. If *encoding* is not ``None``, it is used to open the file + with that encoding. If *delay* is true, then file opening is deferred until the + first call to :meth:`emit`. By default, the file grows indefinitely. If + *errors* is specified, it's used to determine how encoding errors are handled. + + .. versionchanged:: 3.6 + As well as string values, :class:`~pathlib.Path` objects are also accepted + for the *filename* argument. + + .. versionchanged:: 3.9 + The *errors* parameter was added. + + .. method:: close() + + Closes the file. + + .. method:: emit(record) + + Outputs the record to the file. + + +.. _null-handler: + +NullHandler +^^^^^^^^^^^ + +.. versionadded:: 3.1 + +The :class:`NullHandler` class, located in the core :mod:`logging` package, +does not do any formatting or output. It is essentially a 'no-op' handler +for use by library developers. + +.. class:: NullHandler() + + Returns a new instance of the :class:`NullHandler` class. + + .. method:: emit(record) + + This method does nothing. + + .. method:: handle(record) + + This method does nothing. + + .. method:: createLock() + + This method returns ``None`` for the lock, since there is no + underlying I/O to which access needs to be serialized. + + +See :ref:`library-config` for more information on how to use +:class:`NullHandler`. + +.. _watched-file-handler: + +WatchedFileHandler +^^^^^^^^^^^^^^^^^^ + +.. currentmodule:: logging.handlers + +The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers` +module, is a :class:`FileHandler` which watches the file it is logging to. If +the file changes, it is closed and reopened using the file name. + +A file change can happen because of usage of programs such as *newsyslog* and +*logrotate* which perform log file rotation. This handler, intended for use +under Unix/Linux, watches the file to see if it has changed since the last emit. +(A file is deemed to have changed if its device or inode have changed.) If the +file has changed, the old file stream is closed, and the file opened to get a +new stream. + +This handler is not appropriate for use under Windows, because under Windows +open log files cannot be moved or renamed - logging opens the files with +exclusive locks - and so there is no need for such a handler. Furthermore, +*ST_INO* is not supported under Windows; :func:`~os.stat` always returns zero +for this value. + + +.. class:: WatchedFileHandler(filename, mode='a', encoding=None, delay=False, errors=None) + + Returns a new instance of the :class:`WatchedFileHandler` class. The specified + file is opened and used as the stream for logging. If *mode* is not specified, + :const:`'a'` is used. If *encoding* is not ``None``, it is used to open the file + with that encoding. If *delay* is true, then file opening is deferred until the + first call to :meth:`emit`. By default, the file grows indefinitely. If + *errors* is provided, it determines how encoding errors are handled. + + .. versionchanged:: 3.6 + As well as string values, :class:`~pathlib.Path` objects are also accepted + for the *filename* argument. + + .. versionchanged:: 3.9 + The *errors* parameter was added. + + .. method:: reopenIfNeeded() + + Checks to see if the file has changed. If it has, the existing stream is + flushed and closed and the file opened again, typically as a precursor to + outputting the record to the file. + + .. versionadded:: 3.6 + + + .. method:: emit(record) + + Outputs the record to the file, but first calls :meth:`reopenIfNeeded` to + reopen the file if it has changed. + +.. _base-rotating-handler: + +BaseRotatingHandler +^^^^^^^^^^^^^^^^^^^ + +The :class:`BaseRotatingHandler` class, located in the :mod:`logging.handlers` +module, is the base class for the rotating file handlers, +:class:`RotatingFileHandler` and :class:`TimedRotatingFileHandler`. You should +not need to instantiate this class, but it has attributes and methods you may +need to override. + +.. class:: BaseRotatingHandler(filename, mode, encoding=None, delay=False, errors=None) + + The parameters are as for :class:`FileHandler`. The attributes are: + + .. attribute:: namer + + If this attribute is set to a callable, the :meth:`rotation_filename` + method delegates to this callable. The parameters passed to the callable + are those passed to :meth:`rotation_filename`. + + .. note:: The namer function is called quite a few times during rollover, + so it should be as simple and as fast as possible. It should also + return the same output every time for a given input, otherwise the + rollover behaviour may not work as expected. + + .. versionadded:: 3.3 + + + .. attribute:: BaseRotatingHandler.rotator + + If this attribute is set to a callable, the :meth:`rotate` method + delegates to this callable. The parameters passed to the callable are + those passed to :meth:`rotate`. + + .. versionadded:: 3.3 + + .. method:: BaseRotatingHandler.rotation_filename(default_name) + + Modify the filename of a log file when rotating. + + This is provided so that a custom filename can be provided. + + The default implementation calls the 'namer' attribute of the handler, + if it's callable, passing the default name to it. If the attribute isn't + callable (the default is ``None``), the name is returned unchanged. + + :param default_name: The default name for the log file. + + .. versionadded:: 3.3 + + + .. method:: BaseRotatingHandler.rotate(source, dest) + + When rotating, rotate the current log. + + The default implementation calls the 'rotator' attribute of the handler, + if it's callable, passing the source and dest arguments to it. If the + attribute isn't callable (the default is ``None``), the source is simply + renamed to the destination. + + :param source: The source filename. This is normally the base + filename, e.g. 'test.log'. + :param dest: The destination filename. This is normally + what the source is rotated to, e.g. 'test.log.1'. + + .. versionadded:: 3.3 + +The reason the attributes exist is to save you having to subclass - you can use +the same callables for instances of :class:`RotatingFileHandler` and +:class:`TimedRotatingFileHandler`. If either the namer or rotator callable +raises an exception, this will be handled in the same way as any other +exception during an :meth:`emit` call, i.e. via the :meth:`handleError` method +of the handler. + +If you need to make more significant changes to rotation processing, you can +override the methods. + +For an example, see :ref:`cookbook-rotator-namer`. + + +.. _rotating-file-handler: + +RotatingFileHandler +^^^^^^^^^^^^^^^^^^^ + +The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers` +module, supports rotation of disk log files. + + +.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False, errors=None) + + Returns a new instance of the :class:`RotatingFileHandler` class. The specified + file is opened and used as the stream for logging. If *mode* is not specified, + ``'a'`` is used. If *encoding* is not ``None``, it is used to open the file + with that encoding. If *delay* is true, then file opening is deferred until the + first call to :meth:`emit`. By default, the file grows indefinitely. If + *errors* is provided, it determines how encoding errors are handled. + + You can use the *maxBytes* and *backupCount* values to allow the file to + :dfn:`rollover` at a predetermined size. When the size is about to be exceeded, + the file is closed and a new file is silently opened for output. Rollover occurs + whenever the current log file is nearly *maxBytes* in length; but if either of + *maxBytes* or *backupCount* is zero, rollover never occurs, so you generally want + to set *backupCount* to at least 1, and have a non-zero *maxBytes*. + When *backupCount* is non-zero, the system will save old log files by appending + the extensions '.1', '.2' etc., to the filename. For example, with a *backupCount* + of 5 and a base file name of :file:`app.log`, you would get :file:`app.log`, + :file:`app.log.1`, :file:`app.log.2`, up to :file:`app.log.5`. The file being + written to is always :file:`app.log`. When this file is filled, it is closed + and renamed to :file:`app.log.1`, and if files :file:`app.log.1`, + :file:`app.log.2`, etc. exist, then they are renamed to :file:`app.log.2`, + :file:`app.log.3` etc. respectively. + + .. versionchanged:: 3.6 + As well as string values, :class:`~pathlib.Path` objects are also accepted + for the *filename* argument. + + .. versionchanged:: 3.9 + The *errors* parameter was added. + + .. method:: doRollover() + + Does a rollover, as described above. + + + .. method:: emit(record) + + Outputs the record to the file, catering for rollover as described + previously. + +.. _timed-rotating-file-handler: + +TimedRotatingFileHandler +^^^^^^^^^^^^^^^^^^^^^^^^ + +The :class:`TimedRotatingFileHandler` class, located in the +:mod:`logging.handlers` module, supports rotation of disk log files at certain +timed intervals. + + +.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None, errors=None) + + Returns a new instance of the :class:`TimedRotatingFileHandler` class. The + specified file is opened and used as the stream for logging. On rotating it also + sets the filename suffix. Rotating happens based on the product of *when* and + *interval*. + + You can use the *when* to specify the type of *interval*. The list of possible + values is below. Note that they are not case sensitive. + + +----------------+----------------------------+-------------------------+ + | Value | Type of interval | If/how *atTime* is used | + +================+============================+=========================+ + | ``'S'`` | Seconds | Ignored | + +----------------+----------------------------+-------------------------+ + | ``'M'`` | Minutes | Ignored | + +----------------+----------------------------+-------------------------+ + | ``'H'`` | Hours | Ignored | + +----------------+----------------------------+-------------------------+ + | ``'D'`` | Days | Ignored | + +----------------+----------------------------+-------------------------+ + | ``'W0'-'W6'`` | Weekday (0=Monday) | Used to compute initial | + | | | rollover time | + +----------------+----------------------------+-------------------------+ + | ``'midnight'`` | Roll over at midnight, if | Used to compute initial | + | | *atTime* not specified, | rollover time | + | | else at time *atTime* | | + +----------------+----------------------------+-------------------------+ + + When using weekday-based rotation, specify 'W0' for Monday, 'W1' for + Tuesday, and so on up to 'W6' for Sunday. In this case, the value passed for + *interval* isn't used. + + The system will save old log files by appending extensions to the filename. + The extensions are date-and-time based, using the strftime format + ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the + rollover interval. + + When computing the next rollover time for the first time (when the handler + is created), the last modification time of an existing log file, or else + the current time, is used to compute when the next rotation will occur. + + If the *utc* argument is true, times in UTC will be used; otherwise + local time is used. + + If *backupCount* is nonzero, at most *backupCount* files + will be kept, and if more would be created when rollover occurs, the oldest + one is deleted. The deletion logic uses the interval to determine which + files to delete, so changing the interval may leave old files lying around. + + If *delay* is true, then file opening is deferred until the first call to + :meth:`emit`. + + If *atTime* is not ``None``, it must be a ``datetime.time`` instance which + specifies the time of day when rollover occurs, for the cases where rollover + is set to happen "at midnight" or "on a particular weekday". Note that in + these cases, the *atTime* value is effectively used to compute the *initial* + rollover, and subsequent rollovers would be calculated via the normal + interval calculation. + + If *errors* is specified, it's used to determine how encoding errors are + handled. + + .. note:: Calculation of the initial rollover time is done when the handler + is initialised. Calculation of subsequent rollover times is done only + when rollover occurs, and rollover occurs only when emitting output. If + this is not kept in mind, it might lead to some confusion. For example, + if an interval of "every minute" is set, that does not mean you will + always see log files with times (in the filename) separated by a minute; + if, during application execution, logging output is generated more + frequently than once a minute, *then* you can expect to see log files + with times separated by a minute. If, on the other hand, logging messages + are only output once every five minutes (say), then there will be gaps in + the file times corresponding to the minutes where no output (and hence no + rollover) occurred. + + .. versionchanged:: 3.4 + *atTime* parameter was added. + + .. versionchanged:: 3.6 + As well as string values, :class:`~pathlib.Path` objects are also accepted + for the *filename* argument. + + .. versionchanged:: 3.9 + The *errors* parameter was added. + + .. method:: doRollover() + + Does a rollover, as described above. + + .. method:: emit(record) + + Outputs the record to the file, catering for rollover as described above. + + +.. _socket-handler: + +SocketHandler +^^^^^^^^^^^^^ + +The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module, +sends logging output to a network socket. The base class uses a TCP socket. + + +.. class:: SocketHandler(host, port) + + Returns a new instance of the :class:`SocketHandler` class intended to + communicate with a remote machine whose address is given by *host* and *port*. + + .. versionchanged:: 3.4 + If ``port`` is specified as ``None``, a Unix domain socket is created + using the value in ``host`` - otherwise, a TCP socket is created. + + .. method:: close() + + Closes the socket. + + + .. method:: emit() + + Pickles the record's attribute dictionary and writes it to the socket in + binary format. If there is an error with the socket, silently drops the + packet. If the connection was previously lost, re-establishes the + connection. To unpickle the record at the receiving end into a + :class:`~logging.LogRecord`, use the :func:`~logging.makeLogRecord` + function. + + + .. method:: handleError() + + Handles an error which has occurred during :meth:`emit`. The most likely + cause is a lost connection. Closes the socket so that we can retry on the + next event. + + + .. method:: makeSocket() + + This is a factory method which allows subclasses to define the precise + type of socket they want. The default implementation creates a TCP socket + (:const:`socket.SOCK_STREAM`). + + + .. method:: makePickle(record) + + Pickles the record's attribute dictionary in binary format with a length + prefix, and returns it ready for transmission across the socket. The + details of this operation are equivalent to:: + + data = pickle.dumps(record_attr_dict, 1) + datalen = struct.pack('>L', len(data)) + return datalen + data + + Note that pickles aren't completely secure. If you are concerned about + security, you may want to override this method to implement a more secure + mechanism. For example, you can sign pickles using HMAC and then verify + them on the receiving end, or alternatively you can disable unpickling of + global objects on the receiving end. + + + .. method:: send(packet) + + Send a pickled byte-string *packet* to the socket. The format of the sent + byte-string is as described in the documentation for + :meth:`~SocketHandler.makePickle`. + + This function allows for partial sends, which can happen when the network + is busy. + + + .. method:: createSocket() + + Tries to create a socket; on failure, uses an exponential back-off + algorithm. On initial failure, the handler will drop the message it was + trying to send. When subsequent messages are handled by the same + instance, it will not try connecting until some time has passed. The + default parameters are such that the initial delay is one second, and if + after that delay the connection still can't be made, the handler will + double the delay each time up to a maximum of 30 seconds. + + This behaviour is controlled by the following handler attributes: + + * ``retryStart`` (initial delay, defaulting to 1.0 seconds). + * ``retryFactor`` (multiplier, defaulting to 2.0). + * ``retryMax`` (maximum delay, defaulting to 30.0 seconds). + + This means that if the remote listener starts up *after* the handler has + been used, you could lose messages (since the handler won't even attempt + a connection until the delay has elapsed, but just silently drop messages + during the delay period). + + +.. _datagram-handler: + +DatagramHandler +^^^^^^^^^^^^^^^ + +The :class:`DatagramHandler` class, located in the :mod:`logging.handlers` +module, inherits from :class:`SocketHandler` to support sending logging messages +over UDP sockets. + + +.. class:: DatagramHandler(host, port) + + Returns a new instance of the :class:`DatagramHandler` class intended to + communicate with a remote machine whose address is given by *host* and *port*. + + .. versionchanged:: 3.4 + If ``port`` is specified as ``None``, a Unix domain socket is created + using the value in ``host`` - otherwise, a UDP socket is created. + + .. method:: emit() + + Pickles the record's attribute dictionary and writes it to the socket in + binary format. If there is an error with the socket, silently drops the + packet. To unpickle the record at the receiving end into a + :class:`~logging.LogRecord`, use the :func:`~logging.makeLogRecord` + function. + + + .. method:: makeSocket() + + The factory method of :class:`SocketHandler` is here overridden to create + a UDP socket (:const:`socket.SOCK_DGRAM`). + + + .. method:: send(s) + + Send a pickled byte-string to a socket. The format of the sent byte-string + is as described in the documentation for :meth:`SocketHandler.makePickle`. + + +.. _syslog-handler: + +SysLogHandler +^^^^^^^^^^^^^ + +The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module, +supports sending logging messages to a remote or local Unix syslog. + + +.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM) + + Returns a new instance of the :class:`SysLogHandler` class intended to + communicate with a remote Unix machine whose address is given by *address* in + the form of a ``(host, port)`` tuple. If *address* is not specified, + ``('localhost', 514)`` is used. The address is used to open a socket. An + alternative to providing a ``(host, port)`` tuple is providing an address as a + string, for example '/dev/log'. In this case, a Unix domain socket is used to + send the message to the syslog. If *facility* is not specified, + :const:`LOG_USER` is used. The type of socket opened depends on the + *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus + opens a UDP socket. To open a TCP socket (for use with the newer syslog + daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`. + + Note that if your server is not listening on UDP port 514, + :class:`SysLogHandler` may appear not to work. In that case, check what + address you should be using for a domain socket - it's system dependent. + For example, on Linux it's usually '/dev/log' but on OS/X it's + '/var/run/syslog'. You'll need to check your platform and use the + appropriate address (you may need to do this check at runtime if your + application needs to run on several platforms). On Windows, you pretty + much have to use the UDP option. + + .. versionchanged:: 3.2 + *socktype* was added. + + + .. method:: close() + + Closes the socket to the remote host. + + + .. method:: emit(record) + + The record is formatted, and then sent to the syslog server. If exception + information is present, it is *not* sent to the server. + + .. versionchanged:: 3.2.1 + (See: :issue:`12168`.) In earlier versions, the message sent to the + syslog daemons was always terminated with a NUL byte, because early + versions of these daemons expected a NUL terminated message - even + though it's not in the relevant specification (:rfc:`5424`). More recent + versions of these daemons don't expect the NUL byte but strip it off + if it's there, and even more recent daemons (which adhere more closely + to RFC 5424) pass the NUL byte on as part of the message. + + To enable easier handling of syslog messages in the face of all these + differing daemon behaviours, the appending of the NUL byte has been + made configurable, through the use of a class-level attribute, + ``append_nul``. This defaults to ``True`` (preserving the existing + behaviour) but can be set to ``False`` on a ``SysLogHandler`` instance + in order for that instance to *not* append the NUL terminator. + + .. versionchanged:: 3.3 + (See: :issue:`12419`.) In earlier versions, there was no facility for + an "ident" or "tag" prefix to identify the source of the message. This + can now be specified using a class-level attribute, defaulting to + ``""`` to preserve existing behaviour, but which can be overridden on + a ``SysLogHandler`` instance in order for that instance to prepend + the ident to every message handled. Note that the provided ident must + be text, not bytes, and is prepended to the message exactly as is. + + .. method:: encodePriority(facility, priority) + + Encodes the facility and priority into an integer. You can pass in strings + or integers - if strings are passed, internal mapping dictionaries are + used to convert them to integers. + + The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and + mirror the values defined in the ``sys/syslog.h`` header file. + + **Priorities** + + +--------------------------+---------------+ + | Name (string) | Symbolic value| + +==========================+===============+ + | ``alert`` | LOG_ALERT | + +--------------------------+---------------+ + | ``crit`` or ``critical`` | LOG_CRIT | + +--------------------------+---------------+ + | ``debug`` | LOG_DEBUG | + +--------------------------+---------------+ + | ``emerg`` or ``panic`` | LOG_EMERG | + +--------------------------+---------------+ + | ``err`` or ``error`` | LOG_ERR | + +--------------------------+---------------+ + | ``info`` | LOG_INFO | + +--------------------------+---------------+ + | ``notice`` | LOG_NOTICE | + +--------------------------+---------------+ + | ``warn`` or ``warning`` | LOG_WARNING | + +--------------------------+---------------+ + + **Facilities** + + +---------------+---------------+ + | Name (string) | Symbolic value| + +===============+===============+ + | ``auth`` | LOG_AUTH | + +---------------+---------------+ + | ``authpriv`` | LOG_AUTHPRIV | + +---------------+---------------+ + | ``cron`` | LOG_CRON | + +---------------+---------------+ + | ``daemon`` | LOG_DAEMON | + +---------------+---------------+ + | ``ftp`` | LOG_FTP | + +---------------+---------------+ + | ``kern`` | LOG_KERN | + +---------------+---------------+ + | ``lpr`` | LOG_LPR | + +---------------+---------------+ + | ``mail`` | LOG_MAIL | + +---------------+---------------+ + | ``news`` | LOG_NEWS | + +---------------+---------------+ + | ``syslog`` | LOG_SYSLOG | + +---------------+---------------+ + | ``user`` | LOG_USER | + +---------------+---------------+ + | ``uucp`` | LOG_UUCP | + +---------------+---------------+ + | ``local0`` | LOG_LOCAL0 | + +---------------+---------------+ + | ``local1`` | LOG_LOCAL1 | + +---------------+---------------+ + | ``local2`` | LOG_LOCAL2 | + +---------------+---------------+ + | ``local3`` | LOG_LOCAL3 | + +---------------+---------------+ + | ``local4`` | LOG_LOCAL4 | + +---------------+---------------+ + | ``local5`` | LOG_LOCAL5 | + +---------------+---------------+ + | ``local6`` | LOG_LOCAL6 | + +---------------+---------------+ + | ``local7`` | LOG_LOCAL7 | + +---------------+---------------+ + + .. method:: mapPriority(levelname) + + Maps a logging level name to a syslog priority name. + You may need to override this if you are using custom levels, or + if the default algorithm is not suitable for your needs. The + default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and + ``CRITICAL`` to the equivalent syslog names, and all other level + names to 'warning'. + +.. _nt-eventlog-handler: + +NTEventLogHandler +^^^^^^^^^^^^^^^^^ + +The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers` +module, supports sending logging messages to a local Windows NT, Windows 2000 or +Windows XP event log. Before you can use it, you need Mark Hammond's Win32 +extensions for Python installed. + + +.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application') + + Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is + used to define the application name as it appears in the event log. An + appropriate registry entry is created using this name. The *dllname* should give + the fully qualified pathname of a .dll or .exe which contains message + definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used + - this is installed with the Win32 extensions and contains some basic + placeholder message definitions. Note that use of these placeholders will make + your event logs big, as the entire message source is held in the log. If you + want slimmer logs, you have to pass in the name of your own .dll or .exe which + contains the message definitions you want to use in the event log). The + *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and + defaults to ``'Application'``. + + + .. method:: close() + + At this point, you can remove the application name from the registry as a + source of event log entries. However, if you do this, you will not be able + to see the events as you intended in the Event Log Viewer - it needs to be + able to access the registry to get the .dll name. The current version does + not do this. + + + .. method:: emit(record) + + Determines the message ID, event category and event type, and then logs + the message in the NT event log. + + + .. method:: getEventCategory(record) + + Returns the event category for the record. Override this if you want to + specify your own categories. This version returns 0. + + + .. method:: getEventType(record) + + Returns the event type for the record. Override this if you want to + specify your own types. This version does a mapping using the handler's + typemap attribute, which is set up in :meth:`__init__` to a dictionary + which contains mappings for :const:`DEBUG`, :const:`INFO`, + :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using + your own levels, you will either need to override this method or place a + suitable dictionary in the handler's *typemap* attribute. + + + .. method:: getMessageID(record) + + Returns the message ID for the record. If you are using your own messages, + you could do this by having the *msg* passed to the logger being an ID + rather than a format string. Then, in here, you could use a dictionary + lookup to get the message ID. This version returns 1, which is the base + message ID in :file:`win32service.pyd`. + +.. _smtp-handler: + +SMTPHandler +^^^^^^^^^^^ + +The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module, +supports sending logging messages to an email address via SMTP. + + +.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0) + + Returns a new instance of the :class:`SMTPHandler` class. The instance is + initialized with the from and to addresses and subject line of the email. The + *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use + the (host, port) tuple format for the *mailhost* argument. If you use a string, + the standard SMTP port is used. If your SMTP server requires authentication, you + can specify a (username, password) tuple for the *credentials* argument. + + To specify the use of a secure protocol (TLS), pass in a tuple to the + *secure* argument. This will only be used when authentication credentials are + supplied. The tuple should be either an empty tuple, or a single-value tuple + with the name of a keyfile, or a 2-value tuple with the names of the keyfile + and certificate file. (This tuple is passed to the + :meth:`smtplib.SMTP.starttls` method.) + + A timeout can be specified for communication with the SMTP server using the + *timeout* argument. + + .. versionadded:: 3.3 + The *timeout* argument was added. + + .. method:: emit(record) + + Formats the record and sends it to the specified addressees. + + + .. method:: getSubject(record) + + If you want to specify a subject line which is record-dependent, override + this method. + +.. _memory-handler: + +MemoryHandler +^^^^^^^^^^^^^ + +The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module, +supports buffering of logging records in memory, periodically flushing them to a +:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an +event of a certain severity or greater is seen. + +:class:`MemoryHandler` is a subclass of the more general +:class:`BufferingHandler`, which is an abstract class. This buffers logging +records in memory. Whenever each record is added to the buffer, a check is made +by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it +should, then :meth:`flush` is expected to do the flushing. + + +.. class:: BufferingHandler(capacity) + + Initializes the handler with a buffer of the specified capacity. Here, + *capacity* means the number of logging records buffered. + + + .. method:: emit(record) + + Append the record to the buffer. If :meth:`shouldFlush` returns true, + call :meth:`flush` to process the buffer. + + + .. method:: flush() + + You can override this to implement custom flushing behavior. This version + just zaps the buffer to empty. + + + .. method:: shouldFlush(record) + + Return ``True`` if the buffer is up to capacity. This method can be + overridden to implement custom flushing strategies. + + +.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None, flushOnClose=True) + + Returns a new instance of the :class:`MemoryHandler` class. The instance is + initialized with a buffer size of *capacity* (number of records buffered). + If *flushLevel* is not specified, :const:`ERROR` is used. If no *target* is + specified, the target will need to be set using :meth:`setTarget` before this + handler does anything useful. If *flushOnClose* is specified as ``False``, + then the buffer is *not* flushed when the handler is closed. If not specified + or specified as ``True``, the previous behaviour of flushing the buffer will + occur when the handler is closed. + + .. versionchanged:: 3.6 + The *flushOnClose* parameter was added. + + + .. method:: close() + + Calls :meth:`flush`, sets the target to ``None`` and clears the + buffer. + + + .. method:: flush() + + For a :class:`MemoryHandler`, flushing means just sending the buffered + records to the target, if there is one. The buffer is also cleared when + this happens. Override if you want different behavior. + + + .. method:: setTarget(target) + + Sets the target handler for this handler. + + + .. method:: shouldFlush(record) + + Checks for buffer full or a record at the *flushLevel* or higher. + + +.. _http-handler: + +HTTPHandler +^^^^^^^^^^^ + +The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module, +supports sending logging messages to a Web server, using either ``GET`` or +``POST`` semantics. + + +.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None, context=None) + + Returns a new instance of the :class:`HTTPHandler` class. The *host* can be + of the form ``host:port``, should you need to use a specific port number. If + no *method* is specified, ``GET`` is used. If *secure* is true, a HTTPS + connection will be used. The *context* parameter may be set to a + :class:`ssl.SSLContext` instance to configure the SSL settings used for the + HTTPS connection. If *credentials* is specified, it should be a 2-tuple + consisting of userid and password, which will be placed in a HTTP + 'Authorization' header using Basic authentication. If you specify + credentials, you should also specify secure=True so that your userid and + password are not passed in cleartext across the wire. + + .. versionchanged:: 3.5 + The *context* parameter was added. + + .. method:: mapLogRecord(record) + + Provides a dictionary, based on ``record``, which is to be URL-encoded + and sent to the web server. The default implementation just returns + ``record.__dict__``. This method can be overridden if e.g. only a + subset of :class:`~logging.LogRecord` is to be sent to the web server, or + if more specific customization of what's sent to the server is required. + + .. method:: emit(record) + + Sends the record to the Web server as a URL-encoded dictionary. The + :meth:`mapLogRecord` method is used to convert the record to the + dictionary to be sent. + + .. note:: Since preparing a record for sending it to a Web server is not + the same as a generic formatting operation, using + :meth:`~logging.Handler.setFormatter` to specify a + :class:`~logging.Formatter` for a :class:`HTTPHandler` has no effect. + Instead of calling :meth:`~logging.Handler.format`, this handler calls + :meth:`mapLogRecord` and then :func:`urllib.parse.urlencode` to encode the + dictionary in a form suitable for sending to a Web server. + + +.. _queue-handler: + + +QueueHandler +^^^^^^^^^^^^ + +.. versionadded:: 3.2 + +The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module, +supports sending logging messages to a queue, such as those implemented in the +:mod:`queue` or :mod:`multiprocessing` modules. + +Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used +to let handlers do their work on a separate thread from the one which does the +logging. This is important in Web applications and also other service +applications where threads servicing clients need to respond as quickly as +possible, while any potentially slow operations (such as sending an email via +:class:`SMTPHandler`) are done on a separate thread. + +.. class:: QueueHandler(queue) + + Returns a new instance of the :class:`QueueHandler` class. The instance is + initialized with the queue to send messages to. The *queue* can be any + queue-like object; it's used as-is by the :meth:`enqueue` method, which + needs to know how to send messages to it. The queue is not *required* to + have the task tracking API, which means that you can use + :class:`~queue.SimpleQueue` instances for *queue*. + + + .. method:: emit(record) + + Enqueues the result of preparing the LogRecord. Should an exception + occur (e.g. because a bounded queue has filled up), the + :meth:`~logging.Handler.handleError` method is called to handle the + error. This can result in the record silently being dropped (if + :attr:`logging.raiseExceptions` is ``False``) or a message printed to + ``sys.stderr`` (if :attr:`logging.raiseExceptions` is ``True``). + + .. method:: prepare(record) + + Prepares a record for queuing. The object returned by this + method is enqueued. + + The base implementation formats the record to merge the message, + arguments, and exception information, if present. It also + removes unpickleable items from the record in-place. + + You might want to override this method if you want to convert + the record to a dict or JSON string, or send a modified copy + of the record while leaving the original intact. + + .. method:: enqueue(record) + + Enqueues the record on the queue using ``put_nowait()``; you may + want to override this if you want to use blocking behaviour, or a + timeout, or a customized queue implementation. + + + +.. _queue-listener: + +QueueListener +^^^^^^^^^^^^^ + +.. versionadded:: 3.2 + +The :class:`QueueListener` class, located in the :mod:`logging.handlers` +module, supports receiving logging messages from a queue, such as those +implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The +messages are received from a queue in an internal thread and passed, on +the same thread, to one or more handlers for processing. While +:class:`QueueListener` is not itself a handler, it is documented here +because it works hand-in-hand with :class:`QueueHandler`. + +Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used +to let handlers do their work on a separate thread from the one which does the +logging. This is important in Web applications and also other service +applications where threads servicing clients need to respond as quickly as +possible, while any potentially slow operations (such as sending an email via +:class:`SMTPHandler`) are done on a separate thread. + +.. class:: QueueListener(queue, *handlers, respect_handler_level=False) + + Returns a new instance of the :class:`QueueListener` class. The instance is + initialized with the queue to send messages to and a list of handlers which + will handle entries placed on the queue. The queue can be any queue-like + object; it's passed as-is to the :meth:`dequeue` method, which needs + to know how to get messages from it. The queue is not *required* to have the + task tracking API (though it's used if available), which means that you can + use :class:`~queue.SimpleQueue` instances for *queue*. + + If ``respect_handler_level`` is ``True``, a handler's level is respected + (compared with the level for the message) when deciding whether to pass + messages to that handler; otherwise, the behaviour is as in previous Python + versions - to always pass each message to each handler. + + .. versionchanged:: 3.5 + The ``respect_handler_level`` argument was added. + + .. method:: dequeue(block) + + Dequeues a record and return it, optionally blocking. + + The base implementation uses ``get()``. You may want to override this + method if you want to use timeouts or work with custom queue + implementations. + + .. method:: prepare(record) + + Prepare a record for handling. + + This implementation just returns the passed-in record. You may want to + override this method if you need to do any custom marshalling or + manipulation of the record before passing it to the handlers. + + .. method:: handle(record) + + Handle a record. + + This just loops through the handlers offering them the record + to handle. The actual object passed to the handlers is that which + is returned from :meth:`prepare`. + + .. method:: start() + + Starts the listener. + + This starts up a background thread to monitor the queue for + LogRecords to process. + + .. method:: stop() + + Stops the listener. + + This asks the thread to terminate, and then waits for it to do so. + Note that if you don't call this before your application exits, there + may be some records still left on the queue, which won't be processed. + + .. method:: enqueue_sentinel() + + Writes a sentinel to the queue to tell the listener to quit. This + implementation uses ``put_nowait()``. You may want to override this + method if you want to use timeouts or work with custom queue + implementations. + + .. versionadded:: 3.3 + + +.. seealso:: + + Module :mod:`logging` + API reference for the logging module. + + Module :mod:`logging.config` + Configuration API for the logging module. + + diff --git a/cpython_2/environment/repo/Doc/library/logging.rst b/cpython_2/environment/repo/Doc/library/logging.rst new file mode 100644 index 0000000000000000000000000000000000000000..7267f812cc1925bdea4a9c14f5e7e514c3632194 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/logging.rst @@ -0,0 +1,1340 @@ +:mod:`logging` --- Logging facility for Python +============================================== + +.. module:: logging + :synopsis: Flexible event logging system for applications. + +.. moduleauthor:: Vinay Sajip +.. sectionauthor:: Vinay Sajip + +**Source code:** :source:`Lib/logging/__init__.py` + +.. index:: pair: Errors; logging + +.. sidebar:: Important + + This page contains the API reference information. For tutorial + information and discussion of more advanced topics, see + + * :ref:`Basic Tutorial ` + * :ref:`Advanced Tutorial ` + * :ref:`Logging Cookbook ` + +-------------- + +This module defines functions and classes which implement a flexible event +logging system for applications and libraries. + +The key benefit of having the logging API provided by a standard library module +is that all Python modules can participate in logging, so your application log +can include your own messages integrated with messages from third-party +modules. + +The module provides a lot of functionality and flexibility. If you are +unfamiliar with logging, the best way to get to grips with it is to see the +tutorials (see the links on the right). + +The basic classes defined by the module, together with their functions, are +listed below. + +* Loggers expose the interface that application code directly uses. +* Handlers send the log records (created by loggers) to the appropriate + destination. +* Filters provide a finer grained facility for determining which log records + to output. +* Formatters specify the layout of log records in the final output. + + +.. _logger: + +Logger Objects +-------------- + +Loggers have the following attributes and methods. Note that Loggers should +*NEVER* be instantiated directly, but always through the module-level function +``logging.getLogger(name)``. Multiple calls to :func:`getLogger` with the same +name will always return a reference to the same Logger object. + +The ``name`` is potentially a period-separated hierarchical value, like +``foo.bar.baz`` (though it could also be just plain ``foo``, for example). +Loggers that are further down in the hierarchical list are children of loggers +higher up in the list. For example, given a logger with a name of ``foo``, +loggers with names of ``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all +descendants of ``foo``. The logger name hierarchy is analogous to the Python +package hierarchy, and identical to it if you organise your loggers on a +per-module basis using the recommended construction +``logging.getLogger(__name__)``. That's because in a module, ``__name__`` +is the module's name in the Python package namespace. + + +.. class:: Logger + + .. attribute:: Logger.propagate + + If this attribute evaluates to true, events logged to this logger will be + passed to the handlers of higher level (ancestor) loggers, in addition to + any handlers attached to this logger. Messages are passed directly to the + ancestor loggers' handlers - neither the level nor filters of the ancestor + loggers in question are considered. + + If this evaluates to false, logging messages are not passed to the handlers + of ancestor loggers. + + The constructor sets this attribute to ``True``. + + .. note:: If you attach a handler to a logger *and* one or more of its + ancestors, it may emit the same record multiple times. In general, you + should not need to attach a handler to more than one logger - if you just + attach it to the appropriate logger which is highest in the logger + hierarchy, then it will see all events logged by all descendant loggers, + provided that their propagate setting is left set to ``True``. A common + scenario is to attach handlers only to the root logger, and to let + propagation take care of the rest. + + .. method:: Logger.setLevel(level) + + Sets the threshold for this logger to *level*. Logging messages which are less + severe than *level* will be ignored; logging messages which have severity *level* + or higher will be emitted by whichever handler or handlers service this logger, + unless a handler's level has been set to a higher severity level than *level*. + + When a logger is created, the level is set to :const:`NOTSET` (which causes + all messages to be processed when the logger is the root logger, or delegation + to the parent when the logger is a non-root logger). Note that the root logger + is created with level :const:`WARNING`. + + The term 'delegation to the parent' means that if a logger has a level of + NOTSET, its chain of ancestor loggers is traversed until either an ancestor with + a level other than NOTSET is found, or the root is reached. + + If an ancestor is found with a level other than NOTSET, then that ancestor's + level is treated as the effective level of the logger where the ancestor search + began, and is used to determine how a logging event is handled. + + If the root is reached, and it has a level of NOTSET, then all messages will be + processed. Otherwise, the root's level will be used as the effective level. + + See :ref:`levels` for a list of levels. + + .. versionchanged:: 3.2 + The *level* parameter now accepts a string representation of the + level such as 'INFO' as an alternative to the integer constants + such as :const:`INFO`. Note, however, that levels are internally stored + as integers, and methods such as e.g. :meth:`getEffectiveLevel` and + :meth:`isEnabledFor` will return/expect to be passed integers. + + + .. method:: Logger.isEnabledFor(level) + + Indicates if a message of severity *level* would be processed by this logger. + This method checks first the module-level level set by + ``logging.disable(level)`` and then the logger's effective level as determined + by :meth:`getEffectiveLevel`. + + + .. method:: Logger.getEffectiveLevel() + + Indicates the effective level for this logger. If a value other than + :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise, + the hierarchy is traversed towards the root until a value other than + :const:`NOTSET` is found, and that value is returned. The value returned is + an integer, typically one of :const:`logging.DEBUG`, :const:`logging.INFO` + etc. + + + .. method:: Logger.getChild(suffix) + + Returns a logger which is a descendant to this logger, as determined by the suffix. + Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same + logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a + convenience method, useful when the parent logger is named using e.g. ``__name__`` + rather than a literal string. + + .. versionadded:: 3.2 + + + .. method:: Logger.debug(msg, *args, **kwargs) + + Logs a message with level :const:`DEBUG` on this logger. The *msg* is the + message format string, and the *args* are the arguments which are merged into + *msg* using the string formatting operator. (Note that this means that you can + use keywords in the format string, together with a single dictionary argument.) + No % formatting operation is performed on *msg* when no *args* are supplied. + + There are four keyword arguments in *kwargs* which are inspected: + *exc_info*, *stack_info*, *stacklevel* and *extra*. + + If *exc_info* does not evaluate as false, it causes exception information to be + added to the logging message. If an exception tuple (in the format returned by + :func:`sys.exc_info`) or an exception instance is provided, it is used; + otherwise, :func:`sys.exc_info` is called to get the exception information. + + The second optional keyword argument is *stack_info*, which defaults to + ``False``. If true, stack information is added to the logging + message, including the actual logging call. Note that this is not the same + stack information as that displayed through specifying *exc_info*: The + former is stack frames from the bottom of the stack up to the logging call + in the current thread, whereas the latter is information about stack frames + which have been unwound, following an exception, while searching for + exception handlers. + + You can specify *stack_info* independently of *exc_info*, e.g. to just show + how you got to a certain point in your code, even when no exceptions were + raised. The stack frames are printed following a header line which says: + + .. code-block:: none + + Stack (most recent call last): + + This mimics the ``Traceback (most recent call last):`` which is used when + displaying exception frames. + + The third optional keyword argument is *stacklevel*, which defaults to ``1``. + If greater than 1, the corresponding number of stack frames are skipped + when computing the line number and function name set in the :class:`LogRecord` + created for the logging event. This can be used in logging helpers so that + the function name, filename and line number recorded are not the information + for the helper function/method, but rather its caller. The name of this + parameter mirrors the equivalent one in the :mod:`warnings` module. + + The fourth keyword argument is *extra* which can be used to pass a + dictionary which is used to populate the __dict__ of the :class:`LogRecord` + created for the logging event with user-defined attributes. These custom + attributes can then be used as you like. For example, they could be + incorporated into logged messages. For example:: + + FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s' + logging.basicConfig(format=FORMAT) + d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} + logger = logging.getLogger('tcpserver') + logger.warning('Protocol problem: %s', 'connection reset', extra=d) + + would print something like + + .. code-block:: none + + 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset + + The keys in the dictionary passed in *extra* should not clash with the keys used + by the logging system. (See the :class:`Formatter` documentation for more + information on which keys are used by the logging system.) + + If you choose to use these attributes in logged messages, you need to exercise + some care. In the above example, for instance, the :class:`Formatter` has been + set up with a format string which expects 'clientip' and 'user' in the attribute + dictionary of the :class:`LogRecord`. If these are missing, the message will + not be logged because a string formatting exception will occur. So in this case, + you always need to pass the *extra* dictionary with these keys. + + While this might be annoying, this feature is intended for use in specialized + circumstances, such as multi-threaded servers where the same code executes in + many contexts, and interesting conditions which arise are dependent on this + context (such as remote client IP address and authenticated user name, in the + above example). In such circumstances, it is likely that specialized + :class:`Formatter`\ s would be used with particular :class:`Handler`\ s. + + .. versionchanged:: 3.2 + The *stack_info* parameter was added. + + .. versionchanged:: 3.5 + The *exc_info* parameter can now accept exception instances. + + .. versionchanged:: 3.8 + The *stacklevel* parameter was added. + + + .. method:: Logger.info(msg, *args, **kwargs) + + Logs a message with level :const:`INFO` on this logger. The arguments are + interpreted as for :meth:`debug`. + + + .. method:: Logger.warning(msg, *args, **kwargs) + + Logs a message with level :const:`WARNING` on this logger. The arguments are + interpreted as for :meth:`debug`. + + .. note:: There is an obsolete method ``warn`` which is functionally + identical to ``warning``. As ``warn`` is deprecated, please do not use + it - use ``warning`` instead. + + .. method:: Logger.error(msg, *args, **kwargs) + + Logs a message with level :const:`ERROR` on this logger. The arguments are + interpreted as for :meth:`debug`. + + + .. method:: Logger.critical(msg, *args, **kwargs) + + Logs a message with level :const:`CRITICAL` on this logger. The arguments are + interpreted as for :meth:`debug`. + + + .. method:: Logger.log(level, msg, *args, **kwargs) + + Logs a message with integer level *level* on this logger. The other arguments are + interpreted as for :meth:`debug`. + + + .. method:: Logger.exception(msg, *args, **kwargs) + + Logs a message with level :const:`ERROR` on this logger. The arguments are + interpreted as for :meth:`debug`. Exception info is added to the logging + message. This method should only be called from an exception handler. + + + .. method:: Logger.addFilter(filter) + + Adds the specified filter *filter* to this logger. + + + .. method:: Logger.removeFilter(filter) + + Removes the specified filter *filter* from this logger. + + + .. method:: Logger.filter(record) + + Apply this logger's filters to the record and return ``True`` if the + record is to be processed. The filters are consulted in turn, until one of + them returns a false value. If none of them return a false value, the record + will be processed (passed to handlers). If one returns a false value, no + further processing of the record occurs. + + + .. method:: Logger.addHandler(hdlr) + + Adds the specified handler *hdlr* to this logger. + + + .. method:: Logger.removeHandler(hdlr) + + Removes the specified handler *hdlr* from this logger. + + + .. method:: Logger.findCaller(stack_info=False, stacklevel=1) + + Finds the caller's source filename and line number. Returns the filename, line + number, function name and stack information as a 4-element tuple. The stack + information is returned as ``None`` unless *stack_info* is ``True``. + + The *stacklevel* parameter is passed from code calling the :meth:`debug` + and other APIs. If greater than 1, the excess is used to skip stack frames + before determining the values to be returned. This will generally be useful + when calling logging APIs from helper/wrapper code, so that the information + in the event log refers not to the helper/wrapper code, but to the code that + calls it. + + + .. method:: Logger.handle(record) + + Handles a record by passing it to all handlers associated with this logger and + its ancestors (until a false value of *propagate* is found). This method is used + for unpickled records received from a socket, as well as those created locally. + Logger-level filtering is applied using :meth:`~Logger.filter`. + + + .. method:: Logger.makeRecord(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None) + + This is a factory method which can be overridden in subclasses to create + specialized :class:`LogRecord` instances. + + .. method:: Logger.hasHandlers() + + Checks to see if this logger has any handlers configured. This is done by + looking for handlers in this logger and its parents in the logger hierarchy. + Returns ``True`` if a handler was found, else ``False``. The method stops searching + up the hierarchy whenever a logger with the 'propagate' attribute set to + false is found - that will be the last logger which is checked for the + existence of handlers. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.7 + Loggers can now be pickled and unpickled. + +.. _levels: + +Logging Levels +-------------- + +The numeric values of logging levels are given in the following table. These are +primarily of interest if you want to define your own levels, and need them to +have specific values relative to the predefined levels. If you define a level +with the same numeric value, it overwrites the predefined value; the predefined +name is lost. + ++--------------+---------------+ +| Level | Numeric value | ++==============+===============+ +| ``CRITICAL`` | 50 | ++--------------+---------------+ +| ``ERROR`` | 40 | ++--------------+---------------+ +| ``WARNING`` | 30 | ++--------------+---------------+ +| ``INFO`` | 20 | ++--------------+---------------+ +| ``DEBUG`` | 10 | ++--------------+---------------+ +| ``NOTSET`` | 0 | ++--------------+---------------+ + + +.. _handler: + +Handler Objects +--------------- + +Handlers have the following attributes and methods. Note that :class:`Handler` +is never instantiated directly; this class acts as a base for more useful +subclasses. However, the :meth:`__init__` method in subclasses needs to call +:meth:`Handler.__init__`. + +.. class:: Handler + + .. method:: Handler.__init__(level=NOTSET) + + Initializes the :class:`Handler` instance by setting its level, setting the list + of filters to the empty list and creating a lock (using :meth:`createLock`) for + serializing access to an I/O mechanism. + + + .. method:: Handler.createLock() + + Initializes a thread lock which can be used to serialize access to underlying + I/O functionality which may not be threadsafe. + + + .. method:: Handler.acquire() + + Acquires the thread lock created with :meth:`createLock`. + + + .. method:: Handler.release() + + Releases the thread lock acquired with :meth:`acquire`. + + + .. method:: Handler.setLevel(level) + + Sets the threshold for this handler to *level*. Logging messages which are + less severe than *level* will be ignored. When a handler is created, the + level is set to :const:`NOTSET` (which causes all messages to be + processed). + + See :ref:`levels` for a list of levels. + + .. versionchanged:: 3.2 + The *level* parameter now accepts a string representation of the + level such as 'INFO' as an alternative to the integer constants + such as :const:`INFO`. + + + .. method:: Handler.setFormatter(fmt) + + Sets the :class:`Formatter` for this handler to *fmt*. + + + .. method:: Handler.addFilter(filter) + + Adds the specified filter *filter* to this handler. + + + .. method:: Handler.removeFilter(filter) + + Removes the specified filter *filter* from this handler. + + + .. method:: Handler.filter(record) + + Apply this handler's filters to the record and return ``True`` if the + record is to be processed. The filters are consulted in turn, until one of + them returns a false value. If none of them return a false value, the record + will be emitted. If one returns a false value, the handler will not emit the + record. + + + .. method:: Handler.flush() + + Ensure all logging output has been flushed. This version does nothing and is + intended to be implemented by subclasses. + + + .. method:: Handler.close() + + Tidy up any resources used by the handler. This version does no output but + removes the handler from an internal list of handlers which is closed when + :func:`shutdown` is called. Subclasses should ensure that this gets called + from overridden :meth:`close` methods. + + + .. method:: Handler.handle(record) + + Conditionally emits the specified logging record, depending on filters which may + have been added to the handler. Wraps the actual emission of the record with + acquisition/release of the I/O thread lock. + + + .. method:: Handler.handleError(record) + + This method should be called from handlers when an exception is encountered + during an :meth:`emit` call. If the module-level attribute + ``raiseExceptions`` is ``False``, exceptions get silently ignored. This is + what is mostly wanted for a logging system - most users will not care about + errors in the logging system, they are more interested in application + errors. You could, however, replace this with a custom handler if you wish. + The specified record is the one which was being processed when the exception + occurred. (The default value of ``raiseExceptions`` is ``True``, as that is + more useful during development). + + + .. method:: Handler.format(record) + + Do formatting for a record - if a formatter is set, use it. Otherwise, use the + default formatter for the module. + + + .. method:: Handler.emit(record) + + Do whatever it takes to actually log the specified logging record. This version + is intended to be implemented by subclasses and so raises a + :exc:`NotImplementedError`. + +For a list of handlers included as standard, see :mod:`logging.handlers`. + +.. _formatter-objects: + +Formatter Objects +----------------- + +.. currentmodule:: logging + +:class:`Formatter` objects have the following attributes and methods. They are +responsible for converting a :class:`LogRecord` to (usually) a string which can +be interpreted by either a human or an external system. The base +:class:`Formatter` allows a formatting string to be specified. If none is +supplied, the default value of ``'%(message)s'`` is used, which just includes +the message in the logging call. To have additional items of information in the +formatted output (such as a timestamp), keep reading. + +A Formatter can be initialized with a format string which makes use of knowledge +of the :class:`LogRecord` attributes - such as the default value mentioned above +making use of the fact that the user's message and arguments are pre-formatted +into a :class:`LogRecord`'s *message* attribute. This format string contains +standard Python %-style mapping keys. See section :ref:`old-string-formatting` +for more information on string formatting. + +The useful mapping keys in a :class:`LogRecord` are given in the section on +:ref:`logrecord-attributes`. + + +.. class:: Formatter(fmt=None, datefmt=None, style='%', validate=True) + + Returns a new instance of the :class:`Formatter` class. The instance is + initialized with a format string for the message as a whole, as well as a + format string for the date/time portion of a message. If no *fmt* is + specified, ``'%(message)s'`` is used. If no *datefmt* is specified, a format + is used which is described in the :meth:`formatTime` documentation. + + The *style* parameter can be one of '%', '{' or '$' and determines how + the format string will be merged with its data: using one of %-formatting, + :meth:`str.format` or :class:`string.Template`. This only applies to the + format string *fmt* (e.g. ``'%(message)s'`` or ``{message}``), not to the + actual log messages passed to ``Logger.debug`` etc; see + :ref:`formatting-styles` for more information on using {- and $-formatting + for log messages. + + .. versionchanged:: 3.2 + The *style* parameter was added. + + .. versionchanged:: 3.8 + The *validate* parameter was added. Incorrect or mismatched style and fmt + will raise a ``ValueError``. + For example: ``logging.Formatter('%(asctime)s - %(message)s', style='{')``. + + .. method:: format(record) + + The record's attribute dictionary is used as the operand to a string + formatting operation. Returns the resulting string. Before formatting the + dictionary, a couple of preparatory steps are carried out. The *message* + attribute of the record is computed using *msg* % *args*. If the + formatting string contains ``'(asctime)'``, :meth:`formatTime` is called + to format the event time. If there is exception information, it is + formatted using :meth:`formatException` and appended to the message. Note + that the formatted exception information is cached in attribute + *exc_text*. This is useful because the exception information can be + pickled and sent across the wire, but you should be careful if you have + more than one :class:`Formatter` subclass which customizes the formatting + of exception information. In this case, you will have to clear the cached + value after a formatter has done its formatting, so that the next + formatter to handle the event doesn't use the cached value but + recalculates it afresh. + + If stack information is available, it's appended after the exception + information, using :meth:`formatStack` to transform it if necessary. + + + .. method:: formatTime(record, datefmt=None) + + This method should be called from :meth:`format` by a formatter which + wants to make use of a formatted time. This method can be overridden in + formatters to provide for any specific requirement, but the basic behavior + is as follows: if *datefmt* (a string) is specified, it is used with + :func:`time.strftime` to format the creation time of the + record. Otherwise, the format '%Y-%m-%d %H:%M:%S,uuu' is used, where the + uuu part is a millisecond value and the other letters are as per the + :func:`time.strftime` documentation. An example time in this format is + ``2003-01-23 00:29:50,411``. The resulting string is returned. + + This function uses a user-configurable function to convert the creation + time to a tuple. By default, :func:`time.localtime` is used; to change + this for a particular formatter instance, set the ``converter`` attribute + to a function with the same signature as :func:`time.localtime` or + :func:`time.gmtime`. To change it for all formatters, for example if you + want all logging times to be shown in GMT, set the ``converter`` + attribute in the ``Formatter`` class. + + .. versionchanged:: 3.3 + Previously, the default format was hard-coded as in this example: + ``2010-09-06 22:38:15,292`` where the part before the comma is + handled by a strptime format string (``'%Y-%m-%d %H:%M:%S'``), and the + part after the comma is a millisecond value. Because strptime does not + have a format placeholder for milliseconds, the millisecond value is + appended using another format string, ``'%s,%03d'`` --- and both of these + format strings have been hardcoded into this method. With the change, + these strings are defined as class-level attributes which can be + overridden at the instance level when desired. The names of the + attributes are ``default_time_format`` (for the strptime format string) + and ``default_msec_format`` (for appending the millisecond value). + + .. versionchanged:: 3.9 + The ``default_msec_format`` can be ``None``. + + .. method:: formatException(exc_info) + + Formats the specified exception information (a standard exception tuple as + returned by :func:`sys.exc_info`) as a string. This default implementation + just uses :func:`traceback.print_exception`. The resulting string is + returned. + + .. method:: formatStack(stack_info) + + Formats the specified stack information (a string as returned by + :func:`traceback.print_stack`, but with the last newline removed) as a + string. This default implementation just returns the input value. + +.. _filter: + +Filter Objects +-------------- + +``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated +filtering than is provided by levels. The base filter class only allows events +which are below a certain point in the logger hierarchy. For example, a filter +initialized with 'A.B' will allow events logged by loggers 'A.B', 'A.B.C', +'A.B.C.D', 'A.B.D' etc. but not 'A.BB', 'B.A.B' etc. If initialized with the +empty string, all events are passed. + + +.. class:: Filter(name='') + + Returns an instance of the :class:`Filter` class. If *name* is specified, it + names a logger which, together with its children, will have its events allowed + through the filter. If *name* is the empty string, allows every event. + + + .. method:: filter(record) + + Is the specified record to be logged? Returns zero for no, nonzero for + yes. If deemed appropriate, the record may be modified in-place by this + method. + +Note that filters attached to handlers are consulted before an event is +emitted by the handler, whereas filters attached to loggers are consulted +whenever an event is logged (using :meth:`debug`, :meth:`info`, +etc.), before sending an event to handlers. This means that events which have +been generated by descendant loggers will not be filtered by a logger's filter +setting, unless the filter has also been applied to those descendant loggers. + +You don't actually need to subclass ``Filter``: you can pass any instance +which has a ``filter`` method with the same semantics. + +.. versionchanged:: 3.2 + You don't need to create specialized ``Filter`` classes, or use other + classes with a ``filter`` method: you can use a function (or other + callable) as a filter. The filtering logic will check to see if the filter + object has a ``filter`` attribute: if it does, it's assumed to be a + ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's + assumed to be a callable and called with the record as the single + parameter. The returned value should conform to that returned by + :meth:`~Filter.filter`. + +Although filters are used primarily to filter records based on more +sophisticated criteria than levels, they get to see every record which is +processed by the handler or logger they're attached to: this can be useful if +you want to do things like counting how many records were processed by a +particular logger or handler, or adding, changing or removing attributes in +the :class:`LogRecord` being processed. Obviously changing the LogRecord needs +to be done with some care, but it does allow the injection of contextual +information into logs (see :ref:`filters-contextual`). + +.. _log-record: + +LogRecord Objects +----------------- + +:class:`LogRecord` instances are created automatically by the :class:`Logger` +every time something is logged, and can be created manually via +:func:`makeLogRecord` (for example, from a pickled event received over the +wire). + + +.. class:: LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None) + + Contains all the information pertinent to the event being logged. + + The primary information is passed in :attr:`msg` and :attr:`args`, which + are combined using ``msg % args`` to create the :attr:`message` field of the + record. + + :param name: The name of the logger used to log the event represented by + this LogRecord. Note that this name will always have this + value, even though it may be emitted by a handler attached to + a different (ancestor) logger. + :param level: The numeric level of the logging event (one of DEBUG, INFO etc.) + Note that this is converted to *two* attributes of the LogRecord: + ``levelno`` for the numeric value and ``levelname`` for the + corresponding level name. + :param pathname: The full pathname of the source file where the logging call + was made. + :param lineno: The line number in the source file where the logging call was + made. + :param msg: The event description message, possibly a format string with + placeholders for variable data. + :param args: Variable data to merge into the *msg* argument to obtain the + event description. + :param exc_info: An exception tuple with the current exception information, + or ``None`` if no exception information is available. + :param func: The name of the function or method from which the logging call + was invoked. + :param sinfo: A text string representing stack information from the base of + the stack in the current thread, up to the logging call. + + .. method:: getMessage() + + Returns the message for this :class:`LogRecord` instance after merging any + user-supplied arguments with the message. If the user-supplied message + argument to the logging call is not a string, :func:`str` is called on it to + convert it to a string. This allows use of user-defined classes as + messages, whose ``__str__`` method can return the actual format string to + be used. + + .. versionchanged:: 3.2 + The creation of a :class:`LogRecord` has been made more configurable by + providing a factory which is used to create the record. The factory can be + set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory` + (see this for the factory's signature). + + This functionality can be used to inject your own values into a + :class:`LogRecord` at creation time. You can use the following pattern:: + + old_factory = logging.getLogRecordFactory() + + def record_factory(*args, **kwargs): + record = old_factory(*args, **kwargs) + record.custom_attribute = 0xdecafbad + return record + + logging.setLogRecordFactory(record_factory) + + With this pattern, multiple factories could be chained, and as long + as they don't overwrite each other's attributes or unintentionally + overwrite the standard attributes listed above, there should be no + surprises. + + +.. _logrecord-attributes: + +LogRecord attributes +-------------------- + +The LogRecord has a number of attributes, most of which are derived from the +parameters to the constructor. (Note that the names do not always correspond +exactly between the LogRecord constructor parameters and the LogRecord +attributes.) These attributes can be used to merge data from the record into +the format string. The following table lists (in alphabetical order) the +attribute names, their meanings and the corresponding placeholder in a %-style +format string. + +If you are using {}-formatting (:func:`str.format`), you can use +``{attrname}`` as the placeholder in the format string. If you are using +$-formatting (:class:`string.Template`), use the form ``${attrname}``. In +both cases, of course, replace ``attrname`` with the actual attribute name +you want to use. + +In the case of {}-formatting, you can specify formatting flags by placing them +after the attribute name, separated from it with a colon. For example: a +placeholder of ``{msecs:03d}`` would format a millisecond value of ``4`` as +``004``. Refer to the :meth:`str.format` documentation for full details on +the options available to you. + ++----------------+-------------------------+-----------------------------------------------+ +| Attribute name | Format | Description | ++================+=========================+===============================================+ +| args | You shouldn't need to | The tuple of arguments merged into ``msg`` to | +| | format this yourself. | produce ``message``, or a dict whose values | +| | | are used for the merge (when there is only one| +| | | argument, and it is a dictionary). | ++----------------+-------------------------+-----------------------------------------------+ +| asctime | ``%(asctime)s`` | Human-readable time when the | +| | | :class:`LogRecord` was created. By default | +| | | this is of the form '2003-07-08 16:49:45,896' | +| | | (the numbers after the comma are millisecond | +| | | portion of the time). | ++----------------+-------------------------+-----------------------------------------------+ +| created | ``%(created)f`` | Time when the :class:`LogRecord` was created | +| | | (as returned by :func:`time.time`). | ++----------------+-------------------------+-----------------------------------------------+ +| exc_info | You shouldn't need to | Exception tuple (à la ``sys.exc_info``) or, | +| | format this yourself. | if no exception has occurred, ``None``. | ++----------------+-------------------------+-----------------------------------------------+ +| filename | ``%(filename)s`` | Filename portion of ``pathname``. | ++----------------+-------------------------+-----------------------------------------------+ +| funcName | ``%(funcName)s`` | Name of function containing the logging call. | ++----------------+-------------------------+-----------------------------------------------+ +| levelname | ``%(levelname)s`` | Text logging level for the message | +| | | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, | +| | | ``'ERROR'``, ``'CRITICAL'``). | ++----------------+-------------------------+-----------------------------------------------+ +| levelno | ``%(levelno)s`` | Numeric logging level for the message | +| | | (:const:`DEBUG`, :const:`INFO`, | +| | | :const:`WARNING`, :const:`ERROR`, | +| | | :const:`CRITICAL`). | ++----------------+-------------------------+-----------------------------------------------+ +| lineno | ``%(lineno)d`` | Source line number where the logging call was | +| | | issued (if available). | ++----------------+-------------------------+-----------------------------------------------+ +| message | ``%(message)s`` | The logged message, computed as ``msg % | +| | | args``. This is set when | +| | | :meth:`Formatter.format` is invoked. | ++----------------+-------------------------+-----------------------------------------------+ +| module | ``%(module)s`` | Module (name portion of ``filename``). | ++----------------+-------------------------+-----------------------------------------------+ +| msecs | ``%(msecs)d`` | Millisecond portion of the time when the | +| | | :class:`LogRecord` was created. | ++----------------+-------------------------+-----------------------------------------------+ +| msg | You shouldn't need to | The format string passed in the original | +| | format this yourself. | logging call. Merged with ``args`` to | +| | | produce ``message``, or an arbitrary object | +| | | (see :ref:`arbitrary-object-messages`). | ++----------------+-------------------------+-----------------------------------------------+ +| name | ``%(name)s`` | Name of the logger used to log the call. | ++----------------+-------------------------+-----------------------------------------------+ +| pathname | ``%(pathname)s`` | Full pathname of the source file where the | +| | | logging call was issued (if available). | ++----------------+-------------------------+-----------------------------------------------+ +| process | ``%(process)d`` | Process ID (if available). | ++----------------+-------------------------+-----------------------------------------------+ +| processName | ``%(processName)s`` | Process name (if available). | ++----------------+-------------------------+-----------------------------------------------+ +| relativeCreated| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was | +| | | created, relative to the time the logging | +| | | module was loaded. | ++----------------+-------------------------+-----------------------------------------------+ +| stack_info | You shouldn't need to | Stack frame information (where available) | +| | format this yourself. | from the bottom of the stack in the current | +| | | thread, up to and including the stack frame | +| | | of the logging call which resulted in the | +| | | creation of this record. | ++----------------+-------------------------+-----------------------------------------------+ +| thread | ``%(thread)d`` | Thread ID (if available). | ++----------------+-------------------------+-----------------------------------------------+ +| threadName | ``%(threadName)s`` | Thread name (if available). | ++----------------+-------------------------+-----------------------------------------------+ + +.. versionchanged:: 3.1 + *processName* was added. + + +.. _logger-adapter: + +LoggerAdapter Objects +--------------------- + +:class:`LoggerAdapter` instances are used to conveniently pass contextual +information into logging calls. For a usage example, see the section on +:ref:`adding contextual information to your logging output `. + +.. class:: LoggerAdapter(logger, extra) + + Returns an instance of :class:`LoggerAdapter` initialized with an + underlying :class:`Logger` instance and a dict-like object. + + .. method:: process(msg, kwargs) + + Modifies the message and/or keyword arguments passed to a logging call in + order to insert contextual information. This implementation takes the object + passed as *extra* to the constructor and adds it to *kwargs* using key + 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the + (possibly modified) versions of the arguments passed in. + +In addition to the above, :class:`LoggerAdapter` supports the following +methods of :class:`Logger`: :meth:`~Logger.debug`, :meth:`~Logger.info`, +:meth:`~Logger.warning`, :meth:`~Logger.error`, :meth:`~Logger.exception`, +:meth:`~Logger.critical`, :meth:`~Logger.log`, :meth:`~Logger.isEnabledFor`, +:meth:`~Logger.getEffectiveLevel`, :meth:`~Logger.setLevel` and +:meth:`~Logger.hasHandlers`. These methods have the same signatures as their +counterparts in :class:`Logger`, so you can use the two types of instances +interchangeably. + +.. versionchanged:: 3.2 + The :meth:`~Logger.isEnabledFor`, :meth:`~Logger.getEffectiveLevel`, + :meth:`~Logger.setLevel` and :meth:`~Logger.hasHandlers` methods were added + to :class:`LoggerAdapter`. These methods delegate to the underlying logger. + + +Thread Safety +------------- + +The logging module is intended to be thread-safe without any special work +needing to be done by its clients. It achieves this though using threading +locks; there is one lock to serialize access to the module's shared data, and +each handler also creates a lock to serialize access to its underlying I/O. + +If you are implementing asynchronous signal handlers using the :mod:`signal` +module, you may not be able to use logging from within such handlers. This is +because lock implementations in the :mod:`threading` module are not always +re-entrant, and so cannot be invoked from such signal handlers. + + +Module-Level Functions +---------------------- + +In addition to the classes described above, there are a number of module-level +functions. + + +.. function:: getLogger(name=None) + + Return a logger with the specified name or, if name is ``None``, return a + logger which is the root logger of the hierarchy. If specified, the name is + typically a dot-separated hierarchical name like *'a'*, *'a.b'* or *'a.b.c.d'*. + Choice of these names is entirely up to the developer who is using logging. + + All calls to this function with a given name return the same logger instance. + This means that logger instances never need to be passed between different parts + of an application. + + +.. function:: getLoggerClass() + + Return either the standard :class:`Logger` class, or the last class passed to + :func:`setLoggerClass`. This function may be called from within a new class + definition, to ensure that installing a customized :class:`Logger` class will + not undo customizations already applied by other code. For example:: + + class MyLogger(logging.getLoggerClass()): + # ... override behaviour here + + +.. function:: getLogRecordFactory() + + Return a callable which is used to create a :class:`LogRecord`. + + .. versionadded:: 3.2 + This function has been provided, along with :func:`setLogRecordFactory`, + to allow developers more control over how the :class:`LogRecord` + representing a logging event is constructed. + + See :func:`setLogRecordFactory` for more information about the how the + factory is called. + +.. function:: debug(msg, *args, **kwargs) + + Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the + message format string, and the *args* are the arguments which are merged into + *msg* using the string formatting operator. (Note that this means that you can + use keywords in the format string, together with a single dictionary argument.) + + There are three keyword arguments in *kwargs* which are inspected: *exc_info* + which, if it does not evaluate as false, causes exception information to be + added to the logging message. If an exception tuple (in the format returned by + :func:`sys.exc_info`) or an exception instance is provided, it is used; + otherwise, :func:`sys.exc_info` is called to get the exception information. + + The second optional keyword argument is *stack_info*, which defaults to + ``False``. If true, stack information is added to the logging + message, including the actual logging call. Note that this is not the same + stack information as that displayed through specifying *exc_info*: The + former is stack frames from the bottom of the stack up to the logging call + in the current thread, whereas the latter is information about stack frames + which have been unwound, following an exception, while searching for + exception handlers. + + You can specify *stack_info* independently of *exc_info*, e.g. to just show + how you got to a certain point in your code, even when no exceptions were + raised. The stack frames are printed following a header line which says: + + .. code-block:: none + + Stack (most recent call last): + + This mimics the ``Traceback (most recent call last):`` which is used when + displaying exception frames. + + The third optional keyword argument is *extra* which can be used to pass a + dictionary which is used to populate the __dict__ of the LogRecord created for + the logging event with user-defined attributes. These custom attributes can then + be used as you like. For example, they could be incorporated into logged + messages. For example:: + + FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s' + logging.basicConfig(format=FORMAT) + d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} + logging.warning('Protocol problem: %s', 'connection reset', extra=d) + + would print something like: + + .. code-block:: none + + 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset + + The keys in the dictionary passed in *extra* should not clash with the keys used + by the logging system. (See the :class:`Formatter` documentation for more + information on which keys are used by the logging system.) + + If you choose to use these attributes in logged messages, you need to exercise + some care. In the above example, for instance, the :class:`Formatter` has been + set up with a format string which expects 'clientip' and 'user' in the attribute + dictionary of the LogRecord. If these are missing, the message will not be + logged because a string formatting exception will occur. So in this case, you + always need to pass the *extra* dictionary with these keys. + + While this might be annoying, this feature is intended for use in specialized + circumstances, such as multi-threaded servers where the same code executes in + many contexts, and interesting conditions which arise are dependent on this + context (such as remote client IP address and authenticated user name, in the + above example). In such circumstances, it is likely that specialized + :class:`Formatter`\ s would be used with particular :class:`Handler`\ s. + + .. versionchanged:: 3.2 + The *stack_info* parameter was added. + +.. function:: info(msg, *args, **kwargs) + + Logs a message with level :const:`INFO` on the root logger. The arguments are + interpreted as for :func:`debug`. + + +.. function:: warning(msg, *args, **kwargs) + + Logs a message with level :const:`WARNING` on the root logger. The arguments + are interpreted as for :func:`debug`. + + .. note:: There is an obsolete function ``warn`` which is functionally + identical to ``warning``. As ``warn`` is deprecated, please do not use + it - use ``warning`` instead. + + +.. function:: error(msg, *args, **kwargs) + + Logs a message with level :const:`ERROR` on the root logger. The arguments are + interpreted as for :func:`debug`. + + +.. function:: critical(msg, *args, **kwargs) + + Logs a message with level :const:`CRITICAL` on the root logger. The arguments + are interpreted as for :func:`debug`. + + +.. function:: exception(msg, *args, **kwargs) + + Logs a message with level :const:`ERROR` on the root logger. The arguments are + interpreted as for :func:`debug`. Exception info is added to the logging + message. This function should only be called from an exception handler. + +.. function:: log(level, msg, *args, **kwargs) + + Logs a message with level *level* on the root logger. The other arguments are + interpreted as for :func:`debug`. + + .. note:: The above module-level convenience functions, which delegate to the + root logger, call :func:`basicConfig` to ensure that at least one handler + is available. Because of this, they should *not* be used in threads, + in versions of Python earlier than 2.7.1 and 3.2, unless at least one + handler has been added to the root logger *before* the threads are + started. In earlier versions of Python, due to a thread safety shortcoming + in :func:`basicConfig`, this can (under rare circumstances) lead to + handlers being added multiple times to the root logger, which can in turn + lead to multiple messages for the same event. + +.. function:: disable(level=CRITICAL) + + Provides an overriding level *level* for all loggers which takes precedence over + the logger's own level. When the need arises to temporarily throttle logging + output down across the whole application, this function can be useful. Its + effect is to disable all logging calls of severity *level* and below, so that + if you call it with a value of INFO, then all INFO and DEBUG events would be + discarded, whereas those of severity WARNING and above would be processed + according to the logger's effective level. If + ``logging.disable(logging.NOTSET)`` is called, it effectively removes this + overriding level, so that logging output again depends on the effective + levels of individual loggers. + + Note that if you have defined any custom logging level higher than + ``CRITICAL`` (this is not recommended), you won't be able to rely on the + default value for the *level* parameter, but will have to explicitly supply a + suitable value. + + .. versionchanged:: 3.7 + The *level* parameter was defaulted to level ``CRITICAL``. See Issue + #28524 for more information about this change. + +.. function:: addLevelName(level, levelName) + + Associates level *level* with text *levelName* in an internal dictionary, which is + used to map numeric levels to a textual representation, for example when a + :class:`Formatter` formats a message. This function can also be used to define + your own levels. The only constraints are that all levels used must be + registered using this function, levels should be positive integers and they + should increase in increasing order of severity. + + .. note:: If you are thinking of defining your own levels, please see the + section on :ref:`custom-levels`. + +.. function:: getLevelName(level) + + Returns the textual representation of logging level *level*. If the level is one + of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`, + :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you + have associated levels with names using :func:`addLevelName` then the name you + have associated with *level* is returned. If a numeric value corresponding to one + of the defined levels is passed in, the corresponding string representation is + returned. Otherwise, the string 'Level %s' % level is returned. + + .. note:: Levels are internally integers (as they need to be compared in the + logging logic). This function is used to convert between an integer level + and the level name displayed in the formatted log output by means of the + ``%(levelname)s`` format specifier (see :ref:`logrecord-attributes`). + + .. versionchanged:: 3.4 + In Python versions earlier than 3.4, this function could also be passed a + text level, and would return the corresponding numeric value of the level. + This undocumented behaviour was considered a mistake, and was removed in + Python 3.4, but reinstated in 3.4.2 due to retain backward compatibility. + +.. function:: makeLogRecord(attrdict) + + Creates and returns a new :class:`LogRecord` instance whose attributes are + defined by *attrdict*. This function is useful for taking a pickled + :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting + it as a :class:`LogRecord` instance at the receiving end. + + +.. function:: basicConfig(**kwargs) + + Does basic configuration for the logging system by creating a + :class:`StreamHandler` with a default :class:`Formatter` and adding it to the + root logger. The functions :func:`debug`, :func:`info`, :func:`warning`, + :func:`error` and :func:`critical` will call :func:`basicConfig` automatically + if no handlers are defined for the root logger. + + This function does nothing if the root logger already has handlers + configured, unless the keyword argument *force* is set to ``True``. + + .. note:: This function should be called from the main thread + before other threads are started. In versions of Python prior to + 2.7.1 and 3.2, if this function is called from multiple threads, + it is possible (in rare circumstances) that a handler will be added + to the root logger more than once, leading to unexpected results + such as messages being duplicated in the log. + + The following keyword arguments are supported. + + .. tabularcolumns:: |l|L| + + +--------------+---------------------------------------------+ + | Format | Description | + +==============+=============================================+ + | *filename* | Specifies that a FileHandler be created, | + | | using the specified filename, rather than a | + | | StreamHandler. | + +--------------+---------------------------------------------+ + | *filemode* | If *filename* is specified, open the file | + | | in this :ref:`mode `. Defaults | + | | to ``'a'``. | + +--------------+---------------------------------------------+ + | *format* | Use the specified format string for the | + | | handler. | + +--------------+---------------------------------------------+ + | *datefmt* | Use the specified date/time format, as | + | | accepted by :func:`time.strftime`. | + +--------------+---------------------------------------------+ + | *style* | If *format* is specified, use this style | + | | for the format string. One of ``'%'``, | + | | ``'{'`` or ``'$'`` for :ref:`printf-style | + | | `, | + | | :meth:`str.format` or | + | | :class:`string.Template` respectively. | + | | Defaults to ``'%'``. | + +--------------+---------------------------------------------+ + | *level* | Set the root logger level to the specified | + | | :ref:`level `. | + +--------------+---------------------------------------------+ + | *stream* | Use the specified stream to initialize the | + | | StreamHandler. Note that this argument is | + | | incompatible with *filename* - if both | + | | are present, a ``ValueError`` is raised. | + +--------------+---------------------------------------------+ + | *handlers* | If specified, this should be an iterable of | + | | already created handlers to add to the root | + | | logger. Any handlers which don't already | + | | have a formatter set will be assigned the | + | | default formatter created in this function. | + | | Note that this argument is incompatible | + | | with *filename* or *stream* - if both | + | | are present, a ``ValueError`` is raised. | + +--------------+---------------------------------------------+ + | *force* | If this keyword argument is specified as | + | | true, any existing handlers attached to the | + | | root logger are removed and closed, before | + | | carrying out the configuration as specified | + | | by the other arguments. | + +--------------+---------------------------------------------+ + | *encoding* | If this keyword argument is specified along | + | | with *filename*, its value is used when the | + | | FileHandler is created, and thus used when | + | | opening the output file. | + +--------------+---------------------------------------------+ + | *errors* | If this keyword argument is specified along | + | | with *filename*, its value is used when the | + | | FileHandler is created, and thus used when | + | | opening the output file. If not specified, | + | | the value 'backslashreplace' is used. Note | + | | that if ``None`` is specified, it will be | + | | passed as such to func:`open`, which means | + | | that it will be treated the same as passing | + | | 'errors'. | + +--------------+---------------------------------------------+ + + .. versionchanged:: 3.2 + The *style* argument was added. + + .. versionchanged:: 3.3 + The *handlers* argument was added. Additional checks were added to + catch situations where incompatible arguments are specified (e.g. + *handlers* together with *stream* or *filename*, or *stream* + together with *filename*). + + .. versionchanged:: 3.8 + The *force* argument was added. + + .. versionchanged:: 3.9 + The *encoding* and *errors* arguments were added. + +.. function:: shutdown() + + Informs the logging system to perform an orderly shutdown by flushing and + closing all handlers. This should be called at application exit and no + further use of the logging system should be made after this call. + + When the logging module is imported, it registers this function as an exit + handler (see :mod:`atexit`), so normally there's no need to do that + manually. + + +.. function:: setLoggerClass(klass) + + Tells the logging system to use the class *klass* when instantiating a logger. + The class should define :meth:`__init__` such that only a name argument is + required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This + function is typically called before any loggers are instantiated by applications + which need to use custom logger behavior. After this call, as at any other + time, do not instantiate loggers directly using the subclass: continue to use + the :func:`logging.getLogger` API to get your loggers. + + +.. function:: setLogRecordFactory(factory) + + Set a callable which is used to create a :class:`LogRecord`. + + :param factory: The factory callable to be used to instantiate a log record. + + .. versionadded:: 3.2 + This function has been provided, along with :func:`getLogRecordFactory`, to + allow developers more control over how the :class:`LogRecord` representing + a logging event is constructed. + + The factory has the following signature: + + ``factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)`` + + :name: The logger name. + :level: The logging level (numeric). + :fn: The full pathname of the file where the logging call was made. + :lno: The line number in the file where the logging call was made. + :msg: The logging message. + :args: The arguments for the logging message. + :exc_info: An exception tuple, or ``None``. + :func: The name of the function or method which invoked the logging + call. + :sinfo: A stack traceback such as is provided by + :func:`traceback.print_stack`, showing the call hierarchy. + :kwargs: Additional keyword arguments. + + +Module-Level Attributes +----------------------- + +.. attribute:: lastResort + + A "handler of last resort" is available through this attribute. This + is a :class:`StreamHandler` writing to ``sys.stderr`` with a level of + ``WARNING``, and is used to handle logging events in the absence of any + logging configuration. The end result is to just print the message to + ``sys.stderr``. This replaces the earlier error message saying that + "no handlers could be found for logger XYZ". If you need the earlier + behaviour for some reason, ``lastResort`` can be set to ``None``. + + .. versionadded:: 3.2 + +Integration with the warnings module +------------------------------------ + +The :func:`captureWarnings` function can be used to integrate :mod:`logging` +with the :mod:`warnings` module. + +.. function:: captureWarnings(capture) + + This function is used to turn the capture of warnings by logging on and + off. + + If *capture* is ``True``, warnings issued by the :mod:`warnings` module will + be redirected to the logging system. Specifically, a warning will be + formatted using :func:`warnings.formatwarning` and the resulting string + logged to a logger named ``'py.warnings'`` with a severity of :const:`WARNING`. + + If *capture* is ``False``, the redirection of warnings to the logging system + will stop, and warnings will be redirected to their original destinations + (i.e. those in effect before ``captureWarnings(True)`` was called). + + +.. seealso:: + + Module :mod:`logging.config` + Configuration API for the logging module. + + Module :mod:`logging.handlers` + Useful handlers included with the logging module. + + :pep:`282` - A Logging System + The proposal which described this feature for inclusion in the Python standard + library. + + `Original Python logging package `_ + This is the original source for the :mod:`logging` package. The version of the + package available from this site is suitable for use with Python 1.5.2, 2.1.x + and 2.2.x, which do not include the :mod:`logging` package in the standard + library. diff --git a/cpython_2/environment/repo/Doc/library/lzma.rst b/cpython_2/environment/repo/Doc/library/lzma.rst new file mode 100644 index 0000000000000000000000000000000000000000..4bfff9c6147ed4c9e00e7b5f7e3a9294b106a986 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/lzma.rst @@ -0,0 +1,434 @@ +:mod:`lzma` --- Compression using the LZMA algorithm +==================================================== + +.. module:: lzma + :synopsis: A Python wrapper for the liblzma compression library. + +.. moduleauthor:: Nadeem Vawda +.. sectionauthor:: Nadeem Vawda + +.. versionadded:: 3.3 + +**Source code:** :source:`Lib/lzma.py` + +-------------- + +This module provides classes and convenience functions for compressing and +decompressing data using the LZMA compression algorithm. Also included is a file +interface supporting the ``.xz`` and legacy ``.lzma`` file formats used by the +:program:`xz` utility, as well as raw compressed streams. + +The interface provided by this module is very similar to that of the :mod:`bz2` +module. However, note that :class:`LZMAFile` is *not* thread-safe, unlike +:class:`bz2.BZ2File`, so if you need to use a single :class:`LZMAFile` instance +from multiple threads, it is necessary to protect it with a lock. + + +.. exception:: LZMAError + + This exception is raised when an error occurs during compression or + decompression, or while initializing the compressor/decompressor state. + + +Reading and writing compressed files +------------------------------------ + +.. function:: open(filename, mode="rb", \*, format=None, check=-1, preset=None, filters=None, encoding=None, errors=None, newline=None) + + Open an LZMA-compressed file in binary or text mode, returning a :term:`file + object`. + + The *filename* argument can be either an actual file name (given as a + :class:`str`, :class:`bytes` or :term:`path-like ` object), in + which case the named file is opened, or it can be an existing file object + to read from or write to. + + The *mode* argument can be any of ``"r"``, ``"rb"``, ``"w"``, ``"wb"``, + ``"x"``, ``"xb"``, ``"a"`` or ``"ab"`` for binary mode, or ``"rt"``, + ``"wt"``, ``"xt"``, or ``"at"`` for text mode. The default is ``"rb"``. + + When opening a file for reading, the *format* and *filters* arguments have + the same meanings as for :class:`LZMADecompressor`. In this case, the *check* + and *preset* arguments should not be used. + + When opening a file for writing, the *format*, *check*, *preset* and + *filters* arguments have the same meanings as for :class:`LZMACompressor`. + + For binary mode, this function is equivalent to the :class:`LZMAFile` + constructor: ``LZMAFile(filename, mode, ...)``. In this case, the *encoding*, + *errors* and *newline* arguments must not be provided. + + For text mode, a :class:`LZMAFile` object is created, and wrapped in an + :class:`io.TextIOWrapper` instance with the specified encoding, error + handling behavior, and line ending(s). + + .. versionchanged:: 3.4 + Added support for the ``"x"``, ``"xb"`` and ``"xt"`` modes. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. class:: LZMAFile(filename=None, mode="r", \*, format=None, check=-1, preset=None, filters=None) + + Open an LZMA-compressed file in binary mode. + + An :class:`LZMAFile` can wrap an already-open :term:`file object`, or operate + directly on a named file. The *filename* argument specifies either the file + object to wrap, or the name of the file to open (as a :class:`str`, + :class:`bytes` or :term:`path-like ` object). When wrapping an + existing file object, the wrapped file will not be closed when the + :class:`LZMAFile` is closed. + + The *mode* argument can be either ``"r"`` for reading (default), ``"w"`` for + overwriting, ``"x"`` for exclusive creation, or ``"a"`` for appending. These + can equivalently be given as ``"rb"``, ``"wb"``, ``"xb"`` and ``"ab"`` + respectively. + + If *filename* is a file object (rather than an actual file name), a mode of + ``"w"`` does not truncate the file, and is instead equivalent to ``"a"``. + + When opening a file for reading, the input file may be the concatenation of + multiple separate compressed streams. These are transparently decoded as a + single logical stream. + + When opening a file for reading, the *format* and *filters* arguments have + the same meanings as for :class:`LZMADecompressor`. In this case, the *check* + and *preset* arguments should not be used. + + When opening a file for writing, the *format*, *check*, *preset* and + *filters* arguments have the same meanings as for :class:`LZMACompressor`. + + :class:`LZMAFile` supports all the members specified by + :class:`io.BufferedIOBase`, except for :meth:`detach` and :meth:`truncate`. + Iteration and the :keyword:`with` statement are supported. + + The following method is also provided: + + .. method:: peek(size=-1) + + Return buffered data without advancing the file position. At least one + byte of data will be returned, unless EOF has been reached. The exact + number of bytes returned is unspecified (the *size* argument is ignored). + + .. note:: While calling :meth:`peek` does not change the file position of + the :class:`LZMAFile`, it may change the position of the underlying + file object (e.g. if the :class:`LZMAFile` was constructed by passing a + file object for *filename*). + + .. versionchanged:: 3.4 + Added support for the ``"x"`` and ``"xb"`` modes. + + .. versionchanged:: 3.5 + The :meth:`~io.BufferedIOBase.read` method now accepts an argument of + ``None``. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +Compressing and decompressing data in memory +-------------------------------------------- + +.. class:: LZMACompressor(format=FORMAT_XZ, check=-1, preset=None, filters=None) + + Create a compressor object, which can be used to compress data incrementally. + + For a more convenient way of compressing a single chunk of data, see + :func:`compress`. + + The *format* argument specifies what container format should be used. + Possible values are: + + * :const:`FORMAT_XZ`: The ``.xz`` container format. + This is the default format. + + * :const:`FORMAT_ALONE`: The legacy ``.lzma`` container format. + This format is more limited than ``.xz`` -- it does not support integrity + checks or multiple filters. + + * :const:`FORMAT_RAW`: A raw data stream, not using any container format. + This format specifier does not support integrity checks, and requires that + you always specify a custom filter chain (for both compression and + decompression). Additionally, data compressed in this manner cannot be + decompressed using :const:`FORMAT_AUTO` (see :class:`LZMADecompressor`). + + The *check* argument specifies the type of integrity check to include in the + compressed data. This check is used when decompressing, to ensure that the + data has not been corrupted. Possible values are: + + * :const:`CHECK_NONE`: No integrity check. + This is the default (and the only acceptable value) for + :const:`FORMAT_ALONE` and :const:`FORMAT_RAW`. + + * :const:`CHECK_CRC32`: 32-bit Cyclic Redundancy Check. + + * :const:`CHECK_CRC64`: 64-bit Cyclic Redundancy Check. + This is the default for :const:`FORMAT_XZ`. + + * :const:`CHECK_SHA256`: 256-bit Secure Hash Algorithm. + + If the specified check is not supported, an :class:`LZMAError` is raised. + + The compression settings can be specified either as a preset compression + level (with the *preset* argument), or in detail as a custom filter chain + (with the *filters* argument). + + The *preset* argument (if provided) should be an integer between ``0`` and + ``9`` (inclusive), optionally OR-ed with the constant + :const:`PRESET_EXTREME`. If neither *preset* nor *filters* are given, the + default behavior is to use :const:`PRESET_DEFAULT` (preset level ``6``). + Higher presets produce smaller output, but make the compression process + slower. + + .. note:: + + In addition to being more CPU-intensive, compression with higher presets + also requires much more memory (and produces output that needs more memory + to decompress). With preset ``9`` for example, the overhead for an + :class:`LZMACompressor` object can be as high as 800 MiB. For this reason, + it is generally best to stick with the default preset. + + The *filters* argument (if provided) should be a filter chain specifier. + See :ref:`filter-chain-specs` for details. + + .. method:: compress(data) + + Compress *data* (a :class:`bytes` object), returning a :class:`bytes` + object containing compressed data for at least part of the input. Some of + *data* may be buffered internally, for use in later calls to + :meth:`compress` and :meth:`flush`. The returned data should be + concatenated with the output of any previous calls to :meth:`compress`. + + .. method:: flush() + + Finish the compression process, returning a :class:`bytes` object + containing any data stored in the compressor's internal buffers. + + The compressor cannot be used after this method has been called. + + +.. class:: LZMADecompressor(format=FORMAT_AUTO, memlimit=None, filters=None) + + Create a decompressor object, which can be used to decompress data + incrementally. + + For a more convenient way of decompressing an entire compressed stream at + once, see :func:`decompress`. + + The *format* argument specifies the container format that should be used. The + default is :const:`FORMAT_AUTO`, which can decompress both ``.xz`` and + ``.lzma`` files. Other possible values are :const:`FORMAT_XZ`, + :const:`FORMAT_ALONE`, and :const:`FORMAT_RAW`. + + The *memlimit* argument specifies a limit (in bytes) on the amount of memory + that the decompressor can use. When this argument is used, decompression will + fail with an :class:`LZMAError` if it is not possible to decompress the input + within the given memory limit. + + The *filters* argument specifies the filter chain that was used to create + the stream being decompressed. This argument is required if *format* is + :const:`FORMAT_RAW`, but should not be used for other formats. + See :ref:`filter-chain-specs` for more information about filter chains. + + .. note:: + This class does not transparently handle inputs containing multiple + compressed streams, unlike :func:`decompress` and :class:`LZMAFile`. To + decompress a multi-stream input with :class:`LZMADecompressor`, you must + create a new decompressor for each stream. + + .. method:: decompress(data, max_length=-1) + + Decompress *data* (a :term:`bytes-like object`), returning + uncompressed data as bytes. Some of *data* may be buffered + internally, for use in later calls to :meth:`decompress`. The + returned data should be concatenated with the output of any + previous calls to :meth:`decompress`. + + If *max_length* is nonnegative, returns at most *max_length* + bytes of decompressed data. If this limit is reached and further + output can be produced, the :attr:`~.needs_input` attribute will + be set to ``False``. In this case, the next call to + :meth:`~.decompress` may provide *data* as ``b''`` to obtain + more of the output. + + If all of the input data was decompressed and returned (either + because this was less than *max_length* bytes, or because + *max_length* was negative), the :attr:`~.needs_input` attribute + will be set to ``True``. + + Attempting to decompress data after the end of stream is reached + raises an `EOFError`. Any data found after the end of the + stream is ignored and saved in the :attr:`~.unused_data` attribute. + + .. versionchanged:: 3.5 + Added the *max_length* parameter. + + .. attribute:: check + + The ID of the integrity check used by the input stream. This may be + :const:`CHECK_UNKNOWN` until enough of the input has been decoded to + determine what integrity check it uses. + + .. attribute:: eof + + ``True`` if the end-of-stream marker has been reached. + + .. attribute:: unused_data + + Data found after the end of the compressed stream. + + Before the end of the stream is reached, this will be ``b""``. + + .. attribute:: needs_input + + ``False`` if the :meth:`.decompress` method can provide more + decompressed data before requiring new uncompressed input. + + .. versionadded:: 3.5 + +.. function:: compress(data, format=FORMAT_XZ, check=-1, preset=None, filters=None) + + Compress *data* (a :class:`bytes` object), returning the compressed data as a + :class:`bytes` object. + + See :class:`LZMACompressor` above for a description of the *format*, *check*, + *preset* and *filters* arguments. + + +.. function:: decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None) + + Decompress *data* (a :class:`bytes` object), returning the uncompressed data + as a :class:`bytes` object. + + If *data* is the concatenation of multiple distinct compressed streams, + decompress all of these streams, and return the concatenation of the results. + + See :class:`LZMADecompressor` above for a description of the *format*, + *memlimit* and *filters* arguments. + + +Miscellaneous +------------- + +.. function:: is_check_supported(check) + + Return ``True`` if the given integrity check is supported on this system. + + :const:`CHECK_NONE` and :const:`CHECK_CRC32` are always supported. + :const:`CHECK_CRC64` and :const:`CHECK_SHA256` may be unavailable if you are + using a version of :program:`liblzma` that was compiled with a limited + feature set. + + +.. _filter-chain-specs: + +Specifying custom filter chains +------------------------------- + +A filter chain specifier is a sequence of dictionaries, where each dictionary +contains the ID and options for a single filter. Each dictionary must contain +the key ``"id"``, and may contain additional keys to specify filter-dependent +options. Valid filter IDs are as follows: + +* Compression filters: + * :const:`FILTER_LZMA1` (for use with :const:`FORMAT_ALONE`) + * :const:`FILTER_LZMA2` (for use with :const:`FORMAT_XZ` and :const:`FORMAT_RAW`) + +* Delta filter: + * :const:`FILTER_DELTA` + +* Branch-Call-Jump (BCJ) filters: + * :const:`FILTER_X86` + * :const:`FILTER_IA64` + * :const:`FILTER_ARM` + * :const:`FILTER_ARMTHUMB` + * :const:`FILTER_POWERPC` + * :const:`FILTER_SPARC` + +A filter chain can consist of up to 4 filters, and cannot be empty. The last +filter in the chain must be a compression filter, and any other filters must be +delta or BCJ filters. + +Compression filters support the following options (specified as additional +entries in the dictionary representing the filter): + + * ``preset``: A compression preset to use as a source of default values for + options that are not specified explicitly. + * ``dict_size``: Dictionary size in bytes. This should be between 4 KiB and + 1.5 GiB (inclusive). + * ``lc``: Number of literal context bits. + * ``lp``: Number of literal position bits. The sum ``lc + lp`` must be at + most 4. + * ``pb``: Number of position bits; must be at most 4. + * ``mode``: :const:`MODE_FAST` or :const:`MODE_NORMAL`. + * ``nice_len``: What should be considered a "nice length" for a match. + This should be 273 or less. + * ``mf``: What match finder to use -- :const:`MF_HC3`, :const:`MF_HC4`, + :const:`MF_BT2`, :const:`MF_BT3`, or :const:`MF_BT4`. + * ``depth``: Maximum search depth used by match finder. 0 (default) means to + select automatically based on other filter options. + +The delta filter stores the differences between bytes, producing more repetitive +input for the compressor in certain circumstances. It supports one option, +``dist``. This indicates the distance between bytes to be subtracted. The +default is 1, i.e. take the differences between adjacent bytes. + +The BCJ filters are intended to be applied to machine code. They convert +relative branches, calls and jumps in the code to use absolute addressing, with +the aim of increasing the redundancy that can be exploited by the compressor. +These filters support one option, ``start_offset``. This specifies the address +that should be mapped to the beginning of the input data. The default is 0. + + +Examples +-------- + +Reading in a compressed file:: + + import lzma + with lzma.open("file.xz") as f: + file_content = f.read() + +Creating a compressed file:: + + import lzma + data = b"Insert Data Here" + with lzma.open("file.xz", "w") as f: + f.write(data) + +Compressing data in memory:: + + import lzma + data_in = b"Insert Data Here" + data_out = lzma.compress(data_in) + +Incremental compression:: + + import lzma + lzc = lzma.LZMACompressor() + out1 = lzc.compress(b"Some data\n") + out2 = lzc.compress(b"Another piece of data\n") + out3 = lzc.compress(b"Even more data\n") + out4 = lzc.flush() + # Concatenate all the partial results: + result = b"".join([out1, out2, out3, out4]) + +Writing compressed data to an already-open file:: + + import lzma + with open("file.xz", "wb") as f: + f.write(b"This data will not be compressed\n") + with lzma.open(f, "w") as lzf: + lzf.write(b"This *will* be compressed\n") + f.write(b"Not compressed\n") + +Creating a compressed file using a custom filter chain:: + + import lzma + my_filters = [ + {"id": lzma.FILTER_DELTA, "dist": 5}, + {"id": lzma.FILTER_LZMA2, "preset": 7 | lzma.PRESET_EXTREME}, + ] + with lzma.open("file.xz", "w", filters=my_filters) as f: + f.write(b"blah blah blah") diff --git a/cpython_2/environment/repo/Doc/library/mailbox.rst b/cpython_2/environment/repo/Doc/library/mailbox.rst new file mode 100644 index 0000000000000000000000000000000000000000..f82a3b200deb7c4d01820376a7d51a72e2c4dc7b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/mailbox.rst @@ -0,0 +1,1596 @@ +:mod:`mailbox` --- Manipulate mailboxes in various formats +========================================================== + +.. module:: mailbox + :synopsis: Manipulate mailboxes in various formats + +.. moduleauthor:: Gregory K. Johnson +.. sectionauthor:: Gregory K. Johnson + +**Source code:** :source:`Lib/mailbox.py` + +-------------- + +This module defines two classes, :class:`Mailbox` and :class:`Message`, for +accessing and manipulating on-disk mailboxes and the messages they contain. +:class:`Mailbox` offers a dictionary-like mapping from keys to messages. +:class:`Message` extends the :mod:`email.message` module's +:class:`~email.message.Message` class with format-specific state and behavior. +Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF. + + +.. seealso:: + + Module :mod:`email` + Represent and manipulate messages. + + +.. _mailbox-objects: + +:class:`Mailbox` objects +------------------------ + +.. class:: Mailbox + + A mailbox, which may be inspected and modified. + + The :class:`Mailbox` class defines an interface and is not intended to be + instantiated. Instead, format-specific subclasses should inherit from + :class:`Mailbox` and your code should instantiate a particular subclass. + + The :class:`Mailbox` interface is dictionary-like, with small keys + corresponding to messages. Keys are issued by the :class:`Mailbox` instance + with which they will be used and are only meaningful to that :class:`Mailbox` + instance. A key continues to identify a message even if the corresponding + message is modified, such as by replacing it with another message. + + Messages may be added to a :class:`Mailbox` instance using the set-like + method :meth:`add` and removed using a ``del`` statement or the set-like + methods :meth:`remove` and :meth:`discard`. + + :class:`Mailbox` interface semantics differ from dictionary semantics in some + noteworthy ways. Each time a message is requested, a new representation + (typically a :class:`Message` instance) is generated based upon the current + state of the mailbox. Similarly, when a message is added to a + :class:`Mailbox` instance, the provided message representation's contents are + copied. In neither case is a reference to the message representation kept by + the :class:`Mailbox` instance. + + The default :class:`Mailbox` iterator iterates over message representations, + not keys as the default dictionary iterator does. Moreover, modification of a + mailbox during iteration is safe and well-defined. Messages added to the + mailbox after an iterator is created will not be seen by the + iterator. Messages removed from the mailbox before the iterator yields them + will be silently skipped, though using a key from an iterator may result in a + :exc:`KeyError` exception if the corresponding message is subsequently + removed. + + .. warning:: + + Be very cautious when modifying mailboxes that might be simultaneously + changed by some other process. The safest mailbox format to use for such + tasks is Maildir; try to avoid using single-file formats such as mbox for + concurrent writing. If you're modifying a mailbox, you *must* lock it by + calling the :meth:`lock` and :meth:`unlock` methods *before* reading any + messages in the file or making any changes by adding or deleting a + message. Failing to lock the mailbox runs the risk of losing messages or + corrupting the entire mailbox. + + :class:`Mailbox` instances have the following methods: + + + .. method:: add(message) + + Add *message* to the mailbox and return the key that has been assigned to + it. + + Parameter *message* may be a :class:`Message` instance, an + :class:`email.message.Message` instance, a string, a byte string, or a + file-like object (which should be open in binary mode). If *message* is + an instance of the + appropriate format-specific :class:`Message` subclass (e.g., if it's an + :class:`mboxMessage` instance and this is an :class:`mbox` instance), its + format-specific information is used. Otherwise, reasonable defaults for + format-specific information are used. + + .. versionchanged:: 3.2 + Support for binary input was added. + + + .. method:: remove(key) + __delitem__(key) + discard(key) + + Delete the message corresponding to *key* from the mailbox. + + If no such message exists, a :exc:`KeyError` exception is raised if the + method was called as :meth:`remove` or :meth:`__delitem__` but no + exception is raised if the method was called as :meth:`discard`. The + behavior of :meth:`discard` may be preferred if the underlying mailbox + format supports concurrent modification by other processes. + + + .. method:: __setitem__(key, message) + + Replace the message corresponding to *key* with *message*. Raise a + :exc:`KeyError` exception if no message already corresponds to *key*. + + As with :meth:`add`, parameter *message* may be a :class:`Message` + instance, an :class:`email.message.Message` instance, a string, a byte + string, or a file-like object (which should be open in binary mode). If + *message* is an + instance of the appropriate format-specific :class:`Message` subclass + (e.g., if it's an :class:`mboxMessage` instance and this is an + :class:`mbox` instance), its format-specific information is + used. Otherwise, the format-specific information of the message that + currently corresponds to *key* is left unchanged. + + + .. method:: iterkeys() + keys() + + Return an iterator over all keys if called as :meth:`iterkeys` or return a + list of keys if called as :meth:`keys`. + + + .. method:: itervalues() + __iter__() + values() + + Return an iterator over representations of all messages if called as + :meth:`itervalues` or :meth:`__iter__` or return a list of such + representations if called as :meth:`values`. The messages are represented + as instances of the appropriate format-specific :class:`Message` subclass + unless a custom message factory was specified when the :class:`Mailbox` + instance was initialized. + + .. note:: + + The behavior of :meth:`__iter__` is unlike that of dictionaries, which + iterate over keys. + + + .. method:: iteritems() + items() + + Return an iterator over (*key*, *message*) pairs, where *key* is a key and + *message* is a message representation, if called as :meth:`iteritems` or + return a list of such pairs if called as :meth:`items`. The messages are + represented as instances of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. + + + .. method:: get(key, default=None) + __getitem__(key) + + Return a representation of the message corresponding to *key*. If no such + message exists, *default* is returned if the method was called as + :meth:`get` and a :exc:`KeyError` exception is raised if the method was + called as :meth:`__getitem__`. The message is represented as an instance + of the appropriate format-specific :class:`Message` subclass unless a + custom message factory was specified when the :class:`Mailbox` instance + was initialized. + + + .. method:: get_message(key) + + Return a representation of the message corresponding to *key* as an + instance of the appropriate format-specific :class:`Message` subclass, or + raise a :exc:`KeyError` exception if no such message exists. + + + .. method:: get_bytes(key) + + Return a byte representation of the message corresponding to *key*, or + raise a :exc:`KeyError` exception if no such message exists. + + .. versionadded:: 3.2 + + + .. method:: get_string(key) + + Return a string representation of the message corresponding to *key*, or + raise a :exc:`KeyError` exception if no such message exists. The + message is processed through :class:`email.message.Message` to + convert it to a 7bit clean representation. + + + .. method:: get_file(key) + + Return a file-like representation of the message corresponding to *key*, + or raise a :exc:`KeyError` exception if no such message exists. The + file-like object behaves as if open in binary mode. This file should be + closed once it is no longer needed. + + .. versionchanged:: 3.2 + The file object really is a binary file; previously it was incorrectly + returned in text mode. Also, the file-like object now supports the + context management protocol: you can use a :keyword:`with` statement to + automatically close it. + + .. note:: + + Unlike other representations of messages, file-like representations are + not necessarily independent of the :class:`Mailbox` instance that + created them or of the underlying mailbox. More specific documentation + is provided by each subclass. + + + .. method:: __contains__(key) + + Return ``True`` if *key* corresponds to a message, ``False`` otherwise. + + + .. method:: __len__() + + Return a count of messages in the mailbox. + + + .. method:: clear() + + Delete all messages from the mailbox. + + + .. method:: pop(key, default=None) + + Return a representation of the message corresponding to *key* and delete + the message. If no such message exists, return *default*. The message is + represented as an instance of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. + + + .. method:: popitem() + + Return an arbitrary (*key*, *message*) pair, where *key* is a key and + *message* is a message representation, and delete the corresponding + message. If the mailbox is empty, raise a :exc:`KeyError` exception. The + message is represented as an instance of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. + + + .. method:: update(arg) + + Parameter *arg* should be a *key*-to-*message* mapping or an iterable of + (*key*, *message*) pairs. Updates the mailbox so that, for each given + *key* and *message*, the message corresponding to *key* is set to + *message* as if by using :meth:`__setitem__`. As with :meth:`__setitem__`, + each *key* must already correspond to a message in the mailbox or else a + :exc:`KeyError` exception will be raised, so in general it is incorrect + for *arg* to be a :class:`Mailbox` instance. + + .. note:: + + Unlike with dictionaries, keyword arguments are not supported. + + + .. method:: flush() + + Write any pending changes to the filesystem. For some :class:`Mailbox` + subclasses, changes are always written immediately and :meth:`flush` does + nothing, but you should still make a habit of calling this method. + + + .. method:: lock() + + Acquire an exclusive advisory lock on the mailbox so that other processes + know not to modify it. An :exc:`ExternalClashError` is raised if the lock + is not available. The particular locking mechanisms used depend upon the + mailbox format. You should *always* lock the mailbox before making any + modifications to its contents. + + + .. method:: unlock() + + Release the lock on the mailbox, if any. + + + .. method:: close() + + Flush the mailbox, unlock it if necessary, and close any open files. For + some :class:`Mailbox` subclasses, this method does nothing. + + +.. _mailbox-maildir: + +:class:`Maildir` +^^^^^^^^^^^^^^^^ + + +.. class:: Maildir(dirname, factory=None, create=True) + + A subclass of :class:`Mailbox` for mailboxes in Maildir format. Parameter + *factory* is a callable object that accepts a file-like message representation + (which behaves as if opened in binary mode) and returns a custom representation. + If *factory* is ``None``, :class:`MaildirMessage` is used as the default message + representation. If *create* is ``True``, the mailbox is created if it does not + exist. + + If *create* is ``True`` and the *dirname* path exists, it will be treated as + an existing maildir without attempting to verify its directory layout. + + It is for historical reasons that *dirname* is named as such rather than *path*. + + Maildir is a directory-based mailbox format invented for the qmail mail + transfer agent and now widely supported by other programs. Messages in a + Maildir mailbox are stored in separate files within a common directory + structure. This design allows Maildir mailboxes to be accessed and modified + by multiple unrelated programs without data corruption, so file locking is + unnecessary. + + Maildir mailboxes contain three subdirectories, namely: :file:`tmp`, + :file:`new`, and :file:`cur`. Messages are created momentarily in the + :file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to + finalize delivery. A mail user agent may subsequently move the message to the + :file:`cur` subdirectory and store information about the state of the message + in a special "info" section appended to its file name. + + Folders of the style introduced by the Courier mail transfer agent are also + supported. Any subdirectory of the main mailbox is considered a folder if + ``'.'`` is the first character in its name. Folder names are represented by + :class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir + mailbox but should not contain other folders. Instead, a logical nesting is + indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07". + + .. note:: + + The Maildir specification requires the use of a colon (``':'``) in certain + message file names. However, some operating systems do not permit this + character in file names, If you wish to use a Maildir-like format on such + an operating system, you should specify another character to use + instead. The exclamation point (``'!'``) is a popular choice. For + example:: + + import mailbox + mailbox.Maildir.colon = '!' + + The :attr:`colon` attribute may also be set on a per-instance basis. + + :class:`Maildir` instances have all of the methods of :class:`Mailbox` in + addition to the following: + + + .. method:: list_folders() + + Return a list of the names of all folders. + + + .. method:: get_folder(folder) + + Return a :class:`Maildir` instance representing the folder whose name is + *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder + does not exist. + + + .. method:: add_folder(folder) + + Create a folder whose name is *folder* and return a :class:`Maildir` + instance representing it. + + + .. method:: remove_folder(folder) + + Delete the folder whose name is *folder*. If the folder contains any + messages, a :exc:`NotEmptyError` exception will be raised and the folder + will not be deleted. + + + .. method:: clean() + + Delete temporary files from the mailbox that have not been accessed in the + last 36 hours. The Maildir specification says that mail-reading programs + should do this occasionally. + + Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special + remarks: + + + .. method:: add(message) + __setitem__(key, message) + update(arg) + + .. warning:: + + These methods generate unique file names based upon the current process + ID. When using multiple threads, undetected name clashes may occur and + cause corruption of the mailbox unless threads are coordinated to avoid + using these methods to manipulate the same mailbox simultaneously. + + + .. method:: flush() + + All changes to Maildir mailboxes are immediately applied, so this method + does nothing. + + + .. method:: lock() + unlock() + + Maildir mailboxes do not support (or require) locking, so these methods do + nothing. + + + .. method:: close() + + :class:`Maildir` instances do not keep any open files and the underlying + mailboxes do not support locking, so this method does nothing. + + + .. method:: get_file(key) + + Depending upon the host platform, it may not be possible to modify or + remove the underlying message while the returned file remains open. + + +.. seealso:: + + `maildir man page from qmail `_ + The original specification of the format. + + `Using maildir format `_ + Notes on Maildir by its inventor. Includes an updated name-creation scheme and + details on "info" semantics. + + `maildir man page from Courier `_ + Another specification of the format. Describes a common extension for supporting + folders. + + +.. _mailbox-mbox: + +:class:`mbox` +^^^^^^^^^^^^^ + + +.. class:: mbox(path, factory=None, create=True) + + A subclass of :class:`Mailbox` for mailboxes in mbox format. Parameter *factory* + is a callable object that accepts a file-like message representation (which + behaves as if opened in binary mode) and returns a custom representation. If + *factory* is ``None``, :class:`mboxMessage` is used as the default message + representation. If *create* is ``True``, the mailbox is created if it does not + exist. + + The mbox format is the classic format for storing mail on Unix systems. All + messages in an mbox mailbox are stored in a single file with the beginning of + each message indicated by a line whose first five characters are "From ". + + Several variations of the mbox format exist to address perceived shortcomings in + the original. In the interest of compatibility, :class:`mbox` implements the + original format, which is sometimes referred to as :dfn:`mboxo`. This means that + the :mailheader:`Content-Length` header, if present, is ignored and that any + occurrences of "From " at the beginning of a line in a message body are + transformed to ">From " when storing the message, although occurrences of ">From + " are not transformed to "From " when reading the message. + + Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special + remarks: + + + .. method:: get_file(key) + + Using the file after calling :meth:`flush` or :meth:`close` on the + :class:`mbox` instance may yield unpredictable results or raise an + exception. + + + .. method:: lock() + unlock() + + Three locking mechanisms are used---dot locking and, if available, the + :c:func:`flock` and :c:func:`lockf` system calls. + + +.. seealso:: + + `mbox man page from qmail `_ + A specification of the format and its variations. + + `mbox man page from tin `_ + Another specification of the format, with details on locking. + + `Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad `_ + An argument for using the original mbox format rather than a variation. + + `"mbox" is a family of several mutually incompatible mailbox formats `_ + A history of mbox variations. + + +.. _mailbox-mh: + +:class:`MH` +^^^^^^^^^^^ + + +.. class:: MH(path, factory=None, create=True) + + A subclass of :class:`Mailbox` for mailboxes in MH format. Parameter *factory* + is a callable object that accepts a file-like message representation (which + behaves as if opened in binary mode) and returns a custom representation. If + *factory* is ``None``, :class:`MHMessage` is used as the default message + representation. If *create* is ``True``, the mailbox is created if it does not + exist. + + MH is a directory-based mailbox format invented for the MH Message Handling + System, a mail user agent. Each message in an MH mailbox resides in its own + file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in + addition to messages. Folders may be nested indefinitely. MH mailboxes also + support :dfn:`sequences`, which are named lists used to logically group + messages without moving them to sub-folders. Sequences are defined in a file + called :file:`.mh_sequences` in each folder. + + The :class:`MH` class manipulates MH mailboxes, but it does not attempt to + emulate all of :program:`mh`'s behaviors. In particular, it does not modify + and is not affected by the :file:`context` or :file:`.mh_profile` files that + are used by :program:`mh` to store its state and configuration. + + :class:`MH` instances have all of the methods of :class:`Mailbox` in addition + to the following: + + + .. method:: list_folders() + + Return a list of the names of all folders. + + + .. method:: get_folder(folder) + + Return an :class:`MH` instance representing the folder whose name is + *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder + does not exist. + + + .. method:: add_folder(folder) + + Create a folder whose name is *folder* and return an :class:`MH` instance + representing it. + + + .. method:: remove_folder(folder) + + Delete the folder whose name is *folder*. If the folder contains any + messages, a :exc:`NotEmptyError` exception will be raised and the folder + will not be deleted. + + + .. method:: get_sequences() + + Return a dictionary of sequence names mapped to key lists. If there are no + sequences, the empty dictionary is returned. + + + .. method:: set_sequences(sequences) + + Re-define the sequences that exist in the mailbox based upon *sequences*, + a dictionary of names mapped to key lists, like returned by + :meth:`get_sequences`. + + + .. method:: pack() + + Rename messages in the mailbox as necessary to eliminate gaps in + numbering. Entries in the sequences list are updated correspondingly. + + .. note:: + + Already-issued keys are invalidated by this operation and should not be + subsequently used. + + Some :class:`Mailbox` methods implemented by :class:`MH` deserve special + remarks: + + + .. method:: remove(key) + __delitem__(key) + discard(key) + + These methods immediately delete the message. The MH convention of marking + a message for deletion by prepending a comma to its name is not used. + + + .. method:: lock() + unlock() + + Three locking mechanisms are used---dot locking and, if available, the + :c:func:`flock` and :c:func:`lockf` system calls. For MH mailboxes, locking + the mailbox means locking the :file:`.mh_sequences` file and, only for the + duration of any operations that affect them, locking individual message + files. + + + .. method:: get_file(key) + + Depending upon the host platform, it may not be possible to remove the + underlying message while the returned file remains open. + + + .. method:: flush() + + All changes to MH mailboxes are immediately applied, so this method does + nothing. + + + .. method:: close() + + :class:`MH` instances do not keep any open files, so this method is + equivalent to :meth:`unlock`. + + +.. seealso:: + + `nmh - Message Handling System `_ + Home page of :program:`nmh`, an updated version of the original :program:`mh`. + + `MH & nmh: Email for Users & Programmers `_ + A GPL-licensed book on :program:`mh` and :program:`nmh`, with some information + on the mailbox format. + + +.. _mailbox-babyl: + +:class:`Babyl` +^^^^^^^^^^^^^^ + + +.. class:: Babyl(path, factory=None, create=True) + + A subclass of :class:`Mailbox` for mailboxes in Babyl format. Parameter + *factory* is a callable object that accepts a file-like message representation + (which behaves as if opened in binary mode) and returns a custom representation. + If *factory* is ``None``, :class:`BabylMessage` is used as the default message + representation. If *create* is ``True``, the mailbox is created if it does not + exist. + + Babyl is a single-file mailbox format used by the Rmail mail user agent + included with Emacs. The beginning of a message is indicated by a line + containing the two characters Control-Underscore (``'\037'``) and Control-L + (``'\014'``). The end of a message is indicated by the start of the next + message or, in the case of the last message, a line containing a + Control-Underscore (``'\037'``) character. + + Messages in a Babyl mailbox have two sets of headers, original headers and + so-called visible headers. Visible headers are typically a subset of the + original headers that have been reformatted or abridged to be more + attractive. Each message in a Babyl mailbox also has an accompanying list of + :dfn:`labels`, or short strings that record extra information about the + message, and a list of all user-defined labels found in the mailbox is kept + in the Babyl options section. + + :class:`Babyl` instances have all of the methods of :class:`Mailbox` in + addition to the following: + + + .. method:: get_labels() + + Return a list of the names of all user-defined labels used in the mailbox. + + .. note:: + + The actual messages are inspected to determine which labels exist in + the mailbox rather than consulting the list of labels in the Babyl + options section, but the Babyl section is updated whenever the mailbox + is modified. + + Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special + remarks: + + + .. method:: get_file(key) + + In Babyl mailboxes, the headers of a message are not stored contiguously + with the body of the message. To generate a file-like representation, the + headers and body are copied together into an :class:`io.BytesIO` instance, + which has an API identical to that of a + file. As a result, the file-like object is truly independent of the + underlying mailbox but does not save memory compared to a string + representation. + + + .. method:: lock() + unlock() + + Three locking mechanisms are used---dot locking and, if available, the + :c:func:`flock` and :c:func:`lockf` system calls. + + +.. seealso:: + + `Format of Version 5 Babyl Files `_ + A specification of the Babyl format. + + `Reading Mail with Rmail `_ + The Rmail manual, with some information on Babyl semantics. + + +.. _mailbox-mmdf: + +:class:`MMDF` +^^^^^^^^^^^^^ + + +.. class:: MMDF(path, factory=None, create=True) + + A subclass of :class:`Mailbox` for mailboxes in MMDF format. Parameter *factory* + is a callable object that accepts a file-like message representation (which + behaves as if opened in binary mode) and returns a custom representation. If + *factory* is ``None``, :class:`MMDFMessage` is used as the default message + representation. If *create* is ``True``, the mailbox is created if it does not + exist. + + MMDF is a single-file mailbox format invented for the Multichannel Memorandum + Distribution Facility, a mail transfer agent. Each message is in the same + form as an mbox message but is bracketed before and after by lines containing + four Control-A (``'\001'``) characters. As with the mbox format, the + beginning of each message is indicated by a line whose first five characters + are "From ", but additional occurrences of "From " are not transformed to + ">From " when storing messages because the extra message separator lines + prevent mistaking such occurrences for the starts of subsequent messages. + + Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special + remarks: + + + .. method:: get_file(key) + + Using the file after calling :meth:`flush` or :meth:`close` on the + :class:`MMDF` instance may yield unpredictable results or raise an + exception. + + + .. method:: lock() + unlock() + + Three locking mechanisms are used---dot locking and, if available, the + :c:func:`flock` and :c:func:`lockf` system calls. + + +.. seealso:: + + `mmdf man page from tin `_ + A specification of MMDF format from the documentation of tin, a newsreader. + + `MMDF `_ + A Wikipedia article describing the Multichannel Memorandum Distribution + Facility. + + +.. _mailbox-message-objects: + +:class:`Message` objects +------------------------ + + +.. class:: Message(message=None) + + A subclass of the :mod:`email.message` module's + :class:`~email.message.Message`. Subclasses of :class:`mailbox.Message` add + mailbox-format-specific state and behavior. + + If *message* is omitted, the new instance is created in a default, empty state. + If *message* is an :class:`email.message.Message` instance, its contents are + copied; furthermore, any format-specific information is converted insofar as + possible if *message* is a :class:`Message` instance. If *message* is a string, + a byte string, + or a file, it should contain an :rfc:`2822`\ -compliant message, which is read + and parsed. Files should be open in binary mode, but text mode files + are accepted for backward compatibility. + + The format-specific state and behaviors offered by subclasses vary, but in + general it is only the properties that are not specific to a particular + mailbox that are supported (although presumably the properties are specific + to a particular mailbox format). For example, file offsets for single-file + mailbox formats and file names for directory-based mailbox formats are not + retained, because they are only applicable to the original mailbox. But state + such as whether a message has been read by the user or marked as important is + retained, because it applies to the message itself. + + There is no requirement that :class:`Message` instances be used to represent + messages retrieved using :class:`Mailbox` instances. In some situations, the + time and memory required to generate :class:`Message` representations might + not be acceptable. For such situations, :class:`Mailbox` instances also + offer string and file-like representations, and a custom message factory may + be specified when a :class:`Mailbox` instance is initialized. + + +.. _mailbox-maildirmessage: + +:class:`MaildirMessage` +^^^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: MaildirMessage(message=None) + + A message with Maildir-specific behaviors. Parameter *message* has the same + meaning as with the :class:`Message` constructor. + + Typically, a mail user agent application moves all of the messages in the + :file:`new` subdirectory to the :file:`cur` subdirectory after the first time + the user opens and closes the mailbox, recording that the messages are old + whether or not they've actually been read. Each message in :file:`cur` has an + "info" section added to its file name to store information about its state. + (Some mail readers may also add an "info" section to messages in + :file:`new`.) The "info" section may take one of two forms: it may contain + "2," followed by a list of standardized flags (e.g., "2,FR") or it may + contain "1," followed by so-called experimental information. Standard flags + for Maildir messages are as follows: + + +------+---------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+=========+================================+ + | D | Draft | Under composition | + +------+---------+--------------------------------+ + | F | Flagged | Marked as important | + +------+---------+--------------------------------+ + | P | Passed | Forwarded, resent, or bounced | + +------+---------+--------------------------------+ + | R | Replied | Replied to | + +------+---------+--------------------------------+ + | S | Seen | Read | + +------+---------+--------------------------------+ + | T | Trashed | Marked for subsequent deletion | + +------+---------+--------------------------------+ + + :class:`MaildirMessage` instances offer the following methods: + + + .. method:: get_subdir() + + Return either "new" (if the message should be stored in the :file:`new` + subdirectory) or "cur" (if the message should be stored in the :file:`cur` + subdirectory). + + .. note:: + + A message is typically moved from :file:`new` to :file:`cur` after its + mailbox has been accessed, whether or not the message is has been + read. A message ``msg`` has been read if ``"S" in msg.get_flags()`` is + ``True``. + + + .. method:: set_subdir(subdir) + + Set the subdirectory the message should be stored in. Parameter *subdir* + must be either "new" or "cur". + + + .. method:: get_flags() + + Return a string specifying the flags that are currently set. If the + message complies with the standard Maildir format, the result is the + concatenation in alphabetical order of zero or one occurrence of each of + ``'D'``, ``'F'``, ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string + is returned if no flags are set or if "info" contains experimental + semantics. + + + .. method:: set_flags(flags) + + Set the flags specified by *flags* and unset all others. + + + .. method:: add_flag(flag) + + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. The current "info" is overwritten whether or not it contains + experimental information rather than flags. + + + .. method:: remove_flag(flag) + + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. If "info" contains experimental information rather than + flags, the current "info" is not modified. + + + .. method:: get_date() + + Return the delivery date of the message as a floating-point number + representing seconds since the epoch. + + + .. method:: set_date(date) + + Set the delivery date of the message to *date*, a floating-point number + representing seconds since the epoch. + + + .. method:: get_info() + + Return a string containing the "info" for a message. This is useful for + accessing and modifying "info" that is experimental (i.e., not a list of + flags). + + + .. method:: set_info(info) + + Set "info" to *info*, which should be a string. + +When a :class:`MaildirMessage` instance is created based upon an +:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status` +and :mailheader:`X-Status` headers are omitted and the following conversions +take place: + ++--------------------+----------------------------------------------+ +| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` | +| | state | ++====================+==============================================+ +| "cur" subdirectory | O flag | ++--------------------+----------------------------------------------+ +| F flag | F flag | ++--------------------+----------------------------------------------+ +| R flag | A flag | ++--------------------+----------------------------------------------+ +| S flag | R flag | ++--------------------+----------------------------------------------+ +| T flag | D flag | ++--------------------+----------------------------------------------+ + +When a :class:`MaildirMessage` instance is created based upon an +:class:`MHMessage` instance, the following conversions take place: + ++-------------------------------+--------------------------+ +| Resulting state | :class:`MHMessage` state | ++===============================+==========================+ +| "cur" subdirectory | "unseen" sequence | ++-------------------------------+--------------------------+ +| "cur" subdirectory and S flag | no "unseen" sequence | ++-------------------------------+--------------------------+ +| F flag | "flagged" sequence | ++-------------------------------+--------------------------+ +| R flag | "replied" sequence | ++-------------------------------+--------------------------+ + +When a :class:`MaildirMessage` instance is created based upon a +:class:`BabylMessage` instance, the following conversions take place: + ++-------------------------------+-------------------------------+ +| Resulting state | :class:`BabylMessage` state | ++===============================+===============================+ +| "cur" subdirectory | "unseen" label | ++-------------------------------+-------------------------------+ +| "cur" subdirectory and S flag | no "unseen" label | ++-------------------------------+-------------------------------+ +| P flag | "forwarded" or "resent" label | ++-------------------------------+-------------------------------+ +| R flag | "answered" label | ++-------------------------------+-------------------------------+ +| T flag | "deleted" label | ++-------------------------------+-------------------------------+ + + +.. _mailbox-mboxmessage: + +:class:`mboxMessage` +^^^^^^^^^^^^^^^^^^^^ + + +.. class:: mboxMessage(message=None) + + A message with mbox-specific behaviors. Parameter *message* has the same meaning + as with the :class:`Message` constructor. + + Messages in an mbox mailbox are stored together in a single file. The + sender's envelope address and the time of delivery are typically stored in a + line beginning with "From " that is used to indicate the start of a message, + though there is considerable variation in the exact format of this data among + mbox implementations. Flags that indicate the state of the message, such as + whether it has been read or marked as important, are typically stored in + :mailheader:`Status` and :mailheader:`X-Status` headers. + + Conventional flags for mbox messages are as follows: + + +------+----------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+==========+================================+ + | R | Read | Read | + +------+----------+--------------------------------+ + | O | Old | Previously detected by MUA | + +------+----------+--------------------------------+ + | D | Deleted | Marked for subsequent deletion | + +------+----------+--------------------------------+ + | F | Flagged | Marked as important | + +------+----------+--------------------------------+ + | A | Answered | Replied to | + +------+----------+--------------------------------+ + + The "R" and "O" flags are stored in the :mailheader:`Status` header, and the + "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The + flags and headers typically appear in the order mentioned. + + :class:`mboxMessage` instances offer the following methods: + + + .. method:: get_from() + + Return a string representing the "From " line that marks the start of the + message in an mbox mailbox. The leading "From " and the trailing newline + are excluded. + + + .. method:: set_from(from_, time_=None) + + Set the "From " line to *from_*, which should be specified without a + leading "From " or trailing newline. For convenience, *time_* may be + specified and will be formatted appropriately and appended to *from_*. If + *time_* is specified, it should be a :class:`time.struct_time` instance, a + tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use + :meth:`time.gmtime`). + + + .. method:: get_flags() + + Return a string specifying the flags that are currently set. If the + message complies with the conventional format, the result is the + concatenation in the following order of zero or one occurrence of each of + ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. + + + .. method:: set_flags(flags) + + Set the flags specified by *flags* and unset all others. Parameter *flags* + should be the concatenation in any order of zero or more occurrences of + each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. + + + .. method:: add_flag(flag) + + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. + + + .. method:: remove_flag(flag) + + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. + +When an :class:`mboxMessage` instance is created based upon a +:class:`MaildirMessage` instance, a "From " line is generated based upon the +:class:`MaildirMessage` instance's delivery date, and the following conversions +take place: + ++-----------------+-------------------------------+ +| Resulting state | :class:`MaildirMessage` state | ++=================+===============================+ +| R flag | S flag | ++-----------------+-------------------------------+ +| O flag | "cur" subdirectory | ++-----------------+-------------------------------+ +| D flag | T flag | ++-----------------+-------------------------------+ +| F flag | F flag | ++-----------------+-------------------------------+ +| A flag | R flag | ++-----------------+-------------------------------+ + +When an :class:`mboxMessage` instance is created based upon an +:class:`MHMessage` instance, the following conversions take place: + ++-------------------+--------------------------+ +| Resulting state | :class:`MHMessage` state | ++===================+==========================+ +| R flag and O flag | no "unseen" sequence | ++-------------------+--------------------------+ +| O flag | "unseen" sequence | ++-------------------+--------------------------+ +| F flag | "flagged" sequence | ++-------------------+--------------------------+ +| A flag | "replied" sequence | ++-------------------+--------------------------+ + +When an :class:`mboxMessage` instance is created based upon a +:class:`BabylMessage` instance, the following conversions take place: + ++-------------------+-----------------------------+ +| Resulting state | :class:`BabylMessage` state | ++===================+=============================+ +| R flag and O flag | no "unseen" label | ++-------------------+-----------------------------+ +| O flag | "unseen" label | ++-------------------+-----------------------------+ +| D flag | "deleted" label | ++-------------------+-----------------------------+ +| A flag | "answered" label | ++-------------------+-----------------------------+ + +When a :class:`Message` instance is created based upon an :class:`MMDFMessage` +instance, the "From " line is copied and all flags directly correspond: + ++-----------------+----------------------------+ +| Resulting state | :class:`MMDFMessage` state | ++=================+============================+ +| R flag | R flag | ++-----------------+----------------------------+ +| O flag | O flag | ++-----------------+----------------------------+ +| D flag | D flag | ++-----------------+----------------------------+ +| F flag | F flag | ++-----------------+----------------------------+ +| A flag | A flag | ++-----------------+----------------------------+ + + +.. _mailbox-mhmessage: + +:class:`MHMessage` +^^^^^^^^^^^^^^^^^^ + + +.. class:: MHMessage(message=None) + + A message with MH-specific behaviors. Parameter *message* has the same meaning + as with the :class:`Message` constructor. + + MH messages do not support marks or flags in the traditional sense, but they + do support sequences, which are logical groupings of arbitrary messages. Some + mail reading programs (although not the standard :program:`mh` and + :program:`nmh`) use sequences in much the same way flags are used with other + formats, as follows: + + +----------+------------------------------------------+ + | Sequence | Explanation | + +==========+==========================================+ + | unseen | Not read, but previously detected by MUA | + +----------+------------------------------------------+ + | replied | Replied to | + +----------+------------------------------------------+ + | flagged | Marked as important | + +----------+------------------------------------------+ + + :class:`MHMessage` instances offer the following methods: + + + .. method:: get_sequences() + + Return a list of the names of sequences that include this message. + + + .. method:: set_sequences(sequences) + + Set the list of sequences that include this message. + + + .. method:: add_sequence(sequence) + + Add *sequence* to the list of sequences that include this message. + + + .. method:: remove_sequence(sequence) + + Remove *sequence* from the list of sequences that include this message. + +When an :class:`MHMessage` instance is created based upon a +:class:`MaildirMessage` instance, the following conversions take place: + ++--------------------+-------------------------------+ +| Resulting state | :class:`MaildirMessage` state | ++====================+===============================+ +| "unseen" sequence | no S flag | ++--------------------+-------------------------------+ +| "replied" sequence | R flag | ++--------------------+-------------------------------+ +| "flagged" sequence | F flag | ++--------------------+-------------------------------+ + +When an :class:`MHMessage` instance is created based upon an +:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status` +and :mailheader:`X-Status` headers are omitted and the following conversions +take place: + ++--------------------+----------------------------------------------+ +| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` | +| | state | ++====================+==============================================+ +| "unseen" sequence | no R flag | ++--------------------+----------------------------------------------+ +| "replied" sequence | A flag | ++--------------------+----------------------------------------------+ +| "flagged" sequence | F flag | ++--------------------+----------------------------------------------+ + +When an :class:`MHMessage` instance is created based upon a +:class:`BabylMessage` instance, the following conversions take place: + ++--------------------+-----------------------------+ +| Resulting state | :class:`BabylMessage` state | ++====================+=============================+ +| "unseen" sequence | "unseen" label | ++--------------------+-----------------------------+ +| "replied" sequence | "answered" label | ++--------------------+-----------------------------+ + + +.. _mailbox-babylmessage: + +:class:`BabylMessage` +^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: BabylMessage(message=None) + + A message with Babyl-specific behaviors. Parameter *message* has the same + meaning as with the :class:`Message` constructor. + + Certain message labels, called :dfn:`attributes`, are defined by convention + to have special meanings. The attributes are as follows: + + +-----------+------------------------------------------+ + | Label | Explanation | + +===========+==========================================+ + | unseen | Not read, but previously detected by MUA | + +-----------+------------------------------------------+ + | deleted | Marked for subsequent deletion | + +-----------+------------------------------------------+ + | filed | Copied to another file or mailbox | + +-----------+------------------------------------------+ + | answered | Replied to | + +-----------+------------------------------------------+ + | forwarded | Forwarded | + +-----------+------------------------------------------+ + | edited | Modified by the user | + +-----------+------------------------------------------+ + | resent | Resent | + +-----------+------------------------------------------+ + + By default, Rmail displays only visible headers. The :class:`BabylMessage` + class, though, uses the original headers because they are more + complete. Visible headers may be accessed explicitly if desired. + + :class:`BabylMessage` instances offer the following methods: + + + .. method:: get_labels() + + Return a list of labels on the message. + + + .. method:: set_labels(labels) + + Set the list of labels on the message to *labels*. + + + .. method:: add_label(label) + + Add *label* to the list of labels on the message. + + + .. method:: remove_label(label) + + Remove *label* from the list of labels on the message. + + + .. method:: get_visible() + + Return an :class:`Message` instance whose headers are the message's + visible headers and whose body is empty. + + + .. method:: set_visible(visible) + + Set the message's visible headers to be the same as the headers in + *message*. Parameter *visible* should be a :class:`Message` instance, an + :class:`email.message.Message` instance, a string, or a file-like object + (which should be open in text mode). + + + .. method:: update_visible() + + When a :class:`BabylMessage` instance's original headers are modified, the + visible headers are not automatically modified to correspond. This method + updates the visible headers as follows: each visible header with a + corresponding original header is set to the value of the original header, + each visible header without a corresponding original header is removed, + and any of :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`, + :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are + present in the original headers but not the visible headers are added to + the visible headers. + +When a :class:`BabylMessage` instance is created based upon a +:class:`MaildirMessage` instance, the following conversions take place: + ++-------------------+-------------------------------+ +| Resulting state | :class:`MaildirMessage` state | ++===================+===============================+ +| "unseen" label | no S flag | ++-------------------+-------------------------------+ +| "deleted" label | T flag | ++-------------------+-------------------------------+ +| "answered" label | R flag | ++-------------------+-------------------------------+ +| "forwarded" label | P flag | ++-------------------+-------------------------------+ + +When a :class:`BabylMessage` instance is created based upon an +:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status` +and :mailheader:`X-Status` headers are omitted and the following conversions +take place: + ++------------------+----------------------------------------------+ +| Resulting state | :class:`mboxMessage` or :class:`MMDFMessage` | +| | state | ++==================+==============================================+ +| "unseen" label | no R flag | ++------------------+----------------------------------------------+ +| "deleted" label | D flag | ++------------------+----------------------------------------------+ +| "answered" label | A flag | ++------------------+----------------------------------------------+ + +When a :class:`BabylMessage` instance is created based upon an +:class:`MHMessage` instance, the following conversions take place: + ++------------------+--------------------------+ +| Resulting state | :class:`MHMessage` state | ++==================+==========================+ +| "unseen" label | "unseen" sequence | ++------------------+--------------------------+ +| "answered" label | "replied" sequence | ++------------------+--------------------------+ + + +.. _mailbox-mmdfmessage: + +:class:`MMDFMessage` +^^^^^^^^^^^^^^^^^^^^ + + +.. class:: MMDFMessage(message=None) + + A message with MMDF-specific behaviors. Parameter *message* has the same meaning + as with the :class:`Message` constructor. + + As with message in an mbox mailbox, MMDF messages are stored with the + sender's address and the delivery date in an initial line beginning with + "From ". Likewise, flags that indicate the state of the message are + typically stored in :mailheader:`Status` and :mailheader:`X-Status` headers. + + Conventional flags for MMDF messages are identical to those of mbox message + and are as follows: + + +------+----------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+==========+================================+ + | R | Read | Read | + +------+----------+--------------------------------+ + | O | Old | Previously detected by MUA | + +------+----------+--------------------------------+ + | D | Deleted | Marked for subsequent deletion | + +------+----------+--------------------------------+ + | F | Flagged | Marked as important | + +------+----------+--------------------------------+ + | A | Answered | Replied to | + +------+----------+--------------------------------+ + + The "R" and "O" flags are stored in the :mailheader:`Status` header, and the + "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The + flags and headers typically appear in the order mentioned. + + :class:`MMDFMessage` instances offer the following methods, which are + identical to those offered by :class:`mboxMessage`: + + + .. method:: get_from() + + Return a string representing the "From " line that marks the start of the + message in an mbox mailbox. The leading "From " and the trailing newline + are excluded. + + + .. method:: set_from(from_, time_=None) + + Set the "From " line to *from_*, which should be specified without a + leading "From " or trailing newline. For convenience, *time_* may be + specified and will be formatted appropriately and appended to *from_*. If + *time_* is specified, it should be a :class:`time.struct_time` instance, a + tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use + :meth:`time.gmtime`). + + + .. method:: get_flags() + + Return a string specifying the flags that are currently set. If the + message complies with the conventional format, the result is the + concatenation in the following order of zero or one occurrence of each of + ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. + + + .. method:: set_flags(flags) + + Set the flags specified by *flags* and unset all others. Parameter *flags* + should be the concatenation in any order of zero or more occurrences of + each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. + + + .. method:: add_flag(flag) + + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. + + + .. method:: remove_flag(flag) + + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. + +When an :class:`MMDFMessage` instance is created based upon a +:class:`MaildirMessage` instance, a "From " line is generated based upon the +:class:`MaildirMessage` instance's delivery date, and the following conversions +take place: + ++-----------------+-------------------------------+ +| Resulting state | :class:`MaildirMessage` state | ++=================+===============================+ +| R flag | S flag | ++-----------------+-------------------------------+ +| O flag | "cur" subdirectory | ++-----------------+-------------------------------+ +| D flag | T flag | ++-----------------+-------------------------------+ +| F flag | F flag | ++-----------------+-------------------------------+ +| A flag | R flag | ++-----------------+-------------------------------+ + +When an :class:`MMDFMessage` instance is created based upon an +:class:`MHMessage` instance, the following conversions take place: + ++-------------------+--------------------------+ +| Resulting state | :class:`MHMessage` state | ++===================+==========================+ +| R flag and O flag | no "unseen" sequence | ++-------------------+--------------------------+ +| O flag | "unseen" sequence | ++-------------------+--------------------------+ +| F flag | "flagged" sequence | ++-------------------+--------------------------+ +| A flag | "replied" sequence | ++-------------------+--------------------------+ + +When an :class:`MMDFMessage` instance is created based upon a +:class:`BabylMessage` instance, the following conversions take place: + ++-------------------+-----------------------------+ +| Resulting state | :class:`BabylMessage` state | ++===================+=============================+ +| R flag and O flag | no "unseen" label | ++-------------------+-----------------------------+ +| O flag | "unseen" label | ++-------------------+-----------------------------+ +| D flag | "deleted" label | ++-------------------+-----------------------------+ +| A flag | "answered" label | ++-------------------+-----------------------------+ + +When an :class:`MMDFMessage` instance is created based upon an +:class:`mboxMessage` instance, the "From " line is copied and all flags directly +correspond: + ++-----------------+----------------------------+ +| Resulting state | :class:`mboxMessage` state | ++=================+============================+ +| R flag | R flag | ++-----------------+----------------------------+ +| O flag | O flag | ++-----------------+----------------------------+ +| D flag | D flag | ++-----------------+----------------------------+ +| F flag | F flag | ++-----------------+----------------------------+ +| A flag | A flag | ++-----------------+----------------------------+ + + +Exceptions +---------- + +The following exception classes are defined in the :mod:`mailbox` module: + + +.. exception:: Error() + + The based class for all other module-specific exceptions. + + +.. exception:: NoSuchMailboxError() + + Raised when a mailbox is expected but is not found, such as when instantiating a + :class:`Mailbox` subclass with a path that does not exist (and with the *create* + parameter set to ``False``), or when opening a folder that does not exist. + + +.. exception:: NotEmptyError() + + Raised when a mailbox is not empty but is expected to be, such as when deleting + a folder that contains messages. + + +.. exception:: ExternalClashError() + + Raised when some mailbox-related condition beyond the control of the program + causes it to be unable to proceed, such as when failing to acquire a lock that + another program already holds a lock, or when a uniquely-generated file name + already exists. + + +.. exception:: FormatError() + + Raised when the data in a file cannot be parsed, such as when an :class:`MH` + instance attempts to read a corrupted :file:`.mh_sequences` file. + + +.. _mailbox-examples: + +Examples +-------- + +A simple example of printing the subjects of all messages in a mailbox that seem +interesting:: + + import mailbox + for message in mailbox.mbox('~/mbox'): + subject = message['subject'] # Could possibly be None. + if subject and 'python' in subject.lower(): + print(subject) + +To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the +format-specific information that can be converted:: + + import mailbox + destination = mailbox.MH('~/Mail') + destination.lock() + for message in mailbox.Babyl('~/RMAIL'): + destination.add(mailbox.MHMessage(message)) + destination.flush() + destination.unlock() + +This example sorts mail from several mailing lists into different mailboxes, +being careful to avoid mail corruption due to concurrent modification by other +programs, mail loss due to interruption of the program, or premature termination +due to malformed messages in the mailbox:: + + import mailbox + import email.errors + + list_names = ('python-list', 'python-dev', 'python-bugs') + + boxes = {name: mailbox.mbox('~/email/%s' % name) for name in list_names} + inbox = mailbox.Maildir('~/Maildir', factory=None) + + for key in inbox.iterkeys(): + try: + message = inbox[key] + except email.errors.MessageParseError: + continue # The message is malformed. Just leave it. + + for name in list_names: + list_id = message['list-id'] + if list_id and name in list_id: + # Get mailbox to use + box = boxes[name] + + # Write copy to disk before removing original. + # If there's a crash, you might duplicate a message, but + # that's better than losing a message completely. + box.lock() + box.add(message) + box.flush() + box.unlock() + + # Remove original message + inbox.lock() + inbox.discard(key) + inbox.flush() + inbox.unlock() + break # Found destination, so stop looking. + + for box in boxes.itervalues(): + box.close() + diff --git a/cpython_2/environment/repo/Doc/library/mailcap.rst b/cpython_2/environment/repo/Doc/library/mailcap.rst new file mode 100644 index 0000000000000000000000000000000000000000..bf9639bdaca50a8c7b9b833bb06f0497760adadf --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/mailcap.rst @@ -0,0 +1,76 @@ +:mod:`mailcap` --- Mailcap file handling +======================================== + +.. module:: mailcap + :synopsis: Mailcap file handling. + +**Source code:** :source:`Lib/mailcap.py` + +-------------- + +Mailcap files are used to configure how MIME-aware applications such as mail +readers and Web browsers react to files with different MIME types. (The name +"mailcap" is derived from the phrase "mail capability".) For example, a mailcap +file might contain a line like ``video/mpeg; xmpeg %s``. Then, if the user +encounters an email message or Web document with the MIME type +:mimetype:`video/mpeg`, ``%s`` will be replaced by a filename (usually one +belonging to a temporary file) and the :program:`xmpeg` program can be +automatically started to view the file. + +The mailcap format is documented in :rfc:`1524`, "A User Agent Configuration +Mechanism For Multimedia Mail Format Information", but is not an Internet +standard. However, mailcap files are supported on most Unix systems. + + +.. function:: findmatch(caps, MIMEtype, key='view', filename='/dev/null', plist=[]) + + Return a 2-tuple; the first element is a string containing the command line to + be executed (which can be passed to :func:`os.system`), and the second element + is the mailcap entry for a given MIME type. If no matching MIME type can be + found, ``(None, None)`` is returned. + + *key* is the name of the field desired, which represents the type of activity to + be performed; the default value is 'view', since in the most common case you + simply want to view the body of the MIME-typed data. Other possible values + might be 'compose' and 'edit', if you wanted to create a new body of the given + MIME type or alter the existing body data. See :rfc:`1524` for a complete list + of these fields. + + *filename* is the filename to be substituted for ``%s`` in the command line; the + default value is ``'/dev/null'`` which is almost certainly not what you want, so + usually you'll override it by specifying a filename. + + *plist* can be a list containing named parameters; the default value is simply + an empty list. Each entry in the list must be a string containing the parameter + name, an equals sign (``'='``), and the parameter's value. Mailcap entries can + contain named parameters like ``%{foo}``, which will be replaced by the value + of the parameter named 'foo'. For example, if the command line ``showpartial + %{id} %{number} %{total}`` was in a mailcap file, and *plist* was set to + ``['id=1', 'number=2', 'total=3']``, the resulting command line would be + ``'showpartial 1 2 3'``. + + In a mailcap file, the "test" field can optionally be specified to test some + external condition (such as the machine architecture, or the window system in + use) to determine whether or not the mailcap line applies. :func:`findmatch` + will automatically check such conditions and skip the entry if the check fails. + + +.. function:: getcaps() + + Returns a dictionary mapping MIME types to a list of mailcap file entries. This + dictionary must be passed to the :func:`findmatch` function. An entry is stored + as a list of dictionaries, but it shouldn't be necessary to know the details of + this representation. + + The information is derived from all of the mailcap files found on the system. + Settings in the user's mailcap file :file:`$HOME/.mailcap` will override + settings in the system mailcap files :file:`/etc/mailcap`, + :file:`/usr/etc/mailcap`, and :file:`/usr/local/etc/mailcap`. + +An example usage:: + + >>> import mailcap + >>> d = mailcap.getcaps() + >>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223') + ('xmpeg tmp1223', {'view': 'xmpeg %s'}) + diff --git a/cpython_2/environment/repo/Doc/library/markup.rst b/cpython_2/environment/repo/Doc/library/markup.rst new file mode 100644 index 0000000000000000000000000000000000000000..1588aa8a6aee707e48445c7b2c526b6ea388d213 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/markup.rst @@ -0,0 +1,27 @@ +.. _markup: + +********************************** +Structured Markup Processing Tools +********************************** + +Python supports a variety of modules to work with various forms of structured +data markup. This includes modules to work with the Standard Generalized Markup +Language (SGML) and the Hypertext Markup Language (HTML), and several interfaces +for working with the Extensible Markup Language (XML). + + +.. toctree:: + + html.rst + html.parser.rst + html.entities.rst + xml.rst + xml.etree.elementtree.rst + xml.dom.rst + xml.dom.minidom.rst + xml.dom.pulldom.rst + xml.sax.rst + xml.sax.handler.rst + xml.sax.utils.rst + xml.sax.reader.rst + pyexpat.rst diff --git a/cpython_2/environment/repo/Doc/library/marshal.rst b/cpython_2/environment/repo/Doc/library/marshal.rst new file mode 100644 index 0000000000000000000000000000000000000000..d65afc200411334700eb18d3a2a0cc13027422ce --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/marshal.rst @@ -0,0 +1,118 @@ +:mod:`marshal` --- Internal Python object serialization +======================================================= + +.. module:: marshal + :synopsis: Convert Python objects to streams of bytes and back (with different + constraints). + +-------------- + +This module contains functions that can read and write Python values in a binary +format. The format is specific to Python, but independent of machine +architecture issues (e.g., you can write a Python value to a file on a PC, +transport the file to a Sun, and read it back there). Details of the format are +undocumented on purpose; it may change between Python versions (although it +rarely does). [#]_ + +.. index:: + module: pickle + module: shelve + +This is not a general "persistence" module. For general persistence and +transfer of Python objects through RPC calls, see the modules :mod:`pickle` and +:mod:`shelve`. The :mod:`marshal` module exists mainly to support reading and +writing the "pseudo-compiled" code for Python modules of :file:`.pyc` files. +Therefore, the Python maintainers reserve the right to modify the marshal format +in backward incompatible ways should the need arise. If you're serializing and +de-serializing Python objects, use the :mod:`pickle` module instead -- the +performance is comparable, version independence is guaranteed, and pickle +supports a substantially wider range of objects than marshal. + +.. warning:: + + The :mod:`marshal` module is not intended to be secure against erroneous or + maliciously constructed data. Never unmarshal data received from an + untrusted or unauthenticated source. + +.. index:: object; code, code object + +Not all Python object types are supported; in general, only objects whose value +is independent from a particular invocation of Python can be written and read by +this module. The following types are supported: booleans, integers, floating +point numbers, complex numbers, strings, bytes, bytearrays, tuples, lists, sets, +frozensets, dictionaries, and code objects, where it should be understood that +tuples, lists, sets, frozensets and dictionaries are only supported as long as +the values contained therein are themselves supported. The +singletons :const:`None`, :const:`Ellipsis` and :exc:`StopIteration` can also be +marshalled and unmarshalled. +For format *version* lower than 3, recursive lists, sets and dictionaries cannot +be written (see below). + +There are functions that read/write files as well as functions operating on +bytes-like objects. + +The module defines these functions: + + +.. function:: dump(value, file[, version]) + + Write the value on the open file. The value must be a supported type. The + file must be a writeable :term:`binary file`. + + If the value has (or contains an object that has) an unsupported type, a + :exc:`ValueError` exception is raised --- but garbage data will also be written + to the file. The object will not be properly read back by :func:`load`. + + The *version* argument indicates the data format that ``dump`` should use + (see below). + + +.. function:: load(file) + + Read one value from the open file and return it. If no valid value is read + (e.g. because the data has a different Python version's incompatible marshal + format), raise :exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`. The + file must be a readable :term:`binary file`. + + .. note:: + + If an object containing an unsupported type was marshalled with :func:`dump`, + :func:`load` will substitute ``None`` for the unmarshallable type. + + +.. function:: dumps(value[, version]) + + Return the bytes object that would be written to a file by ``dump(value, file)``. The + value must be a supported type. Raise a :exc:`ValueError` exception if value + has (or contains an object that has) an unsupported type. + + The *version* argument indicates the data format that ``dumps`` should use + (see below). + + +.. function:: loads(bytes) + + Convert the :term:`bytes-like object` to a value. If no valid value is found, raise + :exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`. Extra bytes in the + input are ignored. + + +In addition, the following constants are defined: + +.. data:: version + + Indicates the format that the module uses. Version 0 is the historical + format, version 1 shares interned strings and version 2 uses a binary format + for floating point numbers. + Version 3 adds support for object instancing and recursion. + The current version is 4. + + +.. rubric:: Footnotes + +.. [#] The name of this module stems from a bit of terminology used by the designers of + Modula-3 (amongst others), who use the term "marshalling" for shipping of data + around in a self-contained form. Strictly speaking, "to marshal" means to + convert some data from internal to external form (in an RPC buffer for instance) + and "unmarshalling" for the reverse process. + diff --git a/cpython_2/environment/repo/Doc/library/math.rst b/cpython_2/environment/repo/Doc/library/math.rst new file mode 100644 index 0000000000000000000000000000000000000000..6ec1feee35a6dc7151c5fd981f7e6db9a96703a3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/math.rst @@ -0,0 +1,656 @@ +:mod:`math` --- Mathematical functions +====================================== + +.. module:: math + :synopsis: Mathematical functions (sin() etc.). + +.. testsetup:: + + from math import fsum + +-------------- + +This module provides access to the mathematical functions defined by the C +standard. + +These functions cannot be used with complex numbers; use the functions of the +same name from the :mod:`cmath` module if you require support for complex +numbers. The distinction between functions which support complex numbers and +those which don't is made since most users do not want to learn quite as much +mathematics as required to understand complex numbers. Receiving an exception +instead of a complex result allows earlier detection of the unexpected complex +number used as a parameter, so that the programmer can determine how and why it +was generated in the first place. + +The following functions are provided by this module. Except when explicitly +noted otherwise, all return values are floats. + + +Number-theoretic and representation functions +--------------------------------------------- + +.. function:: ceil(x) + + Return the ceiling of *x*, the smallest integer greater than or equal to *x*. + If *x* is not a float, delegates to ``x.__ceil__()``, which should return an + :class:`~numbers.Integral` value. + + +.. function:: comb(n, k) + + Return the number of ways to choose *k* items from *n* items without repetition + and without order. + + Evaluates to ``n! / (k! * (n - k)!)`` when ``k <= n`` and evaluates + to zero when ``k > n``. + + Also called the binomial coefficient because it is equivalent + to the coefficient of k-th term in polynomial expansion of the + expression ``(1 + x) ** n``. + + Raises :exc:`TypeError` if either of the arguments are not integers. + Raises :exc:`ValueError` if either of the arguments are negative. + + .. versionadded:: 3.8 + + +.. function:: copysign(x, y) + + Return a float with the magnitude (absolute value) of *x* but the sign of + *y*. On platforms that support signed zeros, ``copysign(1.0, -0.0)`` + returns *-1.0*. + + +.. function:: fabs(x) + + Return the absolute value of *x*. + + +.. function:: factorial(x) + + Return *x* factorial as an integer. Raises :exc:`ValueError` if *x* is not integral or + is negative. + + .. deprecated:: 3.9 + Accepting floats with integral values (like ``5.0``) is deprecated. + + +.. function:: floor(x) + + Return the floor of *x*, the largest integer less than or equal to *x*. + If *x* is not a float, delegates to ``x.__floor__()``, which should return an + :class:`~numbers.Integral` value. + + +.. function:: fmod(x, y) + + Return ``fmod(x, y)``, as defined by the platform C library. Note that the + Python expression ``x % y`` may not return the same result. The intent of the C + standard is that ``fmod(x, y)`` be exactly (mathematically; to infinite + precision) equal to ``x - n*y`` for some integer *n* such that the result has + the same sign as *x* and magnitude less than ``abs(y)``. Python's ``x % y`` + returns a result with the sign of *y* instead, and may not be exactly computable + for float arguments. For example, ``fmod(-1e-100, 1e100)`` is ``-1e-100``, but + the result of Python's ``-1e-100 % 1e100`` is ``1e100-1e-100``, which cannot be + represented exactly as a float, and rounds to the surprising ``1e100``. For + this reason, function :func:`fmod` is generally preferred when working with + floats, while Python's ``x % y`` is preferred when working with integers. + + +.. function:: frexp(x) + + Return the mantissa and exponent of *x* as the pair ``(m, e)``. *m* is a float + and *e* is an integer such that ``x == m * 2**e`` exactly. If *x* is zero, + returns ``(0.0, 0)``, otherwise ``0.5 <= abs(m) < 1``. This is used to "pick + apart" the internal representation of a float in a portable way. + + +.. function:: fsum(iterable) + + Return an accurate floating point sum of values in the iterable. Avoids + loss of precision by tracking multiple intermediate partial sums:: + + >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) + 0.9999999999999999 + >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) + 1.0 + + The algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the + typical case where the rounding mode is half-even. On some non-Windows + builds, the underlying C library uses extended precision addition and may + occasionally double-round an intermediate sum causing it to be off in its + least significant bit. + + For further discussion and two alternative approaches, see the `ASPN cookbook + recipes for accurate floating point summation + `_\. + + +.. function:: gcd(*integers) + + Return the greatest common divisor of the specified integer arguments. + If any of the arguments is nonzero, then the returned value is the largest + positive integer that is a divisor af all arguments. If all arguments + are zero, then the returned value is ``0``. ``gcd()`` without arguments + returns ``0``. + + .. versionadded:: 3.5 + + .. versionchanged:: 3.9 + Added support for an arbitrary number of arguments. Formerly, only two + arguments were supported. + + +.. function:: isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) + + Return ``True`` if the values *a* and *b* are close to each other and + ``False`` otherwise. + + Whether or not two values are considered close is determined according to + given absolute and relative tolerances. + + *rel_tol* is the relative tolerance -- it is the maximum allowed difference + between *a* and *b*, relative to the larger absolute value of *a* or *b*. + For example, to set a tolerance of 5%, pass ``rel_tol=0.05``. The default + tolerance is ``1e-09``, which assures that the two values are the same + within about 9 decimal digits. *rel_tol* must be greater than zero. + + *abs_tol* is the minimum absolute tolerance -- useful for comparisons near + zero. *abs_tol* must be at least zero. + + If no errors occur, the result will be: + ``abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)``. + + The IEEE 754 special values of ``NaN``, ``inf``, and ``-inf`` will be + handled according to IEEE rules. Specifically, ``NaN`` is not considered + close to any other value, including ``NaN``. ``inf`` and ``-inf`` are only + considered close to themselves. + + .. versionadded:: 3.5 + + .. seealso:: + + :pep:`485` -- A function for testing approximate equality + + +.. function:: isfinite(x) + + Return ``True`` if *x* is neither an infinity nor a NaN, and + ``False`` otherwise. (Note that ``0.0`` *is* considered finite.) + + .. versionadded:: 3.2 + + +.. function:: isinf(x) + + Return ``True`` if *x* is a positive or negative infinity, and + ``False`` otherwise. + + +.. function:: isnan(x) + + Return ``True`` if *x* is a NaN (not a number), and ``False`` otherwise. + + +.. function:: isqrt(n) + + Return the integer square root of the nonnegative integer *n*. This is the + floor of the exact square root of *n*, or equivalently the greatest integer + *a* such that *a*\ ² |nbsp| ≤ |nbsp| *n*. + + For some applications, it may be more convenient to have the least integer + *a* such that *n* |nbsp| ≤ |nbsp| *a*\ ², or in other words the ceiling of + the exact square root of *n*. For positive *n*, this can be computed using + ``a = 1 + isqrt(n - 1)``. + + .. versionadded:: 3.8 + + +.. function:: lcm(*integers) + + Return the least common multiple of the specified integer arguments. + If all arguments are nonzero, then the returned value is the smallest + positive integer that is a multiple of all arguments. If any of the arguments + is zero, then the returned value is ``0``. ``lcm()`` without arguments + returns ``1``. + + .. versionadded:: 3.9 + + +.. function:: ldexp(x, i) + + Return ``x * (2**i)``. This is essentially the inverse of function + :func:`frexp`. + + +.. function:: modf(x) + + Return the fractional and integer parts of *x*. Both results carry the sign + of *x* and are floats. + + +.. function:: nextafter(x, y) + + Return the next floating-point value after *x* towards *y*. + + If *x* is equal to *y*, return *y*. + + Examples: + + * ``math.nextafter(x, math.inf)`` goes up: towards positive infinity. + * ``math.nextafter(x, -math.inf)`` goes down: towards minus infinity. + * ``math.nextafter(x, 0.0)`` goes towards zero. + * ``math.nextafter(x, math.copysign(math.inf, x))`` goes away from zero. + + See also :func:`math.ulp`. + + .. versionadded:: 3.9 + +.. function:: perm(n, k=None) + + Return the number of ways to choose *k* items from *n* items + without repetition and with order. + + Evaluates to ``n! / (n - k)!`` when ``k <= n`` and evaluates + to zero when ``k > n``. + + If *k* is not specified or is None, then *k* defaults to *n* + and the function returns ``n!``. + + Raises :exc:`TypeError` if either of the arguments are not integers. + Raises :exc:`ValueError` if either of the arguments are negative. + + .. versionadded:: 3.8 + + +.. function:: prod(iterable, *, start=1) + + Calculate the product of all the elements in the input *iterable*. + The default *start* value for the product is ``1``. + + When the iterable is empty, return the start value. This function is + intended specifically for use with numeric values and may reject + non-numeric types. + + .. versionadded:: 3.8 + + +.. function:: remainder(x, y) + + Return the IEEE 754-style remainder of *x* with respect to *y*. For + finite *x* and finite nonzero *y*, this is the difference ``x - n*y``, + where ``n`` is the closest integer to the exact value of the quotient ``x / + y``. If ``x / y`` is exactly halfway between two consecutive integers, the + nearest *even* integer is used for ``n``. The remainder ``r = remainder(x, + y)`` thus always satisfies ``abs(r) <= 0.5 * abs(y)``. + + Special cases follow IEEE 754: in particular, ``remainder(x, math.inf)`` is + *x* for any finite *x*, and ``remainder(x, 0)`` and + ``remainder(math.inf, x)`` raise :exc:`ValueError` for any non-NaN *x*. + If the result of the remainder operation is zero, that zero will have + the same sign as *x*. + + On platforms using IEEE 754 binary floating-point, the result of this + operation is always exactly representable: no rounding error is introduced. + + .. versionadded:: 3.7 + + +.. function:: trunc(x) + + Return the :class:`~numbers.Real` value *x* truncated to an + :class:`~numbers.Integral` (usually an integer). Delegates to + :meth:`x.__trunc__() `. + +.. function:: ulp(x) + + Return the value of the least significant bit of the float *x*: + + * If *x* is a NaN (not a number), return *x*. + * If *x* is negative, return ``ulp(-x)``. + * If *x* is a positive infinity, return *x*. + * If *x* is equal to zero, return the smallest positive + *denormalized* representable float (smaller than the minimum positive + *normalized* float, :data:`sys.float_info.min `). + * If *x* is equal to the largest positive representable float, + return the value of the least significant bit of *x*, such that the first + float smaller than *x* is ``x - ulp(x)``. + * Otherwise (*x* is a positive finite number), return the value of the least + significant bit of *x*, such that the first float bigger than *x* + is ``x + ulp(x)``. + + ULP stands for "Unit in the Last Place". + + See also :func:`math.nextafter` and :data:`sys.float_info.epsilon + `. + + .. versionadded:: 3.9 + + +Note that :func:`frexp` and :func:`modf` have a different call/return pattern +than their C equivalents: they take a single argument and return a pair of +values, rather than returning their second return value through an 'output +parameter' (there is no such thing in Python). + +For the :func:`ceil`, :func:`floor`, and :func:`modf` functions, note that *all* +floating-point numbers of sufficiently large magnitude are exact integers. +Python floats typically carry no more than 53 bits of precision (the same as the +platform C double type), in which case any float *x* with ``abs(x) >= 2**52`` +necessarily has no fractional bits. + + +Power and logarithmic functions +------------------------------- + +.. function:: exp(x) + + Return *e* raised to the power *x*, where *e* = 2.718281... is the base + of natural logarithms. This is usually more accurate than ``math.e ** x`` + or ``pow(math.e, x)``. + + +.. function:: expm1(x) + + Return *e* raised to the power *x*, minus 1. Here *e* is the base of natural + logarithms. For small floats *x*, the subtraction in ``exp(x) - 1`` + can result in a `significant loss of precision + `_\; the :func:`expm1` + function provides a way to compute this quantity to full precision:: + + >>> from math import exp, expm1 + >>> exp(1e-5) - 1 # gives result accurate to 11 places + 1.0000050000069649e-05 + >>> expm1(1e-5) # result accurate to full precision + 1.0000050000166668e-05 + + .. versionadded:: 3.2 + + +.. function:: log(x[, base]) + + With one argument, return the natural logarithm of *x* (to base *e*). + + With two arguments, return the logarithm of *x* to the given *base*, + calculated as ``log(x)/log(base)``. + + +.. function:: log1p(x) + + Return the natural logarithm of *1+x* (base *e*). The + result is calculated in a way which is accurate for *x* near zero. + + +.. function:: log2(x) + + Return the base-2 logarithm of *x*. This is usually more accurate than + ``log(x, 2)``. + + .. versionadded:: 3.3 + + .. seealso:: + + :meth:`int.bit_length` returns the number of bits necessary to represent + an integer in binary, excluding the sign and leading zeros. + + +.. function:: log10(x) + + Return the base-10 logarithm of *x*. This is usually more accurate + than ``log(x, 10)``. + + +.. function:: pow(x, y) + + Return ``x`` raised to the power ``y``. Exceptional cases follow + Annex 'F' of the C99 standard as far as possible. In particular, + ``pow(1.0, x)`` and ``pow(x, 0.0)`` always return ``1.0``, even + when ``x`` is a zero or a NaN. If both ``x`` and ``y`` are finite, + ``x`` is negative, and ``y`` is not an integer then ``pow(x, y)`` + is undefined, and raises :exc:`ValueError`. + + Unlike the built-in ``**`` operator, :func:`math.pow` converts both + its arguments to type :class:`float`. Use ``**`` or the built-in + :func:`pow` function for computing exact integer powers. + + +.. function:: sqrt(x) + + Return the square root of *x*. + + +Trigonometric functions +----------------------- + +.. function:: acos(x) + + Return the arc cosine of *x*, in radians. The result is between ``0`` and + ``pi``. + + +.. function:: asin(x) + + Return the arc sine of *x*, in radians. The result is between ``-pi/2`` and + ``pi/2``. + + +.. function:: atan(x) + + Return the arc tangent of *x*, in radians. The result is between ``-pi/2`` and + ``pi/2``. + + +.. function:: atan2(y, x) + + Return ``atan(y / x)``, in radians. The result is between ``-pi`` and ``pi``. + The vector in the plane from the origin to point ``(x, y)`` makes this angle + with the positive X axis. The point of :func:`atan2` is that the signs of both + inputs are known to it, so it can compute the correct quadrant for the angle. + For example, ``atan(1)`` and ``atan2(1, 1)`` are both ``pi/4``, but ``atan2(-1, + -1)`` is ``-3*pi/4``. + + +.. function:: cos(x) + + Return the cosine of *x* radians. + + +.. function:: dist(p, q) + + Return the Euclidean distance between two points *p* and *q*, each + given as a sequence (or iterable) of coordinates. The two points + must have the same dimension. + + Roughly equivalent to:: + + sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) + + .. versionadded:: 3.8 + + +.. function:: hypot(*coordinates) + + Return the Euclidean norm, ``sqrt(sum(x**2 for x in coordinates))``. + This is the length of the vector from the origin to the point + given by the coordinates. + + For a two dimensional point ``(x, y)``, this is equivalent to computing + the hypotenuse of a right triangle using the Pythagorean theorem, + ``sqrt(x*x + y*y)``. + + .. versionchanged:: 3.8 + Added support for n-dimensional points. Formerly, only the two + dimensional case was supported. + + +.. function:: sin(x) + + Return the sine of *x* radians. + + +.. function:: tan(x) + + Return the tangent of *x* radians. + + +Angular conversion +------------------ + +.. function:: degrees(x) + + Convert angle *x* from radians to degrees. + + +.. function:: radians(x) + + Convert angle *x* from degrees to radians. + + +Hyperbolic functions +-------------------- + +`Hyperbolic functions `_ +are analogs of trigonometric functions that are based on hyperbolas +instead of circles. + +.. function:: acosh(x) + + Return the inverse hyperbolic cosine of *x*. + + +.. function:: asinh(x) + + Return the inverse hyperbolic sine of *x*. + + +.. function:: atanh(x) + + Return the inverse hyperbolic tangent of *x*. + + +.. function:: cosh(x) + + Return the hyperbolic cosine of *x*. + + +.. function:: sinh(x) + + Return the hyperbolic sine of *x*. + + +.. function:: tanh(x) + + Return the hyperbolic tangent of *x*. + + +Special functions +----------------- + +.. function:: erf(x) + + Return the `error function `_ at + *x*. + + The :func:`erf` function can be used to compute traditional statistical + functions such as the `cumulative standard normal distribution + `_:: + + def phi(x): + 'Cumulative distribution function for the standard normal distribution' + return (1.0 + erf(x / sqrt(2.0))) / 2.0 + + .. versionadded:: 3.2 + + +.. function:: erfc(x) + + Return the complementary error function at *x*. The `complementary error + function `_ is defined as + ``1.0 - erf(x)``. It is used for large values of *x* where a subtraction + from one would cause a `loss of significance + `_\. + + .. versionadded:: 3.2 + + +.. function:: gamma(x) + + Return the `Gamma function `_ at + *x*. + + .. versionadded:: 3.2 + + +.. function:: lgamma(x) + + Return the natural logarithm of the absolute value of the Gamma + function at *x*. + + .. versionadded:: 3.2 + + +Constants +--------- + +.. data:: pi + + The mathematical constant *π* = 3.141592..., to available precision. + + +.. data:: e + + The mathematical constant *e* = 2.718281..., to available precision. + + +.. data:: tau + + The mathematical constant *τ* = 6.283185..., to available precision. + Tau is a circle constant equal to 2\ *π*, the ratio of a circle's circumference to + its radius. To learn more about Tau, check out Vi Hart's video `Pi is (still) + Wrong `_, and start celebrating + `Tau day `_ by eating twice as much pie! + + .. versionadded:: 3.6 + + +.. data:: inf + + A floating-point positive infinity. (For negative infinity, use + ``-math.inf``.) Equivalent to the output of ``float('inf')``. + + .. versionadded:: 3.5 + + +.. data:: nan + + A floating-point "not a number" (NaN) value. Equivalent to the output of + ``float('nan')``. + + .. versionadded:: 3.5 + + +.. impl-detail:: + + The :mod:`math` module consists mostly of thin wrappers around the platform C + math library functions. Behavior in exceptional cases follows Annex F of + the C99 standard where appropriate. The current implementation will raise + :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)`` + (where C99 Annex F recommends signaling invalid operation or divide-by-zero), + and :exc:`OverflowError` for results that overflow (for example, + ``exp(1000.0)``). A NaN will not be returned from any of the functions + above unless one or more of the input arguments was a NaN; in that case, + most functions will return a NaN, but (again following C99 Annex F) there + are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or + ``hypot(float('nan'), float('inf'))``. + + Note that Python makes no effort to distinguish signaling NaNs from + quiet NaNs, and behavior for signaling NaNs remains unspecified. + Typical behavior is to treat all NaNs as though they were quiet. + + +.. seealso:: + + Module :mod:`cmath` + Complex number versions of many of these functions. + +.. |nbsp| unicode:: 0xA0 + :trim: diff --git a/cpython_2/environment/repo/Doc/library/mimetypes.rst b/cpython_2/environment/repo/Doc/library/mimetypes.rst new file mode 100644 index 0000000000000000000000000000000000000000..f610032acbe41779b8c57c4eefe1513ba4aefd2f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/mimetypes.rst @@ -0,0 +1,274 @@ +:mod:`mimetypes` --- Map filenames to MIME types +================================================ + +.. module:: mimetypes + :synopsis: Mapping of filename extensions to MIME types. + +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/mimetypes.py` + +.. index:: pair: MIME; content type + +-------------- + +The :mod:`mimetypes` module converts between a filename or URL and the MIME type +associated with the filename extension. Conversions are provided from filename +to MIME type and from MIME type to filename extension; encodings are not +supported for the latter conversion. + +The module provides one class and a number of convenience functions. The +functions are the normal interface to this module, but some applications may be +interested in the class as well. + +The functions described below provide the primary interface for this module. If +the module has not been initialized, they will call :func:`init` if they rely on +the information :func:`init` sets up. + + +.. function:: guess_type(url, strict=True) + + .. index:: pair: MIME; headers + + Guess the type of a file based on its filename, path or URL, given by *url*. + URL can be a string or a :term:`path-like object`. + + The return value is a tuple ``(type, encoding)`` where *type* is ``None`` if the + type can't be guessed (missing or unknown suffix) or a string of the form + ``'type/subtype'``, usable for a MIME :mailheader:`content-type` header. + + *encoding* is ``None`` for no encoding or the name of the program used to encode + (e.g. :program:`compress` or :program:`gzip`). The encoding is suitable for use + as a :mailheader:`Content-Encoding` header, **not** as a + :mailheader:`Content-Transfer-Encoding` header. The mappings are table driven. + Encoding suffixes are case sensitive; type suffixes are first tried case + sensitively, then case insensitively. + + The optional *strict* argument is a flag specifying whether the list of known MIME types + is limited to only the official types `registered with IANA + `_. + When *strict* is ``True`` (the default), only the IANA types are supported; when + *strict* is ``False``, some additional non-standard but commonly used MIME types + are also recognized. + + .. versionchanged:: 3.8 + Added support for url being a :term:`path-like object`. + + +.. function:: guess_all_extensions(type, strict=True) + + Guess the extensions for a file based on its MIME type, given by *type*. The + return value is a list of strings giving all possible filename extensions, + including the leading dot (``'.'``). The extensions are not guaranteed to have + been associated with any particular data stream, but would be mapped to the MIME + type *type* by :func:`guess_type`. + + The optional *strict* argument has the same meaning as with the :func:`guess_type` function. + + +.. function:: guess_extension(type, strict=True) + + Guess the extension for a file based on its MIME type, given by *type*. The + return value is a string giving a filename extension, including the leading dot + (``'.'``). The extension is not guaranteed to have been associated with any + particular data stream, but would be mapped to the MIME type *type* by + :func:`guess_type`. If no extension can be guessed for *type*, ``None`` is + returned. + + The optional *strict* argument has the same meaning as with the :func:`guess_type` function. + +Some additional functions and data items are available for controlling the +behavior of the module. + + +.. function:: init(files=None) + + Initialize the internal data structures. If given, *files* must be a sequence + of file names which should be used to augment the default type map. If omitted, + the file names to use are taken from :const:`knownfiles`; on Windows, the + current registry settings are loaded. Each file named in *files* or + :const:`knownfiles` takes precedence over those named before it. Calling + :func:`init` repeatedly is allowed. + + Specifying an empty list for *files* will prevent the system defaults from + being applied: only the well-known values will be present from a built-in list. + + If *files* is ``None`` the internal data structure is completely rebuilt to its + initial default value. This is a stable operation and will produce the same results + when called multiple times. + + .. versionchanged:: 3.2 + Previously, Windows registry settings were ignored. + + +.. function:: read_mime_types(filename) + + Load the type map given in the file *filename*, if it exists. The type map is + returned as a dictionary mapping filename extensions, including the leading dot + (``'.'``), to strings of the form ``'type/subtype'``. If the file *filename* + does not exist or cannot be read, ``None`` is returned. + + +.. function:: add_type(type, ext, strict=True) + + Add a mapping from the MIME type *type* to the extension *ext*. When the + extension is already known, the new type will replace the old one. When the type + is already known the extension will be added to the list of known extensions. + + When *strict* is ``True`` (the default), the mapping will be added to the + official MIME types, otherwise to the non-standard ones. + + +.. data:: inited + + Flag indicating whether or not the global data structures have been initialized. + This is set to ``True`` by :func:`init`. + + +.. data:: knownfiles + + .. index:: single: file; mime.types + + List of type map file names commonly installed. These files are typically named + :file:`mime.types` and are installed in different locations by different + packages. + + +.. data:: suffix_map + + Dictionary mapping suffixes to suffixes. This is used to allow recognition of + encoded files for which the encoding and the type are indicated by the same + extension. For example, the :file:`.tgz` extension is mapped to :file:`.tar.gz` + to allow the encoding and type to be recognized separately. + + +.. data:: encodings_map + + Dictionary mapping filename extensions to encoding types. + + +.. data:: types_map + + Dictionary mapping filename extensions to MIME types. + + +.. data:: common_types + + Dictionary mapping filename extensions to non-standard, but commonly found MIME + types. + + +An example usage of the module:: + + >>> import mimetypes + >>> mimetypes.init() + >>> mimetypes.knownfiles + ['/etc/mime.types', '/etc/httpd/mime.types', ... ] + >>> mimetypes.suffix_map['.tgz'] + '.tar.gz' + >>> mimetypes.encodings_map['.gz'] + 'gzip' + >>> mimetypes.types_map['.tgz'] + 'application/x-tar-gz' + + +.. _mimetypes-objects: + +MimeTypes Objects +----------------- + +The :class:`MimeTypes` class may be useful for applications which may want more +than one MIME-type database; it provides an interface similar to the one of the +:mod:`mimetypes` module. + + +.. class:: MimeTypes(filenames=(), strict=True) + + This class represents a MIME-types database. By default, it provides access to + the same database as the rest of this module. The initial database is a copy of + that provided by the module, and may be extended by loading additional + :file:`mime.types`\ -style files into the database using the :meth:`read` or + :meth:`readfp` methods. The mapping dictionaries may also be cleared before + loading additional data if the default data is not desired. + + The optional *filenames* parameter can be used to cause additional files to be + loaded "on top" of the default database. + + + .. attribute:: MimeTypes.suffix_map + + Dictionary mapping suffixes to suffixes. This is used to allow recognition of + encoded files for which the encoding and the type are indicated by the same + extension. For example, the :file:`.tgz` extension is mapped to :file:`.tar.gz` + to allow the encoding and type to be recognized separately. This is initially a + copy of the global :data:`suffix_map` defined in the module. + + + .. attribute:: MimeTypes.encodings_map + + Dictionary mapping filename extensions to encoding types. This is initially a + copy of the global :data:`encodings_map` defined in the module. + + + .. attribute:: MimeTypes.types_map + + Tuple containing two dictionaries, mapping filename extensions to MIME types: + the first dictionary is for the non-standards types and the second one is for + the standard types. They are initialized by :data:`common_types` and + :data:`types_map`. + + + .. attribute:: MimeTypes.types_map_inv + + Tuple containing two dictionaries, mapping MIME types to a list of filename + extensions: the first dictionary is for the non-standards types and the + second one is for the standard types. They are initialized by + :data:`common_types` and :data:`types_map`. + + + .. method:: MimeTypes.guess_extension(type, strict=True) + + Similar to the :func:`guess_extension` function, using the tables stored as part + of the object. + + + .. method:: MimeTypes.guess_type(url, strict=True) + + Similar to the :func:`guess_type` function, using the tables stored as part of + the object. + + + .. method:: MimeTypes.guess_all_extensions(type, strict=True) + + Similar to the :func:`guess_all_extensions` function, using the tables stored + as part of the object. + + + .. method:: MimeTypes.read(filename, strict=True) + + Load MIME information from a file named *filename*. This uses :meth:`readfp` to + parse the file. + + If *strict* is ``True``, information will be added to list of standard types, + else to the list of non-standard types. + + + .. method:: MimeTypes.readfp(fp, strict=True) + + Load MIME type information from an open file *fp*. The file must have the format of + the standard :file:`mime.types` files. + + If *strict* is ``True``, information will be added to the list of standard + types, else to the list of non-standard types. + + + .. method:: MimeTypes.read_windows_registry(strict=True) + + Load MIME type information from the Windows registry. + + .. availability:: Windows. + + If *strict* is ``True``, information will be added to the list of standard + types, else to the list of non-standard types. + + .. versionadded:: 3.2 diff --git a/cpython_2/environment/repo/Doc/library/misc.rst b/cpython_2/environment/repo/Doc/library/misc.rst new file mode 100644 index 0000000000000000000000000000000000000000..0943235246a91b2ce5714d180e6eb8b9662e6bcb --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/misc.rst @@ -0,0 +1,13 @@ +.. _misc: + +********************** +Miscellaneous Services +********************** + +The modules described in this chapter provide miscellaneous services that are +available in all Python versions. Here's an overview: + + +.. toctree:: + + formatter.rst diff --git a/cpython_2/environment/repo/Doc/library/mm.rst b/cpython_2/environment/repo/Doc/library/mm.rst new file mode 100644 index 0000000000000000000000000000000000000000..c8f79c4de1cdf258d00f4c546b13ea57ade708fa --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/mm.rst @@ -0,0 +1,22 @@ +.. _mmedia: + +******************* +Multimedia Services +******************* + +The modules described in this chapter implement various algorithms or interfaces +that are mainly useful for multimedia applications. They are available at the +discretion of the installation. Here's an overview: + + +.. toctree:: + + audioop.rst + aifc.rst + sunau.rst + wave.rst + chunk.rst + colorsys.rst + imghdr.rst + sndhdr.rst + ossaudiodev.rst diff --git a/cpython_2/environment/repo/Doc/library/mmap.rst b/cpython_2/environment/repo/Doc/library/mmap.rst new file mode 100644 index 0000000000000000000000000000000000000000..1f3fbc340fc26762227e81044782704a2d299365 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/mmap.rst @@ -0,0 +1,344 @@ +:mod:`mmap` --- Memory-mapped file support +========================================== + +.. module:: mmap + :synopsis: Interface to memory-mapped files for Unix and Windows. + +-------------- + +Memory-mapped file objects behave like both :class:`bytearray` and like +:term:`file objects `. You can use mmap objects in most places +where :class:`bytearray` are expected; for example, you can use the :mod:`re` +module to search through a memory-mapped file. You can also change a single +byte by doing ``obj[index] = 97``, or change a subsequence by assigning to a +slice: ``obj[i1:i2] = b'...'``. You can also read and write data starting at +the current file position, and :meth:`seek` through the file to different positions. + +A memory-mapped file is created by the :class:`~mmap.mmap` constructor, which is +different on Unix and on Windows. In either case you must provide a file +descriptor for a file opened for update. If you wish to map an existing Python +file object, use its :meth:`fileno` method to obtain the correct value for the +*fileno* parameter. Otherwise, you can open the file using the +:func:`os.open` function, which returns a file descriptor directly (the file +still needs to be closed when done). + +.. note:: + If you want to create a memory-mapping for a writable, buffered file, you + should :func:`~io.IOBase.flush` the file first. This is necessary to ensure + that local modifications to the buffers are actually available to the + mapping. + +For both the Unix and Windows versions of the constructor, *access* may be +specified as an optional keyword parameter. *access* accepts one of four +values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY` to +specify read-only, write-through or copy-on-write memory respectively, or +:const:`ACCESS_DEFAULT` to defer to *prot*. *access* can be used on both Unix +and Windows. If *access* is not specified, Windows mmap returns a +write-through mapping. The initial memory values for all three access types +are taken from the specified file. Assignment to an :const:`ACCESS_READ` +memory map raises a :exc:`TypeError` exception. Assignment to an +:const:`ACCESS_WRITE` memory map affects both memory and the underlying file. +Assignment to an :const:`ACCESS_COPY` memory map affects memory but does not +update the underlying file. + +.. versionchanged:: 3.7 + Added :const:`ACCESS_DEFAULT` constant. + +To map anonymous memory, -1 should be passed as the fileno along with the length. + +.. class:: mmap(fileno, length, tagname=None, access=ACCESS_DEFAULT[, offset]) + + **(Windows version)** Maps *length* bytes from the file specified by the + file handle *fileno*, and creates a mmap object. If *length* is larger + than the current size of the file, the file is extended to contain *length* + bytes. If *length* is ``0``, the maximum length of the map is the current + size of the file, except that if the file is empty Windows raises an + exception (you cannot create an empty mapping on Windows). + + *tagname*, if specified and not ``None``, is a string giving a tag name for + the mapping. Windows allows you to have many different mappings against + the same file. If you specify the name of an existing tag, that tag is + opened, otherwise a new tag of this name is created. If this parameter is + omitted or ``None``, the mapping is created without a name. Avoiding the + use of the tag parameter will assist in keeping your code portable between + Unix and Windows. + + *offset* may be specified as a non-negative integer offset. mmap references + will be relative to the offset from the beginning of the file. *offset* + defaults to 0. *offset* must be a multiple of the :const:`ALLOCATIONGRANULARITY`. + + .. audit-event:: mmap.__new__ fileno,length,access,offset mmap.mmap + +.. class:: mmap(fileno, length, flags=MAP_SHARED, prot=PROT_WRITE|PROT_READ, access=ACCESS_DEFAULT[, offset]) + :noindex: + + **(Unix version)** Maps *length* bytes from the file specified by the file + descriptor *fileno*, and returns a mmap object. If *length* is ``0``, the + maximum length of the map will be the current size of the file when + :class:`~mmap.mmap` is called. + + *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a + private copy-on-write mapping, so changes to the contents of the mmap + object will be private to this process, and :const:`MAP_SHARED` creates a + mapping that's shared with all other processes mapping the same areas of + the file. The default value is :const:`MAP_SHARED`. + + *prot*, if specified, gives the desired memory protection; the two most + useful values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify + that the pages may be read or written. *prot* defaults to + :const:`PROT_READ \| PROT_WRITE`. + + *access* may be specified in lieu of *flags* and *prot* as an optional + keyword parameter. It is an error to specify both *flags*, *prot* and + *access*. See the description of *access* above for information on how to + use this parameter. + + *offset* may be specified as a non-negative integer offset. mmap references + will be relative to the offset from the beginning of the file. *offset* + defaults to 0. *offset* must be a multiple of :const:`ALLOCATIONGRANULARITY` + which is equal to :const:`PAGESIZE` on Unix systems. + + To ensure validity of the created memory mapping the file specified + by the descriptor *fileno* is internally automatically synchronized + with physical backing store on Mac OS X and OpenVMS. + + This example shows a simple way of using :class:`~mmap.mmap`:: + + import mmap + + # write a simple example file + with open("hello.txt", "wb") as f: + f.write(b"Hello Python!\n") + + with open("hello.txt", "r+b") as f: + # memory-map the file, size 0 means whole file + mm = mmap.mmap(f.fileno(), 0) + # read content via standard file methods + print(mm.readline()) # prints b"Hello Python!\n" + # read content via slice notation + print(mm[:5]) # prints b"Hello" + # update content using slice notation; + # note that new content must have same size + mm[6:] = b" world!\n" + # ... and read again using standard file methods + mm.seek(0) + print(mm.readline()) # prints b"Hello world!\n" + # close the map + mm.close() + + + :class:`~mmap.mmap` can also be used as a context manager in a :keyword:`with` + statement:: + + import mmap + + with mmap.mmap(-1, 13) as mm: + mm.write(b"Hello world!") + + .. versionadded:: 3.2 + Context manager support. + + + The next example demonstrates how to create an anonymous map and exchange + data between the parent and child processes:: + + import mmap + import os + + mm = mmap.mmap(-1, 13) + mm.write(b"Hello world!") + + pid = os.fork() + + if pid == 0: # In a child process + mm.seek(0) + print(mm.readline()) + + mm.close() + + .. audit-event:: mmap.__new__ fileno,length,access,offset mmap.mmap + + Memory-mapped file objects support the following methods: + + .. method:: close() + + Closes the mmap. Subsequent calls to other methods of the object will + result in a ValueError exception being raised. This will not close + the open file. + + + .. attribute:: closed + + ``True`` if the file is closed. + + .. versionadded:: 3.2 + + + .. method:: find(sub[, start[, end]]) + + Returns the lowest index in the object where the subsequence *sub* is + found, such that *sub* is contained in the range [*start*, *end*]. + Optional arguments *start* and *end* are interpreted as in slice notation. + Returns ``-1`` on failure. + + .. versionchanged:: 3.5 + Writable :term:`bytes-like object` is now accepted. + + + .. method:: flush([offset[, size]]) + + Flushes changes made to the in-memory copy of a file back to disk. Without + use of this call there is no guarantee that changes are written back before + the object is destroyed. If *offset* and *size* are specified, only + changes to the given range of bytes will be flushed to disk; otherwise, the + whole extent of the mapping is flushed. *offset* must be a multiple of the + :const:`PAGESIZE` or :const:`ALLOCATIONGRANULARITY`. + + ``None`` is returned to indicate success. An exception is raised when the + call failed. + + .. versionchanged:: 3.8 + Previously, a nonzero value was returned on success; zero was returned + on error under Windows. A zero value was returned on success; an + exception was raised on error under Unix. + + + .. method:: madvise(option[, start[, length]]) + + Send advice *option* to the kernel about the memory region beginning at + *start* and extending *length* bytes. *option* must be one of the + :ref:`MADV_* constants ` available on the system. If + *start* and *length* are omitted, the entire mapping is spanned. On + some systems (including Linux), *start* must be a multiple of the + :const:`PAGESIZE`. + + Availability: Systems with the ``madvise()`` system call. + + .. versionadded:: 3.8 + + + .. method:: move(dest, src, count) + + Copy the *count* bytes starting at offset *src* to the destination index + *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to + move will raise a :exc:`TypeError` exception. + + + .. method:: read([n]) + + Return a :class:`bytes` containing up to *n* bytes starting from the + current file position. If the argument is omitted, ``None`` or negative, + return all bytes from the current file position to the end of the + mapping. The file position is updated to point after the bytes that were + returned. + + .. versionchanged:: 3.3 + Argument can be omitted or ``None``. + + .. method:: read_byte() + + Returns a byte at the current file position as an integer, and advances + the file position by 1. + + + .. method:: readline() + + Returns a single line, starting at the current file position and up to the + next newline. The file position is updated to point after the bytes that were + returned. + + + .. method:: resize(newsize) + + Resizes the map and the underlying file, if any. If the mmap was created + with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will + raise a :exc:`TypeError` exception. + + + .. method:: rfind(sub[, start[, end]]) + + Returns the highest index in the object where the subsequence *sub* is + found, such that *sub* is contained in the range [*start*, *end*]. + Optional arguments *start* and *end* are interpreted as in slice notation. + Returns ``-1`` on failure. + + .. versionchanged:: 3.5 + Writable :term:`bytes-like object` is now accepted. + + + .. method:: seek(pos[, whence]) + + Set the file's current position. *whence* argument is optional and + defaults to ``os.SEEK_SET`` or ``0`` (absolute file 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). + + + .. method:: size() + + Return the length of the file, which can be larger than the size of the + memory-mapped area. + + + .. method:: tell() + + Returns the current position of the file pointer. + + + .. method:: write(bytes) + + Write the bytes in *bytes* into memory at the current position of the + file pointer and return the number of bytes written (never less than + ``len(bytes)``, since if the write fails, a :exc:`ValueError` will be + raised). The file position is updated to point after the bytes that + were written. If the mmap was created with :const:`ACCESS_READ`, then + writing to it will raise a :exc:`TypeError` exception. + + .. versionchanged:: 3.5 + Writable :term:`bytes-like object` is now accepted. + + .. versionchanged:: 3.6 + The number of bytes written is now returned. + + + .. method:: write_byte(byte) + + Write the integer *byte* into memory at the current + position of the file pointer; the file position is advanced by ``1``. If + the mmap was created with :const:`ACCESS_READ`, then writing to it will + raise a :exc:`TypeError` exception. + +.. _madvise-constants: + +MADV_* Constants +++++++++++++++++ + +.. data:: MADV_NORMAL + MADV_RANDOM + MADV_SEQUENTIAL + MADV_WILLNEED + MADV_DONTNEED + MADV_REMOVE + MADV_DONTFORK + MADV_DOFORK + MADV_HWPOISON + MADV_MERGEABLE + MADV_UNMERGEABLE + MADV_SOFT_OFFLINE + MADV_HUGEPAGE + MADV_NOHUGEPAGE + MADV_DONTDUMP + MADV_DODUMP + MADV_FREE + MADV_NOSYNC + MADV_AUTOSYNC + MADV_NOCORE + MADV_CORE + MADV_PROTECT + + These options can be passed to :meth:`mmap.madvise`. Not every option will + be present on every system. + + Availability: Systems with the madvise() system call. + + .. versionadded:: 3.8 diff --git a/cpython_2/environment/repo/Doc/library/modulefinder.rst b/cpython_2/environment/repo/Doc/library/modulefinder.rst new file mode 100644 index 0000000000000000000000000000000000000000..7b39ce7d1aae5d5fc1e9d2c77c34cc063e0d56e3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/modulefinder.rst @@ -0,0 +1,114 @@ +:mod:`modulefinder` --- Find modules used by a script +===================================================== + +.. module:: modulefinder + :synopsis: Find modules used by a script. + +.. sectionauthor:: A.M. Kuchling + +**Source code:** :source:`Lib/modulefinder.py` + +-------------- + +This module provides a :class:`ModuleFinder` class that can be used to determine +the set of modules imported by a script. ``modulefinder.py`` can also be run as +a script, giving the filename of a Python script as its argument, after which a +report of the imported modules will be printed. + + +.. function:: AddPackagePath(pkg_name, path) + + Record that the package named *pkg_name* can be found in the specified *path*. + + +.. function:: ReplacePackage(oldname, newname) + + Allows specifying that the module named *oldname* is in fact the package named + *newname*. + + +.. class:: ModuleFinder(path=None, debug=0, excludes=[], replace_paths=[]) + + This class provides :meth:`run_script` and :meth:`report` methods to determine + the set of modules imported by a script. *path* can be a list of directories to + search for modules; if not specified, ``sys.path`` is used. *debug* sets the + debugging level; higher values make the class print debugging messages about + what it's doing. *excludes* is a list of module names to exclude from the + analysis. *replace_paths* is a list of ``(oldpath, newpath)`` tuples that will + be replaced in module paths. + + + .. method:: report() + + Print a report to standard output that lists the modules imported by the + script and their paths, as well as modules that are missing or seem to be + missing. + + .. method:: run_script(pathname) + + Analyze the contents of the *pathname* file, which must contain Python + code. + + .. attribute:: modules + + A dictionary mapping module names to modules. See + :ref:`modulefinder-example`. + + +.. _modulefinder-example: + +Example usage of :class:`ModuleFinder` +-------------------------------------- + +The script that is going to get analyzed later on (bacon.py):: + + import re, itertools + + try: + import baconhameggs + except ImportError: + pass + + try: + import guido.python.ham + except ImportError: + pass + + +The script that will output the report of bacon.py:: + + from modulefinder import ModuleFinder + + finder = ModuleFinder() + finder.run_script('bacon.py') + + print('Loaded modules:') + for name, mod in finder.modules.items(): + print('%s: ' % name, end='') + print(','.join(list(mod.globalnames.keys())[:3])) + + print('-'*50) + print('Modules not imported:') + print('\n'.join(finder.badmodules.keys())) + +Sample output (may vary depending on the architecture):: + + Loaded modules: + _types: + copyreg: _inverted_registry,_slotnames,__all__ + sre_compile: isstring,_sre,_optimize_unicode + _sre: + sre_constants: REPEAT_ONE,makedict,AT_END_LINE + sys: + re: __module__,finditer,_expand + itertools: + __main__: re,itertools,baconhameggs + sre_parse: _PATTERNENDERS,SRE_FLAG_UNICODE + array: + types: __module__,IntType,TypeType + --------------------------------------------------- + Modules not imported: + guido.python.ham + baconhameggs + + diff --git a/cpython_2/environment/repo/Doc/library/modules.rst b/cpython_2/environment/repo/Doc/library/modules.rst new file mode 100644 index 0000000000000000000000000000000000000000..565ce0525c2c99f6ad693af42fe504a71e0e4732 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/modules.rst @@ -0,0 +1,20 @@ +.. _modules: + +***************** +Importing Modules +***************** + +The modules described in this chapter provide new ways to import other Python +modules and hooks for customizing the import process. + +The full list of modules described in this chapter is: + + +.. toctree:: + + zipimport.rst + pkgutil.rst + modulefinder.rst + runpy.rst + importlib.rst + importlib.metadata.rst diff --git a/cpython_2/environment/repo/Doc/library/msilib.rst b/cpython_2/environment/repo/Doc/library/msilib.rst new file mode 100644 index 0000000000000000000000000000000000000000..83b3d4973bf0d96dc4880c2ff3581eced2f91c6d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/msilib.rst @@ -0,0 +1,563 @@ +:mod:`msilib` --- Read and write Microsoft Installer files +========================================================== + +.. module:: msilib + :platform: Windows + :synopsis: Creation of Microsoft Installer files, and CAB files. + +.. moduleauthor:: Martin v. Löwis +.. sectionauthor:: Martin v. Löwis + +**Source code:** :source:`Lib/msilib/__init__.py` + +.. index:: single: msi + +-------------- + +The :mod:`msilib` supports the creation of Microsoft Installer (``.msi``) files. +Because these files often contain an embedded "cabinet" file (``.cab``), it also +exposes an API to create CAB files. Support for reading ``.cab`` files is +currently not implemented; read support for the ``.msi`` database is possible. + +This package aims to provide complete access to all tables in an ``.msi`` file, +therefore, it is a fairly low-level API. Two primary applications of this +package are the :mod:`distutils` command ``bdist_msi``, and the creation of +Python installer package itself (although that currently uses a different +version of ``msilib``). + +The package contents can be roughly split into four parts: low-level CAB +routines, low-level MSI routines, higher-level MSI routines, and standard table +structures. + + +.. function:: FCICreate(cabname, files) + + Create a new CAB file named *cabname*. *files* must be a list of tuples, each + containing the name of the file on disk, and the name of the file inside the CAB + file. + + The files are added to the CAB file in the order they appear in the list. All + files are added into a single CAB file, using the MSZIP compression algorithm. + + Callbacks to Python for the various steps of MSI creation are currently not + exposed. + + +.. function:: UuidCreate() + + Return the string representation of a new unique identifier. This wraps the + Windows API functions :c:func:`UuidCreate` and :c:func:`UuidToString`. + + +.. function:: OpenDatabase(path, persist) + + Return a new database object by calling MsiOpenDatabase. *path* is the file + name of the MSI file; *persist* can be one of the constants + ``MSIDBOPEN_CREATEDIRECT``, ``MSIDBOPEN_CREATE``, ``MSIDBOPEN_DIRECT``, + ``MSIDBOPEN_READONLY``, or ``MSIDBOPEN_TRANSACT``, and may include the flag + ``MSIDBOPEN_PATCHFILE``. See the Microsoft documentation for the meaning of + these flags; depending on the flags, an existing database is opened, or a new + one created. + + +.. function:: CreateRecord(count) + + Return a new record object by calling :c:func:`MSICreateRecord`. *count* is the + number of fields of the record. + + +.. function:: init_database(name, schema, ProductName, ProductCode, ProductVersion, Manufacturer) + + Create and return a new database *name*, initialize it with *schema*, and set + the properties *ProductName*, *ProductCode*, *ProductVersion*, and + *Manufacturer*. + + *schema* must be a module object containing ``tables`` and + ``_Validation_records`` attributes; typically, :mod:`msilib.schema` should be + used. + + The database will contain just the schema and the validation records when this + function returns. + + +.. function:: add_data(database, table, records) + + Add all *records* to the table named *table* in *database*. + + The *table* argument must be one of the predefined tables in the MSI schema, + e.g. ``'Feature'``, ``'File'``, ``'Component'``, ``'Dialog'``, ``'Control'``, + etc. + + *records* should be a list of tuples, each one containing all fields of a + record according to the schema of the table. For optional fields, + ``None`` can be passed. + + Field values can be ints, strings, or instances of the Binary class. + + +.. class:: Binary(filename) + + Represents entries in the Binary table; inserting such an object using + :func:`add_data` reads the file named *filename* into the table. + + +.. function:: add_tables(database, module) + + Add all table content from *module* to *database*. *module* must contain an + attribute *tables* listing all tables for which content should be added, and one + attribute per table that has the actual content. + + This is typically used to install the sequence tables. + + +.. function:: add_stream(database, name, path) + + Add the file *path* into the ``_Stream`` table of *database*, with the stream + name *name*. + + +.. function:: gen_uuid() + + Return a new UUID, in the format that MSI typically requires (i.e. in curly + braces, and with all hexdigits in upper-case). + + +.. seealso:: + + `FCICreate `_ + `UuidCreate `_ + `UuidToString `_ + +.. _database-objects: + +Database Objects +---------------- + + +.. method:: Database.OpenView(sql) + + Return a view object, by calling :c:func:`MSIDatabaseOpenView`. *sql* is the SQL + statement to execute. + + +.. method:: Database.Commit() + + Commit the changes pending in the current transaction, by calling + :c:func:`MSIDatabaseCommit`. + + +.. method:: Database.GetSummaryInformation(count) + + Return a new summary information object, by calling + :c:func:`MsiGetSummaryInformation`. *count* is the maximum number of updated + values. + +.. method:: Database.Close() + + Close the database object, through :c:func:`MsiCloseHandle`. + + .. versionadded:: 3.7 + +.. seealso:: + + `MSIDatabaseOpenView `_ + `MSIDatabaseCommit `_ + `MSIGetSummaryInformation `_ + `MsiCloseHandle `_ + +.. _view-objects: + +View Objects +------------ + + +.. method:: View.Execute(params) + + Execute the SQL query of the view, through :c:func:`MSIViewExecute`. If + *params* is not ``None``, it is a record describing actual values of the + parameter tokens in the query. + + +.. method:: View.GetColumnInfo(kind) + + Return a record describing the columns of the view, through calling + :c:func:`MsiViewGetColumnInfo`. *kind* can be either ``MSICOLINFO_NAMES`` or + ``MSICOLINFO_TYPES``. + + +.. method:: View.Fetch() + + Return a result record of the query, through calling :c:func:`MsiViewFetch`. + + +.. method:: View.Modify(kind, data) + + Modify the view, by calling :c:func:`MsiViewModify`. *kind* can be one of + ``MSIMODIFY_SEEK``, ``MSIMODIFY_REFRESH``, ``MSIMODIFY_INSERT``, + ``MSIMODIFY_UPDATE``, ``MSIMODIFY_ASSIGN``, ``MSIMODIFY_REPLACE``, + ``MSIMODIFY_MERGE``, ``MSIMODIFY_DELETE``, ``MSIMODIFY_INSERT_TEMPORARY``, + ``MSIMODIFY_VALIDATE``, ``MSIMODIFY_VALIDATE_NEW``, + ``MSIMODIFY_VALIDATE_FIELD``, or ``MSIMODIFY_VALIDATE_DELETE``. + + *data* must be a record describing the new data. + + +.. method:: View.Close() + + Close the view, through :c:func:`MsiViewClose`. + + +.. seealso:: + + `MsiViewExecute `_ + `MSIViewGetColumnInfo `_ + `MsiViewFetch `_ + `MsiViewModify `_ + `MsiViewClose `_ + +.. _summary-objects: + +Summary Information Objects +--------------------------- + + +.. method:: SummaryInformation.GetProperty(field) + + Return a property of the summary, through :c:func:`MsiSummaryInfoGetProperty`. + *field* is the name of the property, and can be one of the constants + ``PID_CODEPAGE``, ``PID_TITLE``, ``PID_SUBJECT``, ``PID_AUTHOR``, + ``PID_KEYWORDS``, ``PID_COMMENTS``, ``PID_TEMPLATE``, ``PID_LASTAUTHOR``, + ``PID_REVNUMBER``, ``PID_LASTPRINTED``, ``PID_CREATE_DTM``, + ``PID_LASTSAVE_DTM``, ``PID_PAGECOUNT``, ``PID_WORDCOUNT``, ``PID_CHARCOUNT``, + ``PID_APPNAME``, or ``PID_SECURITY``. + + +.. method:: SummaryInformation.GetPropertyCount() + + Return the number of summary properties, through + :c:func:`MsiSummaryInfoGetPropertyCount`. + + +.. method:: SummaryInformation.SetProperty(field, value) + + Set a property through :c:func:`MsiSummaryInfoSetProperty`. *field* can have the + same values as in :meth:`GetProperty`, *value* is the new value of the property. + Possible value types are integer and string. + + +.. method:: SummaryInformation.Persist() + + Write the modified properties to the summary information stream, using + :c:func:`MsiSummaryInfoPersist`. + + +.. seealso:: + + `MsiSummaryInfoGetProperty `_ + `MsiSummaryInfoGetPropertyCount `_ + `MsiSummaryInfoSetProperty `_ + `MsiSummaryInfoPersist `_ + +.. _record-objects: + +Record Objects +-------------- + + +.. method:: Record.GetFieldCount() + + Return the number of fields of the record, through + :c:func:`MsiRecordGetFieldCount`. + + +.. method:: Record.GetInteger(field) + + Return the value of *field* as an integer where possible. *field* must + be an integer. + + +.. method:: Record.GetString(field) + + Return the value of *field* as a string where possible. *field* must + be an integer. + + +.. method:: Record.SetString(field, value) + + Set *field* to *value* through :c:func:`MsiRecordSetString`. *field* must be an + integer; *value* a string. + + +.. method:: Record.SetStream(field, value) + + Set *field* to the contents of the file named *value*, through + :c:func:`MsiRecordSetStream`. *field* must be an integer; *value* a string. + + +.. method:: Record.SetInteger(field, value) + + Set *field* to *value* through :c:func:`MsiRecordSetInteger`. Both *field* and + *value* must be an integer. + + +.. method:: Record.ClearData() + + Set all fields of the record to 0, through :c:func:`MsiRecordClearData`. + + +.. seealso:: + + `MsiRecordGetFieldCount `_ + `MsiRecordSetString `_ + `MsiRecordSetStream `_ + `MsiRecordSetInteger `_ + `MsiRecordClearData `_ + +.. _msi-errors: + +Errors +------ + +All wrappers around MSI functions raise :exc:`MSIError`; the string inside the +exception will contain more detail. + + +.. _cab: + +CAB Objects +----------- + + +.. class:: CAB(name) + + The class :class:`CAB` represents a CAB file. During MSI construction, files + will be added simultaneously to the ``Files`` table, and to a CAB file. Then, + when all files have been added, the CAB file can be written, then added to the + MSI file. + + *name* is the name of the CAB file in the MSI file. + + + .. method:: append(full, file, logical) + + Add the file with the pathname *full* to the CAB file, under the name + *logical*. If there is already a file named *logical*, a new file name is + created. + + Return the index of the file in the CAB file, and the new name of the file + inside the CAB file. + + + .. method:: commit(database) + + Generate a CAB file, add it as a stream to the MSI file, put it into the + ``Media`` table, and remove the generated file from the disk. + + +.. _msi-directory: + +Directory Objects +----------------- + + +.. class:: Directory(database, cab, basedir, physical, logical, default, [componentflags]) + + Create a new directory in the Directory table. There is a current component at + each point in time for the directory, which is either explicitly created through + :meth:`start_component`, or implicitly when files are added for the first time. + Files are added into the current component, and into the cab file. To create a + directory, a base directory object needs to be specified (can be ``None``), the + path to the physical directory, and a logical directory name. *default* + specifies the DefaultDir slot in the directory table. *componentflags* specifies + the default flags that new components get. + + + .. method:: start_component(component=None, feature=None, flags=None, keyfile=None, uuid=None) + + Add an entry to the Component table, and make this component the current + component for this directory. If no component name is given, the directory + name is used. If no *feature* is given, the current feature is used. If no + *flags* are given, the directory's default flags are used. If no *keyfile* + is given, the KeyPath is left null in the Component table. + + + .. method:: add_file(file, src=None, version=None, language=None) + + Add a file to the current component of the directory, starting a new one + if there is no current component. By default, the file name in the source + and the file table will be identical. If the *src* file is specified, it + is interpreted relative to the current directory. Optionally, a *version* + and a *language* can be specified for the entry in the File table. + + + .. method:: glob(pattern, exclude=None) + + Add a list of files to the current component as specified in the glob + pattern. Individual files can be excluded in the *exclude* list. + + + .. method:: remove_pyc() + + Remove ``.pyc`` files on uninstall. + + +.. seealso:: + + `Directory Table `_ + `File Table `_ + `Component Table `_ + `FeatureComponents Table `_ + +.. _features: + +Features +-------- + + +.. class:: Feature(db, id, title, desc, display, level=1, parent=None, directory=None, attributes=0) + + Add a new record to the ``Feature`` table, using the values *id*, *parent.id*, + *title*, *desc*, *display*, *level*, *directory*, and *attributes*. The + resulting feature object can be passed to the :meth:`start_component` method of + :class:`Directory`. + + + .. method:: set_current() + + Make this feature the current feature of :mod:`msilib`. New components are + automatically added to the default feature, unless a feature is explicitly + specified. + + +.. seealso:: + + `Feature Table `_ + +.. _msi-gui: + +GUI classes +----------- + +:mod:`msilib` provides several classes that wrap the GUI tables in an MSI +database. However, no standard user interface is provided; use +:mod:`~distutils.command.bdist_msi` to create MSI files with a user-interface +for installing Python packages. + + +.. class:: Control(dlg, name) + + Base class of the dialog controls. *dlg* is the dialog object the control + belongs to, and *name* is the control's name. + + + .. method:: event(event, argument, condition=1, ordering=None) + + Make an entry into the ``ControlEvent`` table for this control. + + + .. method:: mapping(event, attribute) + + Make an entry into the ``EventMapping`` table for this control. + + + .. method:: condition(action, condition) + + Make an entry into the ``ControlCondition`` table for this control. + + +.. class:: RadioButtonGroup(dlg, name, property) + + Create a radio button control named *name*. *property* is the installer property + that gets set when a radio button is selected. + + + .. method:: add(name, x, y, width, height, text, value=None) + + Add a radio button named *name* to the group, at the coordinates *x*, *y*, + *width*, *height*, and with the label *text*. If *value* is ``None``, it + defaults to *name*. + + +.. class:: Dialog(db, name, x, y, w, h, attr, title, first, default, cancel) + + Return a new :class:`Dialog` object. An entry in the ``Dialog`` table is made, + with the specified coordinates, dialog attributes, title, name of the first, + default, and cancel controls. + + + .. method:: control(name, type, x, y, width, height, attributes, property, text, control_next, help) + + Return a new :class:`Control` object. An entry in the ``Control`` table is + made with the specified parameters. + + This is a generic method; for specific types, specialized methods are + provided. + + + .. method:: text(name, x, y, width, height, attributes, text) + + Add and return a ``Text`` control. + + + .. method:: bitmap(name, x, y, width, height, text) + + Add and return a ``Bitmap`` control. + + + .. method:: line(name, x, y, width, height) + + Add and return a ``Line`` control. + + + .. method:: pushbutton(name, x, y, width, height, attributes, text, next_control) + + Add and return a ``PushButton`` control. + + + .. method:: radiogroup(name, x, y, width, height, attributes, property, text, next_control) + + Add and return a ``RadioButtonGroup`` control. + + + .. method:: checkbox(name, x, y, width, height, attributes, property, text, next_control) + + Add and return a ``CheckBox`` control. + + +.. seealso:: + + `Dialog Table `_ + `Control Table `_ + `Control Types `_ + `ControlCondition Table `_ + `ControlEvent Table `_ + `EventMapping Table `_ + `RadioButton Table `_ + +.. _msi-tables: + +Precomputed tables +------------------ + +:mod:`msilib` provides a few subpackages that contain only schema and table +definitions. Currently, these definitions are based on MSI version 2.0. + + +.. data:: schema + + This is the standard MSI schema for MSI 2.0, with the *tables* variable + providing a list of table definitions, and *_Validation_records* providing the + data for MSI validation. + + +.. data:: sequence + + This module contains table contents for the standard sequence tables: + *AdminExecuteSequence*, *AdminUISequence*, *AdvtExecuteSequence*, + *InstallExecuteSequence*, and *InstallUISequence*. + + +.. data:: text + + This module contains definitions for the UIText and ActionText tables, for the + standard installer actions. diff --git a/cpython_2/environment/repo/Doc/library/msvcrt.rst b/cpython_2/environment/repo/Doc/library/msvcrt.rst new file mode 100644 index 0000000000000000000000000000000000000000..42fffee6a0f449244178b5dd022f7f99d0120be9 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/msvcrt.rst @@ -0,0 +1,160 @@ +:mod:`msvcrt` --- Useful routines from the MS VC++ runtime +========================================================== + +.. module:: msvcrt + :platform: Windows + :synopsis: Miscellaneous useful routines from the MS VC++ runtime. + +.. sectionauthor:: Fred L. Drake, Jr. + +-------------- + +These functions provide access to some useful capabilities on Windows platforms. +Some higher-level modules use these functions to build the Windows +implementations of their services. For example, the :mod:`getpass` module uses +this in the implementation of the :func:`getpass` function. + +Further documentation on these functions can be found in the Platform API +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 +ever possible. + +.. versionchanged:: 3.3 + Operations in this module now raise :exc:`OSError` where :exc:`IOError` + was raised. + + +.. _msvcrt-files: + +File Operations +--------------- + + +.. function:: locking(fd, mode, nbytes) + + Lock part of a file based on file descriptor *fd* from the C runtime. Raises + :exc:`OSError` on failure. The locked region of the file extends from the + current file position for *nbytes* bytes, and may continue beyond the end of the + file. *mode* must be one of the :const:`LK_\*` constants listed below. Multiple + regions in a file may be locked at the same time, but may not overlap. Adjacent + regions are not merged; they must be unlocked individually. + + .. audit-event:: msvcrt.locking fd,mode,nbytes msvcrt.locking + + +.. data:: LK_LOCK + LK_RLCK + + Locks the specified bytes. If the bytes cannot be locked, the program + immediately tries again after 1 second. If, after 10 attempts, the bytes cannot + be locked, :exc:`OSError` is raised. + + +.. data:: LK_NBLCK + LK_NBRLCK + + Locks the specified bytes. If the bytes cannot be locked, :exc:`OSError` is + raised. + + +.. data:: LK_UNLCK + + Unlocks the specified bytes, which must have been previously locked. + + +.. function:: setmode(fd, flags) + + Set the line-end translation mode for the file descriptor *fd*. To set it to + text mode, *flags* should be :const:`os.O_TEXT`; for binary, it should be + :const:`os.O_BINARY`. + + +.. function:: open_osfhandle(handle, flags) + + Create a C runtime file descriptor from the file handle *handle*. The *flags* + parameter should be a bitwise OR of :const:`os.O_APPEND`, :const:`os.O_RDONLY`, + and :const:`os.O_TEXT`. The returned file descriptor may be used as a parameter + to :func:`os.fdopen` to create a file object. + + .. audit-event:: msvcrt.open_osfhandle handle,flags msvcrt.open_osfhandle + + +.. function:: get_osfhandle(fd) + + Return the file handle for the file descriptor *fd*. Raises :exc:`OSError` if + *fd* is not recognized. + + .. audit-event:: msvcrt.get_osfhandle fd msvcrt.get_osfhandle + + +.. _msvcrt-console: + +Console I/O +----------- + + +.. function:: kbhit() + + Return ``True`` if a keypress is waiting to be read. + + +.. function:: getch() + + Read a keypress and return the resulting character as a byte string. + Nothing is echoed to the console. This call will block if a keypress + is not already available, but will not wait for :kbd:`Enter` to be + pressed. If the pressed key was a special function key, this will + return ``'\000'`` or ``'\xe0'``; the next call will 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() + + Similar to :func:`getch`, but the keypress will be echoed if it represents a + printable character. + + +.. function:: getwche() + + Wide char variant of :func:`getche`, returning a Unicode value. + + +.. function:: putch(char) + + Print the byte string *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 byte string *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: + +Other Functions +--------------- + + +.. function:: heapmin() + + Force the :c:func:`malloc` heap to clean itself up and return unused blocks to + the operating system. On failure, this raises :exc:`OSError`. diff --git a/cpython_2/environment/repo/Doc/library/multiprocessing.rst b/cpython_2/environment/repo/Doc/library/multiprocessing.rst new file mode 100644 index 0000000000000000000000000000000000000000..50b90031ab5a58b7f5f740cc4487bd166050da75 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/multiprocessing.rst @@ -0,0 +1,2915 @@ +:mod:`multiprocessing` --- Process-based parallelism +==================================================== + +.. module:: multiprocessing + :synopsis: Process-based parallelism. + +**Source code:** :source:`Lib/multiprocessing/` + +-------------- + +Introduction +------------ + +:mod:`multiprocessing` is a package that supports spawning processes using an +API similar to the :mod:`threading` module. The :mod:`multiprocessing` package +offers both local and remote concurrency, effectively side-stepping the +:term:`Global Interpreter Lock` by using subprocesses instead of threads. Due +to this, the :mod:`multiprocessing` module allows the programmer to fully +leverage multiple processors on a given machine. It runs on both Unix and +Windows. + +The :mod:`multiprocessing` module also introduces APIs which do not have +analogs in the :mod:`threading` module. A prime example of this is the +:class:`~multiprocessing.pool.Pool` object which offers a convenient means of +parallelizing the execution of a function across multiple input values, +distributing the input data across processes (data parallelism). The following +example demonstrates the common practice of defining such functions in a module +so that child processes can successfully import that module. This basic example +of data parallelism using :class:`~multiprocessing.pool.Pool`, :: + + from multiprocessing import Pool + + def f(x): + return x*x + + if __name__ == '__main__': + with Pool(5) as p: + print(p.map(f, [1, 2, 3])) + +will print to standard output :: + + [1, 4, 9] + + +The :class:`Process` class +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In :mod:`multiprocessing`, processes are spawned by creating a :class:`Process` +object and then calling its :meth:`~Process.start` method. :class:`Process` +follows the API of :class:`threading.Thread`. A trivial example of a +multiprocess program is :: + + from multiprocessing import Process + + def f(name): + print('hello', name) + + if __name__ == '__main__': + p = Process(target=f, args=('bob',)) + p.start() + p.join() + +To show the individual process IDs involved, here is an expanded example:: + + from multiprocessing import Process + import os + + def info(title): + print(title) + 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',)) + p.start() + p.join() + +For an explanation of why the ``if __name__ == '__main__'`` part is +necessary, see :ref:`multiprocessing-programming`. + + + +Contexts and start methods +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _multiprocessing-start-methods: + +Depending on the platform, :mod:`multiprocessing` supports three ways +to start a process. These *start methods* are + + *spawn* + The parent process starts a fresh python interpreter process. The + child process will only inherit those resources necessary to run + the process objects :meth:`~Process.run` method. In particular, + unnecessary file descriptors and handles from the parent process + will not be inherited. Starting a process using this method is + rather slow compared to using *fork* or *forkserver*. + + Available on Unix and Windows. The default on Windows and macOS. + + *fork* + The parent process uses :func:`os.fork` to fork the Python + interpreter. The child process, when it begins, is effectively + identical to the parent process. All resources of the parent are + inherited by the child process. Note that safely forking a + multithreaded process is problematic. + + Available on Unix only. The default on Unix. + + *forkserver* + When the program starts and selects the *forkserver* start method, + a server process is started. From then on, whenever a new process + is needed, the parent process connects to the server and requests + that it fork a new process. The fork server process is single + threaded so it is safe for it to use :func:`os.fork`. No + unnecessary resources are inherited. + + Available on Unix platforms which support passing file descriptors + over Unix pipes. + +.. versionchanged:: 3.8 + + On macOS, the *spawn* start method is now the default. The *fork* start + method should be considered unsafe as it can lead to crashes of the + subprocess. See :issue:`33725`. + +.. versionchanged:: 3.4 + *spawn* added on all unix platforms, and *forkserver* added for + some unix platforms. + Child processes no longer inherit all of the parents inheritable + handles on Windows. + +On Unix using the *spawn* or *forkserver* start methods will also +start a *resource tracker* process which tracks the unlinked named +system resources (such as named semaphores or +:class:`~multiprocessing.shared_memory.SharedMemory` objects) created +by processes of the program. When all processes +have exited the resource tracker unlinks any remaining tracked object. +Usually there should be none, but if a process was killed by a signal +there may be some "leaked" resources. (Neither leaked semaphores nor shared +memory segments will be automatically unlinked until the next reboot. This is +problematic for both objects because the system allows only a limited number of +named semaphores, and shared memory segments occupy some space in the main +memory.) + +To select a start method you use the :func:`set_start_method` in +the ``if __name__ == '__main__'`` clause of the main module. For +example:: + + import multiprocessing as mp + + def foo(q): + q.put('hello') + + if __name__ == '__main__': + mp.set_start_method('spawn') + q = mp.Queue() + p = mp.Process(target=foo, args=(q,)) + p.start() + print(q.get()) + p.join() + +:func:`set_start_method` should not be used more than once in the +program. + +Alternatively, you can use :func:`get_context` to obtain a context +object. Context objects have the same API as the multiprocessing +module, and allow one to use multiple start methods in the same +program. :: + + import multiprocessing as mp + + def foo(q): + q.put('hello') + + if __name__ == '__main__': + ctx = mp.get_context('spawn') + q = ctx.Queue() + p = ctx.Process(target=foo, args=(q,)) + p.start() + print(q.get()) + p.join() + +Note that objects related to one context may not be compatible with +processes for a different context. In particular, locks created using +the *fork* context cannot be passed to processes started using the +*spawn* or *forkserver* start methods. + +A library which wants to use a particular start method should probably +use :func:`get_context` to avoid interfering with the choice of the +library user. + +.. warning:: + + The ``'spawn'`` and ``'forkserver'`` start methods cannot currently + be used with "frozen" executables (i.e., binaries produced by + packages like **PyInstaller** and **cx_Freeze**) on Unix. + The ``'fork'`` start method does work. + + +Exchanging objects between processes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:mod:`multiprocessing` supports two types of communication channel between +processes: + +**Queues** + + The :class:`Queue` class is a near clone of :class:`queue.Queue`. For + example:: + + from multiprocessing import Process, Queue + + def f(q): + q.put([42, None, 'hello']) + + if __name__ == '__main__': + q = Queue() + p = Process(target=f, args=(q,)) + p.start() + print(q.get()) # prints "[42, None, 'hello']" + p.join() + + Queues are thread and process safe. + +**Pipes** + + The :func:`Pipe` function returns a pair of connection objects connected by a + pipe which by default is duplex (two-way). For example:: + + from multiprocessing import Process, Pipe + + def f(conn): + conn.send([42, None, 'hello']) + conn.close() + + if __name__ == '__main__': + parent_conn, child_conn = Pipe() + p = Process(target=f, args=(child_conn,)) + p.start() + print(parent_conn.recv()) # prints "[42, None, 'hello']" + p.join() + + The two connection objects returned by :func:`Pipe` represent the two ends of + the pipe. Each connection object has :meth:`~Connection.send` and + :meth:`~Connection.recv` methods (among others). Note that data in a pipe + may become corrupted if two processes (or threads) try to read from or write + to the *same* end of the pipe at the same time. Of course there is no risk + of corruption from processes using different ends of the pipe at the same + time. + + +Synchronization between processes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:mod:`multiprocessing` contains equivalents of all the synchronization +primitives from :mod:`threading`. For instance one can use a lock to ensure +that only one process prints to standard output at a time:: + + from multiprocessing import Process, Lock + + def f(l, i): + l.acquire() + try: + print('hello world', i) + finally: + l.release() + + if __name__ == '__main__': + lock = Lock() + + for num in range(10): + Process(target=f, args=(lock, num)).start() + +Without using the lock output from the different processes is liable to get all +mixed up. + + +Sharing state between processes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +As mentioned above, when doing concurrent programming it is usually best to +avoid using shared state as far as possible. This is particularly true when +using multiple processes. + +However, if you really do need to use some shared data then +:mod:`multiprocessing` provides a couple of ways of doing so. + +**Shared memory** + + Data can be stored in a shared memory map using :class:`Value` or + :class:`Array`. For example, the following code :: + + from multiprocessing import Process, Value, Array + + def f(n, a): + n.value = 3.1415927 + for i in range(len(a)): + a[i] = -a[i] + + if __name__ == '__main__': + num = Value('d', 0.0) + arr = Array('i', range(10)) + + p = Process(target=f, args=(num, arr)) + p.start() + p.join() + + print(num.value) + print(arr[:]) + + will print :: + + 3.1415927 + [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] + + The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are + typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a + double precision float and ``'i'`` indicates a signed integer. These shared + objects will be process and thread-safe. + + For more flexibility in using shared memory one can use the + :mod:`multiprocessing.sharedctypes` module which supports the creation of + arbitrary ctypes objects allocated from shared memory. + +**Server process** + + A manager object returned by :func:`Manager` controls a server process which + holds Python objects and allows other processes to manipulate them using + proxies. + + A manager returned by :func:`Manager` will support types + :class:`list`, :class:`dict`, :class:`~managers.Namespace`, :class:`Lock`, + :class:`RLock`, :class:`Semaphore`, :class:`BoundedSemaphore`, + :class:`Condition`, :class:`Event`, :class:`Barrier`, + :class:`Queue`, :class:`Value` and :class:`Array`. For example, :: + + from multiprocessing import Process, Manager + + def f(d, l): + d[1] = '1' + d['2'] = 2 + d[0.25] = None + l.reverse() + + if __name__ == '__main__': + with Manager() as manager: + d = manager.dict() + l = manager.list(range(10)) + + p = Process(target=f, args=(d, l)) + p.start() + p.join() + + print(d) + print(l) + + will print :: + + {0.25: None, 1: '1', '2': 2} + [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + + Server process managers are more flexible than using shared memory objects + because they can be made to support arbitrary object types. Also, a single + manager can be shared by processes on different computers over a network. + They are, however, slower than using shared memory. + + +Using a pool of workers +~~~~~~~~~~~~~~~~~~~~~~~ + +The :class:`~multiprocessing.pool.Pool` class represents a pool of worker +processes. It has methods which allows tasks to be offloaded to the worker +processes in a few different ways. + +For example:: + + from multiprocessing import Pool, TimeoutError + import time + import os + + def f(x): + return x*x + + if __name__ == '__main__': + # start 4 worker processes + with Pool(processes=4) as pool: + + # print "[0, 1, 4,..., 81]" + print(pool.map(f, range(10))) + + # print same numbers in arbitrary order + for i in pool.imap_unordered(f, range(10)): + print(i) + + # evaluate "f(20)" asynchronously + res = pool.apply_async(f, (20,)) # runs in *only* one process + print(res.get(timeout=1)) # prints "400" + + # evaluate "os.getpid()" asynchronously + res = pool.apply_async(os.getpid, ()) # runs in *only* one process + print(res.get(timeout=1)) # prints the PID of that process + + # launching multiple evaluations asynchronously *may* use more processes + multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)] + print([res.get(timeout=1) for res in multiple_results]) + + # make a single worker sleep for 10 secs + res = pool.apply_async(time.sleep, (10,)) + try: + print(res.get(timeout=1)) + except TimeoutError: + print("We lacked patience and got a multiprocessing.TimeoutError") + + print("For the moment, the pool remains available for more work") + + # exiting the 'with'-block has stopped the pool + print("Now the pool is closed and no longer available") + +Note that the methods of a pool should only ever be used by the +process which created it. + +.. note:: + + Functionality within this package requires that the ``__main__`` module be + importable by the children. This is covered in :ref:`multiprocessing-programming` + however it is worth pointing out here. This means that some examples, such + as the :class:`multiprocessing.pool.Pool` examples will not work in the + interactive interpreter. For example:: + + >>> from multiprocessing import Pool + >>> p = Pool(5) + >>> def f(x): + ... return x*x + ... + >>> with p: + ... p.map(f, [1,2,3]) + Process PoolWorker-1: + Process PoolWorker-2: + Process PoolWorker-3: + Traceback (most recent call last): + Traceback (most recent call last): + Traceback (most recent call last): + AttributeError: 'module' object has no attribute 'f' + AttributeError: 'module' object has no attribute 'f' + AttributeError: 'module' object has no attribute 'f' + + (If you try this it will actually output three full tracebacks + interleaved in a semi-random fashion, and then you may have to + stop the parent process somehow.) + + +Reference +--------- + +The :mod:`multiprocessing` package mostly replicates the API of the +:mod:`threading` module. + + +:class:`Process` and exceptions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. class:: Process(group=None, target=None, name=None, args=(), kwargs={}, \ + *, daemon=None) + + Process objects represent activity that is run in a separate process. The + :class:`Process` class has equivalents of all the methods of + :class:`threading.Thread`. + + The constructor should always be called with keyword arguments. *group* + should always be ``None``; it exists solely for compatibility with + :class:`threading.Thread`. *target* is the callable object to be invoked by + the :meth:`run()` method. It defaults to ``None``, meaning nothing is + called. *name* is the process name (see :attr:`name` for more details). + *args* is the argument tuple for the target invocation. *kwargs* is a + dictionary of keyword arguments for the target invocation. If provided, + the keyword-only *daemon* argument sets the process :attr:`daemon` flag + to ``True`` or ``False``. If ``None`` (the default), this flag will be + inherited from the creating process. + + By default, no arguments are passed to *target*. + + If a subclass overrides the constructor, it must make sure it invokes the + base class constructor (:meth:`Process.__init__`) before doing anything else + to the process. + + .. versionchanged:: 3.3 + Added the *daemon* argument. + + .. method:: run() + + Method representing the process's activity. + + You may override this method in a subclass. The standard :meth:`run` + method invokes the callable object passed to the object's constructor as + the target argument, if any, with sequential and keyword arguments taken + from the *args* and *kwargs* arguments, respectively. + + .. method:: start() + + Start the process's activity. + + This must be called at most once per process object. It arranges for the + object's :meth:`run` method to be invoked in a separate process. + + .. method:: join([timeout]) + + If the optional argument *timeout* is ``None`` (the default), the method + blocks until the process whose :meth:`join` method is called terminates. + If *timeout* is a positive number, it blocks at most *timeout* seconds. + Note that the method returns ``None`` if its process terminates or if the + method times out. Check the process's :attr:`exitcode` to determine if + it terminated. + + A process can be joined many times. + + A process cannot join itself because this would cause a deadlock. It is + an error to attempt to join a process before it has been started. + + .. attribute:: name + + The process's name. The name is a string used for identification purposes + only. It has no semantics. Multiple processes may be given the same + name. + + The initial name is set by the constructor. If no explicit name is + provided to the constructor, a name of the form + 'Process-N\ :sub:`1`:N\ :sub:`2`:...:N\ :sub:`k`' is constructed, where + each N\ :sub:`k` is the N-th child of its parent. + + .. method:: is_alive + + Return whether the process is alive. + + Roughly, a process object is alive from the moment the :meth:`start` + method returns until the child process terminates. + + .. attribute:: daemon + + The process's daemon flag, a Boolean value. This must be set before + :meth:`start` is called. + + The initial value is inherited from the creating process. + + When a process exits, it attempts to terminate all of its daemonic child + processes. + + Note that a daemonic process is not allowed to create child processes. + Otherwise a daemonic process would leave its children orphaned if it gets + terminated when its parent process exits. Additionally, these are **not** + Unix daemons or services, they are normal processes that will be + terminated (and not joined) if non-daemonic processes have exited. + + In addition to the :class:`threading.Thread` API, :class:`Process` objects + also support the following attributes and methods: + + .. attribute:: pid + + Return the process ID. Before the process is spawned, this will be + ``None``. + + .. attribute:: exitcode + + The child's exit code. This will be ``None`` if the process has not yet + terminated. A negative value *-N* indicates that the child was terminated + by signal *N*. + + .. attribute:: authkey + + The process's authentication key (a byte string). + + When :mod:`multiprocessing` is initialized the main process is assigned a + random string using :func:`os.urandom`. + + When a :class:`Process` object is created, it will inherit the + authentication key of its parent process, although this may be changed by + setting :attr:`authkey` to another byte string. + + See :ref:`multiprocessing-auth-keys`. + + .. attribute:: sentinel + + A numeric handle of a system object which will become "ready" when + the process ends. + + You can use this value if you want to wait on several events at + once using :func:`multiprocessing.connection.wait`. Otherwise + calling :meth:`join()` is simpler. + + On Windows, this is an OS handle usable with the ``WaitForSingleObject`` + and ``WaitForMultipleObjects`` family of API calls. On Unix, this is + a file descriptor usable with primitives from the :mod:`select` module. + + .. versionadded:: 3.3 + + .. method:: terminate() + + Terminate the process. On Unix this is done using the ``SIGTERM`` signal; + on Windows :c:func:`TerminateProcess` is used. Note that exit handlers and + finally clauses, etc., will not be executed. + + Note that descendant processes of the process will *not* be terminated -- + they will simply become orphaned. + + .. warning:: + + If this method is used when the associated process is using a pipe or + queue then the pipe or queue is liable to become corrupted and may + become unusable by other process. Similarly, if the process has + acquired a lock or semaphore etc. then terminating it is liable to + cause other processes to deadlock. + + .. method:: kill() + + Same as :meth:`terminate()` but using the ``SIGKILL`` signal on Unix. + + .. versionadded:: 3.7 + + .. method:: close() + + Close the :class:`Process` object, releasing all resources associated + with it. :exc:`ValueError` is raised if the underlying process + is still running. Once :meth:`close` returns successfully, most + other methods and attributes of the :class:`Process` object will + raise :exc:`ValueError`. + + .. versionadded:: 3.7 + + Note that the :meth:`start`, :meth:`join`, :meth:`is_alive`, + :meth:`terminate` and :attr:`exitcode` methods should only be called by + the process that created the process object. + + Example usage of some of the methods of :class:`Process`: + + .. doctest:: + :options: +ELLIPSIS + + >>> import multiprocessing, time, signal + >>> p = multiprocessing.Process(target=time.sleep, args=(1000,)) + >>> print(p, p.is_alive()) + False + >>> p.start() + >>> print(p, p.is_alive()) + True + >>> p.terminate() + >>> time.sleep(0.1) + >>> print(p, p.is_alive()) + False + >>> p.exitcode == -signal.SIGTERM + True + +.. exception:: ProcessError + + The base class of all :mod:`multiprocessing` exceptions. + +.. exception:: BufferTooShort + + Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied + buffer object is too small for the message read. + + If ``e`` is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give + the message as a byte string. + +.. exception:: AuthenticationError + + Raised when there is an authentication error. + +.. exception:: TimeoutError + + Raised by methods with a timeout when the timeout expires. + +Pipes and Queues +~~~~~~~~~~~~~~~~ + +When using multiple processes, one generally uses message passing for +communication between processes and avoids having to use any synchronization +primitives like locks. + +For passing messages one can use :func:`Pipe` (for a connection between two +processes) or a queue (which allows multiple producers and consumers). + +The :class:`Queue`, :class:`SimpleQueue` and :class:`JoinableQueue` types +are multi-producer, multi-consumer :abbr:`FIFO (first-in, first-out)` +queues modelled on the :class:`queue.Queue` class in the +standard library. They differ in that :class:`Queue` lacks the +:meth:`~queue.Queue.task_done` and :meth:`~queue.Queue.join` methods introduced +into Python 2.5's :class:`queue.Queue` class. + +If you use :class:`JoinableQueue` then you **must** call +:meth:`JoinableQueue.task_done` for each task removed from the queue or else the +semaphore used to count the number of unfinished tasks may eventually overflow, +raising an exception. + +Note that one can also create a shared queue by using a manager object -- see +:ref:`multiprocessing-managers`. + +.. note:: + + :mod:`multiprocessing` uses the usual :exc:`queue.Empty` and + :exc:`queue.Full` exceptions to signal a timeout. They are not available in + the :mod:`multiprocessing` namespace so you need to import them from + :mod:`queue`. + +.. note:: + + When an object is put on a queue, the object is pickled and a + background thread later flushes the pickled data to an underlying + pipe. This has some consequences which are a little surprising, + but should not cause any practical difficulties -- if they really + bother you then you can instead use a queue created with a + :ref:`manager `. + + (1) After putting an object on an empty queue there may be an + infinitesimal delay before the queue's :meth:`~Queue.empty` + method returns :const:`False` and :meth:`~Queue.get_nowait` can + return without raising :exc:`queue.Empty`. + + (2) If multiple processes are enqueuing objects, it is possible for + the objects to be received at the other end out-of-order. + However, objects enqueued by the same process will always be in + the expected order with respect to each other. + +.. warning:: + + If a process is killed using :meth:`Process.terminate` or :func:`os.kill` + while it is trying to use a :class:`Queue`, then the data in the queue is + likely to become corrupted. This may cause any other process to get an + exception when it tries to use the queue later on. + +.. warning:: + + As mentioned above, if a child process has put items on a queue (and it has + not used :meth:`JoinableQueue.cancel_join_thread + `), then that process will + not terminate until all buffered items have been flushed to the pipe. + + This means that if you try joining that process you may get a deadlock unless + you are sure that all items which have been put on the queue have been + consumed. Similarly, if the child process is non-daemonic then the parent + process may hang on exit when it tries to join all its non-daemonic children. + + Note that a queue created using a manager does not have this issue. See + :ref:`multiprocessing-programming`. + +For an example of the usage of queues for interprocess communication see +:ref:`multiprocessing-examples`. + + +.. function:: Pipe([duplex]) + + Returns a pair ``(conn1, conn2)`` of + :class:`~multiprocessing.connection.Connection` objects representing the + ends of a pipe. + + If *duplex* is ``True`` (the default) then the pipe is bidirectional. If + *duplex* is ``False`` then the pipe is unidirectional: ``conn1`` can only be + used for receiving messages and ``conn2`` can only be used for sending + messages. + + +.. class:: Queue([maxsize]) + + Returns a process shared queue implemented using a pipe and a few + locks/semaphores. When a process first puts an item on the queue a feeder + thread is started which transfers objects from a buffer into the pipe. + + The usual :exc:`queue.Empty` and :exc:`queue.Full` exceptions from the + standard library's :mod:`queue` module are raised to signal timeouts. + + :class:`Queue` implements all the methods of :class:`queue.Queue` except for + :meth:`~queue.Queue.task_done` and :meth:`~queue.Queue.join`. + + .. method:: qsize() + + Return the approximate size of the queue. Because of + multithreading/multiprocessing semantics, this number is not reliable. + + Note that this may raise :exc:`NotImplementedError` on Unix platforms like + Mac OS X where ``sem_getvalue()`` is not implemented. + + .. method:: empty() + + Return ``True`` if the queue is empty, ``False`` otherwise. Because of + multithreading/multiprocessing semantics, this is not reliable. + + .. method:: full() + + Return ``True`` if the queue is full, ``False`` otherwise. Because of + multithreading/multiprocessing semantics, this is not reliable. + + .. method:: put(obj[, block[, timeout]]) + + Put obj 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 + free slot was available within that time. Otherwise (*block* is + ``False``), put an item on the queue if a free slot is immediately + available, else raise the :exc:`queue.Full` exception (*timeout* is + ignored in that case). + + .. versionchanged:: 3.8 + If the queue is closed, :exc:`ValueError` is raised instead of + :exc:`AssertionError`. + + .. method:: put_nowait(obj) + + Equivalent to ``put(obj, False)``. + + .. method:: get([block[, timeout]]) + + Remove and return an item from the queue. If optional args *block* is + ``True`` (the default) and *timeout* is ``None`` (the default), block if + necessary until an item is available. If *timeout* is a positive number, + it blocks at most *timeout* seconds and raises the :exc:`queue.Empty` + exception if no item was available within that time. Otherwise (block is + ``False``), return an item if one is immediately available, else raise the + :exc:`queue.Empty` exception (*timeout* is ignored in that case). + + .. versionchanged:: 3.8 + If the queue is closed, :exc:`ValueError` is raised instead of + :exc:`OSError`. + + .. method:: get_nowait() + + Equivalent to ``get(False)``. + + :class:`multiprocessing.Queue` has a few additional methods not found in + :class:`queue.Queue`. These methods are usually unnecessary for most + code: + + .. method:: close() + + Indicate that no more data will be put on this queue by the current + process. The background thread will quit once it has flushed all buffered + data to the pipe. This is called automatically when the queue is garbage + collected. + + .. method:: join_thread() + + Join the background thread. This can only be used after :meth:`close` has + been called. It blocks until the background thread exits, ensuring that + all data in the buffer has been flushed to the pipe. + + By default if a process is not the creator of the queue then on exit it + will attempt to join the queue's background thread. The process can call + :meth:`cancel_join_thread` to make :meth:`join_thread` do nothing. + + .. method:: cancel_join_thread() + + Prevent :meth:`join_thread` from blocking. In particular, this prevents + the background thread from being joined automatically when the process + exits -- see :meth:`join_thread`. + + A better name for this method might be + ``allow_exit_without_flush()``. It is likely to cause enqueued + data to lost, and you almost certainly will not need to use it. + It is really only there if you need the current process to exit + immediately without waiting to flush enqueued data to the + underlying pipe, and you don't care about lost data. + + .. note:: + + This class's functionality requires a functioning shared semaphore + implementation on the host operating system. Without one, the + functionality in this class will be disabled, and attempts to + instantiate a :class:`Queue` will result in an :exc:`ImportError`. See + :issue:`3770` for additional information. The same holds true for any + of the specialized queue types listed below. + +.. class:: SimpleQueue() + + It is a simplified :class:`Queue` type, very close to a locked :class:`Pipe`. + + .. method:: close() + + Close the queue: release internal resources. + + A queue must not be used anymore after it is closed. For example, + :meth:`get`, :meth:`put` and :meth:`empty` methods must no longer be + called. + + .. versionadded:: 3.9 + + .. method:: empty() + + Return ``True`` if the queue is empty, ``False`` otherwise. + + .. method:: get() + + Remove and return an item from the queue. + + .. method:: put(item) + + Put *item* into the queue. + + +.. class:: JoinableQueue([maxsize]) + + :class:`JoinableQueue`, a :class:`Queue` subclass, is a queue which + additionally has :meth:`task_done` and :meth:`join` methods. + + .. method:: task_done() + + Indicate that a formerly enqueued task is complete. Used by queue + consumers. For each :meth:`~Queue.get` used to fetch a task, a subsequent + call to :meth:`task_done` tells the queue that the processing on the task + is complete. + + If a :meth:`~queue.Queue.join` is currently blocking, it will resume when all + items have been processed (meaning that a :meth:`task_done` call was + received for every item that had been :meth:`~Queue.put` into the queue). + + Raises a :exc:`ValueError` if called more times than there were items + placed in the queue. + + + .. method:: join() + + Block until all items in the queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the + queue. The count goes down whenever a consumer calls + :meth:`task_done` to indicate that the item was retrieved and all work on + it is complete. When the count of unfinished tasks drops to zero, + :meth:`~queue.Queue.join` unblocks. + + +Miscellaneous +~~~~~~~~~~~~~ + +.. function:: active_children() + + Return list of all live children of the current process. + + Calling this has the side effect of "joining" any processes which have + already finished. + +.. function:: cpu_count() + + Return the number of CPUs in the system. + + This number is not equivalent to the number of CPUs the current process can + use. The number of usable CPUs can be obtained with + ``len(os.sched_getaffinity(0))`` + + May raise :exc:`NotImplementedError`. + + .. seealso:: + :func:`os.cpu_count` + +.. function:: current_process() + + Return the :class:`Process` object corresponding to the current process. + + An analogue of :func:`threading.current_thread`. + +.. function:: parent_process() + + Return the :class:`Process` object corresponding to the parent process of + the :func:`current_process`. For the main process, ``parent_process`` will + be ``None``. + + .. versionadded:: 3.8 + +.. function:: freeze_support() + + Add support for when a program which uses :mod:`multiprocessing` has been + frozen to produce a Windows executable. (Has been tested with **py2exe**, + **PyInstaller** and **cx_Freeze**.) + + One needs to call this function straight after the ``if __name__ == + '__main__'`` line of the main module. For example:: + + from multiprocessing import Process, freeze_support + + def f(): + print('hello world!') + + if __name__ == '__main__': + freeze_support() + Process(target=f).start() + + If the ``freeze_support()`` line is omitted then trying to run the frozen + executable will raise :exc:`RuntimeError`. + + Calling ``freeze_support()`` has no effect when invoked on any operating + system other than Windows. In addition, if the module is being run + normally by the Python interpreter on Windows (the program has not been + frozen), then ``freeze_support()`` has no effect. + +.. function:: get_all_start_methods() + + Returns a list of the supported start methods, the first of which + is the default. The possible start methods are ``'fork'``, + ``'spawn'`` and ``'forkserver'``. On Windows only ``'spawn'`` is + available. On Unix ``'fork'`` and ``'spawn'`` are always + supported, with ``'fork'`` being the default. + + .. versionadded:: 3.4 + +.. function:: get_context(method=None) + + Return a context object which has the same attributes as the + :mod:`multiprocessing` module. + + If *method* is ``None`` then the default context is returned. + Otherwise *method* should be ``'fork'``, ``'spawn'``, + ``'forkserver'``. :exc:`ValueError` is raised if the specified + start method is not available. + + .. versionadded:: 3.4 + +.. function:: get_start_method(allow_none=False) + + Return the name of start method used for starting processes. + + If the start method has not been fixed and *allow_none* is false, + then the start method is fixed to the default and the name is + returned. If the start method has not been fixed and *allow_none* + is true then ``None`` is returned. + + The return value can be ``'fork'``, ``'spawn'``, ``'forkserver'`` + or ``None``. ``'fork'`` is the default on Unix, while ``'spawn'`` is + the default on Windows. + + .. versionadded:: 3.4 + +.. function:: set_executable() + + Sets the path of the Python interpreter to use when starting a child process. + (By default :data:`sys.executable` is used). Embedders will probably need to + do some thing like :: + + set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe')) + + before they can create child processes. + + .. versionchanged:: 3.4 + Now supported on Unix when the ``'spawn'`` start method is used. + +.. function:: set_start_method(method) + + Set the method which should be used to start child processes. + *method* can be ``'fork'``, ``'spawn'`` or ``'forkserver'``. + + Note that this should be called at most once, and it should be + protected inside the ``if __name__ == '__main__'`` clause of the + main module. + + .. versionadded:: 3.4 + +.. note:: + + :mod:`multiprocessing` contains no analogues of + :func:`threading.active_count`, :func:`threading.enumerate`, + :func:`threading.settrace`, :func:`threading.setprofile`, + :class:`threading.Timer`, or :class:`threading.local`. + + +Connection Objects +~~~~~~~~~~~~~~~~~~ + +.. currentmodule:: multiprocessing.connection + +Connection objects allow the sending and receiving of picklable objects or +strings. They can be thought of as message oriented connected sockets. + +Connection objects are usually created using +:func:`Pipe ` -- see also +:ref:`multiprocessing-listeners-clients`. + +.. class:: Connection + + .. method:: send(obj) + + Send an object to the other end of the connection which should be read + using :meth:`recv`. + + The object must be picklable. Very large pickles (approximately 32 MiB+, + though it depends on the OS) may raise a :exc:`ValueError` exception. + + .. method:: recv() + + Return an object sent from the other end of the connection using + :meth:`send`. Blocks until there is something to receive. Raises + :exc:`EOFError` if there is nothing left to receive + and the other end was closed. + + .. method:: fileno() + + Return the file descriptor or handle used by the connection. + + .. method:: close() + + Close the connection. + + This is called automatically when the connection is garbage collected. + + .. method:: poll([timeout]) + + Return whether there is any data available to be read. + + If *timeout* is not specified then it will return immediately. If + *timeout* is a number then this specifies the maximum time in seconds to + block. If *timeout* is ``None`` then an infinite timeout is used. + + Note that multiple connection objects may be polled at once by + using :func:`multiprocessing.connection.wait`. + + .. method:: send_bytes(buffer[, offset[, size]]) + + Send byte data from a :term:`bytes-like object` as a complete message. + + If *offset* is given then data is read from that position in *buffer*. If + *size* is given then that many bytes will be read from buffer. Very large + buffers (approximately 32 MiB+, though it depends on the OS) may raise a + :exc:`ValueError` exception + + .. method:: recv_bytes([maxlength]) + + Return a complete message of byte data sent from the other end of the + connection as a string. Blocks until there is something to receive. + Raises :exc:`EOFError` if there is nothing left + to receive and the other end has closed. + + If *maxlength* is specified and the message is longer than *maxlength* + then :exc:`OSError` is raised and the connection will no longer be + readable. + + .. versionchanged:: 3.3 + This function used to raise :exc:`IOError`, which is now an + alias of :exc:`OSError`. + + + .. method:: recv_bytes_into(buffer[, offset]) + + Read into *buffer* a complete message of byte data sent from the other end + of the connection and return the number of bytes in the message. Blocks + until there is something to receive. Raises + :exc:`EOFError` if there is nothing left to receive and the other end was + closed. + + *buffer* must be a writable :term:`bytes-like object`. If + *offset* is given then the message will be written into the buffer from + that position. Offset must be a non-negative integer less than the + length of *buffer* (in bytes). + + If the buffer is too short then a :exc:`BufferTooShort` exception is + raised and the complete message is available as ``e.args[0]`` where ``e`` + is the exception instance. + + .. versionchanged:: 3.3 + Connection objects themselves can now be transferred between processes + using :meth:`Connection.send` and :meth:`Connection.recv`. + + .. versionadded:: 3.3 + Connection objects now support the context management protocol -- see + :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` returns the + connection object, and :meth:`~contextmanager.__exit__` calls :meth:`close`. + +For example: + +.. doctest:: + + >>> from multiprocessing import Pipe + >>> a, b = Pipe() + >>> a.send([1, 'hello', None]) + >>> b.recv() + [1, 'hello', None] + >>> b.send_bytes(b'thank you') + >>> a.recv_bytes() + b'thank you' + >>> import array + >>> arr1 = array.array('i', range(5)) + >>> arr2 = array.array('i', [0] * 10) + >>> a.send_bytes(arr1) + >>> count = b.recv_bytes_into(arr2) + >>> assert count == len(arr1) * arr1.itemsize + >>> arr2 + array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0]) + + +.. warning:: + + The :meth:`Connection.recv` method automatically unpickles the data it + receives, which can be a security risk unless you can trust the process + which sent the message. + + Therefore, unless the connection object was produced using :func:`Pipe` you + should only use the :meth:`~Connection.recv` and :meth:`~Connection.send` + methods after performing some sort of authentication. See + :ref:`multiprocessing-auth-keys`. + +.. warning:: + + If a process is killed while it is trying to read or write to a pipe then + the data in the pipe is likely to become corrupted, because it may become + impossible to be sure where the message boundaries lie. + + +Synchronization primitives +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. currentmodule:: multiprocessing + +Generally synchronization primitives are not as necessary in a multiprocess +program as they are in a multithreaded program. See the documentation for +:mod:`threading` module. + +Note that one can also create synchronization primitives by using a manager +object -- see :ref:`multiprocessing-managers`. + +.. class:: Barrier(parties[, action[, timeout]]) + + A barrier object: a clone of :class:`threading.Barrier`. + + .. versionadded:: 3.3 + +.. class:: BoundedSemaphore([value]) + + A bounded semaphore object: a close analog of + :class:`threading.BoundedSemaphore`. + + A solitary difference from its close analog exists: its ``acquire`` method's + first argument is named *block*, as is consistent with :meth:`Lock.acquire`. + + .. note:: + On Mac OS X, this is indistinguishable from :class:`Semaphore` because + ``sem_getvalue()`` is not implemented on that platform. + +.. class:: Condition([lock]) + + A condition variable: an alias for :class:`threading.Condition`. + + If *lock* is specified then it should be a :class:`Lock` or :class:`RLock` + object from :mod:`multiprocessing`. + + .. versionchanged:: 3.3 + The :meth:`~threading.Condition.wait_for` method was added. + +.. class:: Event() + + A clone of :class:`threading.Event`. + + +.. class:: Lock() + + A non-recursive lock object: a close analog of :class:`threading.Lock`. + Once a process or thread has acquired a lock, subsequent attempts to + acquire it from any process or thread will block until it is released; + any process or thread may release it. The concepts and behaviors of + :class:`threading.Lock` as it applies to threads are replicated here in + :class:`multiprocessing.Lock` as it applies to either processes or threads, + except as noted. + + Note that :class:`Lock` is actually a factory function which returns an + instance of ``multiprocessing.synchronize.Lock`` initialized with a + default context. + + :class:`Lock` supports the :term:`context manager` protocol and thus may be + used in :keyword:`with` statements. + + .. method:: acquire(block=True, timeout=None) + + Acquire a lock, blocking or non-blocking. + + With the *block* argument set to ``True`` (the default), the method call + will block until the lock is in an unlocked state, then set it to locked + and return ``True``. Note that the name of this first argument differs + from that in :meth:`threading.Lock.acquire`. + + With the *block* argument set to ``False``, the method call does not + block. If the lock is currently in a locked state, return ``False``; + otherwise set the lock to a locked state and return ``True``. + + When invoked with a positive, floating-point value for *timeout*, block + for at most the number of seconds specified by *timeout* as long as + the lock can not be acquired. Invocations with a negative value for + *timeout* are equivalent to a *timeout* of zero. Invocations with a + *timeout* value of ``None`` (the default) set the timeout period to + infinite. Note that the treatment of negative or ``None`` values for + *timeout* differs from the implemented behavior in + :meth:`threading.Lock.acquire`. The *timeout* argument has no practical + implications if the *block* argument is set to ``False`` and is thus + ignored. Returns ``True`` if the lock has been acquired or ``False`` if + the timeout period has elapsed. + + + .. method:: release() + + Release a lock. This can be called from any process or thread, not only + the process or thread which originally acquired the lock. + + Behavior is the same as in :meth:`threading.Lock.release` except that + when invoked on an unlocked lock, a :exc:`ValueError` is raised. + + +.. class:: RLock() + + A recursive lock object: a close analog of :class:`threading.RLock`. A + recursive lock must be released by the process or thread that acquired it. + Once a process or thread has acquired a recursive lock, the same process + or thread may acquire it again without blocking; that process or thread + must release it once for each time it has been acquired. + + Note that :class:`RLock` is actually a factory function which returns an + instance of ``multiprocessing.synchronize.RLock`` initialized with a + default context. + + :class:`RLock` supports the :term:`context manager` protocol and thus may be + used in :keyword:`with` statements. + + + .. method:: acquire(block=True, timeout=None) + + Acquire a lock, blocking or non-blocking. + + When invoked with the *block* argument set to ``True``, block until the + lock is in an unlocked state (not owned by any process or thread) unless + the lock is already owned by the current process or thread. The current + process or thread then takes ownership of the lock (if it does not + already have ownership) and the recursion level inside the lock increments + by one, resulting in a return value of ``True``. Note that there are + several differences in this first argument's behavior compared to the + implementation of :meth:`threading.RLock.acquire`, starting with the name + of the argument itself. + + When invoked with the *block* argument set to ``False``, do not block. + If the lock has already been acquired (and thus is owned) by another + process or thread, the current process or thread does not take ownership + and the recursion level within the lock is not changed, resulting in + a return value of ``False``. If the lock is in an unlocked state, the + current process or thread takes ownership and the recursion level is + incremented, resulting in a return value of ``True``. + + Use and behaviors of the *timeout* argument are the same as in + :meth:`Lock.acquire`. Note that some of these behaviors of *timeout* + differ from the implemented behaviors in :meth:`threading.RLock.acquire`. + + + .. method:: release() + + Release a lock, decrementing the recursion level. If after the + decrement the recursion level is zero, reset the lock to unlocked (not + owned by any process or thread) and if any other processes or threads + are blocked waiting for the lock to become unlocked, allow exactly one + of them to proceed. If after the decrement the recursion level is still + nonzero, the lock remains locked and owned by the calling process or + thread. + + Only call this method when the calling process or thread owns the lock. + An :exc:`AssertionError` is raised if this method is called by a process + or thread other than the owner or if the lock is in an unlocked (unowned) + state. Note that the type of exception raised in this situation + differs from the implemented behavior in :meth:`threading.RLock.release`. + + +.. class:: Semaphore([value]) + + A semaphore object: a close analog of :class:`threading.Semaphore`. + + A solitary difference from its close analog exists: its ``acquire`` method's + first argument is named *block*, as is consistent with :meth:`Lock.acquire`. + +.. note:: + + On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with + a timeout will emulate that function's behavior using a sleeping loop. + +.. note:: + + If the SIGINT signal generated by :kbd:`Ctrl-C` arrives while the main thread is + blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`, + :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire` + or :meth:`Condition.wait` then the call will be immediately interrupted and + :exc:`KeyboardInterrupt` will be raised. + + This differs from the behaviour of :mod:`threading` where SIGINT will be + ignored while the equivalent blocking calls are in progress. + +.. note:: + + 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 + :issue:`3770` for additional information. + + +Shared :mod:`ctypes` Objects +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +It is possible to create shared objects using shared memory which can be +inherited by child processes. + +.. function:: Value(typecode_or_type, *args, lock=True) + + Return a :mod:`ctypes` object allocated from shared memory. By default the + return value is actually a synchronized wrapper for the object. The object + itself can be accessed via the *value* attribute of a :class:`Value`. + + *typecode_or_type* determines the type of the returned object: it is either a + ctypes type or a one character typecode of the kind used by the :mod:`array` + module. *\*args* is passed on to the constructor for the type. + + If *lock* is ``True`` (the default) then a new recursive lock + object is created to synchronize access to the value. If *lock* is + a :class:`Lock` or :class:`RLock` object then that will be used to + synchronize access to the value. If *lock* is ``False`` then + access to the returned object will not be automatically protected + by a lock, so it will not necessarily be "process-safe". + + Operations like ``+=`` which involve a read and write are not + atomic. So if, for instance, you want to atomically increment a + shared value it is insufficient to just do :: + + counter.value += 1 + + Assuming the associated lock is recursive (which it is by default) + you can instead do :: + + with counter.get_lock(): + counter.value += 1 + + Note that *lock* is a keyword-only argument. + +.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True) + + Return a ctypes array allocated from shared memory. By default the return + value is actually a synchronized wrapper for the array. + + *typecode_or_type* determines the type of the elements of the returned array: + it is either a ctypes type or a one character typecode of the kind used by + the :mod:`array` module. If *size_or_initializer* is an integer, then it + determines the length of the array, and the array will be initially zeroed. + Otherwise, *size_or_initializer* is a sequence which is used to initialize + the array and whose length determines the length of the array. + + If *lock* is ``True`` (the default) then a new lock object is created to + synchronize access to the value. If *lock* is a :class:`Lock` or + :class:`RLock` object then that will be used to synchronize access to the + value. If *lock* is ``False`` then access to the returned object will not be + automatically protected by a lock, so it will not necessarily be + "process-safe". + + Note that *lock* is a keyword only argument. + + Note that an array of :data:`ctypes.c_char` has *value* and *raw* + attributes which allow one to use it to store and retrieve strings. + + +The :mod:`multiprocessing.sharedctypes` module +>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + +.. module:: multiprocessing.sharedctypes + :synopsis: Allocate ctypes objects from shared memory. + +The :mod:`multiprocessing.sharedctypes` module provides functions for allocating +:mod:`ctypes` objects from shared memory which can be inherited by child +processes. + +.. note:: + + Although it is possible to store a pointer in shared memory remember that + this will refer to a location in the address space of a specific process. + However, the pointer is quite likely to be invalid in the context of a second + process and trying to dereference the pointer from the second process may + cause a crash. + +.. function:: RawArray(typecode_or_type, size_or_initializer) + + Return a ctypes array allocated from shared memory. + + *typecode_or_type* determines the type of the elements of the returned array: + it is either a ctypes type or a one character typecode of the kind used by + the :mod:`array` module. If *size_or_initializer* is an integer then it + determines the length of the array, and the array will be initially zeroed. + Otherwise *size_or_initializer* is a sequence which is used to initialize the + array and whose length determines the length of the array. + + Note that setting and getting an element is potentially non-atomic -- use + :func:`Array` instead to make sure that access is automatically synchronized + using a lock. + +.. function:: RawValue(typecode_or_type, *args) + + Return a ctypes object allocated from shared memory. + + *typecode_or_type* determines the type of the returned object: it is either a + ctypes type or a one character typecode of the kind used by the :mod:`array` + module. *\*args* is passed on to the constructor for the type. + + Note that setting and getting the value is potentially non-atomic -- use + :func:`Value` instead to make sure that access is automatically synchronized + using a lock. + + Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw`` + attributes which allow one to use it to store and retrieve strings -- see + documentation for :mod:`ctypes`. + +.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True) + + The same as :func:`RawArray` except that depending on the value of *lock* a + process-safe synchronization wrapper may be returned instead of a raw ctypes + array. + + If *lock* is ``True`` (the default) then a new lock object is created to + synchronize access to the value. If *lock* is a + :class:`~multiprocessing.Lock` or :class:`~multiprocessing.RLock` object + then that will be used to synchronize access to the + value. If *lock* is ``False`` then access to the returned object will not be + automatically protected by a lock, so it will not necessarily be + "process-safe". + + Note that *lock* is a keyword-only argument. + +.. function:: Value(typecode_or_type, *args, lock=True) + + The same as :func:`RawValue` except that depending on the value of *lock* a + process-safe synchronization wrapper may be returned instead of a raw ctypes + object. + + If *lock* is ``True`` (the default) then a new lock object is created to + synchronize access to the value. If *lock* is a :class:`~multiprocessing.Lock` or + :class:`~multiprocessing.RLock` object then that will be used to synchronize access to the + value. If *lock* is ``False`` then access to the returned object will not be + automatically protected by a lock, so it will not necessarily be + "process-safe". + + Note that *lock* is a keyword-only argument. + +.. function:: copy(obj) + + Return a ctypes object allocated from shared memory which is a copy of the + ctypes object *obj*. + +.. function:: synchronized(obj[, lock]) + + Return a process-safe wrapper object for a ctypes object which uses *lock* to + synchronize access. If *lock* is ``None`` (the default) then a + :class:`multiprocessing.RLock` object is created automatically. + + A synchronized wrapper will have two methods in addition to those of the + object it wraps: :meth:`get_obj` returns the wrapped object and + :meth:`get_lock` returns the lock object used for synchronization. + + Note that accessing the ctypes object through the wrapper can be a lot slower + than accessing the raw ctypes object. + + .. versionchanged:: 3.5 + Synchronized objects support the :term:`context manager` protocol. + + +The table below compares the syntax for creating shared ctypes objects from +shared memory with the normal ctypes syntax. (In the table ``MyStruct`` is some +subclass of :class:`ctypes.Structure`.) + +==================== ========================== =========================== +ctypes sharedctypes using type sharedctypes using typecode +==================== ========================== =========================== +c_double(2.4) RawValue(c_double, 2.4) RawValue('d', 2.4) +MyStruct(4, 6) RawValue(MyStruct, 4, 6) +(c_short * 7)() RawArray(c_short, 7) RawArray('h', 7) +(c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8)) +==================== ========================== =========================== + + +Below is an example where a number of ctypes objects are modified by a child +process:: + + from multiprocessing import Process, Lock + from multiprocessing.sharedctypes import Value, Array + from ctypes import Structure, c_double + + class Point(Structure): + _fields_ = [('x', c_double), ('y', c_double)] + + def modify(n, x, s, A): + n.value **= 2 + x.value **= 2 + s.value = s.value.upper() + for a in A: + a.x **= 2 + a.y **= 2 + + if __name__ == '__main__': + lock = Lock() + + n = Value('i', 7) + x = Value(c_double, 1.0/3.0, lock=False) + s = Array('c', b'hello world', lock=lock) + A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock) + + p = Process(target=modify, args=(n, x, s, A)) + p.start() + p.join() + + print(n.value) + print(x.value) + print(s.value) + print([(a.x, a.y) for a in A]) + + +.. highlight:: none + +The results printed are :: + + 49 + 0.1111111111111111 + HELLO WORLD + [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)] + +.. highlight:: python3 + + +.. _multiprocessing-managers: + +Managers +~~~~~~~~ + +Managers provide a way to create data which can be shared between different +processes, including sharing over a network between processes running on +different machines. A manager object controls a server process which manages +*shared objects*. Other processes can access the shared objects by using +proxies. + +.. function:: multiprocessing.Manager() + + Returns a started :class:`~multiprocessing.managers.SyncManager` object which + can be used for sharing objects between processes. The returned manager + object corresponds to a spawned child process and has methods which will + create shared objects and return corresponding proxies. + +.. module:: multiprocessing.managers + :synopsis: Share data between process with shared objects. + +Manager processes will be shutdown as soon as they are garbage collected or +their parent process exits. The manager classes are defined in the +:mod:`multiprocessing.managers` module: + +.. class:: BaseManager([address[, authkey]]) + + Create a BaseManager object. + + Once created one should call :meth:`start` or ``get_server().serve_forever()`` to ensure + that the manager object refers to a started manager process. + + *address* is the address on which the manager process listens for new + connections. If *address* is ``None`` then an arbitrary one is chosen. + + *authkey* is the authentication key which will be used to check the + validity of incoming connections to the server process. If + *authkey* is ``None`` then ``current_process().authkey`` is used. + Otherwise *authkey* is used and it must be a byte string. + + .. method:: start([initializer[, initargs]]) + + Start a subprocess to start the manager. If *initializer* is not ``None`` + then the subprocess will call ``initializer(*initargs)`` when it starts. + + .. 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 + :meth:`serve_forever` method:: + + >>> from multiprocessing.managers import BaseManager + >>> manager = BaseManager(address=('', 50000), authkey=b'abc') + >>> server = manager.get_server() + >>> server.serve_forever() + + :class:`Server` additionally has 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', 50000), authkey=b'abc') + >>> m.connect() + + .. method:: shutdown() + + Stop the process used by the manager. This is only available if + :meth:`start` has been used to start the server process. + + This can be called multiple times. + + .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]]) + + A classmethod which can be used for registering a type or callable with + the manager class. + + *typeid* is a "type identifier" which is used to identify a particular + type of shared object. This must be a string. + + *callable* is a callable used for creating objects for this type + identifier. If a manager instance will be connected to the + server using the :meth:`connect` method, or if the + *create_method* argument is ``False`` then this can be left as + ``None``. + + *proxytype* is a subclass of :class:`BaseProxy` which is used to create + proxies for shared objects with this *typeid*. If ``None`` then a proxy + class is created automatically. + + *exposed* is used to specify a sequence of method names which proxies for + this typeid should be allowed to access using + :meth:`BaseProxy._callmethod`. (If *exposed* is ``None`` then + :attr:`proxytype._exposed_` is used instead if it exists.) In the case + where no exposed list is specified, all "public methods" of the shared + object will be accessible. (Here a "public method" means any attribute + which has a :meth:`~object.__call__` method and whose name does not begin + with ``'_'``.) + + *method_to_typeid* is a mapping used to specify the return type of those + exposed methods which should return a proxy. It maps method names to + typeid strings. (If *method_to_typeid* is ``None`` then + :attr:`proxytype._method_to_typeid_` is used instead if it exists.) If a + method's name is not a key of this mapping or if the mapping is ``None`` + then the object returned by the method will be copied by value. + + *create_method* determines whether a method should be created with name + *typeid* which can be used to tell the server process to create a new + shared object and return a proxy for it. By default it is ``True``. + + :class:`BaseManager` instances also have one read-only property: + + .. attribute:: address + + The address used by the manager. + + .. versionchanged:: 3.3 + Manager objects support the context management protocol -- see + :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` starts the + server process (if it has not already started) and then returns the + manager object. :meth:`~contextmanager.__exit__` calls :meth:`shutdown`. + + In previous versions :meth:`~contextmanager.__enter__` did not start the + manager's server process if it was not already started. + +.. class:: SyncManager + + A subclass of :class:`BaseManager` which can be used for the synchronization + of processes. Objects of this type are returned by + :func:`multiprocessing.Manager`. + + Its methods create and return :ref:`multiprocessing-proxy_objects` for a + number of commonly used data types to be synchronized across processes. + This notably includes shared lists and dictionaries. + + .. method:: Barrier(parties[, action[, timeout]]) + + Create a shared :class:`threading.Barrier` object and return a + proxy for it. + + .. versionadded:: 3.3 + + .. method:: BoundedSemaphore([value]) + + Create a shared :class:`threading.BoundedSemaphore` object and return a + proxy for it. + + .. method:: Condition([lock]) + + Create a shared :class:`threading.Condition` object and return a proxy for + it. + + If *lock* is supplied then it should be a proxy for a + :class:`threading.Lock` or :class:`threading.RLock` object. + + .. versionchanged:: 3.3 + The :meth:`~threading.Condition.wait_for` method was added. + + .. method:: Event() + + Create a shared :class:`threading.Event` object and return a proxy for it. + + .. method:: Lock() + + Create a shared :class:`threading.Lock` object and return a proxy for it. + + .. method:: Namespace() + + Create a shared :class:`Namespace` object and return a proxy for it. + + .. method:: Queue([maxsize]) + + Create a shared :class:`queue.Queue` object and return a proxy for it. + + .. method:: RLock() + + Create a shared :class:`threading.RLock` object and return a proxy for it. + + .. method:: Semaphore([value]) + + Create a shared :class:`threading.Semaphore` object and return a proxy for + it. + + .. method:: Array(typecode, sequence) + + Create an array and return a proxy for it. + + .. method:: Value(typecode, value) + + Create an object with a writable ``value`` attribute and return a proxy + for it. + + .. method:: dict() + dict(mapping) + dict(sequence) + + Create a shared :class:`dict` object and return a proxy for it. + + .. method:: list() + list(sequence) + + Create a shared :class:`list` object and return a proxy for it. + + .. versionchanged:: 3.6 + Shared objects are capable of being nested. For example, a shared + container object such as a shared list can contain other shared objects + which will all be managed and synchronized by the :class:`SyncManager`. + +.. class:: Namespace + + A type that can register with :class:`SyncManager`. + + A namespace object has no public methods, but does have writable attributes. + Its representation shows the values of its attributes. + + However, when using a proxy for a namespace object, an attribute beginning + with ``'_'`` will be an attribute of the proxy and not an attribute of the + referent: + + .. doctest:: + + >>> manager = multiprocessing.Manager() + >>> Global = manager.Namespace() + >>> Global.x = 10 + >>> Global.y = 'hello' + >>> Global._z = 12.3 # this is an attribute of the proxy + >>> print(Global) + Namespace(x=10, y='hello') + + +Customized managers +>>>>>>>>>>>>>>>>>>> + +To create one's own manager, one creates a subclass of :class:`BaseManager` and +uses the :meth:`~BaseManager.register` classmethod to register new types or +callables with the manager class. For example:: + + from multiprocessing.managers import BaseManager + + class MathsClass: + def add(self, x, y): + return x + y + def mul(self, x, y): + return x * y + + class MyManager(BaseManager): + pass + + MyManager.register('Maths', MathsClass) + + if __name__ == '__main__': + with MyManager() as manager: + maths = manager.Maths() + print(maths.add(4, 3)) # prints 7 + print(maths.mul(7, 8)) # prints 56 + + +Using a remote manager +>>>>>>>>>>>>>>>>>>>>>> + +It is possible to run a manager server on one machine and have clients use it +from other machines (assuming that the firewalls involved allow it). + +Running the following commands creates a server for a single shared queue which +remote clients can access:: + + >>> from multiprocessing.managers import BaseManager + >>> from queue import Queue + >>> queue = Queue() + >>> class QueueManager(BaseManager): pass + >>> QueueManager.register('get_queue', callable=lambda:queue) + >>> m = QueueManager(address=('', 50000), authkey=b'abracadabra') + >>> s = m.get_server() + >>> s.serve_forever() + +One client can access the server as follows:: + + >>> from multiprocessing.managers import BaseManager + >>> class QueueManager(BaseManager): pass + >>> QueueManager.register('get_queue') + >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra') + >>> m.connect() + >>> queue = m.get_queue() + >>> queue.put('hello') + +Another client can also use it:: + + >>> from multiprocessing.managers import BaseManager + >>> class QueueManager(BaseManager): pass + >>> QueueManager.register('get_queue') + >>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra') + >>> m.connect() + >>> queue = m.get_queue() + >>> queue.get() + 'hello' + +Local processes can also access that queue, using the code from above on the +client to access it remotely:: + + >>> from multiprocessing import Process, Queue + >>> from multiprocessing.managers import BaseManager + >>> class Worker(Process): + ... def __init__(self, q): + ... self.q = q + ... 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=b'abracadabra') + >>> s = m.get_server() + >>> s.serve_forever() + +.. _multiprocessing-proxy_objects: + +Proxy Objects +~~~~~~~~~~~~~ + +A proxy is an object which *refers* to a shared object which lives (presumably) +in a different process. The shared object is said to be the *referent* of the +proxy. Multiple proxy objects may have the same referent. + +A proxy object has methods which invoke corresponding methods of its referent +(although not every method of the referent will necessarily be available through +the proxy). In this way, a proxy can be used just like its referent can: + +.. doctest:: + + >>> from multiprocessing import Manager + >>> manager = Manager() + >>> l = manager.list([i*i for i in range(10)]) + >>> print(l) + [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + >>> print(repr(l)) + + >>> l[4] + 16 + >>> l[2:5] + [4, 9, 16] + +Notice that applying :func:`str` to a proxy will return the representation of +the referent, whereas applying :func:`repr` will return the representation of +the proxy. + +An important feature of proxy objects is that they are picklable so they can be +passed between processes. As such, a referent can contain +:ref:`multiprocessing-proxy_objects`. This permits nesting of these managed +lists, dicts, and other :ref:`multiprocessing-proxy_objects`: + +.. doctest:: + + >>> a = manager.list() + >>> b = manager.list() + >>> a.append(b) # referent of a now contains referent of b + >>> print(a, b) + [] [] + >>> b.append('hello') + >>> print(a[0], b) + ['hello'] ['hello'] + +Similarly, dict and list proxies may be nested inside one another:: + + >>> l_outer = manager.list([ manager.dict() for i in range(2) ]) + >>> d_first_inner = l_outer[0] + >>> d_first_inner['a'] = 1 + >>> d_first_inner['b'] = 2 + >>> l_outer[1]['c'] = 3 + >>> l_outer[1]['z'] = 26 + >>> print(l_outer[0]) + {'a': 1, 'b': 2} + >>> print(l_outer[1]) + {'c': 3, 'z': 26} + +If standard (non-proxy) :class:`list` or :class:`dict` objects are contained +in a referent, modifications to those mutable values will not be propagated +through the manager because the proxy has no way of knowing when the values +contained within are modified. However, storing a value in a container proxy +(which triggers a ``__setitem__`` on the proxy object) does propagate through +the manager and so to effectively modify such an item, one could re-assign the +modified value to the container proxy:: + + # create a list proxy and append a mutable object (a dictionary) + lproxy = manager.list() + lproxy.append({}) + # now mutate the dictionary + d = lproxy[0] + d['a'] = 1 + d['b'] = 2 + # at this point, the changes to d are not yet synced, but by + # updating the dictionary, the proxy is notified of the change + lproxy[0] = d + +This approach is perhaps less convenient than employing nested +:ref:`multiprocessing-proxy_objects` for most use cases but also +demonstrates a level of control over the synchronization. + +.. note:: + + The proxy types in :mod:`multiprocessing` do nothing to support comparisons + by value. So, for instance, we have: + + .. doctest:: + + >>> manager.list([1,2,3]) == [1,2,3] + False + + One should just use a copy of the referent instead when making comparisons. + +.. class:: BaseProxy + + Proxy objects are instances of subclasses of :class:`BaseProxy`. + + .. method:: _callmethod(methodname[, args[, kwds]]) + + Call and return the result of a method of the proxy's referent. + + If ``proxy`` is a proxy whose referent is ``obj`` then the expression :: + + proxy._callmethod(methodname, args, kwds) + + will evaluate the expression :: + + getattr(obj, methodname)(*args, **kwds) + + in the manager's process. + + The returned value will be a copy of the result of the call or a proxy to + a new shared object -- see documentation for the *method_to_typeid* + argument of :meth:`BaseManager.register`. + + If an exception is raised by the call, then is re-raised by + :meth:`_callmethod`. If some other exception is raised in the manager's + process then this is converted into a :exc:`RemoteError` exception and is + raised by :meth:`_callmethod`. + + Note in particular that an exception will be raised if *methodname* has + not been *exposed*. + + An example of the usage of :meth:`_callmethod`: + + .. doctest:: + + >>> l = manager.list(range(10)) + >>> l._callmethod('__len__') + 10 + >>> l._callmethod('__getitem__', (slice(2, 7),)) # equivalent to l[2:7] + [2, 3, 4, 5, 6] + >>> l._callmethod('__getitem__', (20,)) # equivalent to l[20] + Traceback (most recent call last): + ... + IndexError: list index out of range + + .. method:: _getvalue() + + Return a copy of the referent. + + If the referent is unpicklable then this will raise an exception. + + .. method:: __repr__ + + Return a representation of the proxy object. + + .. method:: __str__ + + Return the representation of the referent. + + +Cleanup +>>>>>>> + +A proxy object uses a weakref callback so that when it gets garbage collected it +deregisters itself from the manager which owns its referent. + +A shared object gets deleted from the manager process when there are no longer +any proxies referring to it. + + +Process Pools +~~~~~~~~~~~~~ + +.. module:: multiprocessing.pool + :synopsis: Create pools of processes. + +One can create a pool of processes which will carry out tasks submitted to it +with the :class:`Pool` class. + +.. class:: Pool([processes[, initializer[, initargs[, maxtasksperchild [, context]]]]]) + + A process pool object which controls a pool of worker processes to which jobs + can be submitted. It supports asynchronous results with timeouts and + callbacks and has a parallel map implementation. + + *processes* is the number of worker processes to use. If *processes* is + ``None`` then the number returned by :func:`os.cpu_count` is used. + + If *initializer* is not ``None`` then each worker process will call + ``initializer(*initargs)`` when it starts. + + *maxtasksperchild* is the number of tasks a worker process can complete + before it will exit and be replaced with a fresh worker process, to enable + unused resources to be freed. The default *maxtasksperchild* is ``None``, which + means worker processes will live as long as the pool. + + *context* can be used to specify the context used for starting + the worker processes. Usually a pool is created using the + function :func:`multiprocessing.Pool` or the :meth:`Pool` method + of a context object. In both cases *context* is set + appropriately. + + Note that the methods of the pool object should only be called by + the process which created the pool. + + .. warning:: + :class:`multiprocessing.pool` objects have internal resources that need to be + properly managed (like any other resource) by using the pool as a context manager + or by calling :meth:`close` and :meth:`terminate` manually. Failure to do this + can lead to the process hanging on finalization. + + Note that is **not correct** to rely on the garbage colletor to destroy the pool + as CPython does not assure that the finalizer of the pool will be called + (see :meth:`object.__del__` for more information). + + .. versionadded:: 3.2 + *maxtasksperchild* + + .. versionadded:: 3.4 + *context* + + .. note:: + + Worker processes within a :class:`Pool` typically live for the complete + duration of the Pool's work queue. A frequent pattern found in other + systems (such as Apache, mod_wsgi, etc) to free resources held by + workers is to allow a worker within a pool to complete only a set + amount of work before being exiting, being cleaned up and a new + process spawned to replace the old one. The *maxtasksperchild* + argument to the :class:`Pool` exposes this ability to the end user. + + .. method:: apply(func[, args[, kwds]]) + + Call *func* with arguments *args* and keyword arguments *kwds*. It blocks + until the result is ready. Given this blocks, :meth:`apply_async` is + better suited for performing work in parallel. Additionally, *func* + is only executed in one of the workers of the pool. + + .. method:: apply_async(func[, args[, kwds[, callback[, error_callback]]]]) + + A variant of the :meth:`apply` method which returns a result object. + + If *callback* is specified then it should be a callable which accepts a + single argument. When the result becomes ready *callback* is applied to + it, that is unless the call failed, in which case the *error_callback* + is applied instead. + + If *error_callback* is specified then it should be a callable which + accepts a single argument. If the target function fails, then + the *error_callback* is called with the exception instance. + + Callbacks should complete immediately since otherwise the thread which + handles the results will get blocked. + + .. method:: map(func, iterable[, chunksize]) + + A parallel equivalent of the :func:`map` built-in function (it supports only + one *iterable* argument though, for multiple iterables see :meth:`starmap`). + It blocks until the result is ready. + + This method chops the iterable into a number of chunks which it submits to + the process pool as separate tasks. The (approximate) size of these + chunks can be specified by setting *chunksize* to a positive integer. + + Note that it may cause high memory usage for very long iterables. Consider + using :meth:`imap` or :meth:`imap_unordered` with explicit *chunksize* + option for better efficiency. + + .. method:: map_async(func, iterable[, chunksize[, callback[, error_callback]]]) + + A variant of the :meth:`.map` method which returns a result object. + + If *callback* is specified then it should be a callable which accepts a + single argument. When the result becomes ready *callback* is applied to + it, that is unless the call failed, in which case the *error_callback* + is applied instead. + + If *error_callback* is specified then it should be a callable which + accepts a single argument. If the target function fails, then + the *error_callback* is called with the exception instance. + + Callbacks should complete immediately since otherwise the thread which + handles the results will get blocked. + + .. method:: imap(func, iterable[, chunksize]) + + A lazier version of :meth:`.map`. + + The *chunksize* argument is the same as the one used by the :meth:`.map` + method. For very long iterables using a large value for *chunksize* can + make the job complete **much** faster than using the default value of + ``1``. + + Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator + returned by the :meth:`imap` method has an optional *timeout* parameter: + ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the + result cannot be returned within *timeout* seconds. + + .. method:: imap_unordered(func, iterable[, chunksize]) + + The same as :meth:`imap` except that the ordering of the results from the + returned iterator should be considered arbitrary. (Only when there is + only one worker process is the order guaranteed to be "correct".) + + .. method:: starmap(func, iterable[, chunksize]) + + Like :meth:`map` except that the elements of the *iterable* are expected + to be iterables that are unpacked as arguments. + + Hence an *iterable* of ``[(1,2), (3, 4)]`` results in ``[func(1,2), + func(3,4)]``. + + .. versionadded:: 3.3 + + .. method:: starmap_async(func, iterable[, chunksize[, callback[, error_callback]]]) + + A combination of :meth:`starmap` and :meth:`map_async` that iterates over + *iterable* of iterables and calls *func* with the iterables unpacked. + Returns a result object. + + .. versionadded:: 3.3 + + .. method:: close() + + Prevents any more tasks from being submitted to the pool. Once all the + tasks have been completed the worker processes will exit. + + .. method:: terminate() + + Stops the worker processes immediately without completing outstanding + work. When the pool object is garbage collected :meth:`terminate` will be + called immediately. + + .. method:: join() + + Wait for the worker processes to exit. One must call :meth:`close` or + :meth:`terminate` before using :meth:`join`. + + .. versionadded:: 3.3 + Pool objects now support the context management protocol -- see + :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` returns the + pool object, and :meth:`~contextmanager.__exit__` calls :meth:`terminate`. + + +.. class:: AsyncResult + + The class of the result returned by :meth:`Pool.apply_async` and + :meth:`Pool.map_async`. + + .. method:: get([timeout]) + + Return the result when it arrives. If *timeout* is not ``None`` and the + result does not arrive within *timeout* seconds then + :exc:`multiprocessing.TimeoutError` is raised. If the remote call raised + an exception then that exception will be reraised by :meth:`get`. + + .. method:: wait([timeout]) + + Wait until the result is available or until *timeout* seconds pass. + + .. method:: ready() + + Return whether the call has completed. + + .. method:: successful() + + Return whether the call completed without raising an exception. Will + raise :exc:`ValueError` if the result is not ready. + + .. versionchanged:: 3.7 + If the result is not ready, :exc:`ValueError` is raised instead of + :exc:`AssertionError`. + +The following example demonstrates the use of a pool:: + + from multiprocessing import Pool + import time + + def f(x): + return x*x + + if __name__ == '__main__': + with Pool(processes=4) as pool: # start 4 worker processes + result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process + print(result.get(timeout=1)) # prints "100" unless your computer is *very* slow + + print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]" + + it = pool.imap(f, range(10)) + print(next(it)) # prints "0" + print(next(it)) # prints "1" + print(it.next(timeout=1)) # prints "4" unless your computer is *very* slow + + result = pool.apply_async(time.sleep, (10,)) + print(result.get(timeout=1)) # raises multiprocessing.TimeoutError + + +.. _multiprocessing-listeners-clients: + +Listeners and Clients +~~~~~~~~~~~~~~~~~~~~~ + +.. module:: multiprocessing.connection + :synopsis: API for dealing with sockets. + +Usually message passing between processes is done using queues or by using +:class:`~Connection` objects returned by +:func:`~multiprocessing.Pipe`. + +However, the :mod:`multiprocessing.connection` module allows some extra +flexibility. It basically gives a high level message oriented API for dealing +with sockets or Windows named pipes. It also has support for *digest +authentication* using the :mod:`hmac` module, and for polling +multiple connections at the same time. + + +.. function:: deliver_challenge(connection, authkey) + + Send a randomly generated message to the other end of the connection and wait + for a reply. + + If the reply matches the digest of the message using *authkey* as the key + then a welcome message is sent to the other end of the connection. Otherwise + :exc:`~multiprocessing.AuthenticationError` is raised. + +.. function:: answer_challenge(connection, authkey) + + Receive a message, calculate the digest of the message using *authkey* as the + key, and then send the digest back. + + If a welcome message is not received, then + :exc:`~multiprocessing.AuthenticationError` is raised. + +.. function:: Client(address[, family[, authkey]]) + + Attempt to set up a connection to the listener which is using address + *address*, returning a :class:`~Connection`. + + The type of the connection is determined by *family* argument, but this can + generally be omitted since it can usually be inferred from the format of + *address*. (See :ref:`multiprocessing-address-formats`) + + If *authkey* is given and not None, it should be a byte string and will be + used as the secret key for an HMAC-based authentication challenge. No + authentication is done if *authkey* is None. + :exc:`~multiprocessing.AuthenticationError` is raised if authentication fails. + See :ref:`multiprocessing-auth-keys`. + +.. class:: Listener([address[, family[, backlog[, authkey]]]]) + + A wrapper for a bound socket or Windows named pipe which is 'listening' for + connections. + + *address* is the address to be used by the bound socket or named pipe of the + listener object. + + .. note:: + + If an address of '0.0.0.0' is used, the address will not be a connectable + end point on Windows. If you require a connectable end-point, + you should use '127.0.0.1'. + + *family* is the type of socket (or named pipe) to use. This can be one of + the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix + domain socket) or ``'AF_PIPE'`` (for a Windows named pipe). Of these only + the first is guaranteed to be available. If *family* is ``None`` then the + family is inferred from the format of *address*. If *address* is also + ``None`` then a default is chosen. This default is the family which is + assumed to be the fastest available. See + :ref:`multiprocessing-address-formats`. Note that if *family* is + ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a + private temporary directory created using :func:`tempfile.mkstemp`. + + If the listener object uses a socket then *backlog* (1 by default) is passed + to the :meth:`~socket.socket.listen` method of the socket once it has been + bound. + + If *authkey* is given and not None, it should be a byte string and will be + used as the secret key for an HMAC-based authentication challenge. No + authentication is done if *authkey* is None. + :exc:`~multiprocessing.AuthenticationError` is raised if authentication fails. + See :ref:`multiprocessing-auth-keys`. + + .. method:: accept() + + Accept a connection on the bound socket or named pipe of the listener + object and return a :class:`~Connection` object. + If authentication is attempted and fails, then + :exc:`~multiprocessing.AuthenticationError` is raised. + + .. method:: close() + + Close the bound socket or named pipe of the listener object. This is + called automatically when the listener is garbage collected. However it + is advisable to call it explicitly. + + Listener objects have the following read-only properties: + + .. attribute:: address + + The address which is being used by the Listener object. + + .. attribute:: last_accepted + + The address from which the last accepted connection came. If this is + unavailable then it is ``None``. + + .. versionadded:: 3.3 + Listener objects now support the context management protocol -- see + :ref:`typecontextmanager`. :meth:`~contextmanager.__enter__` returns the + listener object, and :meth:`~contextmanager.__exit__` calls :meth:`close`. + +.. function:: wait(object_list, timeout=None) + + Wait till an object in *object_list* is ready. Returns the list of + those objects in *object_list* which are ready. If *timeout* is a + float then the call blocks for at most that many seconds. If + *timeout* is ``None`` then it will block for an unlimited period. + A negative timeout is equivalent to a zero timeout. + + For both Unix and Windows, an object can appear in *object_list* if + it is + + * a readable :class:`~multiprocessing.connection.Connection` object; + * a connected and readable :class:`socket.socket` object; or + * the :attr:`~multiprocessing.Process.sentinel` attribute of a + :class:`~multiprocessing.Process` object. + + A connection or socket object is ready when there is data available + to be read from it, or the other end has been closed. + + **Unix**: ``wait(object_list, timeout)`` almost equivalent + ``select.select(object_list, [], [], timeout)``. The difference is + that, if :func:`select.select` is interrupted by a signal, it can + raise :exc:`OSError` with an error number of ``EINTR``, whereas + :func:`wait` will not. + + **Windows**: An item in *object_list* must either be an integer + handle which is waitable (according to the definition used by the + documentation of the Win32 function ``WaitForMultipleObjects()``) + or it can be an object with a :meth:`fileno` method which returns a + socket handle or pipe handle. (Note that pipe handles and socket + handles are **not** waitable handles.) + + .. versionadded:: 3.3 + + +**Examples** + +The following server code creates a listener which uses ``'secret password'`` as +an authentication key. It then waits for a connection and sends some data to +the client:: + + from multiprocessing.connection import Listener + from array import array + + address = ('localhost', 6000) # family is deduced to be 'AF_INET' + + with Listener(address, authkey=b'secret password') as listener: + with listener.accept() as conn: + print('connection accepted from', listener.last_accepted) + + conn.send([2.25, None, 'junk', float]) + + conn.send_bytes(b'hello') + + conn.send_bytes(array('i', [42, 1729])) + +The following code connects to the server and receives some data from the +server:: + + from multiprocessing.connection import Client + from array import array + + address = ('localhost', 6000) + + with Client(address, authkey=b'secret password') as conn: + print(conn.recv()) # => [2.25, None, 'junk', float] + + print(conn.recv_bytes()) # => 'hello' + + arr = array('i', [0, 0, 0, 0, 0]) + print(conn.recv_bytes_into(arr)) # => 8 + print(arr) # => array('i', [42, 1729, 0, 0, 0]) + +The following code uses :func:`~multiprocessing.connection.wait` to +wait for messages from multiple processes at once:: + + import time, random + from multiprocessing import Process, Pipe, current_process + from multiprocessing.connection import wait + + def foo(w): + for i in range(10): + w.send((i, current_process().name)) + w.close() + + if __name__ == '__main__': + readers = [] + + for i in range(4): + r, w = Pipe(duplex=False) + readers.append(r) + p = Process(target=foo, args=(w,)) + p.start() + # We close the writable end of the pipe now to be sure that + # p is the only process which owns a handle for it. This + # ensures that when p closes its handle for the writable end, + # wait() will promptly report the readable end as being ready. + w.close() + + while readers: + for r in wait(readers): + try: + msg = r.recv() + except EOFError: + readers.remove(r) + else: + print(msg) + + +.. _multiprocessing-address-formats: + +Address Formats +>>>>>>>>>>>>>>> + +* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where + *hostname* is a string and *port* is an integer. + +* An ``'AF_UNIX'`` address is a string representing a filename on the + filesystem. + +* An ``'AF_PIPE'`` address is a string of the form + :samp:`r'\\\\.\\pipe\\{PipeName}'`. To use :func:`Client` to connect to a named + pipe on a remote computer called *ServerName* one should use an address of the + form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead. + +Note that any string beginning with two backslashes is assumed by default to be +an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address. + + +.. _multiprocessing-auth-keys: + +Authentication keys +~~~~~~~~~~~~~~~~~~~ + +When one uses :meth:`Connection.recv `, the +data received is automatically +unpickled. Unfortunately unpickling data from an untrusted source is a security +risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module +to provide digest authentication. + +An authentication key is a byte string which can be thought of as a +password: once a connection is established both ends will demand proof +that the other knows the authentication key. (Demonstrating that both +ends are using the same key does **not** involve sending the key over +the connection.) + +If authentication is requested but no authentication key is specified then the +return value of ``current_process().authkey`` is used (see +:class:`~multiprocessing.Process`). This value will be automatically inherited by +any :class:`~multiprocessing.Process` object that the current process creates. +This means that (by default) all processes of a multi-process program will share +a single authentication key which can be used when setting up connections +between themselves. + +Suitable authentication keys can also be generated by using :func:`os.urandom`. + + +Logging +~~~~~~~ + +Some support for logging is available. Note, however, that the :mod:`logging` +package does not use process shared locks so it is possible (depending on the +handler type) for messages from different processes to get mixed up. + +.. currentmodule:: multiprocessing +.. function:: get_logger() + + Returns the logger used by :mod:`multiprocessing`. If necessary, a new one + will be created. + + When first created the logger has level :data:`logging.NOTSET` and no + default handler. Messages sent to this logger will not by default propagate + to the root logger. + + Note that on Windows child processes will only inherit the level of the + parent process's logger -- any other customization of the logger will not be + inherited. + +.. currentmodule:: multiprocessing +.. function:: log_to_stderr() + + This function performs a call to :func:`get_logger` but in addition to + returning the logger created by get_logger, it adds a handler which sends + output to :data:`sys.stderr` using format + ``'[%(levelname)s/%(processName)s] %(message)s'``. + +Below is an example session with logging turned on:: + + >>> import multiprocessing, logging + >>> logger = multiprocessing.log_to_stderr() + >>> logger.setLevel(logging.INFO) + >>> logger.warning('doomed') + [WARNING/MainProcess] doomed + >>> m = multiprocessing.Manager() + [INFO/SyncManager-...] child process calling self.run() + [INFO/SyncManager-...] created temp directory /.../pymp-... + [INFO/SyncManager-...] manager serving at '/.../listener-...' + >>> del m + [INFO/MainProcess] sending shutdown message to manager + [INFO/SyncManager-...] manager exiting with exitcode 0 + +For a full table of logging levels, see the :mod:`logging` module. + + +The :mod:`multiprocessing.dummy` module +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. module:: multiprocessing.dummy + :synopsis: Dumb wrapper around threading. + +:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is +no more than a wrapper around the :mod:`threading` module. + + +.. _multiprocessing-programming: + +Programming guidelines +---------------------- + +There are certain guidelines and idioms which should be adhered to when using +:mod:`multiprocessing`. + + +All start methods +~~~~~~~~~~~~~~~~~ + +The following applies to all start methods. + +Avoid shared state + + As far as possible one should try to avoid shifting large amounts of data + between processes. + + It is probably best to stick to using queues or pipes for communication + between processes rather than using the lower level synchronization + primitives. + +Picklability + + Ensure that the arguments to the methods of proxies are picklable. + +Thread safety of proxies + + Do not use a proxy object from more than one thread unless you protect it + with a lock. + + (There is never a problem with different processes using the *same* proxy.) + +Joining zombie processes + + On Unix when a process finishes but has not been joined it becomes a zombie. + There should never be very many because each time a new process starts (or + :func:`~multiprocessing.active_children` is called) all completed processes + which have not yet been joined will be joined. Also calling a finished + process's :meth:`Process.is_alive ` will + join the process. Even so it is probably good + practice to explicitly join all the processes that you start. + +Better to inherit than pickle/unpickle + + When using the *spawn* or *forkserver* start methods many types + from :mod:`multiprocessing` need to be picklable so that child + processes can use them. However, one should generally avoid + sending shared objects to other processes using pipes or queues. + Instead you should arrange the program so that a process which + needs access to a shared resource created elsewhere can inherit it + from an ancestor process. + +Avoid terminating processes + + Using the :meth:`Process.terminate ` + method to stop a process is liable to + cause any shared resources (such as locks, semaphores, pipes and queues) + currently being used by the process to become broken or unavailable to other + processes. + + Therefore it is probably best to only consider using + :meth:`Process.terminate ` on processes + which never use any shared resources. + +Joining processes that use queues + + Bear in mind that a process that has put items in a queue will wait before + terminating until all the buffered items are fed by the "feeder" thread to + the underlying pipe. (The child process can call the + :meth:`Queue.cancel_join_thread ` + method of the queue to avoid this behaviour.) + + This means that whenever you use a queue you need to make sure that all + items which have been put on the queue will eventually be removed before the + process is joined. Otherwise you cannot be sure that processes which have + put items on the queue will terminate. Remember also that non-daemonic + processes will be joined automatically. + + An example which will deadlock is the following:: + + from multiprocessing import Process, Queue + + def f(q): + q.put('X' * 1000000) + + if __name__ == '__main__': + queue = Queue() + p = Process(target=f, args=(queue,)) + p.start() + p.join() # this deadlocks + obj = queue.get() + + A fix here would be to swap the last two lines (or simply remove the + ``p.join()`` line). + +Explicitly pass resources to child processes + + On Unix using the *fork* start method, a child process can make + use of a shared resource created in a parent process using a + global resource. However, it is better to pass the object as an + argument to the constructor for the child process. + + Apart from making the code (potentially) compatible with Windows + and the other start methods this also ensures that as long as the + child process is still alive the object will not be garbage + collected in the parent process. This might be important if some + resource is freed when the object is garbage collected in the + parent process. + + So for instance :: + + from multiprocessing import Process, Lock + + def f(): + ... do something using "lock" ... + + if __name__ == '__main__': + lock = Lock() + for i in range(10): + Process(target=f).start() + + should be rewritten as :: + + from multiprocessing import Process, Lock + + def f(l): + ... do something using "l" ... + + if __name__ == '__main__': + lock = Lock() + for i in range(10): + Process(target=f, args=(lock,)).start() + +Beware of replacing :data:`sys.stdin` with a "file like object" + + :mod:`multiprocessing` originally unconditionally called:: + + os.close(sys.stdin.fileno()) + + in the :meth:`multiprocessing.Process._bootstrap` method --- this resulted + in issues with processes-in-processes. This has been changed to:: + + sys.stdin.close() + sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False) + + Which solves the fundamental issue of processes colliding with each other + resulting in a bad file descriptor error, but introduces a potential danger + to applications which replace :func:`sys.stdin` with a "file-like object" + with output buffering. This danger is that if multiple processes call + :meth:`~io.IOBase.close()` on this file-like object, it could result in the same + data being flushed to the object multiple times, resulting in corruption. + + If you write a file-like object and implement your own caching, you can + make it fork-safe by storing the pid whenever you append to the cache, + and discarding the cache when the pid changes. For example:: + + @property + def cache(self): + pid = os.getpid() + if pid != self._pid: + self._pid = pid + self._cache = [] + return self._cache + + For more information, see :issue:`5155`, :issue:`5313` and :issue:`5331` + +The *spawn* and *forkserver* start methods +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There are a few extra restriction which don't apply to the *fork* +start method. + +More picklability + + Ensure that all arguments to :meth:`Process.__init__` are picklable. + Also, if you subclass :class:`~multiprocessing.Process` then make sure that + instances will be picklable when the :meth:`Process.start + ` method is called. + +Global variables + + Bear in mind that if code run in a child process tries to access a global + variable, then the value it sees (if any) may not be the same as the value + in the parent process at the time that :meth:`Process.start + ` was called. + + However, global variables which are just module level constants cause no + problems. + +Safe importing of main module + + Make sure that the main module can be safely imported by a new Python + interpreter without causing unintended side effects (such a starting a new + process). + + For example, using the *spawn* or *forkserver* start method + running the following module would fail with a + :exc:`RuntimeError`:: + + from multiprocessing import Process + + def foo(): + print('hello') + + p = Process(target=foo) + p.start() + + Instead one should protect the "entry point" of the program by using ``if + __name__ == '__main__':`` as follows:: + + from multiprocessing import Process, freeze_support, set_start_method + + def foo(): + print('hello') + + if __name__ == '__main__': + freeze_support() + set_start_method('spawn') + p = Process(target=foo) + p.start() + + (The ``freeze_support()`` line can be omitted if the program will be run + normally instead of frozen.) + + This allows the newly spawned Python interpreter to safely import the module + and then run the module's ``foo()`` function. + + Similar restrictions apply if a pool or manager is created in the main + module. + + +.. _multiprocessing-examples: + +Examples +-------- + +Demonstration of how to create and use customized managers and proxies: + +.. literalinclude:: ../includes/mp_newtype.py + :language: python3 + + +Using :class:`~multiprocessing.pool.Pool`: + +.. literalinclude:: ../includes/mp_pool.py + :language: python3 + + +An example showing how to use queues to feed tasks to a collection of worker +processes and collect the results: + +.. literalinclude:: ../includes/mp_workers.py diff --git a/cpython_2/environment/repo/Doc/library/multiprocessing.shared_memory.rst b/cpython_2/environment/repo/Doc/library/multiprocessing.shared_memory.rst new file mode 100644 index 0000000000000000000000000000000000000000..cba576a29e2e2bb1ef58d870006ec4c63f6c510e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/multiprocessing.shared_memory.rst @@ -0,0 +1,344 @@ +:mod:`multiprocessing.shared_memory` --- Provides shared memory for direct access across processes +=================================================================================================== + +.. module:: multiprocessing.shared_memory + :synopsis: Provides shared memory for direct access across processes. + +**Source code:** :source:`Lib/multiprocessing/shared_memory.py` + +.. versionadded:: 3.8 + +.. index:: + single: Shared Memory + single: POSIX Shared Memory + single: Named Shared Memory + +-------------- + +This module provides a class, :class:`SharedMemory`, for the allocation +and management of shared memory to be accessed by one or more processes +on a multicore or symmetric multiprocessor (SMP) machine. To assist with +the life-cycle management of shared memory especially across distinct +processes, a :class:`~multiprocessing.managers.BaseManager` subclass, +:class:`SharedMemoryManager`, is also provided in the +``multiprocessing.managers`` module. + +In this module, shared memory refers to "System V style" shared memory blocks +(though is not necessarily implemented explicitly as such) and does not refer +to "distributed shared memory". This style of shared memory permits distinct +processes to potentially read and write to a common (or shared) region of +volatile memory. Processes are conventionally limited to only have access to +their own process memory space but shared memory permits the sharing +of data between processes, avoiding the need to instead send messages between +processes containing that data. Sharing data directly via memory can provide +significant performance benefits compared to sharing data via disk or socket +or other communications requiring the serialization/deserialization and +copying of data. + + +.. class:: SharedMemory(name=None, create=False, size=0) + + Creates a new shared memory block or attaches to an existing shared + memory block. Each shared memory block is assigned a unique name. + In this way, one process can create a shared memory block with a + particular name and a different process can attach to that same shared + memory block using that same name. + + As a resource for sharing data across processes, shared memory blocks + may outlive the original process that created them. When one process + no longer needs access to a shared memory block that might still be + needed by other processes, the :meth:`close()` method should be called. + When a shared memory block is no longer needed by any process, the + :meth:`unlink()` method should be called to ensure proper cleanup. + + *name* is the unique name for the requested shared memory, specified as + a string. When creating a new shared memory block, if ``None`` (the + default) is supplied for the name, a novel name will be generated. + + *create* controls whether a new shared memory block is created (``True``) + or an existing shared memory block is attached (``False``). + + *size* specifies the requested number of bytes when creating a new shared + memory block. Because some platforms choose to allocate chunks of memory + based upon that platform's memory page size, the exact size of the shared + memory block may be larger or equal to the size requested. When attaching + to an existing shared memory block, the ``size`` parameter is ignored. + + .. method:: close() + + Closes access to the shared memory from this instance. In order to + ensure proper cleanup of resources, all instances should call + ``close()`` once the instance is no longer needed. Note that calling + ``close()`` does not cause the shared memory block itself to be + destroyed. + + .. method:: unlink() + + Requests that the underlying shared memory block be destroyed. In + order to ensure proper cleanup of resources, ``unlink()`` should be + called once (and only once) across all processes which have need + for the shared memory block. After requesting its destruction, a + shared memory block may or may not be immediately destroyed and + this behavior may differ across platforms. Attempts to access data + inside the shared memory block after ``unlink()`` has been called may + result in memory access errors. Note: the last process relinquishing + its hold on a shared memory block may call ``unlink()`` and + :meth:`close()` in either order. + + .. attribute:: buf + + A memoryview of contents of the shared memory block. + + .. attribute:: name + + Read-only access to the unique name of the shared memory block. + + .. attribute:: size + + Read-only access to size in bytes of the shared memory block. + + +The following example demonstrates low-level use of :class:`SharedMemory` +instances:: + + >>> from multiprocessing import shared_memory + >>> shm_a = shared_memory.SharedMemory(create=True, size=10) + >>> type(shm_a.buf) + + >>> buffer = shm_a.buf + >>> len(buffer) + 10 + >>> buffer[:4] = bytearray([22, 33, 44, 55]) # Modify multiple at once + >>> buffer[4] = 100 # Modify single byte at a time + >>> # Attach to an existing shared memory block + >>> shm_b = shared_memory.SharedMemory(shm_a.name) + >>> import array + >>> array.array('b', shm_b.buf[:5]) # Copy the data into a new array.array + array('b', [22, 33, 44, 55, 100]) + >>> shm_b.buf[:5] = b'howdy' # Modify via shm_b using bytes + >>> bytes(shm_a.buf[:5]) # Access via shm_a + b'howdy' + >>> shm_b.close() # Close each SharedMemory instance + >>> shm_a.close() + >>> shm_a.unlink() # Call unlink only once to release the shared memory + + + +The following example demonstrates a practical use of the :class:`SharedMemory` +class with `NumPy arrays `_, accessing the +same ``numpy.ndarray`` from two distinct Python shells: + +.. doctest:: + :options: +SKIP + + >>> # In the first Python interactive shell + >>> import numpy as np + >>> a = np.array([1, 1, 2, 3, 5, 8]) # Start with an existing NumPy array + >>> from multiprocessing import shared_memory + >>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes) + >>> # Now create a NumPy array backed by shared memory + >>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf) + >>> b[:] = a[:] # Copy the original data into shared memory + >>> b + array([1, 1, 2, 3, 5, 8]) + >>> type(b) + + >>> type(a) + + >>> shm.name # We did not specify a name so one was chosen for us + 'psm_21467_46075' + + >>> # In either the same shell or a new Python shell on the same machine + >>> import numpy as np + >>> from multiprocessing import shared_memory + >>> # Attach to the existing shared memory block + >>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075') + >>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example + >>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf) + >>> c + array([1, 1, 2, 3, 5, 8]) + >>> c[-1] = 888 + >>> c + array([ 1, 1, 2, 3, 5, 888]) + + >>> # Back in the first Python interactive shell, b reflects this change + >>> b + array([ 1, 1, 2, 3, 5, 888]) + + >>> # Clean up from within the second Python shell + >>> del c # Unnecessary; merely emphasizing the array is no longer used + >>> existing_shm.close() + + >>> # Clean up from within the first Python shell + >>> del b # Unnecessary; merely emphasizing the array is no longer used + >>> shm.close() + >>> shm.unlink() # Free and release the shared memory block at the very end + + +.. class:: SharedMemoryManager([address[, authkey]]) + :module: multiprocessing.managers + + A subclass of :class:`~multiprocessing.managers.BaseManager` which can be + used for the management of shared memory blocks across processes. + + A call to :meth:`~multiprocessing.managers.BaseManager.start` on a + :class:`SharedMemoryManager` instance causes a new process to be started. + This new process's sole purpose is to manage the life cycle + of all shared memory blocks created through it. To trigger the release + of all shared memory blocks managed by that process, call + :meth:`~multiprocessing.managers.BaseManager.shutdown()` on the instance. + This triggers a :meth:`SharedMemory.unlink()` call on all of the + :class:`SharedMemory` objects managed by that process and then + stops the process itself. By creating ``SharedMemory`` instances + through a ``SharedMemoryManager``, we avoid the need to manually track + and trigger the freeing of shared memory resources. + + This class provides methods for creating and returning :class:`SharedMemory` + instances and for creating a list-like object (:class:`ShareableList`) + backed by shared memory. + + Refer to :class:`multiprocessing.managers.BaseManager` for a description + of the inherited *address* and *authkey* optional input arguments and how + they may be used to connect to an existing ``SharedMemoryManager`` service + from other processes. + + .. method:: SharedMemory(size) + + Create and return a new :class:`SharedMemory` object with the + specified ``size`` in bytes. + + .. method:: ShareableList(sequence) + + Create and return a new :class:`ShareableList` object, initialized + by the values from the input ``sequence``. + + +The following example demonstrates the basic mechanisms of a +:class:`SharedMemoryManager`: + +.. doctest:: + :options: +SKIP + + >>> from multiprocessing.managers import SharedMemoryManager + >>> smm = SharedMemoryManager() + >>> smm.start() # Start the process that manages the shared memory blocks + >>> sl = smm.ShareableList(range(4)) + >>> sl + ShareableList([0, 1, 2, 3], name='psm_6572_7512') + >>> raw_shm = smm.SharedMemory(size=128) + >>> another_sl = smm.ShareableList('alpha') + >>> another_sl + ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221') + >>> smm.shutdown() # Calls unlink() on sl, raw_shm, and another_sl + +The following example depicts a potentially more convenient pattern for using +:class:`SharedMemoryManager` objects via the :keyword:`with` statement to +ensure that all shared memory blocks are released after they are no longer +needed: + +.. doctest:: + :options: +SKIP + + >>> with SharedMemoryManager() as smm: + ... sl = smm.ShareableList(range(2000)) + ... # Divide the work among two processes, storing partial results in sl + ... p1 = Process(target=do_work, args=(sl, 0, 1000)) + ... p2 = Process(target=do_work, args=(sl, 1000, 2000)) + ... p1.start() + ... p2.start() # A multiprocessing.Pool might be more efficient + ... p1.join() + ... p2.join() # Wait for all work to complete in both processes + ... total_result = sum(sl) # Consolidate the partial results now in sl + +When using a :class:`SharedMemoryManager` in a :keyword:`with` statement, the +shared memory blocks created using that manager are all released when the +:keyword:`with` statement's code block finishes execution. + + +.. class:: ShareableList(sequence=None, *, name=None) + + Provides a mutable list-like object where all values stored within are + stored in a shared memory block. This constrains storable values to + only the ``int``, ``float``, ``bool``, ``str`` (less than 10M bytes each), + ``bytes`` (less than 10M bytes each), and ``None`` built-in data types. + It also notably differs from the built-in ``list`` type in that these + lists can not change their overall length (i.e. no append, insert, etc.) + and do not support the dynamic creation of new :class:`ShareableList` + instances via slicing. + + *sequence* is used in populating a new ``ShareableList`` full of values. + Set to ``None`` to instead attach to an already existing + ``ShareableList`` by its unique shared memory name. + + *name* is the unique name for the requested shared memory, as described + in the definition for :class:`SharedMemory`. When attaching to an + existing ``ShareableList``, specify its shared memory block's unique + name while leaving ``sequence`` set to ``None``. + + .. method:: count(value) + + Returns the number of occurrences of ``value``. + + .. method:: index(value) + + Returns first index position of ``value``. Raises :exc:`ValueError` if + ``value`` is not present. + + .. attribute:: format + + Read-only attribute containing the :mod:`struct` packing format used by + all currently stored values. + + .. attribute:: shm + + The :class:`SharedMemory` instance where the values are stored. + + +The following example demonstrates basic use of a :class:`ShareableList` +instance: + + >>> from multiprocessing import shared_memory + >>> a = shared_memory.ShareableList(['howdy', b'HoWdY', -273.154, 100, None, True, 42]) + >>> [ type(entry) for entry in a ] + [, , , , , , ] + >>> a[2] + -273.154 + >>> a[2] = -78.5 + >>> a[2] + -78.5 + >>> a[2] = 'dry ice' # Changing data types is supported as well + >>> a[2] + 'dry ice' + >>> a[2] = 'larger than previously allocated storage space' + Traceback (most recent call last): + ... + ValueError: exceeds available storage for existing str + >>> a[2] + 'dry ice' + >>> len(a) + 7 + >>> a.index(42) + 6 + >>> a.count(b'howdy') + 0 + >>> a.count(b'HoWdY') + 1 + >>> a.shm.close() + >>> a.shm.unlink() + >>> del a # Use of a ShareableList after call to unlink() is unsupported + +The following example depicts how one, two, or many processes may access the +same :class:`ShareableList` by supplying the name of the shared memory block +behind it: + + >>> b = shared_memory.ShareableList(range(5)) # In a first process + >>> c = shared_memory.ShareableList(name=b.shm.name) # In a second process + >>> c + ShareableList([0, 1, 2, 3, 4], name='...') + >>> c[-1] = -999 + >>> b[-1] + -999 + >>> b.shm.close() + >>> c.shm.close() + >>> c.shm.unlink() + diff --git a/cpython_2/environment/repo/Doc/library/netdata.rst b/cpython_2/environment/repo/Doc/library/netdata.rst new file mode 100644 index 0000000000000000000000000000000000000000..491501665e3d716e81dba69c794b70ab72974408 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/netdata.rst @@ -0,0 +1,23 @@ + +.. _netdata: + +********************** +Internet Data Handling +********************** + +This chapter describes modules which support handling data formats commonly used +on the Internet. + + +.. toctree:: + + email.rst + json.rst + mailcap.rst + mailbox.rst + mimetypes.rst + base64.rst + binhex.rst + binascii.rst + quopri.rst + uu.rst diff --git a/cpython_2/environment/repo/Doc/library/netrc.rst b/cpython_2/environment/repo/Doc/library/netrc.rst new file mode 100644 index 0000000000000000000000000000000000000000..3d29ac49b9191a1853d32122c4af284d434b17a1 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/netrc.rst @@ -0,0 +1,90 @@ + +:mod:`netrc` --- netrc file processing +====================================== + +.. module:: netrc + :synopsis: Loading of .netrc files. + +.. moduleauthor:: Eric S. Raymond +.. sectionauthor:: Eric S. Raymond + +**Source code:** :source:`Lib/netrc.py` + +-------------- + +The :class:`~netrc.netrc` class parses and encapsulates the netrc file format used by +the Unix :program:`ftp` program and other FTP clients. + + +.. class:: netrc([file]) + + A :class:`~netrc.netrc` instance or subclass instance encapsulates data from a netrc + file. The initialization argument, if present, specifies the file to parse. If + no argument is given, the file :file:`.netrc` in the user's home directory -- + as determined by :func:`os.path.expanduser` -- will be read. Otherwise, + a :exc:`FileNotFoundError` exception will be raised. + Parse errors will raise :exc:`NetrcParseError` with diagnostic + information including the file name, line number, and terminating token. + If no argument is specified on a POSIX system, the presence of passwords in + the :file:`.netrc` file will raise a :exc:`NetrcParseError` if the file + ownership or permissions are insecure (owned by a user other than the user + running the process, or accessible for read or write by any other user). + This implements security behavior equivalent to that of ftp and other + programs that use :file:`.netrc`. + + .. versionchanged:: 3.4 Added the POSIX permission check. + + .. versionchanged:: 3.7 + :func:`os.path.expanduser` is used to find the location of the + :file:`.netrc` file when *file* is not passed as argument. + + +.. exception:: NetrcParseError + + Exception raised by the :class:`~netrc.netrc` class when syntactical errors are + encountered in source text. Instances of this exception provide three + interesting attributes: :attr:`msg` is a textual explanation of the error, + :attr:`filename` is the name of the source file, and :attr:`lineno` gives the + line number on which the error was found. + + +.. _netrc-objects: + +netrc Objects +------------- + +A :class:`~netrc.netrc` instance has the following methods: + + +.. method:: netrc.authenticators(host) + + Return a 3-tuple ``(login, account, password)`` of authenticators for *host*. + If the netrc file did not contain an entry for the given host, return the tuple + associated with the 'default' entry. If neither matching host nor default entry + is available, return ``None``. + + +.. method:: netrc.__repr__() + + Dump the class data as a string in the format of a netrc file. (This discards + comments and may reorder the entries.) + +Instances of :class:`~netrc.netrc` have public instance variables: + + +.. attribute:: netrc.hosts + + Dictionary mapping host names to ``(login, account, password)`` tuples. The + 'default' entry, if any, is represented as a pseudo-host by that name. + + +.. attribute:: netrc.macros + + Dictionary mapping macro names to string lists. + +.. note:: + + Passwords are limited to a subset of the ASCII character set. All ASCII + punctuation is allowed in passwords, however, note that whitespace and + non-printable characters are not allowed in passwords. This is a limitation + of the way the .netrc file is parsed and may be removed in the future. diff --git a/cpython_2/environment/repo/Doc/library/nis.rst b/cpython_2/environment/repo/Doc/library/nis.rst new file mode 100644 index 0000000000000000000000000000000000000000..10c67cbb81b2f057470ff6f039f37da10336f3a2 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/nis.rst @@ -0,0 +1,65 @@ + +:mod:`nis` --- Interface to Sun's NIS (Yellow Pages) +==================================================== + +.. module:: nis + :platform: Unix + :synopsis: Interface to Sun's NIS (Yellow Pages) library. + +.. moduleauthor:: Fred Gansevles +.. sectionauthor:: Moshe Zadka + +-------------- + +The :mod:`nis` module gives a thin wrapper around the NIS library, useful for +central administration of several hosts. + +Because NIS exists only on Unix systems, this module is only available for Unix. + +The :mod:`nis` module defines the following functions: + + +.. function:: match(key, mapname, domain=default_domain) + + Return the match for *key* in map *mapname*, or raise an error + (:exc:`nis.error`) if there is none. Both should be strings, *key* is 8-bit + clean. Return value is an arbitrary array of bytes (may contain ``NULL`` and + other joys). + + Note that *mapname* is first checked if it is an alias to another name. + + The *domain* argument allows overriding the NIS domain used for the lookup. If + unspecified, lookup is in the default NIS domain. + + +.. function:: cat(mapname, domain=default_domain) + + Return a dictionary mapping *key* to *value* such that ``match(key, + mapname)==value``. Note that both keys and values of the dictionary are + arbitrary arrays of bytes. + + Note that *mapname* is first checked if it is an alias to another name. + + The *domain* argument allows overriding the NIS domain used for the lookup. If + unspecified, lookup is in the default NIS domain. + + +.. function:: maps(domain=default_domain) + + Return a list of all valid maps. + + The *domain* argument allows overriding the NIS domain used for the lookup. If + unspecified, lookup is in the default NIS domain. + + +.. function:: get_default_domain() + + Return the system default NIS domain. + + +The :mod:`nis` module defines the following exception: + +.. exception:: error + + An error raised when a NIS function returns an error code. + diff --git a/cpython_2/environment/repo/Doc/library/nntplib.rst b/cpython_2/environment/repo/Doc/library/nntplib.rst new file mode 100644 index 0000000000000000000000000000000000000000..e7ec9047e015e6cd66f07ad09160cdb72bad8b4e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/nntplib.rst @@ -0,0 +1,563 @@ +:mod:`nntplib` --- NNTP protocol client +======================================= + +.. module:: nntplib + :synopsis: NNTP protocol client (requires sockets). + +**Source code:** :source:`Lib/nntplib.py` + +.. index:: + pair: NNTP; protocol + single: Network News Transfer Protocol + +-------------- + +This module defines the class :class:`NNTP` which implements the client side of +the Network News Transfer Protocol. It can be used to implement a news reader +or poster, or automated news processors. It is compatible with :rfc:`3977` +as well as the older :rfc:`977` and :rfc:`2980`. + +Here are two small examples of how it can be used. To list some statistics +about a newsgroup and print the subjects of the last 10 articles:: + + >>> s = nntplib.NNTP('news.gmane.io') + >>> resp, count, first, last, name = s.group('gmane.comp.python.committers') + >>> print('Group', name, 'has', count, 'articles, range', first, 'to', last) + Group gmane.comp.python.committers has 1096 articles, range 1 to 1096 + >>> resp, overviews = s.over((last - 9, last)) + >>> for id, over in overviews: + ... print(id, nntplib.decode_header(over['subject'])) + ... + 1087 Re: Commit privileges for Łukasz Langa + 1088 Re: 3.2 alpha 2 freeze + 1089 Re: 3.2 alpha 2 freeze + 1090 Re: Commit privileges for Łukasz Langa + 1091 Re: Commit privileges for Łukasz Langa + 1092 Updated ssh key + 1093 Re: Updated ssh key + 1094 Re: Updated ssh key + 1095 Hello fellow committers! + 1096 Re: Hello fellow committers! + >>> s.quit() + '205 Bye!' + +To post an article from a binary file (this assumes that the article has valid +headers, and that you have right to post on the particular newsgroup):: + + >>> s = nntplib.NNTP('news.gmane.io') + >>> f = open('article.txt', 'rb') + >>> s.post(f) + '240 Article posted successfully.' + >>> s.quit() + '205 Bye!' + +The module itself defines the following classes: + + +.. class:: NNTP(host, port=119, user=None, password=None, readermode=None, usenetrc=False, [timeout]) + + Return a new :class:`NNTP` object, representing a connection + to the NNTP server running on host *host*, listening at port *port*. + An optional *timeout* can be specified for the socket connection. + If the optional *user* and *password* are provided, or if suitable + credentials are present in :file:`/.netrc` and the optional flag *usenetrc* + is true, the ``AUTHINFO USER`` and ``AUTHINFO PASS`` commands are used + to identify and authenticate the user to the server. If the optional + flag *readermode* is true, then a ``mode reader`` command is sent before + authentication is performed. Reader mode is sometimes necessary if you are + connecting to an NNTP server on the local machine and intend to call + reader-specific commands, such as ``group``. If you get unexpected + :exc:`NNTPPermanentError`\ s, you might need to set *readermode*. + The :class:`NNTP` class supports the :keyword:`with` statement to + unconditionally consume :exc:`OSError` exceptions and to close the NNTP + connection when done, e.g.: + + >>> from nntplib import NNTP + >>> with NNTP('news.gmane.io') as n: + ... n.group('gmane.comp.python.committers') + ... # doctest: +SKIP + ('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers') + >>> + + .. audit-event:: nntplib.connect self,host,port nntplib.NNTP + + .. audit-event:: nntplib.putline self,line nntplib.NNTP + + All commands will raise an :ref:`auditing event ` + ``nntplib.putline`` with arguments ``self`` and ``line``, + where ``line`` is the bytes about to be sent to the remote host. + + .. versionchanged:: 3.2 + *usenetrc* is now ``False`` by default. + + .. versionchanged:: 3.3 + Support for the :keyword:`with` statement was added. + + .. versionchanged:: 3.9 + If the *timeout* parameter is set to be zero, it will raise a + :class:`ValueError` to prevent the creation of a non-blocking socket. + +.. class:: NNTP_SSL(host, port=563, user=None, password=None, ssl_context=None, readermode=None, usenetrc=False, [timeout]) + + Return a new :class:`NNTP_SSL` object, representing an encrypted + connection to the NNTP server running on host *host*, listening at + port *port*. :class:`NNTP_SSL` objects have the same methods as + :class:`NNTP` objects. If *port* is omitted, port 563 (NNTPS) is used. + *ssl_context* is also optional, and is a :class:`~ssl.SSLContext` object. + Please read :ref:`ssl-security` for best practices. + All other parameters behave the same as for :class:`NNTP`. + + Note that SSL-on-563 is discouraged per :rfc:`4642`, in favor of + STARTTLS as described below. However, some servers only support the + former. + + .. audit-event:: nntplib.connect self,host,port nntplib.NNTP_SSL + + .. audit-event:: nntplib.putline self,line nntplib.NNTP_SSL + + All commands will raise an :ref:`auditing event ` + ``nntplib.putline`` with arguments ``self`` and ``line``, + where ``line`` is the bytes about to be sent to the remote host. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.4 + The class now supports hostname check with + :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see + :data:`ssl.HAS_SNI`). + + .. versionchanged:: 3.9 + If the *timeout* parameter is set to be zero, it will raise a + :class:`ValueError` to prevent the creation of a non-blocking socket. + +.. exception:: NNTPError + + Derived from the standard exception :exc:`Exception`, this is the base + class for all exceptions raised by the :mod:`nntplib` module. Instances + of this class have the following attribute: + + .. attribute:: response + + The response of the server if available, as a :class:`str` object. + + +.. exception:: NNTPReplyError + + Exception raised when an unexpected reply is received from the server. + + +.. exception:: NNTPTemporaryError + + Exception raised when a response code in the range 400--499 is received. + + +.. exception:: NNTPPermanentError + + Exception raised when a response code in the range 500--599 is received. + + +.. exception:: NNTPProtocolError + + Exception raised when a reply is received from the server that does not begin + with a digit in the range 1--5. + + +.. exception:: NNTPDataError + + Exception raised when there is some error in the response data. + + +.. _nntp-objects: + +NNTP Objects +------------ + +When connected, :class:`NNTP` and :class:`NNTP_SSL` objects support the +following methods and attributes. + +Attributes +^^^^^^^^^^ + +.. attribute:: NNTP.nntp_version + + An integer representing the version of the NNTP protocol supported by the + server. In practice, this should be ``2`` for servers advertising + :rfc:`3977` compliance and ``1`` for others. + + .. versionadded:: 3.2 + +.. attribute:: NNTP.nntp_implementation + + A string describing the software name and version of the NNTP server, + or :const:`None` if not advertised by the server. + + .. versionadded:: 3.2 + +Methods +^^^^^^^ + +The *response* that is returned as the first item in the return tuple of almost +all methods is the server's response: a string beginning with a three-digit +code. If the server's response indicates an error, the method raises one of +the above exceptions. + +Many of the following methods take an optional keyword-only argument *file*. +When the *file* argument is supplied, it must be either a :term:`file object` +opened for binary writing, or the name of an on-disk file to be written to. +The method will then write any data returned by the server (except for the +response line and the terminating dot) to the file; any list of lines, +tuples or objects that the method normally returns will be empty. + +.. versionchanged:: 3.2 + Many of the following methods have been reworked and fixed, which makes + them incompatible with their 3.1 counterparts. + + +.. method:: NNTP.quit() + + Send a ``QUIT`` command and close the connection. Once this method has been + called, no other methods of the NNTP object should be called. + + +.. method:: NNTP.getwelcome() + + Return the welcome message sent by the server in reply to the initial + connection. (This message sometimes contains disclaimers or help information + that may be relevant to the user.) + + +.. method:: NNTP.getcapabilities() + + Return the :rfc:`3977` capabilities advertised by the server, as a + :class:`dict` instance mapping capability names to (possibly empty) lists + of values. On legacy servers which don't understand the ``CAPABILITIES`` + command, an empty dictionary is returned instead. + + >>> s = NNTP('news.gmane.io') + >>> 'POST' in s.getcapabilities() + True + + .. versionadded:: 3.2 + + +.. method:: NNTP.login(user=None, password=None, usenetrc=True) + + Send ``AUTHINFO`` commands with the user name and password. If *user* + and *password* are ``None`` and *usenetrc* is true, credentials from + ``~/.netrc`` will be used if possible. + + Unless intentionally delayed, login is normally performed during the + :class:`NNTP` object initialization and separately calling this function + is unnecessary. To force authentication to be delayed, you must not set + *user* or *password* when creating the object, and must set *usenetrc* to + False. + + .. versionadded:: 3.2 + + +.. method:: NNTP.starttls(context=None) + + Send a ``STARTTLS`` command. This will enable encryption on the NNTP + connection. The *context* argument is optional and should be a + :class:`ssl.SSLContext` object. Please read :ref:`ssl-security` for best + practices. + + Note that this may not be done after authentication information has + been transmitted, and authentication occurs by default if possible during a + :class:`NNTP` object initialization. See :meth:`NNTP.login` for information + on suppressing this behavior. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.4 + The method now supports hostname check with + :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see + :data:`ssl.HAS_SNI`). + +.. method:: NNTP.newgroups(date, *, file=None) + + Send a ``NEWGROUPS`` command. The *date* argument should be a + :class:`datetime.date` or :class:`datetime.datetime` object. + Return a pair ``(response, groups)`` where *groups* is a list representing + the groups that are new since the given *date*. If *file* is supplied, + though, then *groups* will be empty. + + >>> from datetime import date, timedelta + >>> resp, groups = s.newgroups(date.today() - timedelta(days=3)) + >>> len(groups) # doctest: +SKIP + 85 + >>> groups[0] # doctest: +SKIP + GroupInfo(group='gmane.network.tor.devel', last='4', first='1', flag='m') + + +.. method:: NNTP.newnews(group, date, *, file=None) + + Send a ``NEWNEWS`` command. Here, *group* is a group name or ``'*'``, and + *date* has the same meaning as for :meth:`newgroups`. Return a pair + ``(response, articles)`` where *articles* is a list of message ids. + + This command is frequently disabled by NNTP server administrators. + + +.. method:: NNTP.list(group_pattern=None, *, file=None) + + Send a ``LIST`` or ``LIST ACTIVE`` command. Return a pair + ``(response, list)`` where *list* is a list of tuples representing all + the groups available from this NNTP server, optionally matching the + pattern string *group_pattern*. Each tuple has the form + ``(group, last, first, flag)``, where *group* is a group name, *last* + and *first* are the last and first article numbers, and *flag* usually + takes one of these values: + + * ``y``: Local postings and articles from peers are allowed. + * ``m``: The group is moderated and all postings must be approved. + * ``n``: No local postings are allowed, only articles from peers. + * ``j``: Articles from peers are filed in the junk group instead. + * ``x``: No local postings, and articles from peers are ignored. + * ``=foo.bar``: Articles are filed in the ``foo.bar`` group instead. + + If *flag* has another value, then the status of the newsgroup should be + considered unknown. + + This command can return very large results, especially if *group_pattern* + is not specified. It is best to cache the results offline unless you + really need to refresh them. + + .. versionchanged:: 3.2 + *group_pattern* was added. + + +.. method:: NNTP.descriptions(grouppattern) + + Send a ``LIST NEWSGROUPS`` command, where *grouppattern* is a wildmat string as + specified in :rfc:`3977` (it's essentially the same as DOS or UNIX shell wildcard + strings). Return a pair ``(response, descriptions)``, where *descriptions* + is a dictionary mapping group names to textual descriptions. + + >>> resp, descs = s.descriptions('gmane.comp.python.*') + >>> len(descs) # doctest: +SKIP + 295 + >>> descs.popitem() # doctest: +SKIP + ('gmane.comp.python.bio.general', 'BioPython discussion list (Moderated)') + + +.. method:: NNTP.description(group) + + Get a description for a single group *group*. If more than one group matches + (if 'group' is a real wildmat string), return the first match. If no group + matches, return an empty string. + + This elides the response code from the server. If the response code is needed, + use :meth:`descriptions`. + + +.. method:: NNTP.group(name) + + Send a ``GROUP`` command, where *name* is the group name. The group is + selected as the current group, if it exists. Return a tuple + ``(response, count, first, last, name)`` where *count* is the (estimated) + number of articles in the group, *first* is the first article number in + the group, *last* is the last article number in the group, and *name* + is the group name. + + +.. method:: NNTP.over(message_spec, *, file=None) + + Send an ``OVER`` command, or an ``XOVER`` command on legacy servers. + *message_spec* can be either a string representing a message id, or + a ``(first, last)`` tuple of numbers indicating a range of articles in + the current group, or a ``(first, None)`` tuple indicating a range of + articles starting from *first* to the last article in the current group, + or :const:`None` to select the current article in the current group. + + Return a pair ``(response, overviews)``. *overviews* is a list of + ``(article_number, overview)`` tuples, one for each article selected + by *message_spec*. Each *overview* is a dictionary with the same number + of items, but this number depends on the server. These items are either + message headers (the key is then the lower-cased header name) or metadata + items (the key is then the metadata name prepended with ``":"``). The + following items are guaranteed to be present by the NNTP specification: + + * the ``subject``, ``from``, ``date``, ``message-id`` and ``references`` + headers + * the ``:bytes`` metadata: the number of bytes in the entire raw article + (including headers and body) + * the ``:lines`` metadata: the number of lines in the article body + + The value of each item is either a string, or :const:`None` if not present. + + It is advisable to use the :func:`decode_header` function on header + values when they may contain non-ASCII characters:: + + >>> _, _, first, last, _ = s.group('gmane.comp.python.devel') + >>> resp, overviews = s.over((last, last)) + >>> art_num, over = overviews[0] + >>> art_num + 117216 + >>> list(over.keys()) + ['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject'] + >>> over['from'] + '=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= ' + >>> nntplib.decode_header(over['from']) + '"Martin v. Löwis" ' + + .. versionadded:: 3.2 + + +.. method:: NNTP.help(*, file=None) + + Send a ``HELP`` command. Return a pair ``(response, list)`` where *list* is a + list of help strings. + + +.. method:: NNTP.stat(message_spec=None) + + Send a ``STAT`` command, where *message_spec* is either a message id + (enclosed in ``'<'`` and ``'>'``) or an article number in the current group. + If *message_spec* is omitted or :const:`None`, the current article in the + current group is considered. Return a triple ``(response, number, id)`` + where *number* is the article number and *id* is the message id. + + >>> _, _, first, last, _ = s.group('gmane.comp.python.devel') + >>> resp, number, message_id = s.stat(first) + >>> number, message_id + (9099, '<20030112190404.GE29873@epoch.metaslash.com>') + + +.. method:: NNTP.next() + + Send a ``NEXT`` command. Return as for :meth:`.stat`. + + +.. method:: NNTP.last() + + Send a ``LAST`` command. Return as for :meth:`.stat`. + + +.. method:: NNTP.article(message_spec=None, *, file=None) + + Send an ``ARTICLE`` command, where *message_spec* has the same meaning as + for :meth:`.stat`. Return a tuple ``(response, info)`` where *info* + is a :class:`~collections.namedtuple` with three attributes *number*, + *message_id* and *lines* (in that order). *number* is the article number + in the group (or 0 if the information is not available), *message_id* the + message id as a string, and *lines* a list of lines (without terminating + newlines) comprising the raw message including headers and body. + + >>> resp, info = s.article('<20030112190404.GE29873@epoch.metaslash.com>') + >>> info.number + 0 + >>> info.message_id + '<20030112190404.GE29873@epoch.metaslash.com>' + >>> len(info.lines) + 65 + >>> info.lines[0] + b'Path: main.gmane.org!not-for-mail' + >>> info.lines[1] + b'From: Neal Norwitz ' + >>> info.lines[-3:] + [b'There is a patch for 2.3 as well as 2.2.', b'', b'Neal'] + + +.. method:: NNTP.head(message_spec=None, *, file=None) + + Same as :meth:`article()`, but sends a ``HEAD`` command. The *lines* + returned (or written to *file*) will only contain the message headers, not + the body. + + +.. method:: NNTP.body(message_spec=None, *, file=None) + + Same as :meth:`article()`, but sends a ``BODY`` command. The *lines* + returned (or written to *file*) will only contain the message body, not the + headers. + + +.. method:: NNTP.post(data) + + Post an article using the ``POST`` command. The *data* argument is either + a :term:`file object` opened for binary reading, or any iterable of bytes + objects (representing raw lines of the article to be posted). It should + represent a well-formed news article, including the required headers. The + :meth:`post` method automatically escapes lines beginning with ``.`` and + appends the termination line. + + If the method succeeds, the server's response is returned. If the server + refuses posting, a :class:`NNTPReplyError` is raised. + + +.. method:: NNTP.ihave(message_id, data) + + Send an ``IHAVE`` command. *message_id* is the id of the message to send + to the server (enclosed in ``'<'`` and ``'>'``). The *data* parameter + and the return value are the same as for :meth:`post()`. + + +.. method:: NNTP.date() + + Return a pair ``(response, date)``. *date* is a :class:`~datetime.datetime` + object containing the current date and time of the server. + + +.. method:: NNTP.slave() + + Send a ``SLAVE`` command. Return the server's *response*. + + +.. method:: NNTP.set_debuglevel(level) + + Set the instance's debugging level. This controls the amount of debugging + output printed. The default, ``0``, produces no debugging output. A value of + ``1`` produces a moderate amount of debugging output, generally a single line + per request or response. A value of ``2`` or higher produces the maximum amount + of debugging output, logging each line sent and received on the connection + (including message text). + + +The following are optional NNTP extensions defined in :rfc:`2980`. Some of +them have been superseded by newer commands in :rfc:`3977`. + + +.. method:: NNTP.xhdr(hdr, str, *, file=None) + + Send an ``XHDR`` command. The *hdr* argument is a header keyword, e.g. + ``'subject'``. The *str* argument should have the form ``'first-last'`` + where *first* and *last* are the first and last article numbers to search. + Return a pair ``(response, list)``, where *list* is a list of pairs ``(id, + text)``, where *id* is an article number (as a string) and *text* is the text of + the requested header for that article. If the *file* parameter is supplied, then + the output of the ``XHDR`` command is stored in a file. If *file* is a string, + then the method will open a file with that name, write to it then close it. + If *file* is a :term:`file object`, then it will start calling :meth:`write` on + it to store the lines of the command output. If *file* is supplied, then the + returned *list* is an empty list. + + +.. method:: NNTP.xover(start, end, *, file=None) + + Send an ``XOVER`` command. *start* and *end* are article numbers + delimiting the range of articles to select. The return value is the + same of for :meth:`over()`. It is recommended to use :meth:`over()` + instead, since it will automatically use the newer ``OVER`` command + if available. + + +Utility functions +----------------- + +The module also defines the following utility function: + + +.. function:: decode_header(header_str) + + Decode a header value, un-escaping any escaped non-ASCII characters. + *header_str* must be a :class:`str` object. The unescaped value is + returned. Using this function is recommended to display some headers + in a human readable form:: + + >>> decode_header("Some subject") + 'Some subject' + >>> decode_header("=?ISO-8859-15?Q?D=E9buter_en_Python?=") + 'Débuter en Python' + >>> decode_header("Re: =?UTF-8?B?cHJvYmzDqG1lIGRlIG1hdHJpY2U=?=") + 'Re: problème de matrice' diff --git a/cpython_2/environment/repo/Doc/library/numbers.rst b/cpython_2/environment/repo/Doc/library/numbers.rst new file mode 100644 index 0000000000000000000000000000000000000000..1b594952ead7241dacf8fa751bd3e7a014ba15a4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/numbers.rst @@ -0,0 +1,223 @@ +:mod:`numbers` --- Numeric abstract base classes +================================================ + +.. module:: numbers + :synopsis: Numeric abstract base classes (Complex, Real, Integral, etc.). + +**Source code:** :source:`Lib/numbers.py` + +-------------- + +The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric +:term:`abstract base classes ` which progressively define +more operations. None of the types defined in this module can be instantiated. + + +.. class:: Number + + The root of the numeric hierarchy. If you just want to check if an argument + *x* is a number, without caring what kind, use ``isinstance(x, Number)``. + + +The numeric tower +----------------- + +.. class:: Complex + + Subclasses of this type describe complex numbers and include the operations + that work on the built-in :class:`complex` type. These are: conversions to + :class:`complex` and :class:`bool`, :attr:`.real`, :attr:`.imag`, ``+``, + ``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All + except ``-`` and ``!=`` are abstract. + + .. attribute:: real + + Abstract. Retrieves the real component of this number. + + .. attribute:: imag + + Abstract. Retrieves the imaginary component of this number. + + .. abstractmethod:: conjugate() + + Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate() + == (1-3j)``. + +.. class:: Real + + To :class:`Complex`, :class:`Real` adds the operations that work on real + numbers. + + In short, those are: a conversion to :class:`float`, :func:`math.trunc`, + :func:`round`, :func:`math.floor`, :func:`math.ceil`, :func:`divmod`, ``//``, + ``%``, ``<``, ``<=``, ``>``, and ``>=``. + + Real also provides defaults for :func:`complex`, :attr:`~Complex.real`, + :attr:`~Complex.imag`, and :meth:`~Complex.conjugate`. + + +.. class:: Rational + + Subtypes :class:`Real` and adds + :attr:`~Rational.numerator` and :attr:`~Rational.denominator` properties, which + should be in lowest terms. With these, it provides a default for + :func:`float`. + + .. attribute:: numerator + + Abstract. + + .. attribute:: denominator + + Abstract. + + +.. class:: Integral + + Subtypes :class:`Rational` and adds a conversion to :class:`int`. Provides + defaults for :func:`float`, :attr:`~Rational.numerator`, and + :attr:`~Rational.denominator`. Adds abstract methods for ``**`` and + bit-string operations: ``<<``, ``>>``, ``&``, ``^``, ``|``, ``~``. + + +Notes for type implementors +--------------------------- + +Implementors should be careful to make equal numbers equal and hash +them to the same values. This may be subtle if there are two different +extensions of the real numbers. For example, :class:`fractions.Fraction` +implements :func:`hash` as follows:: + + def __hash__(self): + if self.denominator == 1: + # Get integers right. + return hash(self.numerator) + # Expensive check, but definitely correct. + if self == float(self): + return hash(float(self)) + else: + # Use tuple's hash to avoid a high collision rate on + # simple fractions. + return hash((self.numerator, self.denominator)) + + +Adding More Numeric ABCs +~~~~~~~~~~~~~~~~~~~~~~~~ + +There are, of course, more possible ABCs for numbers, and this would +be a poor hierarchy if it precluded the possibility of adding +those. You can add ``MyFoo`` between :class:`Complex` and +:class:`Real` with:: + + class MyFoo(Complex): ... + MyFoo.register(Real) + + +.. _implementing-the-arithmetic-operations: + +Implementing the arithmetic operations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We want to implement the arithmetic operations so that mixed-mode +operations either call an implementation whose author knew about the +types of both arguments, or convert both to the nearest built in type +and do the operation there. For subtypes of :class:`Integral`, this +means that :meth:`__add__` and :meth:`__radd__` should be defined as:: + + class MyIntegral(Integral): + + def __add__(self, other): + if isinstance(other, MyIntegral): + return do_my_adding_stuff(self, other) + elif isinstance(other, OtherTypeIKnowAbout): + return do_my_other_adding_stuff(self, other) + else: + return NotImplemented + + def __radd__(self, other): + if isinstance(other, MyIntegral): + return do_my_adding_stuff(other, self) + elif isinstance(other, OtherTypeIKnowAbout): + return do_my_other_adding_stuff(other, self) + elif isinstance(other, Integral): + return int(other) + int(self) + elif isinstance(other, Real): + return float(other) + float(self) + elif isinstance(other, Complex): + return complex(other) + complex(self) + else: + return NotImplemented + + +There are 5 different cases for a mixed-type operation on subclasses +of :class:`Complex`. I'll refer to all of the above code that doesn't +refer to ``MyIntegral`` and ``OtherTypeIKnowAbout`` as +"boilerplate". ``a`` will be an instance of ``A``, which is a subtype +of :class:`Complex` (``a : A <: Complex``), and ``b : B <: +Complex``. I'll consider ``a + b``: + + 1. If ``A`` defines an :meth:`__add__` which accepts ``b``, all is + well. + 2. If ``A`` falls back to the boilerplate code, and it were to + return a value from :meth:`__add__`, we'd miss the possibility + that ``B`` defines a more intelligent :meth:`__radd__`, so the + boilerplate should return :const:`NotImplemented` from + :meth:`__add__`. (Or ``A`` may not implement :meth:`__add__` at + all.) + 3. Then ``B``'s :meth:`__radd__` gets a chance. If it accepts + ``a``, all is well. + 4. If it falls back to the boilerplate, there are no more possible + methods to try, so this is where the default implementation + should live. + 5. If ``B <: A``, Python tries ``B.__radd__`` before + ``A.__add__``. This is ok, because it was implemented with + knowledge of ``A``, so it can handle those instances before + delegating to :class:`Complex`. + +If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge, +then the appropriate shared operation is the one involving the built +in :class:`complex`, and both :meth:`__radd__` s land there, so ``a+b +== b+a``. + +Because most of the operations on any given type will be very similar, +it can be useful to define a helper function which generates the +forward and reverse instances of any given operator. For example, +:class:`fractions.Fraction` uses:: + + def _operator_fallbacks(monomorphic_operator, fallback_operator): + def forward(a, b): + if isinstance(b, (int, Fraction)): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ + + def reverse(b, a): + if isinstance(a, Rational): + # Includes ints. + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ + + return forward, reverse + + def _add(a, b): + """a + b""" + return Fraction(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) + + __add__, __radd__ = _operator_fallbacks(_add, operator.add) + + # ... diff --git a/cpython_2/environment/repo/Doc/library/numeric.rst b/cpython_2/environment/repo/Doc/library/numeric.rst new file mode 100644 index 0000000000000000000000000000000000000000..7c76a479d73b2641c510e7d54e0815e0451bdcae --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/numeric.rst @@ -0,0 +1,26 @@ + +.. _numeric: + +******************************** +Numeric and Mathematical Modules +******************************** + +The modules described in this chapter provide numeric and math-related functions +and data types. The :mod:`numbers` module defines an abstract hierarchy of +numeric types. The :mod:`math` and :mod:`cmath` modules contain various +mathematical functions for floating-point and complex numbers. The :mod:`decimal` +module supports exact representations of decimal numbers, using arbitrary precision +arithmetic. + +The following modules are documented in this chapter: + + +.. toctree:: + + numbers.rst + math.rst + cmath.rst + decimal.rst + fractions.rst + random.rst + statistics.rst diff --git a/cpython_2/environment/repo/Doc/library/operator.rst b/cpython_2/environment/repo/Doc/library/operator.rst new file mode 100644 index 0000000000000000000000000000000000000000..fa02bde84650e1e0cd1145ca6c997069f85ffb82 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/operator.rst @@ -0,0 +1,559 @@ +:mod:`operator` --- Standard operators as functions +=================================================== + +.. module:: operator + :synopsis: Functions corresponding to the standard operators. + +.. sectionauthor:: Skip Montanaro + +**Source code:** :source:`Lib/operator.py` + +.. testsetup:: + + import operator + from operator import itemgetter, iadd + +-------------- + +The :mod:`operator` module exports a set of efficient functions corresponding to +the intrinsic operators of Python. For example, ``operator.add(x, y)`` is +equivalent to the expression ``x+y``. Many function names are those used for +special methods, without the double underscores. For backward compatibility, +many of these have a variant with the double underscores kept. The variants +without the double underscores are preferred for clarity. + +The functions fall into categories that perform object comparisons, logical +operations, mathematical operations and sequence operations. + +The object comparison functions are useful for all objects, and are named after +the rich comparison operators they support: + + +.. function:: lt(a, b) + le(a, b) + eq(a, b) + ne(a, b) + ge(a, b) + gt(a, b) + __lt__(a, b) + __le__(a, b) + __eq__(a, b) + __ne__(a, b) + __ge__(a, b) + __gt__(a, b) + + Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is + equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a, + b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``, + ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a + >= b``. Note that these functions can return any value, which may + or may not be interpretable as a Boolean value. See + :ref:`comparisons` for more information about rich comparisons. + + +The logical operations are also generally applicable to all objects, and support +truth tests, identity tests, and boolean operations: + + +.. function:: not_(obj) + __not__(obj) + + Return the outcome of :keyword:`not` *obj*. (Note that there is no + :meth:`__not__` method for object instances; only the interpreter core defines + this operation. The result is affected by the :meth:`__bool__` and + :meth:`__len__` methods.) + + +.. function:: truth(obj) + + Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is + equivalent to using the :class:`bool` constructor. + + +.. function:: is_(a, b) + + Return ``a is b``. Tests object identity. + + +.. function:: is_not(a, b) + + Return ``a is not b``. Tests object identity. + + +The mathematical and bitwise operations are the most numerous: + + +.. function:: abs(obj) + __abs__(obj) + + Return the absolute value of *obj*. + + +.. function:: add(a, b) + __add__(a, b) + + Return ``a + b``, for *a* and *b* numbers. + + +.. function:: and_(a, b) + __and__(a, b) + + Return the bitwise and of *a* and *b*. + + +.. function:: floordiv(a, b) + __floordiv__(a, b) + + Return ``a // b``. + + +.. function:: index(a) + __index__(a) + + Return *a* converted to an integer. Equivalent to ``a.__index__()``. + + +.. function:: inv(obj) + invert(obj) + __inv__(obj) + __invert__(obj) + + Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``. + + +.. function:: lshift(a, b) + __lshift__(a, b) + + Return *a* shifted left by *b*. + + +.. function:: mod(a, b) + __mod__(a, b) + + Return ``a % b``. + + +.. function:: mul(a, b) + __mul__(a, b) + + Return ``a * b``, for *a* and *b* numbers. + + +.. function:: matmul(a, b) + __matmul__(a, b) + + Return ``a @ b``. + + .. versionadded:: 3.5 + + +.. function:: neg(obj) + __neg__(obj) + + Return *obj* negated (``-obj``). + + +.. function:: or_(a, b) + __or__(a, b) + + Return the bitwise or of *a* and *b*. + + +.. function:: pos(obj) + __pos__(obj) + + Return *obj* positive (``+obj``). + + +.. function:: pow(a, b) + __pow__(a, b) + + Return ``a ** b``, for *a* and *b* numbers. + + +.. function:: rshift(a, b) + __rshift__(a, b) + + Return *a* shifted right by *b*. + + +.. function:: sub(a, b) + __sub__(a, b) + + Return ``a - b``. + + +.. function:: truediv(a, b) + __truediv__(a, b) + + Return ``a / b`` where 2/3 is .66 rather than 0. This is also known as + "true" division. + + +.. function:: xor(a, b) + __xor__(a, b) + + Return the bitwise exclusive or of *a* and *b*. + + +Operations which work with sequences (some of them with mappings too) include: + +.. function:: concat(a, b) + __concat__(a, b) + + Return ``a + b`` for *a* and *b* sequences. + + +.. function:: contains(a, b) + __contains__(a, b) + + Return the outcome of the test ``b in a``. Note the reversed operands. + + +.. function:: countOf(a, b) + + Return the number of occurrences of *b* in *a*. + + +.. function:: delitem(a, b) + __delitem__(a, b) + + Remove the value of *a* at index *b*. + + +.. function:: getitem(a, b) + __getitem__(a, b) + + Return the value of *a* at index *b*. + + +.. function:: indexOf(a, b) + + Return the index of the first of occurrence of *b* in *a*. + + +.. function:: setitem(a, b, c) + __setitem__(a, b, c) + + Set the value of *a* at index *b* to *c*. + + +.. function:: length_hint(obj, default=0) + + Return an estimated length for the object *o*. First try to return its + actual length, then an estimate using :meth:`object.__length_hint__`, and + finally return the default value. + + .. versionadded:: 3.4 + +The :mod:`operator` module also defines tools for generalized attribute and item +lookups. These are useful for making fast field extractors as arguments for +:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that +expect a function argument. + + +.. function:: attrgetter(attr) + attrgetter(*attrs) + + Return a callable object that fetches *attr* from its operand. + If more than one attribute is requested, returns a tuple of attributes. + The attribute names can also contain dots. For example: + + * After ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. + + * After ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns + ``(b.name, b.date)``. + + * After ``f = attrgetter('name.first', 'name.last')``, the call ``f(b)`` + returns ``(b.name.first, b.name.last)``. + + Equivalent to:: + + def attrgetter(*items): + if any(not isinstance(item, str) for item in items): + raise TypeError('attribute name must be a string') + if len(items) == 1: + attr = items[0] + def g(obj): + return resolve_attr(obj, attr) + else: + def g(obj): + return tuple(resolve_attr(obj, attr) for attr in items) + return g + + def resolve_attr(obj, attr): + for name in attr.split("."): + obj = getattr(obj, name) + return obj + + +.. function:: itemgetter(item) + itemgetter(*items) + + Return a callable object that fetches *item* from its operand using the + operand's :meth:`__getitem__` method. If multiple items are specified, + returns a tuple of lookup values. For example: + + * After ``f = itemgetter(2)``, the call ``f(r)`` returns ``r[2]``. + + * After ``g = itemgetter(2, 5, 3)``, the call ``g(r)`` returns + ``(r[2], r[5], r[3])``. + + Equivalent to:: + + def itemgetter(*items): + if len(items) == 1: + item = items[0] + def g(obj): + return obj[item] + else: + 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 + strings accept an index or a slice: + + >>> itemgetter('name')({'name': 'tu', 'age': 18}) + 'tu' + >>> itemgetter(1)('ABCDEFG') + 'B' + >>> itemgetter(1,3,5)('ABCDEFG') + ('B', 'D', 'F') + >>> itemgetter(slice(2,None))('ABCDEFG') + 'CDEFG' + + >>> soldier = dict(rank='captain', name='dotterbart') + >>> itemgetter('rank')(soldier) + 'captain' + + Example of using :func:`itemgetter` to retrieve specific fields from a + tuple record: + + >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] + >>> getcount = itemgetter(1) + >>> list(map(getcount, inventory)) + [3, 2, 5, 1] + >>> sorted(inventory, key=getcount) + [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)] + + +.. function:: methodcaller(name, /, *args, **kwargs) + + Return a callable object that calls the method *name* on its operand. If + additional arguments and/or keyword arguments are given, they will be given + to the method as well. For example: + + * After ``f = methodcaller('name')``, the call ``f(b)`` returns ``b.name()``. + + * After ``f = methodcaller('name', 'foo', bar=1)``, the call ``f(b)`` + returns ``b.name('foo', bar=1)``. + + Equivalent to:: + + def methodcaller(name, /, *args, **kwargs): + def caller(obj): + return getattr(obj, name)(*args, **kwargs) + return caller + + +.. _operator-map: + +Mapping Operators to Functions +------------------------------ + +This table shows how abstract operations correspond to operator symbols in the +Python syntax and the functions in the :mod:`operator` module. + ++-----------------------+-------------------------+---------------------------------------+ +| Operation | Syntax | Function | ++=======================+=========================+=======================================+ +| Addition | ``a + b`` | ``add(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Division | ``a / b`` | ``truediv(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Division | ``a // b`` | ``floordiv(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Bitwise And | ``a & b`` | ``and_(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Bitwise Inversion | ``~ a`` | ``invert(a)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Bitwise Or | ``a | b`` | ``or_(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Exponentiation | ``a ** b`` | ``pow(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Identity | ``a is b`` | ``is_(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Identity | ``a is not b`` | ``is_not(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Indexing | ``obj[k]`` | ``getitem(obj, k)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Left Shift | ``a << b`` | ``lshift(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Modulo | ``a % b`` | ``mod(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Multiplication | ``a * b`` | ``mul(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Matrix Multiplication | ``a @ b`` | ``matmul(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Negation (Arithmetic) | ``- a`` | ``neg(a)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Negation (Logical) | ``not a`` | ``not_(a)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Positive | ``+ a`` | ``pos(a)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Right Shift | ``a >> b`` | ``rshift(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` | ++-----------------------+-------------------------+---------------------------------------+ +| Slicing | ``seq[i:j]`` | ``getitem(seq, slice(i, j))`` | ++-----------------------+-------------------------+---------------------------------------+ +| String Formatting | ``s % obj`` | ``mod(s, obj)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Subtraction | ``a - b`` | ``sub(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Truth Test | ``obj`` | ``truth(obj)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Ordering | ``a < b`` | ``lt(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Ordering | ``a <= b`` | ``le(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Equality | ``a == b`` | ``eq(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Difference | ``a != b`` | ``ne(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Ordering | ``a >= b`` | ``ge(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ +| Ordering | ``a > b`` | ``gt(a, b)`` | ++-----------------------+-------------------------+---------------------------------------+ + +In-place Operators +------------------ + +Many operations have an "in-place" version. Listed below are functions +providing a more primitive access to in-place operators than the usual syntax +does; for example, the :term:`statement` ``x += y`` is equivalent to +``x = operator.iadd(x, y)``. Another way to put it is to say that +``z = operator.iadd(x, y)`` is equivalent to the compound statement +``z = x; z += y``. + +In those examples, note that when an in-place method is called, the computation +and assignment are performed in two separate steps. The in-place functions +listed below only do the first step, calling the in-place method. The second +step, assignment, is not handled. + +For immutable targets such as strings, numbers, and tuples, the updated +value is computed, but not assigned back to the input variable: + +>>> a = 'hello' +>>> iadd(a, ' world') +'hello world' +>>> a +'hello' + +For mutable targets such as lists and dictionaries, the in-place method +will perform the update, so no subsequent assignment is necessary: + +>>> s = ['h', 'e', 'l', 'l', 'o'] +>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd']) +['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] +>>> s +['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] + +.. function:: iadd(a, b) + __iadd__(a, b) + + ``a = iadd(a, b)`` is equivalent to ``a += b``. + + +.. function:: iand(a, b) + __iand__(a, b) + + ``a = iand(a, b)`` is equivalent to ``a &= b``. + + +.. function:: iconcat(a, b) + __iconcat__(a, b) + + ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences. + + +.. function:: ifloordiv(a, b) + __ifloordiv__(a, b) + + ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``. + + +.. function:: ilshift(a, b) + __ilshift__(a, b) + + ``a = ilshift(a, b)`` is equivalent to ``a <<= b``. + + +.. function:: imod(a, b) + __imod__(a, b) + + ``a = imod(a, b)`` is equivalent to ``a %= b``. + + +.. function:: imul(a, b) + __imul__(a, b) + + ``a = imul(a, b)`` is equivalent to ``a *= b``. + + +.. function:: imatmul(a, b) + __imatmul__(a, b) + + ``a = imatmul(a, b)`` is equivalent to ``a @= b``. + + .. versionadded:: 3.5 + + +.. function:: ior(a, b) + __ior__(a, b) + + ``a = ior(a, b)`` is equivalent to ``a |= b``. + + +.. function:: ipow(a, b) + __ipow__(a, b) + + ``a = ipow(a, b)`` is equivalent to ``a **= b``. + + +.. function:: irshift(a, b) + __irshift__(a, b) + + ``a = irshift(a, b)`` is equivalent to ``a >>= b``. + + +.. function:: isub(a, b) + __isub__(a, b) + + ``a = isub(a, b)`` is equivalent to ``a -= b``. + + +.. function:: itruediv(a, b) + __itruediv__(a, b) + + ``a = itruediv(a, b)`` is equivalent to ``a /= b``. + + +.. function:: ixor(a, b) + __ixor__(a, b) + + ``a = ixor(a, b)`` is equivalent to ``a ^= b``. diff --git a/cpython_2/environment/repo/Doc/library/optparse.rst b/cpython_2/environment/repo/Doc/library/optparse.rst new file mode 100644 index 0000000000000000000000000000000000000000..c1a18e0147431901e724bd0297cfa58f76a3b7dc --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/optparse.rst @@ -0,0 +1,2037 @@ +:mod:`optparse` --- Parser for command line options +=================================================== + +.. module:: optparse + :synopsis: Command-line option parsing library. + :deprecated: + +.. moduleauthor:: Greg Ward +.. sectionauthor:: Greg Ward + +**Source code:** :source:`Lib/optparse.py` + +.. deprecated:: 3.2 + The :mod:`optparse` module is deprecated and will not be developed further; + development will continue with the :mod:`argparse` module. + +-------------- + +:mod:`optparse` is a more convenient, flexible, and powerful library for parsing +command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a +more declarative style of command-line parsing: you create an instance of +:class:`OptionParser`, populate it with options, and parse the command +line. :mod:`optparse` allows users to specify options in the conventional +GNU/POSIX syntax, and additionally generates usage and help messages for you. + +Here's an example of using :mod:`optparse` in a simple script:: + + from optparse import OptionParser + ... + parser = OptionParser() + parser.add_option("-f", "--file", dest="filename", + help="write report to FILE", metavar="FILE") + parser.add_option("-q", "--quiet", + action="store_false", dest="verbose", default=True, + help="don't print status messages to stdout") + + (options, args) = parser.parse_args() + +With these few lines of code, users of your script can now do the "usual thing" +on the command-line, for example:: + + --file=outfile -q + +As it parses the command line, :mod:`optparse` sets attributes of the +``options`` object returned by :meth:`parse_args` based on user-supplied +command-line values. When :meth:`parse_args` returns from parsing this command +line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be +``False``. :mod:`optparse` supports both long and short options, allows short +options to be merged together, and allows options to be associated with their +arguments in a variety of ways. Thus, the following command lines are all +equivalent to the above example:: + + -f outfile --quiet + --quiet --file outfile + -q -foutfile + -qfoutfile + +Additionally, users can run one of :: + + -h + --help + +and :mod:`optparse` will print out a brief summary of your script's options: + +.. code-block:: text + + Usage: [options] + + Options: + -h, --help show this help message and exit + -f FILE, --file=FILE write report to FILE + -q, --quiet don't print status messages to stdout + +where the value of *yourscript* is determined at runtime (normally from +``sys.argv[0]``). + + +.. _optparse-background: + +Background +---------- + +:mod:`optparse` was explicitly designed to encourage the creation of programs +with straightforward, conventional command-line interfaces. To that end, it +supports only the most common command-line syntax and semantics conventionally +used under Unix. If you are unfamiliar with these conventions, read this +section to acquaint yourself with them. + + +.. _optparse-terminology: + +Terminology +^^^^^^^^^^^ + +argument + a string entered on the command-line, and passed by the shell to ``execl()`` + or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]`` + (``sys.argv[0]`` is the name of the program being executed). Unix shells + also use the term "word". + + It is occasionally desirable to substitute an argument list other than + ``sys.argv[1:]``, so you should read "argument" as "an element of + ``sys.argv[1:]``, or of some other list provided as a substitute for + ``sys.argv[1:]``". + +option + an argument used to supply extra information to guide or customize the + execution of a program. There are many different syntaxes for options; the + traditional Unix syntax is a hyphen ("-") followed by a single letter, + e.g. ``-x`` or ``-F``. Also, traditional Unix syntax allows multiple + options to be merged into a single argument, e.g. ``-x -F`` is equivalent + to ``-xF``. The GNU project introduced ``--`` followed by a series of + hyphen-separated words, e.g. ``--file`` or ``--dry-run``. These are the + only two option syntaxes provided by :mod:`optparse`. + + Some other option syntaxes that the world has seen include: + + * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same + as multiple options merged into a single argument) + + * a hyphen followed by a whole word, e.g. ``-file`` (this is technically + equivalent to the previous syntax, but they aren't usually seen in the same + program) + + * a plus sign followed by a single letter, or a few letters, or a word, e.g. + ``+f``, ``+rgb`` + + * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``, + ``/file`` + + These option syntaxes are not supported by :mod:`optparse`, and they never + will be. This is deliberate: the first three are non-standard on any + environment, and the last only makes sense if you're exclusively targeting + VMS, MS-DOS, and/or Windows. + +option argument + an argument that follows an option, is closely associated with that option, + and is consumed from the argument list when that option is. With + :mod:`optparse`, option arguments may either be in a separate argument from + their option: + + .. code-block:: text + + -f foo + --file foo + + or included in the same argument: + + .. code-block:: text + + -ffoo + --file=foo + + Typically, a given option either takes an argument or it doesn't. Lots of + people want an "optional option arguments" feature, meaning that some options + will take an argument if they see it, and won't if they don't. This is + somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes + an optional argument and ``-b`` is another option entirely, how do we + interpret ``-ab``? Because of this ambiguity, :mod:`optparse` does not + support this feature. + +positional argument + something leftover in the argument list after options have been parsed, i.e. + after options and their arguments have been parsed and removed from the + argument list. + +required option + an option that must be supplied on the command-line; note that the phrase + "required option" is self-contradictory in English. :mod:`optparse` doesn't + prevent you from implementing required options, but doesn't give you much + help at it either. + +For example, consider this hypothetical command-line:: + + prog -v --report report.txt foo bar + +``-v`` and ``--report`` are both options. Assuming that ``--report`` +takes one argument, ``report.txt`` is an option argument. ``foo`` and +``bar`` are positional arguments. + + +.. _optparse-what-options-for: + +What are options for? +^^^^^^^^^^^^^^^^^^^^^ + +Options are used to provide extra information to tune or customize the execution +of a program. In case it wasn't clear, options are usually *optional*. A +program should be able to run just fine with no options whatsoever. (Pick a +random program from the Unix or GNU toolsets. Can it run without any options at +all and still make sense? The main exceptions are ``find``, ``tar``, and +``dd``\ ---all of which are mutant oddballs that have been rightly criticized +for their non-standard syntax and confusing interfaces.) + +Lots of people want their programs to have "required options". Think about it. +If it's required, then it's *not optional*! If there is a piece of information +that your program absolutely requires in order to run successfully, that's what +positional arguments are for. + +As an example of good command-line interface design, consider the humble ``cp`` +utility, for copying files. It doesn't make much sense to try to copy files +without supplying a destination and at least one source. Hence, ``cp`` fails if +you run it with no arguments. However, it has a flexible, useful syntax that +does not require any options at all:: + + cp SOURCE DEST + cp SOURCE ... DEST-DIR + +You can get pretty far with just that. Most ``cp`` implementations provide a +bunch of options to tweak exactly how the files are copied: you can preserve +mode and modification time, avoid following symlinks, ask before clobbering +existing files, etc. But none of this distracts from the core mission of +``cp``, which is to copy either one file to another, or several files to another +directory. + + +.. _optparse-what-positional-arguments-for: + +What are positional arguments for? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Positional arguments are for those pieces of information that your program +absolutely, positively requires to run. + +A good user interface should have as few absolute requirements as possible. If +your program requires 17 distinct pieces of information in order to run +successfully, it doesn't much matter *how* you get that information from the +user---most people will give up and walk away before they successfully run the +program. This applies whether the user interface is a command-line, a +configuration file, or a GUI: if you make that many demands on your users, most +of them will simply give up. + +In short, try to minimize the amount of information that users are absolutely +required to supply---use sensible defaults whenever possible. Of course, you +also want to make your programs reasonably flexible. That's what options are +for. Again, it doesn't matter if they are entries in a config file, widgets in +the "Preferences" dialog of a GUI, or command-line options---the more options +you implement, the more flexible your program is, and the more complicated its +implementation becomes. Too much flexibility has drawbacks as well, of course; +too many options can overwhelm users and make your code much harder to maintain. + + +.. _optparse-tutorial: + +Tutorial +-------- + +While :mod:`optparse` is quite flexible and powerful, it's also straightforward +to use in most cases. This section covers the code patterns that are common to +any :mod:`optparse`\ -based program. + +First, you need to import the OptionParser class; then, early in the main +program, create an OptionParser instance:: + + from optparse import OptionParser + ... + parser = OptionParser() + +Then you can start defining options. The basic syntax is:: + + parser.add_option(opt_str, ..., + attr=value, ...) + +Each option has one or more option strings, such as ``-f`` or ``--file``, +and several option attributes that tell :mod:`optparse` what to expect and what +to do when it encounters that option on the command line. + +Typically, each option will have one short option string and one long option +string, e.g.:: + + parser.add_option("-f", "--file", ...) + +You're free to define as many short option strings and as many long option +strings as you like (including zero), as long as there is at least one option +string overall. + +The option strings passed to :meth:`OptionParser.add_option` are effectively +labels for the +option defined by that call. For brevity, we will frequently refer to +*encountering an option* on the command line; in reality, :mod:`optparse` +encounters *option strings* and looks up options from them. + +Once all of your options are defined, instruct :mod:`optparse` to parse your +program's command line:: + + (options, args) = parser.parse_args() + +(If you like, you can pass a custom argument list to :meth:`parse_args`, but +that's rarely necessary: by default it uses ``sys.argv[1:]``.) + +:meth:`parse_args` returns two values: + +* ``options``, an object containing values for all of your options---e.g. if + ``--file`` takes a single string argument, then ``options.file`` will be the + filename supplied by the user, or ``None`` if the user did not supply that + option + +* ``args``, the list of positional arguments leftover after parsing options + +This tutorial section only covers the four most important option attributes: +:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest` +(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the +most fundamental. + + +.. _optparse-understanding-option-actions: + +Understanding option actions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Actions tell :mod:`optparse` what to do when it encounters an option on the +command line. There is a fixed set of actions hard-coded into :mod:`optparse`; +adding new actions is an advanced topic covered in section +:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store +a value in some variable---for example, take a string from the command line and +store it in an attribute of ``options``. + +If you don't specify an option action, :mod:`optparse` defaults to ``store``. + + +.. _optparse-store-action: + +The store action +^^^^^^^^^^^^^^^^ + +The most common option action is ``store``, which tells :mod:`optparse` to take +the next argument (or the remainder of the current argument), ensure that it is +of the correct type, and store it to your chosen destination. + +For example:: + + parser.add_option("-f", "--file", + action="store", type="string", dest="filename") + +Now let's make up a fake command line and ask :mod:`optparse` to parse it:: + + args = ["-f", "foo.txt"] + (options, args) = parser.parse_args(args) + +When :mod:`optparse` sees the option string ``-f``, it consumes the next +argument, ``foo.txt``, and stores it in ``options.filename``. So, after this +call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``. + +Some other option types supported by :mod:`optparse` are ``int`` and ``float``. +Here's an option that expects an integer argument:: + + parser.add_option("-n", type="int", dest="num") + +Note that this option has no long option string, which is perfectly acceptable. +Also, there's no explicit action, since the default is ``store``. + +Let's parse another fake command-line. This time, we'll jam the option argument +right up against the option: since ``-n42`` (one argument) is equivalent to +``-n 42`` (two arguments), the code :: + + (options, args) = parser.parse_args(["-n42"]) + print(options.num) + +will print ``42``. + +If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with +the fact that the default action is ``store``, that means our first example can +be a lot shorter:: + + parser.add_option("-f", "--file", dest="filename") + +If you don't supply a destination, :mod:`optparse` figures out a sensible +default from the option strings: if the first long option string is +``--foo-bar``, then the default destination is ``foo_bar``. If there are no +long option strings, :mod:`optparse` looks at the first short option string: the +default destination for ``-f`` is ``f``. + +:mod:`optparse` also includes the built-in ``complex`` type. Adding +types is covered in section :ref:`optparse-extending-optparse`. + + +.. _optparse-handling-boolean-options: + +Handling boolean (flag) options +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Flag options---set a variable to true or false when a particular option is +seen---are quite common. :mod:`optparse` supports them with two separate actions, +``store_true`` and ``store_false``. For example, you might have a ``verbose`` +flag that is turned on with ``-v`` and off with ``-q``:: + + parser.add_option("-v", action="store_true", dest="verbose") + parser.add_option("-q", action="store_false", dest="verbose") + +Here we have two different options with the same destination, which is perfectly +OK. (It just means you have to be a bit careful when setting default +values---see below.) + +When :mod:`optparse` encounters ``-v`` on the command line, it sets +``options.verbose`` to ``True``; when it encounters ``-q``, +``options.verbose`` is set to ``False``. + + +.. _optparse-other-actions: + +Other actions +^^^^^^^^^^^^^ + +Some other actions supported by :mod:`optparse` are: + +``"store_const"`` + store a constant value + +``"append"`` + append this option's argument to a list + +``"count"`` + increment a counter by one + +``"callback"`` + call a specified function + +These are covered in section :ref:`optparse-reference-guide`, +and section :ref:`optparse-option-callbacks`. + + +.. _optparse-default-values: + +Default values +^^^^^^^^^^^^^^ + +All of the above examples involve setting some variable (the "destination") when +certain command-line options are seen. What happens if those options are never +seen? Since we didn't supply any defaults, they are all set to ``None``. This +is usually fine, but sometimes you want more control. :mod:`optparse` lets you +supply a default value for each destination, which is assigned before the +command line is parsed. + +First, consider the verbose/quiet example. If we want :mod:`optparse` to set +``verbose`` to ``True`` unless ``-q`` is seen, then we can do this:: + + parser.add_option("-v", action="store_true", dest="verbose", default=True) + parser.add_option("-q", action="store_false", dest="verbose") + +Since default values apply to the *destination* rather than to any particular +option, and these two options happen to have the same destination, this is +exactly equivalent:: + + parser.add_option("-v", action="store_true", dest="verbose") + parser.add_option("-q", action="store_false", dest="verbose", default=True) + +Consider this:: + + parser.add_option("-v", action="store_true", dest="verbose", default=False) + parser.add_option("-q", action="store_false", dest="verbose", default=True) + +Again, the default value for ``verbose`` will be ``True``: the last default +value supplied for any particular destination is the one that counts. + +A clearer way to specify default values is the :meth:`set_defaults` method of +OptionParser, which you can call at any time before calling :meth:`parse_args`:: + + parser.set_defaults(verbose=True) + parser.add_option(...) + (options, args) = parser.parse_args() + +As before, the last value specified for a given option destination is the one +that counts. For clarity, try to use one method or the other of setting default +values, not both. + + +.. _optparse-generating-help: + +Generating help +^^^^^^^^^^^^^^^ + +:mod:`optparse`'s ability to generate help and usage text automatically is +useful for creating user-friendly command-line interfaces. All you have to do +is supply a :attr:`~Option.help` value for each option, and optionally a short +usage message for your whole program. Here's an OptionParser populated with +user-friendly (documented) options:: + + usage = "usage: %prog [options] arg1 arg2" + parser = OptionParser(usage=usage) + parser.add_option("-v", "--verbose", + action="store_true", dest="verbose", default=True, + help="make lots of noise [default]") + parser.add_option("-q", "--quiet", + action="store_false", dest="verbose", + help="be vewwy quiet (I'm hunting wabbits)") + parser.add_option("-f", "--filename", + metavar="FILE", help="write output to FILE") + parser.add_option("-m", "--mode", + default="intermediate", + help="interaction mode: novice, intermediate, " + "or expert [default: %default]") + +If :mod:`optparse` encounters either ``-h`` or ``--help`` on the +command-line, or if you just call :meth:`parser.print_help`, it prints the +following to standard output: + +.. code-block:: text + + Usage: [options] arg1 arg2 + + Options: + -h, --help show this help message and exit + -v, --verbose make lots of noise [default] + -q, --quiet be vewwy quiet (I'm hunting wabbits) + -f FILE, --filename=FILE + write output to FILE + -m MODE, --mode=MODE interaction mode: novice, intermediate, or + expert [default: intermediate] + +(If the help output is triggered by a help option, :mod:`optparse` exits after +printing the help text.) + +There's a lot going on here to help :mod:`optparse` generate the best possible +help message: + +* the script defines its own usage message:: + + usage = "usage: %prog [options] arg1 arg2" + + :mod:`optparse` expands ``%prog`` in the usage string to the name of the + current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string + is then printed before the detailed option help. + + If you don't supply a usage string, :mod:`optparse` uses a bland but sensible + default: ``"Usage: %prog [options]"``, which is fine if your script doesn't + take any positional arguments. + +* every option defines a help string, and doesn't worry about + line-wrapping---\ :mod:`optparse` takes care of wrapping lines and making + the help output look good. + +* options that take a value indicate this fact in their automatically-generated + help message, e.g. for the "mode" option:: + + -m MODE, --mode=MODE + + Here, "MODE" is called the meta-variable: it stands for the argument that the + user is expected to supply to ``-m``/``--mode``. By default, + :mod:`optparse` converts the destination variable name to uppercase and uses + that for the meta-variable. Sometimes, that's not what you want---for + example, the ``--filename`` option explicitly sets ``metavar="FILE"``, + resulting in this automatically-generated option description:: + + -f FILE, --filename=FILE + + This is important for more than just saving space, though: the manually + written help text uses the meta-variable ``FILE`` to clue the user in that + there's a connection between the semi-formal syntax ``-f FILE`` and the informal + semantic description "write output to FILE". This is a simple but effective + way to make your help text a lot clearer and more useful for end users. + +* options that have a default value can include ``%default`` in the help + string---\ :mod:`optparse` will replace it with :func:`str` of the option's + default value. If an option has no default value (or the default value is + ``None``), ``%default`` expands to ``none``. + +Grouping Options +++++++++++++++++ + +When dealing with many options, it is convenient to group these options for +better help output. An :class:`OptionParser` can contain several option groups, +each of which can contain several options. + +An option group is obtained using the class :class:`OptionGroup`: + +.. class:: OptionGroup(parser, title, description=None) + + where + + * parser is the :class:`OptionParser` instance the group will be inserted in + to + * title is the group title + * description, optional, is a long description of the group + +:class:`OptionGroup` inherits from :class:`OptionContainer` (like +:class:`OptionParser`) and so the :meth:`add_option` method can be used to add +an option to the group. + +Once all the options are declared, using the :class:`OptionParser` method +:meth:`add_option_group` the group is added to the previously defined parser. + +Continuing with the parser defined in the previous section, adding an +:class:`OptionGroup` to a parser is easy:: + + group = OptionGroup(parser, "Dangerous Options", + "Caution: use these options at your own risk. " + "It is believed that some of them bite.") + group.add_option("-g", action="store_true", help="Group option.") + parser.add_option_group(group) + +This would result in the following help output: + +.. code-block:: text + + Usage: [options] arg1 arg2 + + Options: + -h, --help show this help message and exit + -v, --verbose make lots of noise [default] + -q, --quiet be vewwy quiet (I'm hunting wabbits) + -f FILE, --filename=FILE + write output to FILE + -m MODE, --mode=MODE interaction mode: novice, intermediate, or + expert [default: intermediate] + + Dangerous Options: + Caution: use these options at your own risk. It is believed that some + of them bite. + + -g Group option. + +A bit more complete example might involve using more than one group: still +extending the previous example:: + + group = OptionGroup(parser, "Dangerous Options", + "Caution: use these options at your own risk. " + "It is believed that some of them bite.") + group.add_option("-g", action="store_true", help="Group option.") + parser.add_option_group(group) + + group = OptionGroup(parser, "Debug Options") + group.add_option("-d", "--debug", action="store_true", + help="Print debug information") + group.add_option("-s", "--sql", action="store_true", + help="Print all SQL statements executed") + group.add_option("-e", action="store_true", help="Print every action done") + parser.add_option_group(group) + +that results in the following output: + +.. code-block:: text + + Usage: [options] arg1 arg2 + + Options: + -h, --help show this help message and exit + -v, --verbose make lots of noise [default] + -q, --quiet be vewwy quiet (I'm hunting wabbits) + -f FILE, --filename=FILE + write output to FILE + -m MODE, --mode=MODE interaction mode: novice, intermediate, or expert + [default: intermediate] + + Dangerous Options: + Caution: use these options at your own risk. It is believed that some + of them bite. + + -g Group option. + + Debug Options: + -d, --debug Print debug information + -s, --sql Print all SQL statements executed + -e Print every action done + +Another interesting method, in particular when working programmatically with +option groups is: + +.. method:: OptionParser.get_option_group(opt_str) + + Return the :class:`OptionGroup` to which the short or long option + string *opt_str* (e.g. ``'-o'`` or ``'--option'``) belongs. If + there's no such :class:`OptionGroup`, return ``None``. + +.. _optparse-printing-version-string: + +Printing a version string +^^^^^^^^^^^^^^^^^^^^^^^^^ + +Similar to the brief usage string, :mod:`optparse` can also print a version +string for your program. You have to supply the string as the ``version`` +argument to OptionParser:: + + parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0") + +``%prog`` is expanded just like it is in ``usage``. Apart from that, +``version`` can contain anything you like. When you supply it, :mod:`optparse` +automatically adds a ``--version`` option to your parser. If it encounters +this option on the command line, it expands your ``version`` string (by +replacing ``%prog``), prints it to stdout, and exits. + +For example, if your script is called ``/usr/bin/foo``: + +.. code-block:: shell-session + + $ /usr/bin/foo --version + foo 1.0 + +The following two methods can be used to print and get the ``version`` string: + +.. method:: OptionParser.print_version(file=None) + + Print the version message for the current program (``self.version``) to + *file* (default stdout). As with :meth:`print_usage`, any occurrence + of ``%prog`` in ``self.version`` is replaced with the name of the current + program. Does nothing if ``self.version`` is empty or undefined. + +.. method:: OptionParser.get_version() + + Same as :meth:`print_version` but returns the version string instead of + printing it. + + +.. _optparse-how-optparse-handles-errors: + +How :mod:`optparse` handles errors +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +There are two broad classes of errors that :mod:`optparse` has to worry about: +programmer errors and user errors. Programmer errors are usually erroneous +calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown +option attributes, missing option attributes, etc. These are dealt with in the +usual way: raise an exception (either :exc:`optparse.OptionError` or +:exc:`TypeError`) and let the program crash. + +Handling user errors is much more important, since they are guaranteed to happen +no matter how stable your code is. :mod:`optparse` can automatically detect +some user errors, such as bad option arguments (passing ``-n 4x`` where +``-n`` takes an integer argument), missing arguments (``-n`` at the end +of the command line, where ``-n`` takes an argument of any type). Also, +you can call :func:`OptionParser.error` to signal an application-defined error +condition:: + + (options, args) = parser.parse_args() + ... + if options.a and options.b: + parser.error("options -a and -b are mutually exclusive") + +In either case, :mod:`optparse` handles the error the same way: it prints the +program's usage message and an error message to standard error and exits with +error status 2. + +Consider the first example above, where the user passes ``4x`` to an option +that takes an integer: + +.. code-block:: shell-session + + $ /usr/bin/foo -n 4x + Usage: foo [options] + + foo: error: option -n: invalid integer value: '4x' + +Or, where the user fails to pass a value at all: + +.. code-block:: shell-session + + $ /usr/bin/foo -n + Usage: foo [options] + + foo: error: -n option requires an argument + +:mod:`optparse`\ -generated error messages take care always to mention the +option involved in the error; be sure to do the same when calling +:func:`OptionParser.error` from your application code. + +If :mod:`optparse`'s default error-handling behaviour does not suit your needs, +you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit` +and/or :meth:`~OptionParser.error` methods. + + +.. _optparse-putting-it-all-together: + +Putting it all together +^^^^^^^^^^^^^^^^^^^^^^^ + +Here's what :mod:`optparse`\ -based scripts usually look like:: + + from optparse import OptionParser + ... + def main(): + usage = "usage: %prog [options] arg" + parser = OptionParser(usage) + parser.add_option("-f", "--file", dest="filename", + help="read data from FILENAME") + parser.add_option("-v", "--verbose", + action="store_true", dest="verbose") + parser.add_option("-q", "--quiet", + action="store_false", dest="verbose") + ... + (options, args) = parser.parse_args() + if len(args) != 1: + parser.error("incorrect number of arguments") + if options.verbose: + print("reading %s..." % options.filename) + ... + + if __name__ == "__main__": + main() + + +.. _optparse-reference-guide: + +Reference Guide +--------------- + + +.. _optparse-creating-parser: + +Creating the parser +^^^^^^^^^^^^^^^^^^^ + +The first step in using :mod:`optparse` is to create an OptionParser instance. + +.. class:: OptionParser(...) + + The OptionParser constructor has no required arguments, but a number of + optional keyword arguments. You should always pass them as keyword + arguments, i.e. do not rely on the order in which the arguments are declared. + + ``usage`` (default: ``"%prog [options]"``) + The usage summary to print when your program is run incorrectly or with a + help option. When :mod:`optparse` prints the usage string, it expands + ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you + passed that keyword argument). To suppress a usage message, pass the + special value :data:`optparse.SUPPRESS_USAGE`. + + ``option_list`` (default: ``[]``) + A list of Option objects to populate the parser with. The options in + ``option_list`` are added after any options in ``standard_option_list`` (a + class attribute that may be set by OptionParser subclasses), but before + any version or help options. Deprecated; use :meth:`add_option` after + creating the parser instead. + + ``option_class`` (default: optparse.Option) + Class to use when adding options to the parser in :meth:`add_option`. + + ``version`` (default: ``None``) + A version string to print when the user supplies a version option. If you + supply a true value for ``version``, :mod:`optparse` automatically adds a + version option with the single option string ``--version``. The + substring ``%prog`` is expanded the same as for ``usage``. + + ``conflict_handler`` (default: ``"error"``) + Specifies what to do when options with conflicting option strings are + added to the parser; see section + :ref:`optparse-conflicts-between-options`. + + ``description`` (default: ``None``) + A paragraph of text giving a brief overview of your program. + :mod:`optparse` reformats this paragraph to fit the current terminal width + and prints it when the user requests help (after ``usage``, but before the + list of options). + + ``formatter`` (default: a new :class:`IndentedHelpFormatter`) + An instance of optparse.HelpFormatter that will be used for printing help + text. :mod:`optparse` provides two concrete classes for this purpose: + IndentedHelpFormatter and TitledHelpFormatter. + + ``add_help_option`` (default: ``True``) + If true, :mod:`optparse` will add a help option (with option strings ``-h`` + and ``--help``) to the parser. + + ``prog`` + The string to use when expanding ``%prog`` in ``usage`` and ``version`` + instead of ``os.path.basename(sys.argv[0])``. + + ``epilog`` (default: ``None``) + A paragraph of help text to print after the option help. + +.. _optparse-populating-parser: + +Populating the parser +^^^^^^^^^^^^^^^^^^^^^ + +There are several ways to populate the parser with options. The preferred way +is by using :meth:`OptionParser.add_option`, as shown in section +:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways: + +* pass it an Option instance (as returned by :func:`make_option`) + +* pass it any combination of positional and keyword arguments that are + acceptable to :func:`make_option` (i.e., to the Option constructor), and it + will create the Option instance for you + +The other alternative is to pass a list of pre-constructed Option instances to +the OptionParser constructor, as in:: + + option_list = [ + make_option("-f", "--filename", + action="store", type="string", dest="filename"), + make_option("-q", "--quiet", + action="store_false", dest="verbose"), + ] + parser = OptionParser(option_list=option_list) + +(:func:`make_option` is a factory function for creating Option instances; +currently it is an alias for the Option constructor. A future version of +:mod:`optparse` may split Option into several classes, and :func:`make_option` +will pick the right class to instantiate. Do not instantiate Option directly.) + + +.. _optparse-defining-options: + +Defining options +^^^^^^^^^^^^^^^^ + +Each Option instance represents a set of synonymous command-line option strings, +e.g. ``-f`` and ``--file``. You can specify any number of short or +long option strings, but you must specify at least one overall option string. + +The canonical way to create an :class:`Option` instance is with the +:meth:`add_option` method of :class:`OptionParser`. + +.. method:: OptionParser.add_option(option) + OptionParser.add_option(*opt_str, attr=value, ...) + + To define an option with only a short option string:: + + parser.add_option("-f", attr=value, ...) + + And to define an option with only a long option string:: + + parser.add_option("--foo", attr=value, ...) + + The keyword arguments define attributes of the new Option object. The most + important option attribute is :attr:`~Option.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 :exc:`OptionError` exception explaining your mistake. + + An option's *action* determines what :mod:`optparse` does when it encounters + this option on the command-line. The standard option actions hard-coded into + :mod:`optparse` are: + + ``"store"`` + store this option's argument (default) + + ``"store_const"`` + store a constant value + + ``"store_true"`` + store ``True`` + + ``"store_false"`` + store ``False`` + + ``"append"`` + append this option's argument to a list + + ``"append_const"`` + append a constant value to a list + + ``"count"`` + increment a counter by one + + ``"callback"`` + call a specified function + + ``"help"`` + print a usage message including all options and the documentation for them + + (If you don't supply an action, the default is ``"store"``. For this action, + you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option + attributes; see :ref:`optparse-standard-option-actions`.) + +As you can see, most actions involve storing or updating a value somewhere. +:mod:`optparse` always creates a special object for this, conventionally called +``options`` (it happens to be an instance of :class:`optparse.Values`). Option +arguments (and various other values) are stored as attributes of this object, +according to the :attr:`~Option.dest` (destination) option attribute. + +For example, when you call :: + + parser.parse_args() + +one of the first things :mod:`optparse` does is create the ``options`` object:: + + options = Values() + +If one of the options in this parser is defined with :: + + parser.add_option("-f", "--file", action="store", type="string", dest="filename") + +and the command-line being parsed includes any of the following:: + + -ffoo + -f foo + --file=foo + --file foo + +then :mod:`optparse`, on seeing this option, will do the equivalent of :: + + options.filename = "foo" + +The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost +as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only +one that makes sense for *all* options. + + +.. _optparse-option-attributes: + +Option attributes +^^^^^^^^^^^^^^^^^ + +The following option attributes may be passed as keyword arguments to +:meth:`OptionParser.add_option`. If you pass an option attribute that is not +relevant to a particular option, or fail to pass a required option attribute, +:mod:`optparse` raises :exc:`OptionError`. + +.. attribute:: Option.action + + (default: ``"store"``) + + Determines :mod:`optparse`'s behaviour when this option is seen on the + command line; the available options are documented :ref:`here + `. + +.. attribute:: Option.type + + (default: ``"string"``) + + The argument type expected by this option (e.g., ``"string"`` or ``"int"``); + the available option types are documented :ref:`here + `. + +.. attribute:: Option.dest + + (default: derived from option strings) + + If the option's action implies writing or modifying a value somewhere, this + tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an + attribute of the ``options`` object that :mod:`optparse` builds as it parses + the command line. + +.. attribute:: Option.default + + The value to use for this option's destination if the option is not seen on + the command line. See also :meth:`OptionParser.set_defaults`. + +.. attribute:: Option.nargs + + (default: 1) + + How many arguments of type :attr:`~Option.type` should be consumed when this + option is seen. If > 1, :mod:`optparse` will store a tuple of values to + :attr:`~Option.dest`. + +.. attribute:: Option.const + + For actions that store a constant value, the constant value to store. + +.. attribute:: Option.choices + + For options of type ``"choice"``, the list of strings the user may choose + from. + +.. attribute:: Option.callback + + For options with action ``"callback"``, the callable to call when this option + is seen. See section :ref:`optparse-option-callbacks` for detail on the + arguments passed to the callable. + +.. attribute:: Option.callback_args + Option.callback_kwargs + + Additional positional and keyword arguments to pass to ``callback`` after the + four standard callback arguments. + +.. attribute:: Option.help + + Help text to print for this option when listing all available options after + the user supplies a :attr:`~Option.help` option (such as ``--help``). If + no help text is supplied, the option will be listed without help text. To + hide this option, use the special value :data:`optparse.SUPPRESS_HELP`. + +.. attribute:: Option.metavar + + (default: derived from option strings) + + Stand-in for the option argument(s) to use when printing help text. See + section :ref:`optparse-tutorial` for an example. + + +.. _optparse-standard-option-actions: + +Standard option actions +^^^^^^^^^^^^^^^^^^^^^^^ + +The various option actions all have slightly different requirements and effects. +Most actions have several relevant option attributes which you may specify to +guide :mod:`optparse`'s behaviour; a few have required attributes, which you +must specify for any option using that action. + +* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`, + :attr:`~Option.nargs`, :attr:`~Option.choices`] + + The option must be followed by an argument, which is converted to a value + according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If + :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the + command line; all will be converted according to :attr:`~Option.type` and + stored to :attr:`~Option.dest` as a tuple. See the + :ref:`optparse-standard-option-types` section. + + If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type + defaults to ``"choice"``. + + If :attr:`~Option.type` is not supplied, it defaults to ``"string"``. + + If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination + from the first long option string (e.g., ``--foo-bar`` implies + ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a + destination from the first short option string (e.g., ``-f`` implies ``f``). + + Example:: + + parser.add_option("-f") + parser.add_option("-p", type="float", nargs=3, dest="point") + + As it parses the command line :: + + -f foo.txt -p 1 -3.5 4 -fbar.txt + + :mod:`optparse` will set :: + + options.f = "foo.txt" + options.point = (1.0, -3.5, 4.0) + options.f = "bar.txt" + +* ``"store_const"`` [required: :attr:`~Option.const`; relevant: + :attr:`~Option.dest`] + + The value :attr:`~Option.const` is stored in :attr:`~Option.dest`. + + Example:: + + parser.add_option("-q", "--quiet", + action="store_const", const=0, dest="verbose") + parser.add_option("-v", "--verbose", + action="store_const", const=1, dest="verbose") + parser.add_option("--noisy", + action="store_const", const=2, dest="verbose") + + If ``--noisy`` is seen, :mod:`optparse` will set :: + + options.verbose = 2 + +* ``"store_true"`` [relevant: :attr:`~Option.dest`] + + A special case of ``"store_const"`` that stores ``True`` to + :attr:`~Option.dest`. + +* ``"store_false"`` [relevant: :attr:`~Option.dest`] + + Like ``"store_true"``, but stores ``False``. + + Example:: + + parser.add_option("--clobber", action="store_true", dest="clobber") + parser.add_option("--no-clobber", action="store_false", dest="clobber") + +* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`, + :attr:`~Option.nargs`, :attr:`~Option.choices`] + + The option must be followed by an argument, which is appended to the list in + :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is + supplied, an empty list is automatically created when :mod:`optparse` first + encounters this option on the command-line. If :attr:`~Option.nargs` > 1, + multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs` + is appended to :attr:`~Option.dest`. + + The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as + for the ``"store"`` action. + + Example:: + + parser.add_option("-t", "--tracks", action="append", type="int") + + If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent + of:: + + options.tracks = [] + options.tracks.append(int("3")) + + If, a little later on, ``--tracks=4`` is seen, it does:: + + options.tracks.append(int("4")) + + The ``append`` action calls the ``append`` method on the current value of the + option. This means that any default value specified must have an ``append`` + method. It also means that if the default value is non-empty, the default + elements will be present in the parsed value for the option, with any values + from the command line appended after those default values:: + + >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults']) + >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg']) + >>> opts.files + ['~/.mypkg/defaults', 'overrides.mypkg'] + +* ``"append_const"`` [required: :attr:`~Option.const`; relevant: + :attr:`~Option.dest`] + + Like ``"store_const"``, but the value :attr:`~Option.const` is appended to + :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to + ``None``, and an empty list is automatically created the first time the option + is encountered. + +* ``"count"`` [relevant: :attr:`~Option.dest`] + + Increment the integer stored at :attr:`~Option.dest`. If no default value is + supplied, :attr:`~Option.dest` is set to zero before being incremented the + first time. + + Example:: + + parser.add_option("-v", action="count", dest="verbosity") + + The first time ``-v`` is seen on the command line, :mod:`optparse` does the + equivalent of:: + + options.verbosity = 0 + options.verbosity += 1 + + Every subsequent occurrence of ``-v`` results in :: + + options.verbosity += 1 + +* ``"callback"`` [required: :attr:`~Option.callback`; relevant: + :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`, + :attr:`~Option.callback_kwargs`] + + Call the function specified by :attr:`~Option.callback`, which is called as :: + + func(option, opt_str, value, parser, *args, **kwargs) + + See section :ref:`optparse-option-callbacks` for more detail. + +* ``"help"`` + + Prints a complete help message for all the options in the current option + parser. The help message is constructed from the ``usage`` string passed to + OptionParser's constructor and the :attr:`~Option.help` string passed to every + option. + + If no :attr:`~Option.help` string is supplied for an option, it will still be + listed in the help message. To omit an option entirely, use the special value + :data:`optparse.SUPPRESS_HELP`. + + :mod:`optparse` automatically adds a :attr:`~Option.help` option to all + OptionParsers, so you do not normally need to create one. + + Example:: + + from optparse import OptionParser, SUPPRESS_HELP + + # usually, a help option is added automatically, but that can + # be suppressed using the add_help_option argument + parser = OptionParser(add_help_option=False) + + parser.add_option("-h", "--help", action="help") + parser.add_option("-v", action="store_true", dest="verbose", + help="Be moderately verbose") + parser.add_option("--file", dest="filename", + help="Input file to read data from") + parser.add_option("--secret", help=SUPPRESS_HELP) + + If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line, + it will print something like the following help message to stdout (assuming + ``sys.argv[0]`` is ``"foo.py"``): + + .. code-block:: text + + Usage: foo.py [options] + + Options: + -h, --help Show this help message and exit + -v Be moderately verbose + --file=FILENAME Input file to read data from + + After printing the help message, :mod:`optparse` terminates your process with + ``sys.exit(0)``. + +* ``"version"`` + + Prints the version number supplied to the OptionParser to stdout and exits. + The version number is actually formatted and printed by the + ``print_version()`` method of OptionParser. Generally only relevant if the + ``version`` argument is supplied to the OptionParser constructor. As with + :attr:`~Option.help` options, you will rarely create ``version`` options, + since :mod:`optparse` automatically adds them when needed. + + +.. _optparse-standard-option-types: + +Standard option types +^^^^^^^^^^^^^^^^^^^^^ + +:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``, +``"choice"``, ``"float"`` and ``"complex"``. If you need to add new +option types, see section :ref:`optparse-extending-optparse`. + +Arguments to string options are not checked or converted in any way: the text on +the command line is stored in the destination (or passed to the callback) as-is. + +Integer arguments (type ``"int"``) are parsed as follows: + +* if the number starts with ``0x``, it is parsed as a hexadecimal number + +* if the number starts with ``0``, it is parsed as an octal number + +* if the number starts with ``0b``, it is parsed as a binary number + +* otherwise, the number is parsed as a decimal number + + +The conversion is done by calling :func:`int` with the appropriate base (2, 8, +10, or 16). If this fails, so will :mod:`optparse`, although with a more useful +error message. + +``"float"`` and ``"complex"`` option arguments are converted directly with +:func:`float` and :func:`complex`, with similar error-handling. + +``"choice"`` options are a subtype of ``"string"`` options. The +:attr:`~Option.choices` option attribute (a sequence of strings) defines the +set of allowed option arguments. :func:`optparse.check_choice` compares +user-supplied option arguments against this master list and raises +:exc:`OptionValueError` if an invalid string is given. + + +.. _optparse-parsing-arguments: + +Parsing arguments +^^^^^^^^^^^^^^^^^ + +The whole point of creating and populating an OptionParser is to call its +:meth:`parse_args` method:: + + (options, args) = parser.parse_args(args=None, values=None) + +where the input parameters are + +``args`` + the list of arguments to process (default: ``sys.argv[1:]``) + +``values`` + an :class:`optparse.Values` object to store option arguments in (default: a + new instance of :class:`Values`) -- if you give an existing object, the + option defaults will not be initialized on it + +and the return values are + +``options`` + the same object that was passed in as ``values``, or the optparse.Values + instance created by :mod:`optparse` + +``args`` + the leftover positional arguments after all options have been processed + +The most common usage is to supply neither keyword argument. If you supply +``values``, it will be modified with repeated :func:`setattr` calls (roughly one +for every option argument stored to an option destination) and returned by +:meth:`parse_args`. + +If :meth:`parse_args` encounters any errors in the argument list, it calls the +OptionParser's :meth:`error` method with an appropriate end-user error message. +This ultimately terminates your process with an exit status of 2 (the +traditional Unix exit status for command-line errors). + + +.. _optparse-querying-manipulating-option-parser: + +Querying and manipulating your option parser +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The default behavior of the option parser can be customized slightly, and you +can also poke around your option parser and see what's there. OptionParser +provides several methods to help you out: + +.. method:: OptionParser.disable_interspersed_args() + + Set parsing to stop on the first non-option. For example, if ``-a`` and + ``-b`` are both simple options that take no arguments, :mod:`optparse` + normally accepts this syntax:: + + prog -a arg1 -b arg2 + + and treats it as equivalent to :: + + prog -a -b arg1 arg2 + + To disable this feature, call :meth:`disable_interspersed_args`. This + restores traditional Unix syntax, where option parsing stops with the first + non-option argument. + + Use this if you have a command processor which runs another command which has + options of its own and you want to make sure these options don't get + confused. For example, each command might have a different set of options. + +.. method:: OptionParser.enable_interspersed_args() + + Set parsing to not stop on the first non-option, allowing interspersing + switches with command arguments. This is the default behavior. + +.. method:: OptionParser.get_option(opt_str) + + Returns the Option instance with the option string *opt_str*, or ``None`` if + no options have that option string. + +.. method:: OptionParser.has_option(opt_str) + + Return ``True`` if the OptionParser has an option with option string *opt_str* + (e.g., ``-q`` or ``--verbose``). + +.. method:: OptionParser.remove_option(opt_str) + + If the :class:`OptionParser` has an option corresponding to *opt_str*, that + option is removed. If that option provided any other option strings, all of + those option strings become invalid. If *opt_str* does not occur in any + option belonging to this :class:`OptionParser`, raises :exc:`ValueError`. + + +.. _optparse-conflicts-between-options: + +Conflicts between options +^^^^^^^^^^^^^^^^^^^^^^^^^ + +If you're not careful, it's easy to define options with conflicting option +strings:: + + parser.add_option("-n", "--dry-run", ...) + ... + parser.add_option("-n", "--noisy", ...) + +(This is particularly true if you've defined your own OptionParser subclass with +some standard options.) + +Every time you add an option, :mod:`optparse` checks for conflicts with existing +options. If it finds any, it invokes the current conflict-handling mechanism. +You can set the conflict-handling mechanism either in the constructor:: + + parser = OptionParser(..., conflict_handler=handler) + +or with a separate call:: + + parser.set_conflict_handler(handler) + +The available conflict handlers are: + + ``"error"`` (default) + assume option conflicts are a programming error and raise + :exc:`OptionConflictError` + + ``"resolve"`` + resolve option conflicts intelligently (see below) + + +As an example, let's define an :class:`OptionParser` that resolves conflicts +intelligently and add conflicting options to it:: + + parser = OptionParser(conflict_handler="resolve") + parser.add_option("-n", "--dry-run", ..., help="do no harm") + parser.add_option("-n", "--noisy", ..., help="be noisy") + +At this point, :mod:`optparse` detects that a previously-added option is already +using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``, +it resolves the situation by removing ``-n`` from the earlier option's list of +option strings. Now ``--dry-run`` is the only way for the user to activate +that option. If the user asks for help, the help message will reflect that:: + + Options: + --dry-run do no harm + ... + -n, --noisy be noisy + +It's possible to whittle away the option strings for a previously-added option +until there are none left, and the user has no way of invoking that option from +the command-line. In that case, :mod:`optparse` removes that option completely, +so it doesn't show up in help text or anywhere else. Carrying on with our +existing OptionParser:: + + parser.add_option("--dry-run", ..., help="new dry-run option") + +At this point, the original ``-n``/``--dry-run`` option is no longer +accessible, so :mod:`optparse` removes it, leaving this help text:: + + Options: + ... + -n, --noisy be noisy + --dry-run new dry-run option + + +.. _optparse-cleanup: + +Cleanup +^^^^^^^ + +OptionParser instances have several cyclic references. This should not be a +problem for Python's garbage collector, but you may wish to break the cyclic +references explicitly by calling :meth:`~OptionParser.destroy` on your +OptionParser once you are done with it. This is particularly useful in +long-running applications where large object graphs are reachable from your +OptionParser. + + +.. _optparse-other-methods: + +Other methods +^^^^^^^^^^^^^ + +OptionParser supports several other public methods: + +.. method:: OptionParser.set_usage(usage) + + Set the usage string according to the rules described above for the ``usage`` + constructor keyword argument. Passing ``None`` sets the default usage + string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message. + +.. method:: OptionParser.print_usage(file=None) + + Print the usage message for the current program (``self.usage``) to *file* + (default stdout). Any occurrence of the string ``%prog`` in ``self.usage`` + is replaced with the name of the current program. Does nothing if + ``self.usage`` is empty or not defined. + +.. method:: OptionParser.get_usage() + + Same as :meth:`print_usage` but returns the usage string instead of + printing it. + +.. method:: OptionParser.set_defaults(dest=value, ...) + + Set default values for several option destinations at once. Using + :meth:`set_defaults` is the preferred way to set default values for options, + since multiple options can share the same destination. For example, if + several "mode" options all set the same destination, any one of them can set + the default, and the last one wins:: + + parser.add_option("--advanced", action="store_const", + dest="mode", const="advanced", + default="novice") # overridden below + parser.add_option("--novice", action="store_const", + dest="mode", const="novice", + default="advanced") # overrides above setting + + To avoid this confusion, use :meth:`set_defaults`:: + + parser.set_defaults(mode="advanced") + parser.add_option("--advanced", action="store_const", + dest="mode", const="advanced") + parser.add_option("--novice", action="store_const", + dest="mode", const="novice") + + +.. _optparse-option-callbacks: + +Option Callbacks +---------------- + +When :mod:`optparse`'s built-in actions and types aren't quite enough for your +needs, you have two choices: extend :mod:`optparse` or define a callback option. +Extending :mod:`optparse` is more general, but overkill for a lot of simple +cases. Quite often a simple callback is all you need. + +There are two steps to defining a callback option: + +* define the option itself using the ``"callback"`` action + +* write the callback; this is a function (or method) that takes at least four + arguments, as described below + + +.. _optparse-defining-callback-option: + +Defining a callback option +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +As always, the easiest way to define a callback option is by using the +:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the +only option attribute you must specify is ``callback``, the function to call:: + + parser.add_option("-c", action="callback", callback=my_callback) + +``callback`` is a function (or other callable object), so you must have already +defined ``my_callback()`` when you create this callback option. In this simple +case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments, +which usually means that the option takes no arguments---the mere presence of +``-c`` on the command-line is all it needs to know. In some +circumstances, though, you might want your callback to consume an arbitrary +number of command-line arguments. This is where writing callbacks gets tricky; +it's covered later in this section. + +:mod:`optparse` always passes four particular arguments to your callback, and it +will only pass additional arguments if you specify them via +:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the +minimal callback function signature is:: + + def my_callback(option, opt, value, parser): + +The four arguments to a callback are described below. + +There are several other option attributes that you can supply when you define a +callback option: + +:attr:`~Option.type` + has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it + instructs :mod:`optparse` to consume one argument and convert it to + :attr:`~Option.type`. Rather than storing the converted value(s) anywhere, + though, :mod:`optparse` passes it to your callback function. + +:attr:`~Option.nargs` + also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will + consume :attr:`~Option.nargs` arguments, each of which must be convertible to + :attr:`~Option.type`. It then passes a tuple of converted values to your + callback. + +:attr:`~Option.callback_args` + a tuple of extra positional arguments to pass to the callback + +:attr:`~Option.callback_kwargs` + a dictionary of extra keyword arguments to pass to the callback + + +.. _optparse-how-callbacks-called: + +How callbacks are called +^^^^^^^^^^^^^^^^^^^^^^^^ + +All callbacks are called as follows:: + + func(option, opt_str, value, parser, *args, **kwargs) + +where + +``option`` + is the Option instance that's calling the callback + +``opt_str`` + is the option string seen on the command-line that's triggering the callback. + (If an abbreviated long option was used, ``opt_str`` will be the full, + canonical option string---e.g. if the user puts ``--foo`` on the + command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be + ``"--foobar"``.) + +``value`` + is the argument to this option seen on the command-line. :mod:`optparse` will + only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be + the type implied by the option's type. If :attr:`~Option.type` for this option is + ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs` + > 1, ``value`` will be a tuple of values of the appropriate type. + +``parser`` + is the OptionParser instance driving the whole thing, mainly useful because + you can access some other interesting data through its instance attributes: + + ``parser.largs`` + the current list of leftover arguments, ie. arguments that have been + consumed but are neither options nor option arguments. Feel free to modify + ``parser.largs``, e.g. by adding more arguments to it. (This list will + become ``args``, the second return value of :meth:`parse_args`.) + + ``parser.rargs`` + the current list of remaining arguments, ie. with ``opt_str`` and + ``value`` (if applicable) removed, and only the arguments following them + still there. Feel free to modify ``parser.rargs``, e.g. by consuming more + arguments. + + ``parser.values`` + the object where option values are by default stored (an instance of + optparse.OptionValues). This lets callbacks use the same mechanism as the + rest of :mod:`optparse` for storing option values; you don't need to mess + around with globals or closures. You can also access or modify the + value(s) of any options already encountered on the command-line. + +``args`` + is a tuple of arbitrary positional arguments supplied via the + :attr:`~Option.callback_args` option attribute. + +``kwargs`` + is a dictionary of arbitrary keyword arguments supplied via + :attr:`~Option.callback_kwargs`. + + +.. _optparse-raising-errors-in-callback: + +Raising errors in a callback +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The callback function should raise :exc:`OptionValueError` if there are any +problems with the option or its argument(s). :mod:`optparse` catches this and +terminates the program, printing the error message you supply to stderr. Your +message should be clear, concise, accurate, and mention the option at fault. +Otherwise, the user will have a hard time figuring out what they did wrong. + + +.. _optparse-callback-example-1: + +Callback example 1: trivial callback +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Here's an example of a callback option that takes no arguments, and simply +records that the option was seen:: + + def record_foo_seen(option, opt_str, value, parser): + parser.values.saw_foo = True + + parser.add_option("--foo", action="callback", callback=record_foo_seen) + +Of course, you could do that with the ``"store_true"`` action. + + +.. _optparse-callback-example-2: + +Callback example 2: check option order +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Here's a slightly more interesting example: record the fact that ``-a`` is +seen, but blow up if it comes after ``-b`` in the command-line. :: + + def check_order(option, opt_str, value, parser): + if parser.values.b: + raise OptionValueError("can't use -a after -b") + parser.values.a = 1 + ... + parser.add_option("-a", action="callback", callback=check_order) + parser.add_option("-b", action="store_true", dest="b") + + +.. _optparse-callback-example-3: + +Callback example 3: check option order (generalized) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If you want to re-use this callback for several similar options (set a flag, but +blow up if ``-b`` has already been seen), it needs a bit of work: the error +message and the flag that it sets must be generalized. :: + + def check_order(option, opt_str, value, parser): + if parser.values.b: + raise OptionValueError("can't use %s after -b" % opt_str) + setattr(parser.values, option.dest, 1) + ... + parser.add_option("-a", action="callback", callback=check_order, dest='a') + parser.add_option("-b", action="store_true", dest="b") + parser.add_option("-c", action="callback", callback=check_order, dest='c') + + +.. _optparse-callback-example-4: + +Callback example 4: check arbitrary condition +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Of course, you could put any condition in there---you're not limited to checking +the values of already-defined options. For example, if you have options that +should not be called when the moon is full, all you have to do is this:: + + def check_moon(option, opt_str, value, parser): + if is_moon_full(): + raise OptionValueError("%s option invalid when moon is full" + % opt_str) + setattr(parser.values, option.dest, 1) + ... + parser.add_option("--foo", + action="callback", callback=check_moon, dest="foo") + +(The definition of ``is_moon_full()`` is left as an exercise for the reader.) + + +.. _optparse-callback-example-5: + +Callback example 5: fixed arguments +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Things get slightly more interesting when you define callback options that take +a fixed number of arguments. Specifying that a callback option takes arguments +is similar to defining a ``"store"`` or ``"append"`` option: if you define +:attr:`~Option.type`, then the option takes one argument that must be +convertible to that type; if you further define :attr:`~Option.nargs`, then the +option takes :attr:`~Option.nargs` arguments. + +Here's an example that just emulates the standard ``"store"`` action:: + + def store_value(option, opt_str, value, parser): + setattr(parser.values, option.dest, value) + ... + parser.add_option("--foo", + action="callback", callback=store_value, + type="int", nargs=3, dest="foo") + +Note that :mod:`optparse` takes care of consuming 3 arguments and converting +them to integers for you; all you have to do is store them. (Or whatever; +obviously you don't need a callback for this example.) + + +.. _optparse-callback-example-6: + +Callback example 6: variable arguments +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Things get hairy when you want an option to take a variable number of arguments. +For this case, you must write a callback, as :mod:`optparse` doesn't provide any +built-in capabilities for it. And you have to deal with certain intricacies of +conventional Unix command-line parsing that :mod:`optparse` normally handles for +you. In particular, callbacks should implement the conventional rules for bare +``--`` and ``-`` arguments: + +* either ``--`` or ``-`` can be option arguments + +* bare ``--`` (if not the argument to some option): halt command-line + processing and discard the ``--`` + +* bare ``-`` (if not the argument to some option): halt command-line + processing but keep the ``-`` (append it to ``parser.largs``) + +If you want an option that takes a variable number of arguments, there are +several subtle, tricky issues to worry about. The exact implementation you +choose will be based on which trade-offs you're willing to make for your +application (which is why :mod:`optparse` doesn't support this sort of thing +directly). + +Nevertheless, here's a stab at a callback for an option with variable +arguments:: + + def vararg_callback(option, opt_str, value, parser): + assert value is None + value = [] + + def floatable(str): + try: + float(str) + return True + except ValueError: + return False + + for arg in parser.rargs: + # stop on --foo like options + if arg[:2] == "--" and len(arg) > 2: + break + # stop on -a, but not on -3 or -3.0 + if arg[:1] == "-" and len(arg) > 1 and not floatable(arg): + break + value.append(arg) + + del parser.rargs[:len(value)] + setattr(parser.values, option.dest, value) + + ... + parser.add_option("-c", "--callback", dest="vararg_attr", + action="callback", callback=vararg_callback) + + +.. _optparse-extending-optparse: + +Extending :mod:`optparse` +------------------------- + +Since the two major controlling factors in how :mod:`optparse` interprets +command-line options are the action and type of each option, the most likely +direction of extension is to add new actions and new types. + + +.. _optparse-adding-new-types: + +Adding new types +^^^^^^^^^^^^^^^^ + +To add new types, you need to define your own subclass of :mod:`optparse`'s +:class:`Option` class. This class has a couple of attributes that define +:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`. + +.. attribute:: Option.TYPES + + A tuple of type names; in your subclass, simply define a new tuple + :attr:`TYPES` that builds on the standard one. + +.. attribute:: Option.TYPE_CHECKER + + A dictionary mapping type names to type-checking functions. A type-checking + function has the following signature:: + + def check_mytype(option, opt, value) + + where ``option`` is an :class:`Option` instance, ``opt`` is an option string + (e.g., ``-f``), and ``value`` is the string from the command line that must + be checked and converted to your desired type. ``check_mytype()`` should + return an object of the hypothetical type ``mytype``. The value returned by + a type-checking function will wind up in the OptionValues instance returned + by :meth:`OptionParser.parse_args`, or be passed to a callback as the + ``value`` parameter. + + Your type-checking function should raise :exc:`OptionValueError` if it + encounters any problems. :exc:`OptionValueError` takes a single string + argument, which is passed as-is to :class:`OptionParser`'s :meth:`error` + method, which in turn prepends the program name and the string ``"error:"`` + and prints everything to stderr before terminating the process. + +Here's a silly example that demonstrates adding a ``"complex"`` option type to +parse Python-style complex numbers on the command line. (This is even sillier +than it used to be, because :mod:`optparse` 1.3 added built-in support for +complex numbers, but never mind.) + +First, the necessary imports:: + + from copy import copy + from optparse import Option, OptionValueError + +You need to define your type-checker first, since it's referred to later (in the +:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass):: + + def check_complex(option, opt, value): + try: + return complex(value) + except ValueError: + raise OptionValueError( + "option %s: invalid complex value: %r" % (opt, value)) + +Finally, the Option subclass:: + + class MyOption (Option): + TYPES = Option.TYPES + ("complex",) + TYPE_CHECKER = copy(Option.TYPE_CHECKER) + TYPE_CHECKER["complex"] = check_complex + +(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end +up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s +Option class. This being Python, nothing stops you from doing that except good +manners and common sense.) + +That's it! Now you can write a script that uses the new option type just like +any other :mod:`optparse`\ -based script, except you have to instruct your +OptionParser to use MyOption instead of Option:: + + parser = OptionParser(option_class=MyOption) + parser.add_option("-c", type="complex") + +Alternately, you can build your own option list and pass it to OptionParser; if +you don't use :meth:`add_option` in the above way, you don't need to tell +OptionParser which option class to use:: + + option_list = [MyOption("-c", action="store", type="complex", dest="c")] + parser = OptionParser(option_list=option_list) + + +.. _optparse-adding-new-actions: + +Adding new actions +^^^^^^^^^^^^^^^^^^ + +Adding new actions is a bit trickier, because you have to understand that +:mod:`optparse` has a couple of classifications for actions: + +"store" actions + actions that result in :mod:`optparse` storing a value to an attribute of the + current OptionValues instance; these options require a :attr:`~Option.dest` + attribute to be supplied to the Option constructor. + +"typed" actions + actions that take a value from the command line and expect it to be of a + certain type; or rather, a string that can be converted to a certain type. + These options require a :attr:`~Option.type` attribute to the Option + constructor. + +These are overlapping sets: some default "store" actions are ``"store"``, +``"store_const"``, ``"append"``, and ``"count"``, while the default "typed" +actions are ``"store"``, ``"append"``, and ``"callback"``. + +When you add an action, you need to categorize it by listing it in at least one +of the following class attributes of Option (all are lists of strings): + +.. attribute:: Option.ACTIONS + + All actions must be listed in ACTIONS. + +.. attribute:: Option.STORE_ACTIONS + + "store" actions are additionally listed here. + +.. attribute:: Option.TYPED_ACTIONS + + "typed" actions are additionally listed here. + +.. attribute:: Option.ALWAYS_TYPED_ACTIONS + + Actions that always take a type (i.e. whose options always take a value) are + additionally listed here. The only effect of this is that :mod:`optparse` + assigns the default type, ``"string"``, to options with no explicit type + whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`. + +In order to actually implement your new action, you must override Option's +:meth:`take_action` method and add a case that recognizes your action. + +For example, let's add an ``"extend"`` action. This is similar to the standard +``"append"`` action, but instead of taking a single value from the command-line +and appending it to an existing list, ``"extend"`` will take multiple values in +a single comma-delimited string, and extend an existing list with them. That +is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command +line :: + + --names=foo,bar --names blah --names ding,dong + +would result in a list :: + + ["foo", "bar", "blah", "ding", "dong"] + +Again we define a subclass of Option:: + + class MyOption(Option): + + ACTIONS = Option.ACTIONS + ("extend",) + STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",) + TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",) + ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",) + + def take_action(self, action, dest, opt, value, values, parser): + if action == "extend": + lvalue = value.split(",") + values.ensure_value(dest, []).extend(lvalue) + else: + Option.take_action( + self, action, dest, opt, value, values, parser) + +Features of note: + +* ``"extend"`` both expects a value on the command-line and stores that value + somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and + :attr:`~Option.TYPED_ACTIONS`. + +* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to + ``"extend"`` actions, we put the ``"extend"`` action in + :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well. + +* :meth:`MyOption.take_action` implements just this one new action, and passes + control back to :meth:`Option.take_action` for the standard :mod:`optparse` + actions. + +* ``values`` is an instance of the optparse_parser.Values class, which provides + the very useful :meth:`ensure_value` method. :meth:`ensure_value` is + essentially :func:`getattr` with a safety valve; it is called as :: + + values.ensure_value(attr, value) + + If the ``attr`` attribute of ``values`` doesn't exist or is ``None``, then + ensure_value() first sets it to ``value``, and then returns 'value. This is + very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all + of which accumulate data in a variable and expect that variable to be of a + certain type (a list for the first two, an integer for the latter). Using + :meth:`ensure_value` means that scripts using your action don't have to worry + about setting a default value for the option destinations in question; they + can just leave the default as ``None`` and :meth:`ensure_value` will take care of + getting it right when it's needed. diff --git a/cpython_2/environment/repo/Doc/library/os.path.rst b/cpython_2/environment/repo/Doc/library/os.path.rst new file mode 100644 index 0000000000000000000000000000000000000000..a5abacf02144a765113763718cb4cbc76f339107 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/os.path.rst @@ -0,0 +1,478 @@ +:mod:`os.path` --- Common pathname manipulations +================================================ + +.. module:: os.path + :synopsis: Operations on pathnames. + +**Source code:** :source:`Lib/posixpath.py` (for POSIX) and +:source:`Lib/ntpath.py` (for Windows NT). + +.. index:: single: path; operations + +-------------- + +This module implements some useful functions on pathnames. To read or +write files see :func:`open`, and for accessing the filesystem see the +:mod:`os` module. The path parameters can be passed as either strings, +or bytes. Applications are encouraged to represent file names as +(Unicode) character strings. Unfortunately, some file names may not be +representable as strings on Unix, so applications that need to support +arbitrary file names on Unix should use bytes objects to represent +path names. Vice versa, using bytes objects cannot represent all file +names on Windows (in the standard ``mbcs`` encoding), hence Windows +applications should use string objects to access all files. + +Unlike a unix shell, Python does not do any *automatic* path expansions. +Functions such as :func:`expanduser` and :func:`expandvars` can be invoked +explicitly when an application desires shell-like path expansion. (See also +the :mod:`glob` module.) + + +.. seealso:: + The :mod:`pathlib` module offers high-level path objects. + + +.. note:: + + All of these functions accept either only bytes or only string objects as + their parameters. The result is an object of the same type, if a path or + file name is returned. + + +.. note:: + + Since different operating systems have different path name conventions, there + are several versions of this module in the standard library. The + :mod:`os.path` module is always the path module suitable for the operating + system Python is running on, and therefore usable for local paths. However, + you can also import and use the individual modules if you want to manipulate + a path that is *always* in one of the different formats. They all have the + same interface: + + * :mod:`posixpath` for UNIX-style paths + * :mod:`ntpath` for Windows paths + + +.. versionchanged:: 3.8 + + :func:`exists`, :func:`lexists`, :func:`isdir`, :func:`isfile`, + :func:`islink`, and :func:`ismount` now return ``False`` instead of + raising an exception for paths that contain characters or bytes + unrepresentable at the OS level. + + +.. function:: abspath(path) + + Return a normalized absolutized version of the pathname *path*. On most + platforms, this is equivalent to calling the function :func:`normpath` as + follows: ``normpath(join(os.getcwd(), path))``. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: basename(path) + + Return the base name of pathname *path*. This is the second element of the + pair returned by passing *path* to the function :func:`split`. Note that + the result of this function is different + from the Unix :program:`basename` program; where :program:`basename` for + ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an + empty string (``''``). + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: commonpath(paths) + + Return the longest common sub-path of each pathname in the sequence + *paths*. Raise :exc:`ValueError` if *paths* contain both absolute + and relative pathnames, the *paths* are on the different drives or + if *paths* is empty. Unlike :func:`commonprefix`, this returns a + valid path. + + .. availability:: Unix, Windows. + + .. versionadded:: 3.5 + + .. versionchanged:: 3.6 + Accepts a sequence of :term:`path-like objects `. + + +.. function:: commonprefix(list) + + Return the longest path prefix (taken character-by-character) that is a + prefix of all paths in *list*. If *list* is empty, return the empty string + (``''``). + + .. note:: + + This function may return invalid paths because it works a + character at a time. To obtain a valid path, see + :func:`commonpath`. + + :: + + >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib']) + '/usr/l' + + >>> os.path.commonpath(['/usr/lib', '/usr/local/lib']) + '/usr' + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: dirname(path) + + Return the directory name of pathname *path*. This is the first element of + the pair returned by passing *path* to the function :func:`split`. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: exists(path) + + Return ``True`` if *path* refers to an existing path or an open + file descriptor. Returns ``False`` for broken symbolic links. On + some platforms, this function may return ``False`` if permission is + not granted to execute :func:`os.stat` on the requested file, even + if the *path* physically exists. + + .. versionchanged:: 3.3 + *path* can now be an integer: ``True`` is returned if it is an + open file descriptor, ``False`` otherwise. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: lexists(path) + + Return ``True`` if *path* refers to an existing path. Returns ``True`` for + broken symbolic links. Equivalent to :func:`exists` on platforms lacking + :func:`os.lstat`. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. index:: single: ~ (tilde); home directory expansion + +.. function:: expanduser(path) + + On Unix and Windows, return the argument with an initial component of ``~`` or + ``~user`` replaced by that *user*'s home directory. + + .. index:: module: pwd + + On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME` + if it is set; otherwise the current user's home directory is looked up in the + password directory through the built-in module :mod:`pwd`. An initial ``~user`` + is looked up directly in the password directory. + + On Windows, :envvar:`USERPROFILE` will be used if set, otherwise a combination + of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be used. An initial + ``~user`` is handled by stripping the last directory component from the created + user path derived above. + + If the expansion fails or if the path does not begin with a tilde, the path is + returned unchanged. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + .. versionchanged:: 3.8 + No longer uses :envvar:`HOME` on Windows. + +.. index:: + single: $ (dollar); environment variables expansion + single: % (percent); environment variables expansion (Windows) + +.. function:: expandvars(path) + + Return the argument with environment variables expanded. Substrings of the form + ``$name`` or ``${name}`` are replaced by the value of environment variable + *name*. Malformed variable names and references to non-existing variables are + left unchanged. + + On Windows, ``%name%`` expansions are supported in addition to ``$name`` and + ``${name}``. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: getatime(path) + + Return the time of last access of *path*. The return value is a floating point number giving + the number of seconds since the epoch (see the :mod:`time` module). Raise + :exc:`OSError` if the file does not exist or is inaccessible. + + +.. function:: getmtime(path) + + Return the time of last modification of *path*. The return value is a floating point number + giving the number of seconds since the epoch (see the :mod:`time` module). + Raise :exc:`OSError` if the file does not exist or is inaccessible. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: getctime(path) + + Return the system's ctime which, on some systems (like Unix) is the time of the + last metadata change, and, on others (like Windows), is the creation time for *path*. + The return value is a number giving the number of seconds since the epoch (see + the :mod:`time` module). Raise :exc:`OSError` if the file does not exist or + is inaccessible. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: getsize(path) + + Return the size, in bytes, of *path*. Raise :exc:`OSError` if the file does + not exist or is inaccessible. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: isabs(path) + + Return ``True`` if *path* is an absolute pathname. On Unix, that means it + begins with a slash, on Windows that it begins with a (back)slash after chopping + off a potential drive letter. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: isfile(path) + + Return ``True`` if *path* is an :func:`existing ` regular file. + This follows symbolic links, so both :func:`islink` and :func:`isfile` can + be true for the same path. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: isdir(path) + + Return ``True`` if *path* is an :func:`existing ` directory. This + follows symbolic links, so both :func:`islink` and :func:`isdir` can be true + for the same path. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: islink(path) + + Return ``True`` if *path* refers to an :func:`existing ` directory + entry that is a symbolic link. Always ``False`` if symbolic links are not + supported by the Python runtime. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: ismount(path) + + Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a + file system where a different file system has been mounted. On POSIX, the + function checks whether *path*'s parent, :file:`{path}/..`, is on a different + device than *path*, or whether :file:`{path}/..` and *path* point to the same + i-node on the same device --- this should detect mount points for all Unix + and POSIX variants. It is not able to reliably detect bind mounts on the + same filesystem. On Windows, a drive letter root and a share UNC are + always mount points, and for any other path ``GetVolumePathName`` is called + to see if it is different from the input path. + + .. versionadded:: 3.4 + Support for detecting non-root mount points on Windows. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: join(path, *paths) + + Join one or more path components intelligently. The return value is the + concatenation of *path* and any members of *\*paths* with exactly one + directory separator (``os.sep``) following each non-empty part except the + last, meaning that the result will only end in a separator if the last + part is empty. If a component is an absolute path, all previous + components are thrown away and joining continues from the absolute path + component. + + On Windows, the drive letter is not reset when an absolute path component + (e.g., ``r'\foo'``) is encountered. If a component contains a drive + letter, all previous components are thrown away and the drive letter is + reset. Note that since there is a current directory for each drive, + ``os.path.join("c:", "foo")`` represents a path relative to the current + directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` for *path* and *paths*. + + +.. function:: normcase(path) + + Normalize the case of a pathname. On Windows, convert all characters in the + pathname to lowercase, and also convert forward slashes to backward slashes. + On other operating systems, return the path unchanged. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: normpath(path) + + Normalize a pathname by collapsing redundant separators and up-level + references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all + become ``A/B``. This string manipulation may change the meaning of a path + that contains symbolic links. On Windows, it converts forward slashes to + backward slashes. To normalize case, use :func:`normcase`. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: realpath(path) + + Return the canonical path of the specified filename, eliminating any symbolic + links encountered in the path (if they are supported by the operating + system). + + .. note:: + When symbolic link cycles occur, the returned path will be one member of + the cycle, but no guarantee is made about which member that will be. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + .. versionchanged:: 3.8 + Symbolic links and junctions are now resolved on Windows. + + +.. function:: relpath(path, start=os.curdir) + + Return a relative filepath to *path* either from the current directory or + from an optional *start* directory. This is a path computation: the + filesystem is not accessed to confirm the existence or nature of *path* or + *start*. + + *start* defaults to :attr:`os.curdir`. + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: samefile(path1, path2) + + Return ``True`` if both pathname arguments refer to the same file or directory. + This is determined by the device number and i-node number and raises an + exception if an :func:`os.stat` call on either pathname fails. + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.2 + Added Windows support. + + .. versionchanged:: 3.4 + Windows now uses the same implementation as all other platforms. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: sameopenfile(fp1, fp2) + + Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file. + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.2 + Added Windows support. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: samestat(stat1, stat2) + + Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file. + These structures may have been returned by :func:`os.fstat`, + :func:`os.lstat`, or :func:`os.stat`. This function implements the + underlying comparison used by :func:`samefile` and :func:`sameopenfile`. + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.4 + Added Windows support. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: split(path) + + Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the + last pathname component and *head* is everything leading up to that. The + *tail* part will never contain a slash; if *path* ends in a slash, *tail* + will be empty. If there is no slash in *path*, *head* will be empty. If + *path* is empty, both *head* and *tail* are empty. Trailing slashes are + stripped from *head* unless it is the root (one or more slashes only). In + all cases, ``join(head, tail)`` returns a path to the same location as *path* + (but the strings may differ). Also see the functions :func:`dirname` and + :func:`basename`. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: splitdrive(path) + + Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either + a mount point or the empty string. On systems which do not use drive + specifications, *drive* will always be the empty string. In all cases, ``drive + + tail`` will be the same as *path*. + + On Windows, splits a pathname into drive/UNC sharepoint and relative path. + + If the path contains a drive letter, drive will contain everything + up to and including the colon. + e.g. ``splitdrive("c:/dir")`` returns ``("c:", "/dir")`` + + If the path contains a UNC path, drive will contain the host name + and share, up to but not including the fourth separator. + e.g. ``splitdrive("//host/computer/dir")`` returns ``("//host/computer", "/dir")`` + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: splitext(path) + + Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext == + path``, and *ext* is empty or begins with a period and contains at most one + period. Leading periods on the basename are ignored; ``splitext('.cshrc')`` + returns ``('.cshrc', '')``. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. data:: supports_unicode_filenames + + ``True`` if arbitrary Unicode strings can be used as file names (within limitations + imposed by the file system). diff --git a/cpython_2/environment/repo/Doc/library/os.rst b/cpython_2/environment/repo/Doc/library/os.rst new file mode 100644 index 0000000000000000000000000000000000000000..943e67625c8eec0bbf34afac83d140be129556f2 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/os.rst @@ -0,0 +1,4669 @@ +:mod:`os` --- Miscellaneous operating system interfaces +======================================================= + +.. module:: os + :synopsis: Miscellaneous operating system interfaces. + +**Source code:** :source:`Lib/os.py` + +-------------- + +This module provides a portable way of using operating system dependent +functionality. If you just want to read or write a file see :func:`open`, if +you want to manipulate paths, see the :mod:`os.path` module, and if you want to +read all the lines in all the files on the command line see the :mod:`fileinput` +module. For creating temporary files and directories see the :mod:`tempfile` +module, and for high-level file and directory handling see the :mod:`shutil` +module. + +Notes on the availability of these functions: + +* The design of all built-in operating system dependent modules of Python is + such that as long as the same functionality is available, it uses the same + interface; for example, the function ``os.stat(path)`` returns stat + information about *path* in the same format (which happens to have originated + with the POSIX interface). + +* Extensions peculiar to a particular operating system are also available + through the :mod:`os` module, but using them is of course a threat to + portability. + +* All functions accepting path or file names accept both bytes and string + objects, and result in an object of the same type, if a path or file name is + returned. + +* On VxWorks, os.fork, os.execv and os.spawn*p* are not supported. + +.. note:: + + All functions in this module raise :exc:`OSError` (or subclasses thereof) in + the case of invalid or inaccessible file names and paths, or other arguments + that have the correct type, but are not accepted by the operating system. + +.. exception:: error + + An alias for the built-in :exc:`OSError` exception. + + +.. data:: name + + The name of the operating system dependent module imported. The following + names have currently been registered: ``'posix'``, ``'nt'``, + ``'java'``. + + .. seealso:: + :attr:`sys.platform` has a finer granularity. :func:`os.uname` gives + system-dependent version information. + + The :mod:`platform` module provides detailed checks for the + system's identity. + + +.. _os-filenames: +.. _filesystem-encoding: + +File Names, Command Line Arguments, and Environment Variables +------------------------------------------------------------- + +In Python, file names, command line arguments, and environment variables are +represented using the string type. On some systems, decoding these strings to +and from bytes is necessary before passing them to the operating system. Python +uses the file system encoding to perform this conversion (see +:func:`sys.getfilesystemencoding`). + +.. versionchanged:: 3.1 + On some systems, conversion using the file system encoding may fail. In this + case, Python uses the :ref:`surrogateescape encoding error handler + `, which means that undecodable bytes are replaced by a + Unicode character U+DCxx on decoding, and these are again translated to the + original byte on encoding. + + +The file system encoding must guarantee to successfully decode all bytes +below 128. If the file system encoding fails to provide this guarantee, API +functions may raise UnicodeErrors. + + +.. _os-procinfo: + +Process Parameters +------------------ + +These functions and data items provide information and operate on the current +process and user. + + +.. function:: ctermid() + + Return the filename corresponding to the controlling terminal of the process. + + .. availability:: Unix. + + +.. data:: environ + + A :term:`mapping` object representing the string environment. For example, + ``environ['HOME']`` is the pathname of your home directory (on some platforms), + and is equivalent to ``getenv("HOME")`` in C. + + This mapping is captured the first time the :mod:`os` module is imported, + typically during Python startup as part of processing :file:`site.py`. Changes + to the environment made after this time are not reflected in ``os.environ``, + except for changes made by modifying ``os.environ`` directly. + + This mapping may be used to modify the environment as well as query the + environment. :func:`putenv` will be called automatically when the mapping + is modified. + + On Unix, keys and values use :func:`sys.getfilesystemencoding` and + ``'surrogateescape'`` error handler. Use :data:`environb` if you would like + to use a different encoding. + + .. note:: + + Calling :func:`putenv` directly does not change ``os.environ``, so it's better + to modify ``os.environ``. + + .. note:: + + On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may + cause memory leaks. Refer to the system documentation for + :c:func:`putenv`. + + You can delete items in this mapping to unset environment variables. + :func:`unsetenv` will be called automatically when an item is deleted from + ``os.environ``, and when one of the :meth:`pop` or :meth:`clear` methods is + called. + + .. versionchanged:: 3.9 + Updated to support :pep:`584`'s merge (``|``) and update (``|=``) operators. + + +.. data:: environb + + Bytes version of :data:`environ`: a :term:`mapping` object representing the + environment as byte strings. :data:`environ` and :data:`environb` are + synchronized (modify :data:`environb` updates :data:`environ`, and vice + versa). + + :data:`environb` is only available if :data:`supports_bytes_environ` is + ``True``. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.9 + Updated to support :pep:`584`'s merge (``|``) and update (``|=``) operators. + + +.. function:: chdir(path) + fchdir(fd) + getcwd() + :noindex: + + These functions are described in :ref:`os-file-dir`. + + +.. function:: fsencode(filename) + + Encode :term:`path-like ` *filename* to the filesystem + encoding with ``'surrogateescape'`` error handler, or ``'strict'`` on + Windows; return :class:`bytes` unchanged. + + :func:`fsdecode` is the reverse function. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.6 + Support added to accept objects implementing the :class:`os.PathLike` + interface. + + +.. function:: fsdecode(filename) + + Decode the :term:`path-like ` *filename* from the + filesystem encoding with ``'surrogateescape'`` error handler, or ``'strict'`` + on Windows; return :class:`str` unchanged. + + :func:`fsencode` is the reverse function. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.6 + Support added to accept objects implementing the :class:`os.PathLike` + interface. + + +.. function:: fspath(path) + + Return the file system representation of the path. + + If :class:`str` or :class:`bytes` is passed in, it is returned unchanged. + Otherwise :meth:`~os.PathLike.__fspath__` is called and its value is + returned as long as it is a :class:`str` or :class:`bytes` object. + In all other cases, :exc:`TypeError` is raised. + + .. versionadded:: 3.6 + + +.. class:: PathLike + + An :term:`abstract base class` for objects representing a file system path, + e.g. :class:`pathlib.PurePath`. + + .. versionadded:: 3.6 + + .. abstractmethod:: __fspath__() + + Return the file system path representation of the object. + + The method should only return a :class:`str` or :class:`bytes` object, + with the preference being for :class:`str`. + + +.. function:: getenv(key, default=None) + + Return the value of the environment variable *key* if it exists, or + *default* if it doesn't. *key*, *default* and the result are str. + + On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding` + and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you + would like to use a different encoding. + + .. availability:: most flavors of Unix, Windows. + + +.. function:: getenvb(key, default=None) + + Return the value of the environment variable *key* if it exists, or + *default* if it doesn't. *key*, *default* and the result are bytes. + + :func:`getenvb` is only available if :data:`supports_bytes_environ` + is ``True``. + + .. availability:: most flavors of Unix. + + .. versionadded:: 3.2 + + +.. function:: get_exec_path(env=None) + + Returns the list of directories that will be searched for a named + executable, similar to a shell, when launching a process. + *env*, when specified, should be an environment variable dictionary + to lookup the PATH in. + By default, when *env* is ``None``, :data:`environ` is used. + + .. versionadded:: 3.2 + + +.. function:: getegid() + + Return the effective group id of the current process. This corresponds to the + "set id" bit on the file being executed in the current process. + + .. availability:: Unix. + + +.. function:: geteuid() + + .. index:: single: user; effective id + + Return the current process's effective user id. + + .. availability:: Unix. + + +.. function:: getgid() + + .. index:: single: process; group + + Return the real group id of the current process. + + .. availability:: Unix. + + +.. function:: getgrouplist(user, group) + + Return list of group ids that *user* belongs to. If *group* is not in the + list, it is included; typically, *group* is specified as the group ID + field from the password record for *user*. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: getgroups() + + Return list of supplemental group ids associated with the current process. + + .. availability:: Unix. + + .. note:: + + On Mac OS X, :func:`getgroups` behavior differs somewhat from + other Unix platforms. If the Python interpreter was built with a + deployment target of :const:`10.5` or earlier, :func:`getgroups` returns + the list of effective group ids associated with the current user process; + this list is limited to a system-defined number of entries, typically 16, + and may be modified by calls to :func:`setgroups` if suitably privileged. + If built with a deployment target greater than :const:`10.5`, + :func:`getgroups` returns the current group access list for the user + associated with the effective user id of the process; the group access + list may change over the lifetime of the process, it is not affected by + calls to :func:`setgroups`, and its length is not limited to 16. The + deployment target value, :const:`MACOSX_DEPLOYMENT_TARGET`, can be + obtained with :func:`sysconfig.get_config_var`. + + +.. function:: getlogin() + + Return the name of the user logged in on the controlling terminal of the + process. For most purposes, it is more useful to use + :func:`getpass.getuser` since the latter checks the environment variables + :envvar:`LOGNAME` or :envvar:`USERNAME` to find out who the user is, and + falls back to ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the + current real user id. + + .. availability:: Unix, Windows. + + +.. function:: getpgid(pid) + + Return the process group id of the process with process id *pid*. If *pid* is 0, + the process group id of the current process is returned. + + .. availability:: Unix. + +.. function:: getpgrp() + + .. index:: single: process; group + + Return the id of the current process group. + + .. availability:: Unix. + + +.. function:: getpid() + + .. index:: single: process; id + + Return the current process id. + + +.. function:: getppid() + + .. index:: single: process; id of parent + + Return the parent's process id. When the parent process has exited, on Unix + the id returned is the one of the init process (1), on Windows it is still + the same id, which may be already reused by another process. + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.2 + Added support for Windows. + + +.. function:: getpriority(which, who) + + .. index:: single: process; scheduling priority + + Get program scheduling priority. The value *which* is one of + :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who* + is interpreted relative to *which* (a process identifier for + :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a + user ID for :const:`PRIO_USER`). A zero value for *who* denotes + (respectively) the calling process, the process group of the calling process, + or the real user ID of the calling process. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. data:: PRIO_PROCESS + PRIO_PGRP + PRIO_USER + + Parameters for the :func:`getpriority` and :func:`setpriority` functions. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: getresuid() + + Return a tuple (ruid, euid, suid) denoting the current process's + real, effective, and saved user ids. + + .. availability:: Unix. + + .. versionadded:: 3.2 + + +.. function:: getresgid() + + Return a tuple (rgid, egid, sgid) denoting the current process's + real, effective, and saved group ids. + + .. availability:: Unix. + + .. versionadded:: 3.2 + + +.. function:: getuid() + + .. index:: single: user; id + + Return the current process's real user id. + + .. availability:: Unix. + + +.. function:: initgroups(username, gid) + + Call the system initgroups() to initialize the group access list with all of + the groups of which the specified username is a member, plus the specified + group id. + + .. availability:: Unix. + + .. versionadded:: 3.2 + + +.. function:: putenv(key, value) + + .. index:: single: environment variables; setting + + Set the environment variable named *key* to the string *value*. Such + changes to the environment affect subprocesses started with :func:`os.system`, + :func:`popen` or :func:`fork` and :func:`execv`. + + Assignments to items in ``os.environ`` are automatically translated into + corresponding calls to :func:`putenv`; however, calls to :func:`putenv` + don't update ``os.environ``, so it is actually preferable to assign to items + of ``os.environ``. + + .. note:: + + On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may + cause memory leaks. Refer to the system documentation for :c:func:`putenv`. + + .. audit-event:: os.putenv key,value os.putenv + + .. versionchanged:: 3.9 + The function is now always available. + + +.. function:: setegid(egid) + + Set the current process's effective group id. + + .. availability:: Unix. + + +.. function:: seteuid(euid) + + Set the current process's effective user id. + + .. availability:: Unix. + + +.. function:: setgid(gid) + + Set the current process' group id. + + .. availability:: Unix. + + +.. function:: setgroups(groups) + + Set the list of supplemental group ids associated with the current process to + *groups*. *groups* must be a sequence, and each element must be an integer + identifying a group. This operation is typically available only to the superuser. + + .. availability:: Unix. + + .. note:: On Mac OS X, the length of *groups* may not exceed the + system-defined maximum number of effective group ids, typically 16. + See the documentation for :func:`getgroups` for cases where it may not + return the same group list set by calling setgroups(). + +.. function:: setpgrp() + + Call the system call :c:func:`setpgrp` or ``setpgrp(0, 0)`` depending on + which version is implemented (if any). See the Unix manual for the semantics. + + .. availability:: Unix. + + +.. function:: setpgid(pid, pgrp) + + Call the system call :c:func:`setpgid` to set the process group id of the + process with id *pid* to the process group with id *pgrp*. See the Unix manual + for the semantics. + + .. availability:: Unix. + + +.. function:: setpriority(which, who, priority) + + .. index:: single: process; scheduling priority + + Set program scheduling priority. The value *which* is one of + :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who* + is interpreted relative to *which* (a process identifier for + :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a + user ID for :const:`PRIO_USER`). A zero value for *who* denotes + (respectively) the calling process, the process group of the calling process, + or the real user ID of the calling process. + *priority* is a value in the range -20 to 19. The default priority is 0; + lower priorities cause more favorable scheduling. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: setregid(rgid, egid) + + Set the current process's real and effective group ids. + + .. availability:: Unix. + + +.. function:: setresgid(rgid, egid, sgid) + + Set the current process's real, effective, and saved group ids. + + .. availability:: Unix. + + .. versionadded:: 3.2 + + +.. function:: setresuid(ruid, euid, suid) + + Set the current process's real, effective, and saved user ids. + + .. availability:: Unix. + + .. versionadded:: 3.2 + + +.. function:: setreuid(ruid, euid) + + Set the current process's real and effective user ids. + + .. availability:: Unix. + + +.. function:: getsid(pid) + + Call the system call :c:func:`getsid`. See the Unix manual for the semantics. + + .. availability:: Unix. + + +.. function:: setsid() + + Call the system call :c:func:`setsid`. See the Unix manual for the semantics. + + .. availability:: Unix. + + +.. function:: setuid(uid) + + .. index:: single: user; id, setting + + Set the current process's user id. + + .. availability:: Unix. + + +.. placed in this section since it relates to errno.... a little weak +.. function:: strerror(code) + + Return the error message corresponding to the error code in *code*. + On platforms where :c:func:`strerror` returns ``NULL`` when given an unknown + error number, :exc:`ValueError` is raised. + + +.. data:: supports_bytes_environ + + ``True`` if the native OS type of the environment is bytes (eg. ``False`` on + Windows). + + .. versionadded:: 3.2 + + +.. function:: umask(mask) + + Set the current numeric umask and return the previous umask. + + +.. function:: uname() + + .. index:: + single: gethostname() (in module socket) + single: gethostbyaddr() (in module socket) + + Returns information identifying the current operating system. + The return value is an object with five attributes: + + * :attr:`sysname` - operating system name + * :attr:`nodename` - name of machine on network (implementation-defined) + * :attr:`release` - operating system release + * :attr:`version` - operating system version + * :attr:`machine` - hardware identifier + + For backwards compatibility, this object is also iterable, behaving + like a five-tuple containing :attr:`sysname`, :attr:`nodename`, + :attr:`release`, :attr:`version`, and :attr:`machine` + in that order. + + Some systems truncate :attr:`nodename` to 8 characters or to the + leading component; a better way to get the hostname is + :func:`socket.gethostname` or even + ``socket.gethostbyaddr(socket.gethostname())``. + + .. availability:: recent flavors of Unix. + + .. versionchanged:: 3.3 + Return type changed from a tuple to a tuple-like object + with named attributes. + + +.. function:: unsetenv(key) + + .. index:: single: environment variables; deleting + + Unset (delete) the environment variable named *key*. Such changes to the + environment affect subprocesses started with :func:`os.system`, :func:`popen` or + :func:`fork` and :func:`execv`. + + Deletion of items in ``os.environ`` is automatically translated into a + corresponding call to :func:`unsetenv`; however, calls to :func:`unsetenv` + don't update ``os.environ``, so it is actually preferable to delete items of + ``os.environ``. + + .. audit-event:: os.unsetenv key os.unsetenv + + .. versionchanged:: 3.9 + The function is now always available and is also available on Windows. + + +.. _os-newstreams: + +File Object Creation +-------------------- + +These functions create new :term:`file objects `. (See also +:func:`~os.open` for opening file descriptors.) + + +.. function:: fdopen(fd, *args, **kwargs) + + Return an open file object connected to the file descriptor *fd*. This is an + alias of the :func:`open` built-in function and accepts the same arguments. + The only difference is that the first argument of :func:`fdopen` must always + be an integer. + + +.. _os-fd-ops: + +File Descriptor Operations +-------------------------- + +These functions operate on I/O streams referenced using file descriptors. + +File descriptors are small integers corresponding to a file that has been opened +by the current process. For example, standard input is usually file descriptor +0, standard output is 1, and standard error is 2. Further files opened by a +process will then be assigned 3, 4, 5, and so forth. The name "file descriptor" +is slightly deceptive; on Unix platforms, sockets and pipes are also referenced +by file descriptors. + +The :meth:`~io.IOBase.fileno` method can be used to obtain the file descriptor +associated with a :term:`file object` when required. Note that using the file +descriptor directly will bypass the file object methods, ignoring aspects such +as internal buffering of data. + + +.. function:: close(fd) + + Close file descriptor *fd*. + + .. note:: + + This function is intended for low-level I/O and must be applied to a file + descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file + object" returned by the built-in function :func:`open` or by :func:`popen` or + :func:`fdopen`, use its :meth:`~io.IOBase.close` method. + + +.. function:: closerange(fd_low, fd_high) + + Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive), + ignoring errors. Equivalent to (but much faster than):: + + for fd in range(fd_low, fd_high): + try: + os.close(fd) + except OSError: + pass + + +.. function:: copy_file_range(src, dst, count, offset_src=None, offset_dst=None) + + Copy *count* bytes from file descriptor *src*, starting from offset + *offset_src*, to file descriptor *dst*, starting from offset *offset_dst*. + If *offset_src* is None, then *src* is read from the current position; + respectively for *offset_dst*. The files pointed by *src* and *dst* + must reside in the same filesystem, otherwise an :exc:`OSError` is + raised with :attr:`~OSError.errno` set to :data:`errno.EXDEV`. + + This copy is done without the additional cost of transferring data + from the kernel to user space and then back into the kernel. Additionally, + some filesystems could implement extra optimizations. The copy is done as if + both files are opened as binary. + + The return value is the amount of bytes copied. This could be less than the + amount requested. + + .. availability:: Linux kernel >= 4.5 or glibc >= 2.27. + + .. versionadded:: 3.8 + + +.. function:: device_encoding(fd) + + Return a string describing the encoding of the device associated with *fd* + if it is connected to a terminal; else return :const:`None`. + + +.. function:: dup(fd) + + Return a duplicate of file descriptor *fd*. The new file descriptor is + :ref:`non-inheritable `. + + On Windows, when duplicating a standard stream (0: stdin, 1: stdout, + 2: stderr), the new file descriptor is :ref:`inheritable + `. + + .. versionchanged:: 3.4 + The new file descriptor is now non-inheritable. + + +.. function:: dup2(fd, fd2, inheritable=True) + + Duplicate file descriptor *fd* to *fd2*, closing the latter first if + necessary. Return *fd2*. The new file descriptor is :ref:`inheritable + ` by default or non-inheritable if *inheritable* + is ``False``. + + .. versionchanged:: 3.4 + Add the optional *inheritable* parameter. + + .. versionchanged:: 3.7 + Return *fd2* on success. Previously, ``None`` was always returned. + + +.. function:: fchmod(fd, mode) + + Change the mode of the file given by *fd* to the numeric *mode*. See the + docs for :func:`chmod` for possible values of *mode*. As of Python 3.3, this + is equivalent to ``os.chmod(fd, mode)``. + + .. audit-event:: os.chmod path,mode,dir_fd os.fchmod + + .. availability:: Unix. + + +.. function:: fchown(fd, uid, gid) + + Change the owner and group id of the file given by *fd* to the numeric *uid* + and *gid*. To leave one of the ids unchanged, set it to -1. See + :func:`chown`. As of Python 3.3, this is equivalent to ``os.chown(fd, uid, + gid)``. + + .. audit-event:: os.chown path,uid,gid,dir_fd os.fchown + + .. availability:: Unix. + + +.. function:: fdatasync(fd) + + Force write of file with filedescriptor *fd* to disk. Does not force update of + metadata. + + .. availability:: Unix. + + .. note:: + This function is not available on MacOS. + + +.. function:: fpathconf(fd, name) + + Return system configuration information relevant to an open file. *name* + specifies the configuration value to retrieve; it may be a string which is the + name of a defined system value; these names are specified in a number of + standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define + additional names as well. The names known to the host operating system are + given in the ``pathconf_names`` dictionary. For configuration variables not + included in that mapping, passing an integer for *name* is also accepted. + + If *name* is a string and is not known, :exc:`ValueError` is raised. If a + specific value for *name* is not supported by the host system, even if it is + included in ``pathconf_names``, an :exc:`OSError` is raised with + :const:`errno.EINVAL` for the error number. + + As of Python 3.3, this is equivalent to ``os.pathconf(fd, name)``. + + .. availability:: Unix. + + +.. function:: fstat(fd) + + Get the status of the file descriptor *fd*. Return a :class:`stat_result` + object. + + As of Python 3.3, this is equivalent to ``os.stat(fd)``. + + .. seealso:: + + The :func:`.stat` function. + + +.. function:: fstatvfs(fd) + + Return information about the filesystem containing the file associated with + file descriptor *fd*, like :func:`statvfs`. As of Python 3.3, this is + equivalent to ``os.statvfs(fd)``. + + .. availability:: Unix. + + +.. function:: fsync(fd) + + Force write of file with filedescriptor *fd* to disk. On Unix, this calls the + native :c:func:`fsync` function; on Windows, the MS :c:func:`_commit` function. + + If you're starting with a buffered Python :term:`file object` *f*, first do + ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal + buffers associated with *f* are written to disk. + + .. availability:: Unix, Windows. + + +.. function:: ftruncate(fd, length) + + Truncate the file corresponding to file descriptor *fd*, so that it is at + most *length* bytes in size. As of Python 3.3, this is equivalent to + ``os.truncate(fd, length)``. + + .. audit-event:: os.truncate fd,length os.ftruncate + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.5 + Added support for Windows + + +.. function:: get_blocking(fd) + + Get the blocking mode of the file descriptor: ``False`` if the + :data:`O_NONBLOCK` flag is set, ``True`` if the flag is cleared. + + See also :func:`set_blocking` and :meth:`socket.socket.setblocking`. + + .. availability:: Unix. + + .. versionadded:: 3.5 + + +.. function:: isatty(fd) + + Return ``True`` if the file descriptor *fd* is open and connected to a + tty(-like) device, else ``False``. + + +.. function:: lockf(fd, cmd, len) + + Apply, test or remove a POSIX lock on an open file descriptor. + *fd* is an open file descriptor. + *cmd* specifies the command to use - one of :data:`F_LOCK`, :data:`F_TLOCK`, + :data:`F_ULOCK` or :data:`F_TEST`. + *len* specifies the section of the file to lock. + + .. audit-event:: os.lockf fd,cmd,len os.lockf + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. data:: F_LOCK + F_TLOCK + F_ULOCK + F_TEST + + Flags that specify what action :func:`lockf` will take. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: lseek(fd, pos, how) + + Set the current position of file descriptor *fd* to position *pos*, modified + by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the + beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the + current position; :const:`SEEK_END` or ``2`` to set it relative to the end of + the file. Return the new cursor position in bytes, starting from the beginning. + + +.. data:: SEEK_SET + SEEK_CUR + SEEK_END + + Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, + respectively. + + .. versionadded:: 3.3 + Some operating systems could support additional values, like + :data:`os.SEEK_HOLE` or :data:`os.SEEK_DATA`. + + +.. function:: open(path, flags, mode=0o777, *, dir_fd=None) + + Open the file *path* and set various flags according to *flags* and possibly + its mode according to *mode*. When computing *mode*, the current umask value + is first masked out. Return the file descriptor for the newly opened file. + The new file descriptor is :ref:`non-inheritable `. + + For a description of the flag and mode values, see the C run-time documentation; + flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in + the :mod:`os` module. In particular, on Windows adding + :const:`O_BINARY` is needed to open files in binary mode. + + This function can support :ref:`paths relative to directory descriptors + ` with the *dir_fd* parameter. + + .. audit-event:: open path,mode,flags os.open + + .. versionchanged:: 3.4 + The new file descriptor is now non-inheritable. + + .. note:: + + This function is intended for low-level I/O. For normal usage, use the + built-in function :func:`open`, which returns a :term:`file object` with + :meth:`~file.read` and :meth:`~file.write` methods (and many more). To + wrap a file descriptor in a file object, use :func:`fdopen`. + + .. versionadded:: 3.3 + The *dir_fd* argument. + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise an + exception, the function now retries the system call instead of raising an + :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + +The following constants are options for the *flags* parameter to the +:func:`~os.open` function. They can be combined using the bitwise OR operator +``|``. Some of them are not available on all platforms. For descriptions of +their availability and use, consult the :manpage:`open(2)` manual page on Unix +or `the MSDN `_ on Windows. + + +.. data:: O_RDONLY + O_WRONLY + O_RDWR + O_APPEND + O_CREAT + O_EXCL + O_TRUNC + + The above constants are available on Unix and Windows. + + +.. data:: O_DSYNC + O_RSYNC + O_SYNC + O_NDELAY + O_NONBLOCK + O_NOCTTY + O_CLOEXEC + + The above constants are only available on Unix. + + .. versionchanged:: 3.3 + Add :data:`O_CLOEXEC` constant. + +.. data:: O_BINARY + O_NOINHERIT + O_SHORT_LIVED + O_TEMPORARY + O_RANDOM + O_SEQUENTIAL + O_TEXT + + The above constants are only available on Windows. + + +.. data:: O_ASYNC + O_DIRECT + O_DIRECTORY + O_NOFOLLOW + O_NOATIME + O_PATH + O_TMPFILE + O_SHLOCK + O_EXLOCK + + The above constants are extensions and not present if they are not defined by + the C library. + + .. versionchanged:: 3.4 + Add :data:`O_PATH` on systems that support it. + Add :data:`O_TMPFILE`, only available on Linux Kernel 3.11 + or newer. + + +.. function:: openpty() + + .. index:: module: pty + + Open a new pseudo-terminal pair. Return a pair of file descriptors + ``(master, slave)`` for the pty and the tty, respectively. The new file + descriptors are :ref:`non-inheritable `. For a (slightly) more + portable approach, use the :mod:`pty` module. + + .. availability:: some flavors of Unix. + + .. versionchanged:: 3.4 + The new file descriptors are now non-inheritable. + + +.. function:: pipe() + + Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for + reading and writing, respectively. The new file descriptor is + :ref:`non-inheritable `. + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.4 + The new file descriptors are now non-inheritable. + + +.. function:: pipe2(flags) + + Create a pipe with *flags* set atomically. + *flags* can be constructed by ORing together one or more of these values: + :data:`O_NONBLOCK`, :data:`O_CLOEXEC`. + Return a pair of file descriptors ``(r, w)`` usable for reading and writing, + respectively. + + .. availability:: some flavors of Unix. + + .. versionadded:: 3.3 + + +.. function:: posix_fallocate(fd, offset, len) + + Ensures that enough disk space is allocated for the file specified by *fd* + starting from *offset* and continuing for *len* bytes. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: posix_fadvise(fd, offset, len, advice) + + Announces an intention to access data in a specific pattern thus allowing + the kernel to make optimizations. + The advice applies to the region of the file specified by *fd* starting at + *offset* and continuing for *len* bytes. + *advice* is one of :data:`POSIX_FADV_NORMAL`, :data:`POSIX_FADV_SEQUENTIAL`, + :data:`POSIX_FADV_RANDOM`, :data:`POSIX_FADV_NOREUSE`, + :data:`POSIX_FADV_WILLNEED` or :data:`POSIX_FADV_DONTNEED`. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. data:: POSIX_FADV_NORMAL + POSIX_FADV_SEQUENTIAL + POSIX_FADV_RANDOM + POSIX_FADV_NOREUSE + POSIX_FADV_WILLNEED + POSIX_FADV_DONTNEED + + Flags that can be used in *advice* in :func:`posix_fadvise` that specify + the access pattern that is likely to be used. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: pread(fd, n, offset) + + Read at most *n* bytes from file descriptor *fd* at a position of *offset*, + leaving the file offset unchanged. + + Return a bytestring containing the bytes read. If the end of the file + referred to by *fd* has been reached, an empty bytes object is returned. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: preadv(fd, buffers, offset, flags=0) + + Read from a file descriptor *fd* at a position of *offset* into mutable + :term:`bytes-like objects ` *buffers*, leaving the file + offset unchanged. Transfer data into each buffer until it is full and then + move on to the next buffer in the sequence to hold the rest of the data. + + The flags argument contains a bitwise OR of zero or more of the following + flags: + + - :data:`RWF_HIPRI` + - :data:`RWF_NOWAIT` + + Return the total number of bytes actually read which can be less than the + total capacity of all the objects. + + The operating system may set a limit (:func:`sysconf` value + ``'SC_IOV_MAX'``) on the number of buffers that can be used. + + Combine the functionality of :func:`os.readv` and :func:`os.pread`. + + .. availability:: Linux 2.6.30 and newer, FreeBSD 6.0 and newer, + OpenBSD 2.7 and newer. Using flags requires Linux 4.6 or newer. + + .. versionadded:: 3.7 + + +.. data:: RWF_NOWAIT + + Do not wait for data which is not immediately available. If this flag is + specified, the system call will return instantly if it would have to read + data from the backing storage or wait for a lock. + + If some data was successfully read, it will return the number of bytes read. + If no bytes were read, it will return ``-1`` and set errno to + :data:`errno.EAGAIN`. + + .. availability:: Linux 4.14 and newer. + + .. versionadded:: 3.7 + + +.. data:: RWF_HIPRI + + High priority read/write. Allows block-based filesystems to use polling + of the device, which provides lower latency, but may use additional + resources. + + Currently, on Linux, this feature is usable only on a file descriptor opened + using the :data:`O_DIRECT` flag. + + .. availability:: Linux 4.6 and newer. + + .. versionadded:: 3.7 + + +.. function:: pwrite(fd, str, offset) + + Write the bytestring in *str* to file descriptor *fd* at position of + *offset*, leaving the file offset unchanged. + + Return the number of bytes actually written. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: pwritev(fd, buffers, offset, flags=0) + + Write the *buffers* contents to file descriptor *fd* at a offset *offset*, + leaving the file offset unchanged. *buffers* must be a sequence of + :term:`bytes-like objects `. Buffers are processed in + array order. Entire contents of the first buffer is written before + proceeding to the second, and so on. + + The flags argument contains a bitwise OR of zero or more of the following + flags: + + - :data:`RWF_DSYNC` + - :data:`RWF_SYNC` + + Return the total number of bytes actually written. + + The operating system may set a limit (:func:`sysconf` value + ``'SC_IOV_MAX'``) on the number of buffers that can be used. + + Combine the functionality of :func:`os.writev` and :func:`os.pwrite`. + + .. availability:: Linux 2.6.30 and newer, FreeBSD 6.0 and newer, + OpenBSD 2.7 and newer. Using flags requires Linux 4.7 or newer. + + .. versionadded:: 3.7 + + +.. data:: RWF_DSYNC + + Provide a per-write equivalent of the :data:`O_DSYNC` ``open(2)`` flag. This + flag effect applies only to the data range written by the system call. + + .. availability:: Linux 4.7 and newer. + + .. versionadded:: 3.7 + + +.. data:: RWF_SYNC + + Provide a per-write equivalent of the :data:`O_SYNC` ``open(2)`` flag. This + flag effect applies only to the data range written by the system call. + + .. availability:: Linux 4.7 and newer. + + .. versionadded:: 3.7 + + +.. function:: read(fd, n) + + Read at most *n* bytes from file descriptor *fd*. + + Return a bytestring containing the bytes read. If the end of the file + referred to by *fd* has been reached, an empty bytes object is returned. + + .. note:: + + This function is intended for low-level I/O and must be applied to a file + descriptor as returned by :func:`os.open` or :func:`pipe`. To read a + "file object" returned by the built-in function :func:`open` or by + :func:`popen` or :func:`fdopen`, or :data:`sys.stdin`, use its + :meth:`~file.read` or :meth:`~file.readline` methods. + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise an + exception, the function now retries the system call instead of raising an + :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + +.. function:: sendfile(out_fd, in_fd, offset, count) + sendfile(out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0) + + Copy *count* bytes from file descriptor *in_fd* to file descriptor *out_fd* + starting at *offset*. + Return the number of bytes sent. When EOF is reached return ``0``. + + The first function notation is supported by all platforms that define + :func:`sendfile`. + + On Linux, if *offset* is given as ``None``, the bytes are read from the + current position of *in_fd* and the position of *in_fd* is updated. + + The second case may be used on Mac OS X and FreeBSD where *headers* and + *trailers* are arbitrary sequences of buffers that are written before and + after the data from *in_fd* is written. It returns the same as the first case. + + On Mac OS X and FreeBSD, a value of ``0`` for *count* specifies to send until + the end of *in_fd* is reached. + + All platforms support sockets as *out_fd* file descriptor, and some platforms + allow other types (e.g. regular file, pipe) as well. + + Cross-platform applications should not use *headers*, *trailers* and *flags* + arguments. + + .. availability:: Unix. + + .. note:: + + For a higher-level wrapper of :func:`sendfile`, see + :meth:`socket.socket.sendfile`. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.9 + Parameters *out* and *in* was renamed to *out_fd* and *in_fd*. + + +.. function:: set_blocking(fd, blocking) + + Set the blocking mode of the specified file descriptor. Set the + :data:`O_NONBLOCK` flag if blocking is ``False``, clear the flag otherwise. + + See also :func:`get_blocking` and :meth:`socket.socket.setblocking`. + + .. availability:: Unix. + + .. versionadded:: 3.5 + + +.. data:: SF_NODISKIO + SF_MNOWAIT + SF_SYNC + + Parameters to the :func:`sendfile` function, if the implementation supports + them. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: readv(fd, buffers) + + Read from a file descriptor *fd* into a number of mutable :term:`bytes-like + objects ` *buffers*. Transfer data into each buffer until + it is full and then move on to the next buffer in the sequence to hold the + rest of the data. + + Return the total number of bytes actually read which can be less than the + total capacity of all the objects. + + The operating system may set a limit (:func:`sysconf` value + ``'SC_IOV_MAX'``) on the number of buffers that can be used. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: tcgetpgrp(fd) + + Return the process group associated with the terminal given by *fd* (an open + file descriptor as returned by :func:`os.open`). + + .. availability:: Unix. + + +.. function:: tcsetpgrp(fd, pg) + + Set the process group associated with the terminal given by *fd* (an open file + descriptor as returned by :func:`os.open`) to *pg*. + + .. availability:: Unix. + + +.. function:: ttyname(fd) + + Return a string which specifies the terminal device associated with + file descriptor *fd*. If *fd* is not associated with a terminal device, an + exception is raised. + + .. availability:: Unix. + + +.. function:: write(fd, str) + + Write the bytestring in *str* to file descriptor *fd*. + + Return the number of bytes actually written. + + .. note:: + + This function is intended for low-level I/O and must be applied to a file + descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file + object" returned by the built-in function :func:`open` or by :func:`popen` or + :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its + :meth:`~file.write` method. + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise an + exception, the function now retries the system call instead of raising an + :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + +.. function:: writev(fd, buffers) + + Write the contents of *buffers* to file descriptor *fd*. *buffers* must be + a sequence of :term:`bytes-like objects `. Buffers are + processed in array order. Entire contents of the first buffer is written + before proceeding to the second, and so on. + + Returns the total number of bytes actually written. + + The operating system may set a limit (:func:`sysconf` value + ``'SC_IOV_MAX'``) on the number of buffers that can be used. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. _terminal-size: + +Querying the size of a terminal +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 3.3 + +.. function:: get_terminal_size(fd=STDOUT_FILENO) + + Return the size of the terminal window as ``(columns, lines)``, + tuple of type :class:`terminal_size`. + + The optional argument ``fd`` (default ``STDOUT_FILENO``, or standard + output) specifies which file descriptor should be queried. + + If the file descriptor is not connected to a terminal, an :exc:`OSError` + is raised. + + :func:`shutil.get_terminal_size` is the high-level function which + should normally be used, ``os.get_terminal_size`` is the low-level + implementation. + + .. availability:: Unix, Windows. + +.. class:: terminal_size + + A subclass of tuple, holding ``(columns, lines)`` of the terminal window size. + + .. attribute:: columns + + Width of the terminal window in characters. + + .. attribute:: lines + + Height of the terminal window in characters. + + +.. _fd_inheritance: + +Inheritance of File Descriptors +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 3.4 + +A file descriptor has an "inheritable" flag which indicates if the file descriptor +can be inherited by child processes. Since Python 3.4, file descriptors +created by Python are non-inheritable by default. + +On UNIX, non-inheritable file descriptors are closed in child processes at the +execution of a new program, other file descriptors are inherited. + +On Windows, non-inheritable handles and file descriptors are closed in child +processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout +and stderr), which are always inherited. Using :func:`spawn\* ` functions, +all inheritable handles and all inheritable file descriptors are inherited. +Using the :mod:`subprocess` module, all file descriptors except standard +streams are closed, and inheritable handles are only inherited if the +*close_fds* parameter is ``False``. + +.. function:: get_inheritable(fd) + + Get the "inheritable" flag of the specified file descriptor (a boolean). + +.. function:: set_inheritable(fd, inheritable) + + Set the "inheritable" flag of the specified file descriptor. + +.. function:: get_handle_inheritable(handle) + + Get the "inheritable" flag of the specified handle (a boolean). + + .. availability:: Windows. + +.. function:: set_handle_inheritable(handle, inheritable) + + Set the "inheritable" flag of the specified handle. + + .. availability:: Windows. + + +.. _os-file-dir: + +Files and Directories +--------------------- + +On some Unix platforms, many of these functions support one or more of these +features: + +.. _path_fd: + +* **specifying a file descriptor:** + Normally the *path* argument provided to functions in the :mod:`os` module + must be a string specifying a file path. However, some functions now + alternatively accept an open file descriptor for their *path* argument. + The function will then operate on the file referred to by the descriptor. + (For POSIX systems, Python will call the variant of the function prefixed + with ``f`` (e.g. call ``fchdir`` instead of ``chdir``).) + + You can check whether or not *path* can be specified as a file descriptor + for a particular function on your platform using :data:`os.supports_fd`. + If this functionality is unavailable, using it will raise a + :exc:`NotImplementedError`. + + If the function also supports *dir_fd* or *follow_symlinks* arguments, it's + an error to specify one of those when supplying *path* as a file descriptor. + +.. _dir_fd: + +* **paths relative to directory descriptors:** If *dir_fd* is not ``None``, it + should be a file descriptor referring to a directory, and the path to operate + on should be relative; path will then be relative to that directory. If the + path is absolute, *dir_fd* is ignored. (For POSIX systems, Python will call + the variant of the function with an ``at`` suffix and possibly prefixed with + ``f`` (e.g. call ``faccessat`` instead of ``access``). + + You can check whether or not *dir_fd* is supported for a particular function + on your platform using :data:`os.supports_dir_fd`. If it's unavailable, + using it will raise a :exc:`NotImplementedError`. + +.. _follow_symlinks: + +* **not following symlinks:** If *follow_symlinks* is + ``False``, and the last element of the path to operate on is a symbolic link, + the function will operate on the symbolic link itself rather than the file + pointed to by the link. (For POSIX systems, Python will call the ``l...`` + variant of the function.) + + You can check whether or not *follow_symlinks* is supported for a particular + function on your platform using :data:`os.supports_follow_symlinks`. + If it's unavailable, using it will raise a :exc:`NotImplementedError`. + + + +.. function:: access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True) + + Use the real uid/gid to test for access to *path*. Note that most operations + will use the effective uid/gid, therefore this routine can be used in a + suid/sgid environment to test if the invoking user has the specified access to + *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it + can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and + :const:`X_OK` to test permissions. Return :const:`True` if access is allowed, + :const:`False` if not. See the Unix man page :manpage:`access(2)` for more + information. + + This function can support specifying :ref:`paths relative to directory + descriptors ` and :ref:`not following symlinks `. + + If *effective_ids* is ``True``, :func:`access` will perform its access + checks using the effective uid/gid instead of the real uid/gid. + *effective_ids* may not be supported on your platform; you can check whether + or not it is available using :data:`os.supports_effective_ids`. If it is + unavailable, using it will raise a :exc:`NotImplementedError`. + + .. note:: + + Using :func:`access` to check if a user is authorized to e.g. open a file + before actually doing so using :func:`open` creates a security hole, + because the user might exploit the short time interval between checking + and opening the file to manipulate it. It's preferable to use :term:`EAFP` + techniques. For example:: + + if os.access("myfile", os.R_OK): + with open("myfile") as fp: + return fp.read() + return "some default data" + + is better written as:: + + try: + fp = open("myfile") + except PermissionError: + return "some default data" + else: + with fp: + return fp.read() + + .. note:: + + I/O operations may fail even when :func:`access` indicates that they would + succeed, particularly for operations on network filesystems which may have + permissions semantics beyond the usual POSIX permission-bit model. + + .. versionchanged:: 3.3 + Added the *dir_fd*, *effective_ids*, and *follow_symlinks* parameters. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. data:: F_OK + R_OK + W_OK + X_OK + + Values to pass as the *mode* parameter of :func:`access` to test the + existence, readability, writability and executability of *path*, + respectively. + + +.. function:: chdir(path) + + .. index:: single: directory; changing + + Change the current working directory to *path*. + + This function can support :ref:`specifying a file descriptor `. The + descriptor must refer to an opened directory, not an open file. + + This function can raise :exc:`OSError` and subclasses such as + :exc:`FileNotFoundError`, :exc:`PermissionError`, and :exc:`NotADirectoryError`. + + .. audit-event:: os.chdir path os.chdir + + .. versionadded:: 3.3 + Added support for specifying *path* as a file descriptor + on some platforms. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: chflags(path, flags, *, follow_symlinks=True) + + Set the flags of *path* to the numeric *flags*. *flags* may take a combination + (bitwise OR) of the following values (as defined in the :mod:`stat` module): + + * :data:`stat.UF_NODUMP` + * :data:`stat.UF_IMMUTABLE` + * :data:`stat.UF_APPEND` + * :data:`stat.UF_OPAQUE` + * :data:`stat.UF_NOUNLINK` + * :data:`stat.UF_COMPRESSED` + * :data:`stat.UF_HIDDEN` + * :data:`stat.SF_ARCHIVED` + * :data:`stat.SF_IMMUTABLE` + * :data:`stat.SF_APPEND` + * :data:`stat.SF_NOUNLINK` + * :data:`stat.SF_SNAPSHOT` + + This function can support :ref:`not following symlinks `. + + .. audit-event:: os.chflags path,flags os.chflags + + .. availability:: Unix. + + .. versionadded:: 3.3 + The *follow_symlinks* argument. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: chmod(path, mode, *, dir_fd=None, follow_symlinks=True) + + Change the mode of *path* to the numeric *mode*. *mode* may take one of the + following values (as defined in the :mod:`stat` module) or bitwise ORed + combinations of them: + + * :data:`stat.S_ISUID` + * :data:`stat.S_ISGID` + * :data:`stat.S_ENFMT` + * :data:`stat.S_ISVTX` + * :data:`stat.S_IREAD` + * :data:`stat.S_IWRITE` + * :data:`stat.S_IEXEC` + * :data:`stat.S_IRWXU` + * :data:`stat.S_IRUSR` + * :data:`stat.S_IWUSR` + * :data:`stat.S_IXUSR` + * :data:`stat.S_IRWXG` + * :data:`stat.S_IRGRP` + * :data:`stat.S_IWGRP` + * :data:`stat.S_IXGRP` + * :data:`stat.S_IRWXO` + * :data:`stat.S_IROTH` + * :data:`stat.S_IWOTH` + * :data:`stat.S_IXOTH` + + This function can support :ref:`specifying a file descriptor `, + :ref:`paths relative to directory descriptors ` and :ref:`not + following symlinks `. + + .. note:: + + Although Windows supports :func:`chmod`, you can only set the file's + read-only flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD`` + constants or a corresponding integer value). All other bits are ignored. + + .. audit-event:: os.chmod path,mode,dir_fd os.chmod + + .. versionadded:: 3.3 + Added support for specifying *path* as an open file descriptor, + and the *dir_fd* and *follow_symlinks* arguments. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True) + + Change the owner and group id of *path* to the numeric *uid* and *gid*. To + leave one of the ids unchanged, set it to -1. + + This function can support :ref:`specifying a file descriptor `, + :ref:`paths relative to directory descriptors ` and :ref:`not + following symlinks `. + + See :func:`shutil.chown` for a higher-level function that accepts names in + addition to numeric ids. + + .. audit-event:: os.chown path,uid,gid,dir_fd os.chown + + .. availability:: Unix. + + .. versionadded:: 3.3 + Added support for specifying *path* as an open file descriptor, + and the *dir_fd* and *follow_symlinks* arguments. + + .. versionchanged:: 3.6 + Supports a :term:`path-like object`. + + +.. function:: chroot(path) + + Change the root directory of the current process to *path*. + + .. availability:: Unix. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: fchdir(fd) + + Change the current working directory to the directory represented by the file + descriptor *fd*. The descriptor must refer to an opened directory, not an + open file. As of Python 3.3, this is equivalent to ``os.chdir(fd)``. + + .. audit-event:: os.chdir path os.fchdir + + .. availability:: Unix. + + +.. function:: getcwd() + + Return a string representing the current working directory. + + +.. function:: getcwdb() + + Return a bytestring representing the current working directory. + + .. versionchanged:: 3.8 + The function now uses the UTF-8 encoding on Windows, rather than the ANSI + code page: see :pep:`529` for the rationale. The function is no longer + deprecated on Windows. + + +.. function:: lchflags(path, flags) + + Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do + not follow symbolic links. As of Python 3.3, this is equivalent to + ``os.chflags(path, flags, follow_symlinks=False)``. + + .. audit-event:: os.chflags path,flags os.lchflags + + .. availability:: Unix. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: lchmod(path, mode) + + Change the mode of *path* to the numeric *mode*. If path is a symlink, this + affects the symlink rather than the target. See the docs for :func:`chmod` + for possible values of *mode*. As of Python 3.3, this is equivalent to + ``os.chmod(path, mode, follow_symlinks=False)``. + + .. audit-event:: os.chmod path,mode,dir_fd os.lchmod + + .. availability:: Unix. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + +.. function:: lchown(path, uid, gid) + + Change the owner and group id of *path* to the numeric *uid* and *gid*. This + function will not follow symbolic links. As of Python 3.3, this is equivalent + to ``os.chown(path, uid, gid, follow_symlinks=False)``. + + .. audit-event:: os.chown path,uid,gid,dir_fd os.lchown + + .. availability:: Unix. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True) + + Create a hard link pointing to *src* named *dst*. + + This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to + supply :ref:`paths relative to directory descriptors `, and :ref:`not + following symlinks `. + + .. audit-event:: os.link src,dst,src_dir_fd,dst_dir_fd os.link + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.2 + Added Windows support. + + .. versionadded:: 3.3 + Added the *src_dir_fd*, *dst_dir_fd*, and *follow_symlinks* arguments. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` for *src* and *dst*. + + +.. function:: listdir(path='.') + + Return a list containing the names of the entries in the directory given by + *path*. The list is in arbitrary order, and does not include the special + entries ``'.'`` and ``'..'`` even if they are present in the directory. + + *path* may be a :term:`path-like object`. If *path* is of type ``bytes`` + (directly or indirectly through the :class:`PathLike` interface), + the filenames returned will also be of type ``bytes``; + in all other circumstances, they will be of type ``str``. + + This function can also support :ref:`specifying a file descriptor + `; the file descriptor must refer to a directory. + + .. audit-event:: os.listdir path os.listdir + + .. note:: + To encode ``str`` filenames to ``bytes``, use :func:`~os.fsencode`. + + .. seealso:: + + The :func:`scandir` function returns directory entries along with + file attribute information, giving better performance for many + common use cases. + + .. versionchanged:: 3.2 + The *path* parameter became optional. + + .. versionadded:: 3.3 + Added support for specifying *path* as an open file descriptor. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: lstat(path, \*, dir_fd=None) + + Perform the equivalent of an :c:func:`lstat` system call on the given path. + Similar to :func:`~os.stat`, but does not follow symbolic links. Return a + :class:`stat_result` object. + + On platforms that do not support symbolic links, this is an alias for + :func:`~os.stat`. + + As of Python 3.3, this is equivalent to ``os.stat(path, dir_fd=dir_fd, + follow_symlinks=False)``. + + This function can also support :ref:`paths relative to directory descriptors + `. + + .. seealso:: + + The :func:`.stat` function. + + .. versionchanged:: 3.2 + Added support for Windows 6.0 (Vista) symbolic links. + + .. versionchanged:: 3.3 + Added the *dir_fd* parameter. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` for *src* and *dst*. + + .. versionchanged:: 3.8 + On Windows, now opens reparse points that represent another path + (name surrogates), including symbolic links and directory junctions. + Other kinds of reparse points are resolved by the operating system as + for :func:`~os.stat`. + + +.. function:: mkdir(path, mode=0o777, *, dir_fd=None) + + Create a directory named *path* with numeric mode *mode*. + + If the directory already exists, :exc:`FileExistsError` is raised. + + .. _mkdir_modebits: + + On some systems, *mode* is ignored. Where it is used, the current umask + value is first masked out. If bits other than the last 9 (i.e. the last 3 + digits of the octal representation of the *mode*) are set, their meaning is + platform-dependent. On some platforms, they are ignored and you should call + :func:`chmod` explicitly to set them. + + This function can also support :ref:`paths relative to directory descriptors + `. + + It is also possible to create temporary directories; see the + :mod:`tempfile` module's :func:`tempfile.mkdtemp` function. + + .. audit-event:: os.mkdir path,mode,dir_fd os.mkdir + + .. versionadded:: 3.3 + The *dir_fd* argument. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: makedirs(name, mode=0o777, exist_ok=False) + + .. index:: + single: directory; creating + single: UNC paths; and os.makedirs() + + Recursive directory creation function. Like :func:`mkdir`, but makes all + intermediate-level directories needed to contain the leaf directory. + + The *mode* parameter is passed to :func:`mkdir` for creating the leaf + directory; see :ref:`the mkdir() description ` for how it + is interpreted. To set the file permission bits of any newly-created parent + directories you can set the umask before invoking :func:`makedirs`. The + file permission bits of existing parent directories are not changed. + + If *exist_ok* is ``False`` (the default), an :exc:`FileExistsError` is + raised if the target directory already exists. + + .. note:: + + :func:`makedirs` will become confused if the path elements to create + include :data:`pardir` (eg. ".." on UNIX systems). + + This function handles UNC paths correctly. + + .. audit-event:: os.mkdir path,mode,dir_fd os.makedirs + + .. versionadded:: 3.2 + The *exist_ok* parameter. + + .. versionchanged:: 3.4.1 + + Before Python 3.4.1, if *exist_ok* was ``True`` and the directory existed, + :func:`makedirs` would still raise an error if *mode* did not match the + mode of the existing directory. Since this behavior was impossible to + implement safely, it was removed in Python 3.4.1. See :issue:`21082`. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + .. versionchanged:: 3.7 + The *mode* argument no longer affects the file permission bits of + newly-created intermediate-level directories. + + +.. function:: mkfifo(path, mode=0o666, *, dir_fd=None) + + Create a FIFO (a named pipe) named *path* with numeric mode *mode*. + The current umask value is first masked out from the mode. + + This function can also support :ref:`paths relative to directory descriptors + `. + + FIFOs are pipes that can be accessed like regular files. FIFOs exist until they + are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as + rendezvous between "client" and "server" type processes: the server opens the + FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo` + doesn't open the FIFO --- it just creates the rendezvous point. + + .. availability:: Unix. + + .. versionadded:: 3.3 + The *dir_fd* argument. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: mknod(path, mode=0o600, device=0, *, dir_fd=None) + + Create a filesystem node (file, device special file or named pipe) named + *path*. *mode* specifies both the permissions to use and the type of node + to be created, being combined (bitwise OR) with one of ``stat.S_IFREG``, + ``stat.S_IFCHR``, ``stat.S_IFBLK``, and ``stat.S_IFIFO`` (those constants are + available in :mod:`stat`). For ``stat.S_IFCHR`` and ``stat.S_IFBLK``, + *device* defines the newly created device special file (probably using + :func:`os.makedev`), otherwise it is ignored. + + This function can also support :ref:`paths relative to directory descriptors + `. + + .. availability:: Unix. + + .. versionadded:: 3.3 + The *dir_fd* argument. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: major(device) + + Extract the device major number from a raw device number (usually the + :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`). + + +.. function:: minor(device) + + Extract the device minor number from a raw device number (usually the + :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`). + + +.. function:: makedev(major, minor) + + Compose a raw device number from the major and minor device numbers. + + +.. function:: pathconf(path, name) + + Return system configuration information relevant to a named file. *name* + specifies the configuration value to retrieve; it may be a string which is the + name of a defined system value; these names are specified in a number of + standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define + additional names as well. The names known to the host operating system are + given in the ``pathconf_names`` dictionary. For configuration variables not + included in that mapping, passing an integer for *name* is also accepted. + + If *name* is a string and is not known, :exc:`ValueError` is raised. If a + specific value for *name* is not supported by the host system, even if it is + included in ``pathconf_names``, an :exc:`OSError` is raised with + :const:`errno.EINVAL` for the error number. + + This function can support :ref:`specifying a file descriptor + `. + + .. availability:: Unix. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. data:: pathconf_names + + Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to + the integer values defined for those names by the host operating system. This + can be used to determine the set of names known to the system. + + .. availability:: Unix. + + +.. function:: readlink(path, *, dir_fd=None) + + Return a string representing the path to which the symbolic link points. The + result may be either an absolute or relative pathname; if it is relative, it + may be converted to an absolute pathname using + ``os.path.join(os.path.dirname(path), result)``. + + If the *path* is a string object (directly or indirectly through a + :class:`PathLike` interface), the result will also be a string object, + and the call may raise a UnicodeDecodeError. If the *path* is a bytes + object (direct or indirectly), the result will be a bytes object. + + This function can also support :ref:`paths relative to directory descriptors + `. + + When trying to resolve a path that may contain links, use + :func:`~os.path.realpath` to properly handle recursion and platform + differences. + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.2 + Added support for Windows 6.0 (Vista) symbolic links. + + .. versionadded:: 3.3 + The *dir_fd* argument. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` on Unix. + + .. versionchanged:: 3.8 + Accepts a :term:`path-like object` and a bytes object on Windows. + + .. versionchanged:: 3.8 + Added support for directory junctions, and changed to return the + substitution path (which typically includes ``\\?\`` prefix) rather + than the optional "print name" field that was previously returned. + +.. function:: remove(path, *, dir_fd=None) + + Remove (delete) the file *path*. If *path* is a directory, an + :exc:`IsADirectoryError` is raised. Use :func:`rmdir` to remove directories. + + This function can support :ref:`paths relative to directory descriptors + `. + + On Windows, attempting to remove a file that is in use causes an exception to + be raised; on Unix, the directory entry is removed but the storage allocated + to the file is not made available until the original file is no longer in use. + + This function is semantically identical to :func:`unlink`. + + .. audit-event:: os.remove path,dir_fd os.remove + + .. versionadded:: 3.3 + The *dir_fd* argument. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: removedirs(name) + + .. index:: single: directory; deleting + + Remove directories recursively. Works like :func:`rmdir` except that, if the + leaf directory is successfully removed, :func:`removedirs` tries to + successively remove every parent directory mentioned in *path* until an error + is raised (which is ignored, because it generally means that a parent directory + is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove + the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if + they are empty. Raises :exc:`OSError` if the leaf directory could not be + successfully removed. + + .. audit-event:: os.remove path,dir_fd os.removedirs + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None) + + Rename the file or directory *src* to *dst*. If *dst* exists, the operation + will fail with an :exc:`OSError` subclass in a number of cases: + + On Windows, if *dst* exists a :exc:`FileExistsError` is always raised. + + On Unix, if *src* is a file and *dst* is a directory or vice-versa, an + :exc:`IsADirectoryError` or a :exc:`NotADirectoryError` will be raised + respectively. If both are directories and *dst* is empty, *dst* will be + silently replaced. If *dst* is a non-empty directory, an :exc:`OSError` + is raised. If both are files, *dst* it will be replaced silently if the user + has permission. The operation may fail on some Unix flavors if *src* and + *dst* are on different filesystems. If successful, the renaming will be an + atomic operation (this is a POSIX requirement). + + This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to + supply :ref:`paths relative to directory descriptors `. + + If you want cross-platform overwriting of the destination, use :func:`replace`. + + .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.rename + + .. versionadded:: 3.3 + The *src_dir_fd* and *dst_dir_fd* arguments. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` for *src* and *dst*. + + +.. function:: renames(old, new) + + Recursive directory or file renaming function. Works like :func:`rename`, except + creation of any intermediate directories needed to make the new pathname good is + attempted first. After the rename, directories corresponding to rightmost path + segments of the old name will be pruned away using :func:`removedirs`. + + .. note:: + + This function can fail with the new directory structure made if you lack + permissions needed to remove the leaf directory or file. + + .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.renames + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` for *old* and *new*. + + +.. function:: replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None) + + Rename the file or directory *src* to *dst*. If *dst* is a directory, + :exc:`OSError` will be raised. If *dst* exists and is a file, it will + be replaced silently if the user has permission. The operation may fail + if *src* and *dst* are on different filesystems. If successful, + the renaming will be an atomic operation (this is a POSIX requirement). + + This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to + supply :ref:`paths relative to directory descriptors `. + + .. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.replace + + .. versionadded:: 3.3 + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` for *src* and *dst*. + + +.. function:: rmdir(path, *, dir_fd=None) + + Remove (delete) the directory *path*. If the directory does not exist or is + not empty, an :exc:`FileNotFoundError` or an :exc:`OSError` is raised + respectively. In order to remove whole directory trees, + :func:`shutil.rmtree` can be used. + + This function can support :ref:`paths relative to directory descriptors + `. + + .. audit-event:: os.rmdir path,dir_fd os.rmdir + + .. versionadded:: 3.3 + The *dir_fd* parameter. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: scandir(path='.') + + Return an iterator of :class:`os.DirEntry` objects corresponding to the + entries in the directory given by *path*. The entries are yielded in + arbitrary order, and the special entries ``'.'`` and ``'..'`` are not + included. + + Using :func:`scandir` instead of :func:`listdir` can significantly + increase the performance of code that also needs file type or file + attribute information, because :class:`os.DirEntry` objects expose this + information if the operating system provides it when scanning a directory. + All :class:`os.DirEntry` methods may perform a system call, but + :func:`~os.DirEntry.is_dir` and :func:`~os.DirEntry.is_file` usually only + require a system call for symbolic links; :func:`os.DirEntry.stat` + always requires a system call on Unix but only requires one for + symbolic links on Windows. + + *path* may be a :term:`path-like object`. If *path* is of type ``bytes`` + (directly or indirectly through the :class:`PathLike` interface), + the type of the :attr:`~os.DirEntry.name` and :attr:`~os.DirEntry.path` + attributes of each :class:`os.DirEntry` will be ``bytes``; in all other + circumstances, they will be of type ``str``. + + This function can also support :ref:`specifying a file descriptor + `; the file descriptor must refer to a directory. + + .. audit-event:: os.scandir path os.scandir + + The :func:`scandir` iterator supports the :term:`context manager` protocol + and has the following method: + + .. method:: scandir.close() + + Close the iterator and free acquired resources. + + This is called automatically when the iterator is exhausted or garbage + collected, or when an error happens during iterating. However it + is advisable to call it explicitly or use the :keyword:`with` + statement. + + .. versionadded:: 3.6 + + The following example shows a simple use of :func:`scandir` to display all + the files (excluding directories) in the given *path* that don't start with + ``'.'``. The ``entry.is_file()`` call will generally not make an additional + system call:: + + with os.scandir(path) as it: + for entry in it: + if not entry.name.startswith('.') and entry.is_file(): + print(entry.name) + + .. note:: + + On Unix-based systems, :func:`scandir` uses the system's + `opendir() `_ + and + `readdir() `_ + functions. On Windows, it uses the Win32 + `FindFirstFileW `_ + and + `FindNextFileW `_ + functions. + + .. versionadded:: 3.5 + + .. versionadded:: 3.6 + Added support for the :term:`context manager` protocol and the + :func:`~scandir.close()` method. If a :func:`scandir` iterator is neither + exhausted nor explicitly closed a :exc:`ResourceWarning` will be emitted + in its destructor. + + The function accepts a :term:`path-like object`. + + .. versionchanged:: 3.7 + Added support for :ref:`file descriptors ` on Unix. + + +.. class:: DirEntry + + Object yielded by :func:`scandir` to expose the file path and other file + attributes of a directory entry. + + :func:`scandir` will provide as much of this information as possible without + making additional system calls. When a ``stat()`` or ``lstat()`` system call + is made, the ``os.DirEntry`` object will cache the result. + + ``os.DirEntry`` instances are not intended to be stored in long-lived data + structures; if you know the file metadata has changed or if a long time has + elapsed since calling :func:`scandir`, call ``os.stat(entry.path)`` to fetch + up-to-date information. + + Because the ``os.DirEntry`` methods can make operating system calls, they may + also raise :exc:`OSError`. If you need very fine-grained + control over errors, you can catch :exc:`OSError` when calling one of the + ``os.DirEntry`` methods and handle as appropriate. + + To be directly usable as a :term:`path-like object`, ``os.DirEntry`` + implements the :class:`PathLike` interface. + + Attributes and methods on a ``os.DirEntry`` instance are as follows: + + .. attribute:: name + + The entry's base filename, relative to the :func:`scandir` *path* + argument. + + The :attr:`name` attribute will be ``bytes`` if the :func:`scandir` + *path* argument is of type ``bytes`` and ``str`` otherwise. Use + :func:`~os.fsdecode` to decode byte filenames. + + .. attribute:: path + + The entry's full path name: equivalent to ``os.path.join(scandir_path, + entry.name)`` where *scandir_path* is the :func:`scandir` *path* + argument. The path is only absolute if the :func:`scandir` *path* + argument was absolute. If the :func:`scandir` *path* + argument was a :ref:`file descriptor `, the :attr:`path` + attribute is the same as the :attr:`name` attribute. + + The :attr:`path` attribute will be ``bytes`` if the :func:`scandir` + *path* argument is of type ``bytes`` and ``str`` otherwise. Use + :func:`~os.fsdecode` to decode byte filenames. + + .. method:: inode() + + Return the inode number of the entry. + + The result is cached on the ``os.DirEntry`` object. Use + ``os.stat(entry.path, follow_symlinks=False).st_ino`` to fetch up-to-date + information. + + On the first, uncached call, a system call is required on Windows but + not on Unix. + + .. method:: is_dir(\*, follow_symlinks=True) + + Return ``True`` if this entry is a directory or a symbolic link pointing + to a directory; return ``False`` if the entry is or points to any other + kind of file, or if it doesn't exist anymore. + + If *follow_symlinks* is ``False``, return ``True`` only if this entry + is a directory (without following symlinks); return ``False`` if the + entry is any other kind of file or if it doesn't exist anymore. + + The result is cached on the ``os.DirEntry`` object, with a separate cache + for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` along + with :func:`stat.S_ISDIR` to fetch up-to-date information. + + On the first, uncached call, no system call is required in most cases. + Specifically, for non-symlinks, neither Windows or Unix require a system + call, except on certain Unix file systems, such as network file systems, + that return ``dirent.d_type == DT_UNKNOWN``. If the entry is a symlink, + a system call will be required to follow the symlink unless + *follow_symlinks* is ``False``. + + This method can raise :exc:`OSError`, such as :exc:`PermissionError`, + but :exc:`FileNotFoundError` is caught and not raised. + + .. method:: is_file(\*, follow_symlinks=True) + + Return ``True`` if this entry is a file or a symbolic link pointing to a + file; return ``False`` if the entry is or points to a directory or other + non-file entry, or if it doesn't exist anymore. + + If *follow_symlinks* is ``False``, return ``True`` only if this entry + is a file (without following symlinks); return ``False`` if the entry is + a directory or other non-file entry, or if it doesn't exist anymore. + + The result is cached on the ``os.DirEntry`` object. Caching, system calls + made, and exceptions raised are as per :func:`~os.DirEntry.is_dir`. + + .. method:: is_symlink() + + Return ``True`` if this entry is a symbolic link (even if broken); + return ``False`` if the entry points to a directory or any kind of file, + or if it doesn't exist anymore. + + The result is cached on the ``os.DirEntry`` object. Call + :func:`os.path.islink` to fetch up-to-date information. + + On the first, uncached call, no system call is required in most cases. + Specifically, neither Windows or Unix require a system call, except on + certain Unix file systems, such as network file systems, that return + ``dirent.d_type == DT_UNKNOWN``. + + This method can raise :exc:`OSError`, such as :exc:`PermissionError`, + but :exc:`FileNotFoundError` is caught and not raised. + + .. method:: stat(\*, follow_symlinks=True) + + Return a :class:`stat_result` object for this entry. This method + follows symbolic links by default; to stat a symbolic link add the + ``follow_symlinks=False`` argument. + + On Unix, this method always requires a system call. On Windows, it + only requires a system call if *follow_symlinks* is ``True`` and the + entry is a reparse point (for example, a symbolic link or directory + junction). + + On Windows, the ``st_ino``, ``st_dev`` and ``st_nlink`` attributes of the + :class:`stat_result` are always set to zero. Call :func:`os.stat` to + get these attributes. + + The result is cached on the ``os.DirEntry`` object, with a separate cache + for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` to + fetch up-to-date information. + + Note that there is a nice correspondence between several attributes + and methods of ``os.DirEntry`` and of :class:`pathlib.Path`. In + particular, the ``name`` attribute has the same + meaning, as do the ``is_dir()``, ``is_file()``, ``is_symlink()`` + and ``stat()`` methods. + + .. versionadded:: 3.5 + + .. versionchanged:: 3.6 + Added support for the :class:`~os.PathLike` interface. Added support + for :class:`bytes` paths on Windows. + + +.. function:: stat(path, \*, dir_fd=None, follow_symlinks=True) + + Get the status of a file or a file descriptor. Perform the equivalent of a + :c:func:`stat` system call on the given path. *path* may be specified as + either a string or bytes -- directly or indirectly through the :class:`PathLike` + interface -- or as an open file descriptor. Return a :class:`stat_result` + object. + + This function normally follows symlinks; to stat a symlink add the argument + ``follow_symlinks=False``, or use :func:`lstat`. + + This function can support :ref:`specifying a file descriptor ` and + :ref:`not following symlinks `. + + On Windows, passing ``follow_symlinks=False`` will disable following all + name-surrogate reparse points, which includes symlinks and directory + junctions. Other types of reparse points that do not resemble links or that + the operating system is unable to follow will be opened directly. When + following a chain of multiple links, this may result in the original link + being returned instead of the non-link that prevented full traversal. To + obtain stat results for the final path in this case, use the + :func:`os.path.realpath` function to resolve the path name as far as + possible and call :func:`lstat` on the result. This does not apply to + dangling symlinks or junction points, which will raise the usual exceptions. + + .. index:: module: stat + + Example:: + + >>> import os + >>> statinfo = os.stat('somefile.txt') + >>> statinfo + os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026, + st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295, + st_mtime=1297230027, st_ctime=1297230027) + >>> statinfo.st_size + 264 + + .. seealso:: + + :func:`fstat` and :func:`lstat` functions. + + .. versionadded:: 3.3 + Added the *dir_fd* and *follow_symlinks* arguments, specifying a file + descriptor instead of a path. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + .. versionchanged:: 3.8 + On Windows, all reparse points that can be resolved by the operating + system are now followed, and passing ``follow_symlinks=False`` + disables following all name surrogate reparse points. If the operating + system reaches a reparse point that it is not able to follow, *stat* now + returns the information for the original path as if + ``follow_symlinks=False`` had been specified instead of raising an error. + + +.. class:: stat_result + + Object whose attributes correspond roughly to the members of the + :c:type:`stat` structure. It is used for the result of :func:`os.stat`, + :func:`os.fstat` and :func:`os.lstat`. + + Attributes: + + .. attribute:: st_mode + + File mode: file type and file mode bits (permissions). + + .. attribute:: st_ino + + Platform dependent, but if non-zero, uniquely identifies the + file for a given value of ``st_dev``. Typically: + + * the inode number on Unix, + * the `file index + `_ on + Windows + + .. attribute:: st_dev + + Identifier of the device on which this file resides. + + .. attribute:: st_nlink + + Number of hard links. + + .. attribute:: st_uid + + User identifier of the file owner. + + .. attribute:: st_gid + + Group identifier of the file owner. + + .. attribute:: st_size + + Size of the file in bytes, if it is a regular file or a symbolic link. + The size of a symbolic link is the length of the pathname it contains, + without a terminating null byte. + + Timestamps: + + .. attribute:: st_atime + + Time of most recent access expressed in seconds. + + .. attribute:: st_mtime + + Time of most recent content modification expressed in seconds. + + .. attribute:: st_ctime + + Platform dependent: + + * the time of most recent metadata change on Unix, + * the time of creation on Windows, expressed in seconds. + + .. attribute:: st_atime_ns + + Time of most recent access expressed in nanoseconds as an integer. + + .. attribute:: st_mtime_ns + + Time of most recent content modification expressed in nanoseconds as an + integer. + + .. attribute:: st_ctime_ns + + Platform dependent: + + * the time of most recent metadata change on Unix, + * the time of creation on Windows, expressed in nanoseconds as an + integer. + + .. note:: + + The exact meaning and resolution of the :attr:`st_atime`, + :attr:`st_mtime`, and :attr:`st_ctime` attributes depend on the operating + system and the file system. For example, on Windows systems using the FAT + or FAT32 file systems, :attr:`st_mtime` has 2-second resolution, and + :attr:`st_atime` has only 1-day resolution. See your operating system + documentation for details. + + Similarly, although :attr:`st_atime_ns`, :attr:`st_mtime_ns`, + and :attr:`st_ctime_ns` are always expressed in nanoseconds, many + systems do not provide nanosecond precision. On systems that do + provide nanosecond precision, the floating-point object used to + store :attr:`st_atime`, :attr:`st_mtime`, and :attr:`st_ctime` + cannot preserve all of it, and as such will be slightly inexact. + If you need the exact timestamps you should always use + :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and :attr:`st_ctime_ns`. + + On some Unix systems (such as Linux), the following attributes may also be + available: + + .. attribute:: st_blocks + + Number of 512-byte blocks allocated for file. + This may be smaller than :attr:`st_size`/512 when the file has holes. + + .. attribute:: st_blksize + + "Preferred" blocksize for efficient file system I/O. Writing to a file in + smaller chunks may cause an inefficient read-modify-rewrite. + + .. attribute:: st_rdev + + Type of device if an inode device. + + .. attribute:: st_flags + + User defined flags for file. + + On other Unix systems (such as FreeBSD), the following attributes may be + available (but may be only filled out if root tries to use them): + + .. attribute:: st_gen + + File generation number. + + .. attribute:: st_birthtime + + Time of file creation. + + On Solaris and derivatives, the following attributes may also be + available: + + .. attribute:: st_fstype + + String that uniquely identifies the type of the filesystem that + contains the file. + + On Mac OS systems, the following attributes may also be available: + + .. attribute:: st_rsize + + Real size of the file. + + .. attribute:: st_creator + + Creator of the file. + + .. attribute:: st_type + + File type. + + On Windows systems, the following attributes are also available: + + .. attribute:: st_file_attributes + + Windows file attributes: ``dwFileAttributes`` member of the + ``BY_HANDLE_FILE_INFORMATION`` structure returned by + :c:func:`GetFileInformationByHandle`. See the ``FILE_ATTRIBUTE_*`` + constants in the :mod:`stat` module. + + .. attribute:: st_reparse_tag + + When :attr:`st_file_attributes` has the ``FILE_ATTRIBUTE_REPARSE_POINT`` + set, this field contains the tag identifying the type of reparse point. + See the ``IO_REPARSE_TAG_*`` constants in the :mod:`stat` module. + + The standard module :mod:`stat` defines functions and constants that are + useful for extracting information from a :c:type:`stat` structure. (On + Windows, some items are filled with dummy values.) + + For backward compatibility, a :class:`stat_result` instance is also + accessible as a tuple of at least 10 integers giving the most important (and + portable) members of the :c:type:`stat` structure, in the order + :attr:`st_mode`, :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, + :attr:`st_uid`, :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, + :attr:`st_mtime`, :attr:`st_ctime`. More items may be added at the end by + some implementations. For compatibility with older Python versions, + accessing :class:`stat_result` as a tuple always returns integers. + + .. versionadded:: 3.3 + Added the :attr:`st_atime_ns`, :attr:`st_mtime_ns`, and + :attr:`st_ctime_ns` members. + + .. versionadded:: 3.5 + Added the :attr:`st_file_attributes` member on Windows. + + .. versionchanged:: 3.5 + Windows now returns the file index as :attr:`st_ino` when + available. + + .. versionadded:: 3.7 + Added the :attr:`st_fstype` member to Solaris/derivatives. + + .. versionadded:: 3.8 + Added the :attr:`st_reparse_tag` member on Windows. + + .. versionchanged:: 3.8 + On Windows, the :attr:`st_mode` member now identifies special + files as :const:`S_IFCHR`, :const:`S_IFIFO` or :const:`S_IFBLK` + as appropriate. + +.. function:: statvfs(path) + + Perform a :c:func:`statvfs` system call on the given path. The return value is + an object whose attributes describe the filesystem on the given path, and + correspond to the members of the :c:type:`statvfs` structure, namely: + :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`, + :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`, + :attr:`f_flag`, :attr:`f_namemax`, :attr:`f_fsid`. + + Two module-level constants are defined for the :attr:`f_flag` attribute's + bit-flags: if :const:`ST_RDONLY` is set, the filesystem is mounted + read-only, and if :const:`ST_NOSUID` is set, the semantics of + setuid/setgid bits are disabled or not supported. + + Additional module-level constants are defined for GNU/glibc based systems. + These are :const:`ST_NODEV` (disallow access to device special files), + :const:`ST_NOEXEC` (disallow program execution), :const:`ST_SYNCHRONOUS` + (writes are synced at once), :const:`ST_MANDLOCK` (allow mandatory locks on an FS), + :const:`ST_WRITE` (write on file/directory/symlink), :const:`ST_APPEND` + (append-only file), :const:`ST_IMMUTABLE` (immutable file), :const:`ST_NOATIME` + (do not update access times), :const:`ST_NODIRATIME` (do not update directory access + times), :const:`ST_RELATIME` (update atime relative to mtime/ctime). + + This function can support :ref:`specifying a file descriptor `. + + .. availability:: Unix. + + .. versionchanged:: 3.2 + The :const:`ST_RDONLY` and :const:`ST_NOSUID` constants were added. + + .. versionadded:: 3.3 + Added support for specifying *path* as an open file descriptor. + + .. versionchanged:: 3.4 + The :const:`ST_NODEV`, :const:`ST_NOEXEC`, :const:`ST_SYNCHRONOUS`, + :const:`ST_MANDLOCK`, :const:`ST_WRITE`, :const:`ST_APPEND`, + :const:`ST_IMMUTABLE`, :const:`ST_NOATIME`, :const:`ST_NODIRATIME`, + and :const:`ST_RELATIME` constants were added. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + .. versionadded:: 3.7 + Added :attr:`f_fsid`. + + +.. data:: supports_dir_fd + + A :class:`set` object indicating which functions in the :mod:`os` + module accept an open file descriptor for their *dir_fd* parameter. + Different platforms provide different features, and the underlying + functionality Python uses to implement the *dir_fd* parameter is not + available on all platforms Python supports. For consistency's sake, + functions that may support *dir_fd* always allow specifying the + parameter, but will throw an exception if the functionality is used + when it's not locally available. (Specifying ``None`` for *dir_fd* + is always supported on all platforms.) + + To check whether a particular function accepts an open file descriptor + for its *dir_fd* parameter, use the ``in`` operator on ``supports_dir_fd``. + As an example, this expression evaluates to ``True`` if :func:`os.stat` + accepts open file descriptors for *dir_fd* on the local platform:: + + os.stat in os.supports_dir_fd + + Currently *dir_fd* parameters only work on Unix platforms; + none of them work on Windows. + + .. versionadded:: 3.3 + + +.. data:: supports_effective_ids + + A :class:`set` object indicating whether :func:`os.access` permits + specifying ``True`` for its *effective_ids* parameter on the local platform. + (Specifying ``False`` for *effective_ids* is always supported on all + platforms.) If the local platform supports it, the collection will contain + :func:`os.access`; otherwise it will be empty. + + This expression evaluates to ``True`` if :func:`os.access` supports + ``effective_ids=True`` on the local platform:: + + os.access in os.supports_effective_ids + + Currently *effective_ids* is only supported on Unix platforms; + it does not work on Windows. + + .. versionadded:: 3.3 + + +.. data:: supports_fd + + A :class:`set` object indicating which functions in the + :mod:`os` module permit specifying their *path* parameter as an open file + descriptor on the local platform. Different platforms provide different + features, and the underlying functionality Python uses to accept open file + descriptors as *path* arguments is not available on all platforms Python + supports. + + To determine whether a particular function permits specifying an open file + descriptor for its *path* parameter, use the ``in`` operator on + ``supports_fd``. As an example, this expression evaluates to ``True`` if + :func:`os.chdir` accepts open file descriptors for *path* on your local + platform:: + + os.chdir in os.supports_fd + + .. versionadded:: 3.3 + + +.. data:: supports_follow_symlinks + + A :class:`set` object indicating which functions in the :mod:`os` module + accept ``False`` for their *follow_symlinks* parameter on the local platform. + Different platforms provide different features, and the underlying + functionality Python uses to implement *follow_symlinks* is not available + on all platforms Python supports. For consistency's sake, functions that + may support *follow_symlinks* always allow specifying the parameter, but + will throw an exception if the functionality is used when it's not locally + available. (Specifying ``True`` for *follow_symlinks* is always supported + on all platforms.) + + To check whether a particular function accepts ``False`` for its + *follow_symlinks* parameter, use the ``in`` operator on + ``supports_follow_symlinks``. As an example, this expression evaluates + to ``True`` if you may specify ``follow_symlinks=False`` when calling + :func:`os.stat` on the local platform:: + + os.stat in os.supports_follow_symlinks + + .. versionadded:: 3.3 + + +.. function:: symlink(src, dst, target_is_directory=False, *, dir_fd=None) + + Create a symbolic link pointing to *src* named *dst*. + + On Windows, a symlink represents either a file or a directory, and does not + morph to the target dynamically. If the target is present, the type of the + symlink will be created to match. Otherwise, the symlink will be created + as a directory if *target_is_directory* is ``True`` or a file symlink (the + default) otherwise. On non-Windows platforms, *target_is_directory* is ignored. + + This function can support :ref:`paths relative to directory descriptors + `. + + .. note:: + + On newer versions of Windows 10, unprivileged accounts can create symlinks + if Developer Mode is enabled. When Developer Mode is not available/enabled, + the *SeCreateSymbolicLinkPrivilege* privilege is required, or the process + must be run as an administrator. + + + :exc:`OSError` is raised when the function is called by an unprivileged + user. + + .. audit-event:: os.symlink src,dst,dir_fd os.symlink + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.2 + Added support for Windows 6.0 (Vista) symbolic links. + + .. versionadded:: 3.3 + Added the *dir_fd* argument, and now allow *target_is_directory* + on non-Windows platforms. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` for *src* and *dst*. + + .. versionchanged:: 3.8 + Added support for unelevated symlinks on Windows with Developer Mode. + + +.. function:: sync() + + Force write of everything to disk. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: truncate(path, length) + + Truncate the file corresponding to *path*, so that it is at most + *length* bytes in size. + + This function can support :ref:`specifying a file descriptor `. + + .. audit-event:: os.truncate path,length os.truncate + + .. availability:: Unix, Windows. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.5 + Added support for Windows + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: unlink(path, *, dir_fd=None) + + Remove (delete) the file *path*. This function is semantically + identical to :func:`remove`; the ``unlink`` name is its + traditional Unix name. Please see the documentation for + :func:`remove` for further information. + + .. audit-event:: os.remove path,dir_fd os.unlink + + .. versionadded:: 3.3 + The *dir_fd* parameter. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True) + + Set the access and modified times of the file specified by *path*. + + :func:`utime` takes two optional parameters, *times* and *ns*. + These specify the times set on *path* and are used as follows: + + - If *ns* is specified, + it must be a 2-tuple of the form ``(atime_ns, mtime_ns)`` + where each member is an int expressing nanoseconds. + - If *times* is not ``None``, + it must be a 2-tuple of the form ``(atime, mtime)`` + where each member is an int or float expressing seconds. + - If *times* is ``None`` and *ns* is unspecified, + this is equivalent to specifying ``ns=(atime_ns, mtime_ns)`` + where both times are the current time. + + It is an error to specify tuples for both *times* and *ns*. + + Note that the exact times you set here may not be returned by a subsequent + :func:`~os.stat` call, depending on the resolution with which your operating + system records access and modification times; see :func:`~os.stat`. The best + way to preserve exact times is to use the *st_atime_ns* and *st_mtime_ns* + fields from the :func:`os.stat` result object with the *ns* parameter to + `utime`. + + This function can support :ref:`specifying a file descriptor `, + :ref:`paths relative to directory descriptors ` and :ref:`not + following symlinks `. + + .. audit-event:: os.utime path,times,ns,dir_fd os.utime + + .. versionadded:: 3.3 + Added support for specifying *path* as an open file descriptor, + and the *dir_fd*, *follow_symlinks*, and *ns* parameters. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: walk(top, topdown=True, onerror=None, followlinks=False) + + .. index:: + single: directory; walking + single: directory; traversal + + Generate the file names in a directory tree by walking the tree + either top-down or bottom-up. For each directory in the tree rooted at directory + *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames, + filenames)``. + + *dirpath* is a string, the path to the directory. *dirnames* is a list of the + names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``). + *filenames* is a list of the names of the non-directory files in *dirpath*. + Note that the names in the lists contain no path components. To get a full path + (which begins with *top*) to a file or directory in *dirpath*, do + ``os.path.join(dirpath, name)``. + + If optional argument *topdown* is ``True`` or not specified, the triple for a + directory is generated before the triples for any of its subdirectories + (directories are generated top-down). If *topdown* is ``False``, the triple + for a directory is generated after the triples for all of its subdirectories + (directories are generated bottom-up). No matter the value of *topdown*, the + list of subdirectories is retrieved before the tuples for the directory and + its subdirectories are generated. + + When *topdown* is ``True``, the caller can modify the *dirnames* list in-place + (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only + recurse into the subdirectories whose names remain in *dirnames*; this can be + used to prune the search, impose a specific order of visiting, or even to inform + :func:`walk` about directories the caller creates or renames before it resumes + :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` has + no effect on the behavior of the walk, because in bottom-up mode the directories + in *dirnames* are generated before *dirpath* itself is generated. + + By default, errors from the :func:`scandir` call are ignored. If optional + argument *onerror* is specified, it should be a function; it will be called with + one argument, an :exc:`OSError` instance. It can report the error to continue + with the walk, or raise the exception to abort the walk. Note that the filename + is available as the ``filename`` attribute of the exception object. + + By default, :func:`walk` will not walk down into symbolic links that resolve to + directories. Set *followlinks* to ``True`` to visit directories pointed to by + symlinks, on systems that support them. + + .. note:: + + Be aware that setting *followlinks* to ``True`` can lead to infinite + recursion if a link points to a parent directory of itself. :func:`walk` + does not keep track of the directories it visited already. + + .. note:: + + If you pass a relative pathname, don't change the current working directory + between resumptions of :func:`walk`. :func:`walk` never changes the current + directory, and assumes that its caller doesn't either. + + This example displays the number of bytes taken by non-directory files in each + directory under the starting directory, except that it doesn't look under any + CVS subdirectory:: + + import os + from os.path import join, getsize + for root, dirs, files in os.walk('python/Lib/email'): + print(root, "consumes", end=" ") + print(sum(getsize(join(root, name)) for name in files), end=" ") + print("bytes in", len(files), "non-directory files") + if 'CVS' in dirs: + dirs.remove('CVS') # don't visit CVS directories + + In the next example (simple implementation of :func:`shutil.rmtree`), + walking the tree bottom-up is essential, :func:`rmdir` doesn't allow + deleting a directory before the directory is empty:: + + # Delete everything reachable from the directory named in "top", + # assuming there are no symbolic links. + # CAUTION: This is dangerous! For example, if top == '/', it + # could delete all your disk files. + import os + for root, dirs, files in os.walk(top, topdown=False): + for name in files: + os.remove(os.path.join(root, name)) + for name in dirs: + os.rmdir(os.path.join(root, name)) + + .. audit-event:: os.walk top,topdown,onerror,followlinks os.walk + + .. versionchanged:: 3.5 + This function now calls :func:`os.scandir` instead of :func:`os.listdir`, + making it faster by reducing the number of calls to :func:`os.stat`. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None) + + .. index:: + single: directory; walking + single: directory; traversal + + This behaves exactly like :func:`walk`, except that it yields a 4-tuple + ``(dirpath, dirnames, filenames, dirfd)``, and it supports ``dir_fd``. + + *dirpath*, *dirnames* and *filenames* are identical to :func:`walk` output, + and *dirfd* is a file descriptor referring to the directory *dirpath*. + + This function always supports :ref:`paths relative to directory descriptors + ` and :ref:`not following symlinks `. Note however + that, unlike other functions, the :func:`fwalk` default value for + *follow_symlinks* is ``False``. + + .. note:: + + Since :func:`fwalk` yields file descriptors, those are only valid until + the next iteration step, so you should duplicate them (e.g. with + :func:`dup`) if you want to keep them longer. + + This example displays the number of bytes taken by non-directory files in each + directory under the starting directory, except that it doesn't look under any + CVS subdirectory:: + + import os + for root, dirs, files, rootfd in os.fwalk('python/Lib/email'): + print(root, "consumes", end="") + print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]), + end="") + print("bytes in", len(files), "non-directory files") + if 'CVS' in dirs: + dirs.remove('CVS') # don't visit CVS directories + + In the next example, walking the tree bottom-up is essential: + :func:`rmdir` doesn't allow deleting a directory before the directory is + empty:: + + # Delete everything reachable from the directory named in "top", + # assuming there are no symbolic links. + # CAUTION: This is dangerous! For example, if top == '/', it + # could delete all your disk files. + import os + for root, dirs, files, rootfd in os.fwalk(top, topdown=False): + for name in files: + os.unlink(name, dir_fd=rootfd) + for name in dirs: + os.rmdir(name, dir_fd=rootfd) + + .. audit-event:: os.fwalk top,topdown,onerror,follow_symlinks,dir_fd os.fwalk + + .. availability:: Unix. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + .. versionchanged:: 3.7 + Added support for :class:`bytes` paths. + + +.. function:: memfd_create(name[, flags=os.MFD_CLOEXEC]) + + Create an anonymous file and return a file descriptor that refers to it. + *flags* must be one of the ``os.MFD_*`` constants available on the system + (or a bitwise ORed combination of them). By default, the new file + descriptor is :ref:`non-inheritable `. + + The name supplied in *name* is used as a filename and will be displayed as + the target of the corresponding symbolic link in the directory + ``/proc/self/fd/``. The displayed name is always prefixed with ``memfd:`` + and serves only for debugging purposes. Names do not affect the behavior of + the file descriptor, and as such multiple files can have the same name + without any side effects. + + .. availability:: Linux 3.17 or newer with glibc 2.27 or newer. + + .. versionadded:: 3.8 + + +.. data:: MFD_CLOEXEC + MFD_ALLOW_SEALING + MFD_HUGETLB + MFD_HUGE_SHIFT + MFD_HUGE_MASK + MFD_HUGE_64KB + MFD_HUGE_512KB + MFD_HUGE_1MB + MFD_HUGE_2MB + MFD_HUGE_8MB + MFD_HUGE_16MB + MFD_HUGE_32MB + MFD_HUGE_256MB + MFD_HUGE_512MB + MFD_HUGE_1GB + MFD_HUGE_2GB + MFD_HUGE_16GB + + These flags can be passed to :func:`memfd_create`. + + .. availability:: Linux 3.17 or newer with glibc 2.27 or newer. The + ``MFD_HUGE*`` flags are only available since Linux 4.14. + + .. versionadded:: 3.8 + + +Linux extended attributes +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 3.3 + +These functions are all available on Linux only. + +.. function:: getxattr(path, attribute, *, follow_symlinks=True) + + Return the value of the extended filesystem attribute *attribute* for + *path*. *attribute* can be bytes or str (directly or indirectly through the + :class:`PathLike` interface). If it is str, it is encoded with the filesystem + encoding. + + This function can support :ref:`specifying a file descriptor ` and + :ref:`not following symlinks `. + + .. audit-event:: os.getxattr path,attribute os.getxattr + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` for *path* and *attribute*. + + +.. function:: listxattr(path=None, *, follow_symlinks=True) + + Return a list of the extended filesystem attributes on *path*. The + attributes in the list are represented as strings decoded with the filesystem + encoding. If *path* is ``None``, :func:`listxattr` will examine the current + directory. + + This function can support :ref:`specifying a file descriptor ` and + :ref:`not following symlinks `. + + .. audit-event:: os.listxattr path os.listxattr + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. function:: removexattr(path, attribute, *, follow_symlinks=True) + + Removes the extended filesystem attribute *attribute* from *path*. + *attribute* should be bytes or str (directly or indirectly through the + :class:`PathLike` interface). If it is a string, it is encoded + with the filesystem encoding. + + This function can support :ref:`specifying a file descriptor ` and + :ref:`not following symlinks `. + + .. audit-event:: os.removexattr path,attribute os.removexattr + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` for *path* and *attribute*. + + +.. function:: setxattr(path, attribute, value, flags=0, *, follow_symlinks=True) + + Set the extended filesystem attribute *attribute* on *path* to *value*. + *attribute* must be a bytes or str with no embedded NULs (directly or + indirectly through the :class:`PathLike` interface). If it is a str, + it is encoded with the filesystem encoding. *flags* may be + :data:`XATTR_REPLACE` or :data:`XATTR_CREATE`. If :data:`XATTR_REPLACE` is + given and the attribute does not exist, ``EEXISTS`` will be raised. + If :data:`XATTR_CREATE` is given and the attribute already exists, the + attribute will not be created and ``ENODATA`` will be raised. + + This function can support :ref:`specifying a file descriptor ` and + :ref:`not following symlinks `. + + .. note:: + + A bug in Linux kernel versions less than 2.6.39 caused the flags argument + to be ignored on some filesystems. + + .. audit-event:: os.setxattr path,attribute,value,flags os.setxattr + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object` for *path* and *attribute*. + + +.. data:: XATTR_SIZE_MAX + + The maximum size the value of an extended attribute can be. Currently, this + is 64 KiB on Linux. + + +.. data:: XATTR_CREATE + + This is a possible value for the flags argument in :func:`setxattr`. It + indicates the operation must create an attribute. + + +.. data:: XATTR_REPLACE + + This is a possible value for the flags argument in :func:`setxattr`. It + indicates the operation must replace an existing attribute. + + +.. _os-process: + +Process Management +------------------ + +These functions may be used to create and manage processes. + +The various :func:`exec\* ` functions take a list of arguments for the new +program loaded into the process. In each case, the first of these arguments is +passed to the new program as its own name rather than as an argument a user may +have typed on a command line. For the C programmer, this is the ``argv[0]`` +passed to a program's :c:func:`main`. For example, ``os.execv('/bin/echo', +['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem +to be ignored. + + +.. function:: abort() + + Generate a :const:`SIGABRT` signal to the current process. On Unix, the default + behavior is to produce a core dump; on Windows, the process immediately returns + an exit code of ``3``. Be aware that calling this function will not call the + Python signal handler registered for :const:`SIGABRT` with + :func:`signal.signal`. + + +.. function:: add_dll_directory(path) + + Add a path to the DLL search path. + + This search path is used when resolving dependencies for imported + extension modules (the module itself is resolved through sys.path), + and also by :mod:`ctypes`. + + Remove the directory by calling **close()** on the returned object + or using it in a :keyword:`with` statement. + + See the `Microsoft documentation + `_ + for more information about how DLLs are loaded. + + .. audit-event:: os.add_dll_directory path os.add_dll_directory + + .. availability:: Windows. + + .. versionadded:: 3.8 + Previous versions of CPython would resolve DLLs using the default + behavior for the current process. This led to inconsistencies, + such as only sometimes searching :envvar:`PATH` or the current + working directory, and OS functions such as ``AddDllDirectory`` + having no effect. + + In 3.8, the two primary ways DLLs are loaded now explicitly + override the process-wide behavior to ensure consistency. See the + :ref:`porting notes ` for information on + updating libraries. + + +.. function:: execl(path, arg0, arg1, ...) + execle(path, arg0, arg1, ..., env) + execlp(file, arg0, arg1, ...) + execlpe(file, arg0, arg1, ..., env) + execv(path, args) + execve(path, args, env) + execvp(file, args) + execvpe(file, args, env) + + 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. + + The current process is replaced immediately. Open file objects and + descriptors are not flushed, so if there may be data buffered + on these open files, you should flush them using + :func:`sys.stdout.flush` or :func:`os.fsync` before calling an + :func:`exec\* ` function. + + The "l" and "v" variants of the :func:`exec\* ` functions differ in how + command-line arguments are passed. The "l" variants are perhaps the easiest + to work with if the number of parameters is fixed when the code is written; the + individual parameters simply become additional parameters to the :func:`execl\*` + functions. The "v" variants are good when the number of parameters is + variable, with the arguments being passed in a list or tuple as the *args* + parameter. In either case, the arguments to the child process should start with + the name of the command being run, but this is not enforced. + + The variants which include a "p" near the end (:func:`execlp`, + :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the + :envvar:`PATH` environment variable to locate the program *file*. When the + environment is being replaced (using one of the :func:`exec\*e ` variants, + discussed in the next paragraph), the new environment is used as the source of + the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`, + :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to + locate the executable; *path* must contain an appropriate absolute or relative + path. + + For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note + that these all end in "e"), the *env* parameter must be a mapping which is + 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. + + For :func:`execve` on some platforms, *path* may also be specified as an open + file descriptor. This functionality may not be supported on your platform; + you can check whether or not it is available using :data:`os.supports_fd`. + If it is unavailable, using it will raise a :exc:`NotImplementedError`. + + .. audit-event:: os.exec path,args,env os.execl + + .. availability:: Unix, Windows. + + .. versionadded:: 3.3 + Added support for specifying *path* as an open file descriptor + for :func:`execve`. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + +.. function:: _exit(n) + + Exit the process with status *n*, without calling cleanup handlers, flushing + stdio buffers, etc. + + .. note:: + + The standard way to exit is ``sys.exit(n)``. :func:`_exit` should + normally only be used in the child process after a :func:`fork`. + +The following exit codes are defined and can be used with :func:`_exit`, +although they are not required. These are typically used for system programs +written in Python, such as a mail server's external command delivery program. + +.. note:: + + Some of these may not be available on all Unix platforms, since there is some + variation. These constants are defined where they are defined by the underlying + platform. + + +.. data:: EX_OK + + Exit code that means no error occurred. + + .. availability:: Unix. + + +.. data:: EX_USAGE + + Exit code that means the command was used incorrectly, such as when the wrong + number of arguments are given. + + .. availability:: Unix. + + +.. data:: EX_DATAERR + + Exit code that means the input data was incorrect. + + .. availability:: Unix. + + +.. data:: EX_NOINPUT + + Exit code that means an input file did not exist or was not readable. + + .. availability:: Unix. + + +.. data:: EX_NOUSER + + Exit code that means a specified user did not exist. + + .. availability:: Unix. + + +.. data:: EX_NOHOST + + Exit code that means a specified host did not exist. + + .. availability:: Unix. + + +.. data:: EX_UNAVAILABLE + + Exit code that means that a required service is unavailable. + + .. availability:: Unix. + + +.. data:: EX_SOFTWARE + + Exit code that means an internal software error was detected. + + .. availability:: Unix. + + +.. data:: EX_OSERR + + Exit code that means an operating system error was detected, such as the + inability to fork or create a pipe. + + .. availability:: Unix. + + +.. data:: EX_OSFILE + + Exit code that means some system file did not exist, could not be opened, or had + some other kind of error. + + .. availability:: Unix. + + +.. data:: EX_CANTCREAT + + Exit code that means a user specified output file could not be created. + + .. availability:: Unix. + + +.. data:: EX_IOERR + + Exit code that means that an error occurred while doing I/O on some file. + + .. availability:: Unix. + + +.. data:: EX_TEMPFAIL + + Exit code that means a temporary failure occurred. This indicates something + that may not really be an error, such as a network connection that couldn't be + made during a retryable operation. + + .. availability:: Unix. + + +.. data:: EX_PROTOCOL + + Exit code that means that a protocol exchange was illegal, invalid, or not + understood. + + .. availability:: Unix. + + +.. data:: EX_NOPERM + + Exit code that means that there were insufficient permissions to perform the + operation (but not intended for file system problems). + + .. availability:: Unix. + + +.. data:: EX_CONFIG + + Exit code that means that some kind of configuration error occurred. + + .. availability:: Unix. + + +.. data:: EX_NOTFOUND + + Exit code that means something like "an entry was not found". + + .. availability:: Unix. + + +.. function:: fork() + + Fork a child process. Return ``0`` in the child and the child's process id in the + parent. If an error occurs :exc:`OSError` is raised. + + Note that some platforms including FreeBSD <= 6.3 and Cygwin have + known issues when using ``fork()`` from a thread. + + .. audit-event:: os.fork "" os.fork + + .. versionchanged:: 3.8 + Calling ``fork()`` in a subinterpreter is no longer supported + (:exc:`RuntimeError` is raised). + + .. warning:: + + See :mod:`ssl` for applications that use the SSL module with fork(). + + .. availability:: Unix. + + +.. function:: forkpty() + + Fork a child process, using a new pseudo-terminal as the child's controlling + terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the + new child's process id in the parent, and *fd* is the file descriptor of the + master end of the pseudo-terminal. For a more portable approach, use the + :mod:`pty` module. If an error occurs :exc:`OSError` is raised. + + .. audit-event:: os.forkpty "" os.forkpty + + .. versionchanged:: 3.8 + Calling ``forkpty()`` in a subinterpreter is no longer supported + (:exc:`RuntimeError` is raised). + + .. availability:: some flavors of Unix. + + +.. function:: kill(pid, sig) + + .. index:: + single: process; killing + single: process; signalling + + Send signal *sig* to the process *pid*. Constants for the specific signals + available on the host platform are defined in the :mod:`signal` module. + + Windows: The :data:`signal.CTRL_C_EVENT` and + :data:`signal.CTRL_BREAK_EVENT` signals are special signals which can + only be sent to console processes which share a common console window, + e.g., some subprocesses. Any other value for *sig* will cause the process + to be unconditionally killed by the TerminateProcess API, and the exit code + will be set to *sig*. The Windows version of :func:`kill` additionally takes + process handles to be killed. + + See also :func:`signal.pthread_kill`. + + .. audit-event:: os.kill pid,sig os.kill + + .. versionadded:: 3.2 + Windows support. + + +.. function:: killpg(pgid, sig) + + .. index:: + single: process; killing + single: process; signalling + + Send the signal *sig* to the process group *pgid*. + + .. audit-event:: os.killpg pgid,sig os.killpg + + .. availability:: Unix. + + +.. function:: nice(increment) + + Add *increment* to the process's "niceness". Return the new niceness. + + .. availability:: Unix. + + +.. function:: pidfd_open(pid, flags=0) + + Return a file descriptor referring to the process *pid*. This descriptor can + be used to perform process management without races and signals. The *flags* + argument is provided for future extensions; no flag values are currently + defined. + + See the :manpage:`pidfd_open(2)` man page for more details. + + .. availability:: Linux 5.3+ + .. versionadded:: 3.9 + + +.. function:: plock(op) + + Lock program segments into memory. The value of *op* (defined in + ````) determines which segments are locked. + + .. availability:: Unix. + + +.. function:: popen(cmd, mode='r', buffering=-1) + + Open a pipe to or from command *cmd*. + The return value is an open file object + connected to the pipe, which can be read or written depending on whether *mode* + is ``'r'`` (default) or ``'w'``. The *buffering* argument has the same meaning as + the corresponding argument to the built-in :func:`open` function. The + returned file object reads or writes text strings rather than bytes. + + The ``close`` method returns :const:`None` if the subprocess exited + successfully, or the subprocess's return code if there was an + error. On POSIX systems, if the return code is positive it + represents the return value of the process left-shifted by one + byte. If the return code is negative, the process was terminated + by the signal given by the negated value of the return code. (For + example, the return value might be ``- signal.SIGKILL`` if the + subprocess was killed.) On Windows systems, the return value + contains the signed integer return code from the child process. + + On Unix, :func:`waitstatus_to_exitcode` can be used to convert the ``close`` + method result (exit status) into an exit code if it is not ``None``. On + Windows, the ``close`` method result is directly the exit code + (or ``None``). + + This is implemented using :class:`subprocess.Popen`; see that class's + documentation for more powerful ways to manage and communicate with + subprocesses. + + +.. function:: posix_spawn(path, argv, env, *, file_actions=None, \ + setpgroup=None, resetids=False, setsid=False, setsigmask=(), \ + setsigdef=(), scheduler=None) + + Wraps the :c:func:`posix_spawn` C library API for use from Python. + + Most users should use :func:`subprocess.run` instead of :func:`posix_spawn`. + + The positional-only arguments *path*, *args*, and *env* are similar to + :func:`execve`. + + The *path* parameter is the path to the executable file.The *path* should + contain a directory.Use :func:`posix_spawnp` to pass an executable file + without directory. + + The *file_actions* argument may be a sequence of tuples describing actions + to take on specific file descriptors in the child process between the C + library implementation's :c:func:`fork` and :c:func:`exec` steps. + The first item in each tuple must be one of the three type indicator + listed below describing the remaining tuple elements: + + .. data:: POSIX_SPAWN_OPEN + + (``os.POSIX_SPAWN_OPEN``, *fd*, *path*, *flags*, *mode*) + + Performs ``os.dup2(os.open(path, flags, mode), fd)``. + + .. data:: POSIX_SPAWN_CLOSE + + (``os.POSIX_SPAWN_CLOSE``, *fd*) + + Performs ``os.close(fd)``. + + .. data:: POSIX_SPAWN_DUP2 + + (``os.POSIX_SPAWN_DUP2``, *fd*, *new_fd*) + + Performs ``os.dup2(fd, new_fd)``. + + These tuples correspond to the C library + :c:func:`posix_spawn_file_actions_addopen`, + :c:func:`posix_spawn_file_actions_addclose`, and + :c:func:`posix_spawn_file_actions_adddup2` API calls used to prepare + for the :c:func:`posix_spawn` call itself. + + The *setpgroup* argument will set the process group of the child to the value + specified. If the value specified is 0, the child's process group ID will be + made the same as its process ID. If the value of *setpgroup* is not set, the + child will inherit the parent's process group ID. This argument corresponds + to the C library :c:data:`POSIX_SPAWN_SETPGROUP` flag. + + If the *resetids* argument is ``True`` it will reset the effective UID and + GID of the child to the real UID and GID of the parent process. If the + argument is ``False``, then the child retains the effective UID and GID of + the parent. In either case, if the set-user-ID and set-group-ID permission + bits are enabled on the executable file, their effect will override the + setting of the effective UID and GID. This argument corresponds to the C + library :c:data:`POSIX_SPAWN_RESETIDS` flag. + + If the *setsid* argument is ``True``, it will create a new session ID + for `posix_spawn`. *setsid* requires :c:data:`POSIX_SPAWN_SETSID` + or :c:data:`POSIX_SPAWN_SETSID_NP` flag. Otherwise, :exc:`NotImplementedError` + is raised. + + The *setsigmask* argument will set the signal mask to the signal set + specified. If the parameter is not used, then the child inherits the + parent's signal mask. This argument corresponds to the C library + :c:data:`POSIX_SPAWN_SETSIGMASK` flag. + + The *sigdef* argument will reset the disposition of all signals in the set + specified. This argument corresponds to the C library + :c:data:`POSIX_SPAWN_SETSIGDEF` flag. + + The *scheduler* argument must be a tuple containing the (optional) scheduler + policy and an instance of :class:`sched_param` with the scheduler parameters. + A value of ``None`` in the place of the scheduler policy indicates that is + not being provided. This argument is a combination of the C library + :c:data:`POSIX_SPAWN_SETSCHEDPARAM` and :c:data:`POSIX_SPAWN_SETSCHEDULER` + flags. + + .. audit-event:: os.posix_spawn path,argv,env os.posix_spawn + + .. versionadded:: 3.8 + + .. availability:: Unix. + +.. function:: posix_spawnp(path, argv, env, *, file_actions=None, \ + setpgroup=None, resetids=False, setsid=False, setsigmask=(), \ + setsigdef=(), scheduler=None) + + Wraps the :c:func:`posix_spawnp` C library API for use from Python. + + Similar to :func:`posix_spawn` except that the system searches + for the *executable* file in the list of directories specified by the + :envvar:`PATH` environment variable (in the same way as for ``execvp(3)``). + + .. audit-event:: os.posix_spawn path,argv,env os.posix_spawnp + + .. versionadded:: 3.8 + + .. availability:: See :func:`posix_spawn` documentation. + + +.. function:: register_at_fork(*, before=None, after_in_parent=None, \ + after_in_child=None) + + Register callables to be executed when a new child process is forked + using :func:`os.fork` or similar process cloning APIs. + The parameters are optional and keyword-only. + Each specifies a different call point. + + * *before* is a function called before forking a child process. + * *after_in_parent* is a function called from the parent process + after forking a child process. + * *after_in_child* is a function called from the child process. + + These calls are only made if control is expected to return to the + Python interpreter. A typical :mod:`subprocess` launch will not + trigger them as the child is not going to re-enter the interpreter. + + Functions registered for execution before forking are called in + reverse registration order. Functions registered for execution + after forking (either in the parent or in the child) are called + in registration order. + + Note that :c:func:`fork` calls made by third-party C code may not + call those functions, unless it explicitly calls :c:func:`PyOS_BeforeFork`, + :c:func:`PyOS_AfterFork_Parent` and :c:func:`PyOS_AfterFork_Child`. + + There is no way to unregister a function. + + .. availability:: Unix. + + .. versionadded:: 3.7 + + +.. function:: spawnl(mode, path, ...) + spawnle(mode, path, ..., env) + spawnlp(mode, file, ...) + spawnlpe(mode, file, ..., env) + spawnv(mode, path, args) + spawnve(mode, path, args, env) + spawnvp(mode, file, args) + spawnvpe(mode, file, args, env) + + Execute the program *path* in a new process. + + (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 especially the + :ref:`subprocess-replacements` section.) + + If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new + process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it + exits normally, or ``-signal``, where *signal* is the signal that killed the + process. On Windows, the process id will actually be the process handle, so can + be used with the :func:`waitpid` function. + + Note on VxWorks, this function doesn't return ``-signal`` when the new process is + killed. Instead it raises OSError exception. + + The "l" and "v" variants of the :func:`spawn\* ` functions differ in how + command-line arguments are passed. The "l" variants are perhaps the easiest + to work with if the number of parameters is fixed when the code is written; the + individual parameters simply become additional parameters to the + :func:`spawnl\*` functions. The "v" variants are good when the number of + parameters is variable, with the arguments being passed in a list or tuple as + the *args* parameter. In either case, the arguments to the child process must + start with the name of the command being run. + + The variants which include a second "p" near the end (:func:`spawnlp`, + :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the + :envvar:`PATH` environment variable to locate the program *file*. When the + environment is being replaced (using one of the :func:`spawn\*e ` variants, + discussed in the next paragraph), the new environment is used as the source of + the :envvar:`PATH` variable. The other variants, :func:`spawnl`, + :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the + :envvar:`PATH` variable to locate the executable; *path* must contain an + appropriate absolute or relative path. + + For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe` + (note that these all end in "e"), the *env* parameter must be a mapping + which is used to define the environment variables for the new process (they are + used instead of the current process' environment); the functions + :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause + the new process to inherit the environment of the current process. Note that + keys and values in the *env* dictionary must be strings; invalid keys or + values will cause the function to fail, with a return value of ``127``. + + As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are + equivalent:: + + import os + os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') + + L = ['cp', 'index.html', '/dev/null'] + os.spawnvpe(os.P_WAIT, 'cp', L, os.environ) + + .. audit-event:: os.spawn mode,path,args,env os.spawnl + + .. availability:: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp` + and :func:`spawnvpe` are not available on Windows. :func:`spawnle` and + :func:`spawnve` are not thread-safe on Windows; we advise you to use the + :mod:`subprocess` module instead. + + .. versionchanged:: 3.6 + Accepts a :term:`path-like object`. + + +.. data:: P_NOWAIT + P_NOWAITO + + Possible values for the *mode* parameter to the :func:`spawn\* ` family of + functions. If either of these values is given, the :func:`spawn\*` functions + will return as soon as the new process has been created, with the process id as + the return value. + + .. availability:: Unix, Windows. + + +.. data:: P_WAIT + + Possible value for the *mode* parameter to the :func:`spawn\* ` family of + functions. If this is given as *mode*, the :func:`spawn\*` functions will not + return until the new process has run to completion and will return the exit code + of the process the run is successful, or ``-signal`` if a signal kills the + process. + + .. availability:: Unix, Windows. + + +.. data:: P_DETACH + P_OVERLAY + + Possible values for the *mode* parameter to the :func:`spawn\* ` family of + functions. These are less portable than those listed above. :const:`P_DETACH` + is similar to :const:`P_NOWAIT`, but the new process is detached from the + console of the calling process. If :const:`P_OVERLAY` is used, the current + process will be replaced; the :func:`spawn\* ` function will not return. + + .. availability:: Windows. + + +.. function:: startfile(path[, operation]) + + Start a file with its associated application. + + When *operation* is not specified or ``'open'``, this acts like double-clicking + the file in Windows Explorer, or giving the file name as an argument to the + :program:`start` command from the interactive command shell: the file is opened + with whatever application (if any) its extension is associated. + + When another *operation* is given, it must be a "command verb" that specifies + what should be done with the file. Common verbs documented by Microsoft are + ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and + ``'find'`` (to be used on directories). + + :func:`startfile` returns as soon as the associated application is launched. + There is no option to wait for the application to close, and no way to retrieve + the application's exit status. The *path* parameter is relative to the current + directory. If you want to use an absolute path, make sure the first character + is not a slash (``'/'``); the underlying Win32 :c:func:`ShellExecute` function + doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that + the path is properly encoded for Win32. + + To reduce interpreter startup overhead, the Win32 :c:func:`ShellExecute` + function is not resolved until this function is first called. If the function + cannot be resolved, :exc:`NotImplementedError` will be raised. + + .. audit-event:: os.startfile path,operation os.startfile + + .. availability:: Windows. + + +.. function:: system(command) + + Execute the command (a string) in a subshell. This is implemented by calling + the Standard C function :c:func:`system`, and has the same limitations. + Changes to :data:`sys.stdin`, etc. are not reflected in the environment of + the executed command. If *command* generates any output, it will be sent to + the interpreter standard output stream. + + On Unix, the return value is the exit status of the process encoded in the + format specified for :func:`wait`. Note that POSIX does not specify the + meaning of the return value of the C :c:func:`system` function, so the return + value of the Python function is system-dependent. + + On Windows, the return value is that returned by the system shell after + running *command*. The shell is given by the Windows environment variable + :envvar:`COMSPEC`: it is usually :program:`cmd.exe`, which returns the exit + status of the command run; on systems using a non-native shell, consult your + shell documentation. + + The :mod:`subprocess` module provides more powerful facilities for spawning + new processes and retrieving their results; using that module is preferable + to using this function. See the :ref:`subprocess-replacements` section in + the :mod:`subprocess` documentation for some helpful recipes. + + On Unix, :func:`waitstatus_to_exitcode` can be used to convert the result + (exit status) into an exit code. On Windows, the result is directly the exit + code. + + .. audit-event:: os.system command os.system + + .. availability:: Unix, Windows. + + +.. function:: times() + + Returns the current global process times. + The return value is an object with five attributes: + + * :attr:`user` - user time + * :attr:`system` - system time + * :attr:`children_user` - user time of all child processes + * :attr:`children_system` - system time of all child processes + * :attr:`elapsed` - elapsed real time since a fixed point in the past + + For backwards compatibility, this object also behaves like a five-tuple + containing :attr:`user`, :attr:`system`, :attr:`children_user`, + :attr:`children_system`, and :attr:`elapsed` in that order. + + See the Unix manual page + :manpage:`times(2)` and :manpage:`times(3)` manual page on Unix or `the GetProcessTimes MSDN + `_ + on Windows. On Windows, only :attr:`user` and :attr:`system` are known; the other attributes are zero. + + .. availability:: Unix, Windows. + + .. versionchanged:: 3.3 + Return type changed from a tuple to a tuple-like object + with named attributes. + + +.. function:: wait() + + Wait for completion of a child process, and return a tuple containing its pid + and exit status indication: a 16-bit number, whose low byte is the signal number + that killed the process, and whose high byte is the exit status (if the signal + number is zero); the high bit of the low byte is set if a core file was + produced. + + :func:`waitstatus_to_exitcode` can be used to convert the exit status into an + exit code. + + .. availability:: Unix. + + .. seealso:: + + :func:`waitpid` can be used to wait for the completion of a specific + child process and has more options. + +.. function:: waitid(idtype, id, options) + + Wait for the completion of one or more child processes. + *idtype* can be :data:`P_PID`, :data:`P_PGID`, :data:`P_ALL`, or + :data:`P_PIDFD` on Linux. + *id* specifies the pid to wait on. + *options* is constructed from the ORing of one or more of :data:`WEXITED`, + :data:`WSTOPPED` or :data:`WCONTINUED` and additionally may be ORed with + :data:`WNOHANG` or :data:`WNOWAIT`. The return value is an object + representing the data contained in the :c:type:`siginfo_t` structure, namely: + :attr:`si_pid`, :attr:`si_uid`, :attr:`si_signo`, :attr:`si_status`, + :attr:`si_code` or ``None`` if :data:`WNOHANG` is specified and there are no + children in a waitable state. + + .. availability:: Unix. + + .. versionadded:: 3.3 + +.. data:: P_PID + P_PGID + P_ALL + + These are the possible values for *idtype* in :func:`waitid`. They affect + how *id* is interpreted. + + .. availability:: Unix. + + .. versionadded:: 3.3 + +.. data:: P_PIDFD + + This is a Linux-specific *idtype* that indicates that *id* is a file + descriptor that refers to a process. + + .. availability:: Linux 5.4+ + + .. versionadded:: 3.9 + +.. data:: WEXITED + WSTOPPED + WNOWAIT + + Flags that can be used in *options* in :func:`waitid` that specify what + child signal to wait for. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. data:: CLD_EXITED + CLD_KILLED + CLD_DUMPED + CLD_TRAPPED + CLD_STOPPED + CLD_CONTINUED + + These are the possible values for :attr:`si_code` in the result returned by + :func:`waitid`. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.9 + Added :data:`CLD_KILLED` and :data:`CLD_STOPPED` values. + + +.. function:: waitpid(pid, options) + + The details of this function differ on Unix and Windows. + + On Unix: Wait for completion of a child process given by process id *pid*, and + return a tuple containing its process id and exit status indication (encoded as + for :func:`wait`). The semantics of the call are affected by the value of the + integer *options*, which should be ``0`` for normal operation. + + If *pid* is greater than ``0``, :func:`waitpid` requests status information for + that specific process. If *pid* is ``0``, the request is for the status of any + child in the process group of the current process. If *pid* is ``-1``, the + request pertains to any child of the current process. If *pid* is less than + ``-1``, status is requested for any process in the process group ``-pid`` (the + absolute value of *pid*). + + An :exc:`OSError` is raised with the value of errno when the syscall + returns -1. + + On Windows: Wait for completion of a process given by process handle *pid*, and + return a tuple containing *pid*, and its exit status shifted left by 8 bits + (shifting makes cross-platform use of the function easier). A *pid* less than or + equal to ``0`` has no special meaning on Windows, and raises an exception. The + value of integer *options* has no effect. *pid* can refer to any process whose + id is known, not necessarily a child process. The :func:`spawn\* ` + functions called with :const:`P_NOWAIT` return suitable process handles. + + :func:`waitstatus_to_exitcode` can be used to convert the exit status into an + exit code. + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise an + exception, the function now retries the system call instead of raising an + :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + +.. function:: wait3(options) + + Similar to :func:`waitpid`, except no process id argument is given and a + 3-element tuple containing the child's process id, exit status indication, + and resource usage information is returned. Refer to + :mod:`resource`.\ :func:`~resource.getrusage` for details on resource usage + information. The option argument is the same as that provided to + :func:`waitpid` and :func:`wait4`. + + :func:`waitstatus_to_exitcode` can be used to convert the exit status into an + exitcode. + + .. availability:: Unix. + + +.. function:: wait4(pid, options) + + Similar to :func:`waitpid`, except a 3-element tuple, containing the child's + process id, exit status indication, and resource usage information is returned. + Refer to :mod:`resource`.\ :func:`~resource.getrusage` for details on + resource usage information. The arguments to :func:`wait4` are the same + as those provided to :func:`waitpid`. + + :func:`waitstatus_to_exitcode` can be used to convert the exit status into an + exitcode. + + .. availability:: Unix. + + +.. function:: waitstatus_to_exitcode(status) + + Convert a wait status to an exit code. + + On Unix: + + * If the process exited normally (if ``WIFEXITED(status)`` is true), + return the process exit status (return ``WEXITSTATUS(status)``): + result greater than or equal to 0. + * If the process was terminated by a signal (if ``WIFSIGNALED(status)`` is + true), return ``-signum`` where *signum* is the number of the signal that + caused the process to terminate (return ``-WTERMSIG(status)``): + result less than 0. + * Otherwise, raise a :exc:`ValueError`. + + On Windows, return *status* shifted right by 8 bits. + + On Unix, if the process is being traced or if :func:`waitpid` was called + with :data:`WUNTRACED` option, the caller must first check if + ``WIFSTOPPED(status)`` is true. This function must not be called if + ``WIFSTOPPED(status)`` is true. + + .. seealso:: + + :func:`WIFEXITED`, :func:`WEXITSTATUS`, :func:`WIFSIGNALED`, + :func:`WTERMSIG`, :func:`WIFSTOPPED`, :func:`WSTOPSIG` functions. + + .. versionadded:: 3.9 + + +.. data:: WNOHANG + + The option for :func:`waitpid` to return immediately if no child process status + is available immediately. The function returns ``(0, 0)`` in this case. + + .. availability:: Unix. + + +.. data:: WCONTINUED + + This option causes child processes to be reported if they have been continued + from a job control stop since their status was last reported. + + .. availability:: some Unix systems. + + +.. data:: WUNTRACED + + This option causes child processes to be reported if they have been stopped but + their current state has not been reported since they were stopped. + + .. availability:: Unix. + + +The following functions take a process status code as returned by +:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be +used to determine the disposition of a process. + +.. function:: WCOREDUMP(status) + + Return ``True`` if a core dump was generated for the process, otherwise + return ``False``. + + This function should be employed only if :func:`WIFSIGNALED` is true. + + .. availability:: Unix. + + +.. function:: WIFCONTINUED(status) + + Return ``True`` if a stopped child has been resumed by delivery of + :data:`~signal.SIGCONT` (if the process has been continued from a job + control stop), otherwise return ``False``. + + See :data:`WCONTINUED` option. + + .. availability:: Unix. + + +.. function:: WIFSTOPPED(status) + + Return ``True`` if the process was stopped by delivery of a signal, + otherwise return ``False``. + + :func:`WIFSTOPPED` only returns ``True`` if the :func:`waitpid` call was + done using :data:`WUNTRACED` option or when the process is being traced (see + :manpage:`ptrace(2)`). + + .. availability:: Unix. + +.. function:: WIFSIGNALED(status) + + Return ``True`` if the process was terminated by a signal, otherwise return + ``False``. + + .. availability:: Unix. + + +.. function:: WIFEXITED(status) + + Return ``True`` if the process exited terminated normally, that is, + by calling ``exit()`` or ``_exit()``, or by returning from ``main()``; + otherwise return ``False``. + + .. availability:: Unix. + + +.. function:: WEXITSTATUS(status) + + Return the process exit status. + + This function should be employed only if :func:`WIFEXITED` is true. + + .. availability:: Unix. + + +.. function:: WSTOPSIG(status) + + Return the signal which caused the process to stop. + + This function should be employed only if :func:`WIFSTOPPED` is true. + + .. availability:: Unix. + + +.. function:: WTERMSIG(status) + + Return the number of the signal that caused the process to terminate. + + This function should be employed only if :func:`WIFSIGNALED` is true. + + .. availability:: Unix. + + +Interface to the scheduler +-------------------------- + +These functions control how a process is allocated CPU time by the operating +system. They are only available on some Unix platforms. For more detailed +information, consult your Unix manpages. + +.. versionadded:: 3.3 + +The following scheduling policies are exposed if they are supported by the +operating system. + +.. data:: SCHED_OTHER + + The default scheduling policy. + +.. data:: SCHED_BATCH + + Scheduling policy for CPU-intensive processes that tries to preserve + interactivity on the rest of the computer. + +.. data:: SCHED_IDLE + + Scheduling policy for extremely low priority background tasks. + +.. data:: SCHED_SPORADIC + + Scheduling policy for sporadic server programs. + +.. data:: SCHED_FIFO + + A First In First Out scheduling policy. + +.. data:: SCHED_RR + + A round-robin scheduling policy. + +.. data:: SCHED_RESET_ON_FORK + + This flag can be OR'ed with any other scheduling policy. When a process with + this flag set forks, its child's scheduling policy and priority are reset to + the default. + + +.. class:: sched_param(sched_priority) + + This class represents tunable scheduling parameters used in + :func:`sched_setparam`, :func:`sched_setscheduler`, and + :func:`sched_getparam`. It is immutable. + + At the moment, there is only one possible parameter: + + .. attribute:: sched_priority + + The scheduling priority for a scheduling policy. + + +.. function:: sched_get_priority_min(policy) + + Get the minimum priority value for *policy*. *policy* is one of the + scheduling policy constants above. + + +.. function:: sched_get_priority_max(policy) + + Get the maximum priority value for *policy*. *policy* is one of the + scheduling policy constants above. + + +.. function:: sched_setscheduler(pid, policy, param) + + Set the scheduling policy for the process with PID *pid*. A *pid* of 0 means + the calling process. *policy* is one of the scheduling policy constants + above. *param* is a :class:`sched_param` instance. + + +.. function:: sched_getscheduler(pid) + + Return the scheduling policy for the process with PID *pid*. A *pid* of 0 + means the calling process. The result is one of the scheduling policy + constants above. + + +.. function:: sched_setparam(pid, param) + + Set a scheduling parameters for the process with PID *pid*. A *pid* of 0 means + the calling process. *param* is a :class:`sched_param` instance. + + +.. function:: sched_getparam(pid) + + Return the scheduling parameters as a :class:`sched_param` instance for the + process with PID *pid*. A *pid* of 0 means the calling process. + + +.. function:: sched_rr_get_interval(pid) + + Return the round-robin quantum in seconds for the process with PID *pid*. A + *pid* of 0 means the calling process. + + +.. function:: sched_yield() + + Voluntarily relinquish the CPU. + + +.. function:: sched_setaffinity(pid, mask) + + Restrict the process with PID *pid* (or the current process if zero) to a + set of CPUs. *mask* is an iterable of integers representing the set of + CPUs to which the process should be restricted. + + +.. function:: sched_getaffinity(pid) + + Return the set of CPUs the process with PID *pid* (or the current process + if zero) is restricted to. + + +.. _os-path: + +Miscellaneous System Information +-------------------------------- + + +.. function:: confstr(name) + + Return string-valued system configuration values. *name* specifies the + configuration value to retrieve; it may be a string which is the name of a + defined system value; these names are specified in a number of standards (POSIX, + Unix 95, Unix 98, and others). Some platforms define additional names as well. + The names known to the host operating system are given as the keys of the + ``confstr_names`` dictionary. For configuration variables not included in that + mapping, passing an integer for *name* is also accepted. + + If the configuration value specified by *name* isn't defined, ``None`` is + returned. + + If *name* is a string and is not known, :exc:`ValueError` is raised. If a + specific value for *name* is not supported by the host system, even if it is + included in ``confstr_names``, an :exc:`OSError` is raised with + :const:`errno.EINVAL` for the error number. + + .. availability:: Unix. + + +.. data:: confstr_names + + Dictionary mapping names accepted by :func:`confstr` to the integer values + defined for those names by the host operating system. This can be used to + determine the set of names known to the system. + + .. availability:: Unix. + + +.. function:: cpu_count() + + Return the number of CPUs in the system. Returns ``None`` if undetermined. + + This number is not equivalent to the number of CPUs the current process can + use. The number of usable CPUs can be obtained with + ``len(os.sched_getaffinity(0))`` + + + .. versionadded:: 3.4 + + +.. function:: getloadavg() + + Return the number of processes in the system run queue averaged over the last + 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was + unobtainable. + + .. availability:: Unix. + + +.. function:: sysconf(name) + + Return integer-valued system configuration values. If the configuration value + specified by *name* isn't defined, ``-1`` is returned. The comments regarding + the *name* parameter for :func:`confstr` apply here as well; the dictionary that + provides information on the known names is given by ``sysconf_names``. + + .. availability:: Unix. + + +.. data:: sysconf_names + + Dictionary mapping names accepted by :func:`sysconf` to the integer values + defined for those names by the host operating system. This can be used to + determine the set of names known to the system. + + .. availability:: Unix. + +The following data values are used to support path manipulation operations. These +are defined for all platforms. + +Higher-level operations on pathnames are defined in the :mod:`os.path` module. + + +.. index:: single: . (dot); in pathnames +.. data:: curdir + + The constant string used by the operating system to refer to the current + directory. This is ``'.'`` for Windows and POSIX. Also available via + :mod:`os.path`. + + +.. index:: single: ..; in pathnames +.. data:: pardir + + The constant string used by the operating system to refer to the parent + directory. This is ``'..'`` for Windows and POSIX. Also available via + :mod:`os.path`. + + +.. index:: single: / (slash); in pathnames +.. index:: single: \ (backslash); in pathnames (Windows) +.. data:: sep + + The character used by the operating system to separate pathname components. + This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this + is not sufficient to be able to parse or concatenate pathnames --- use + :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally + useful. Also available via :mod:`os.path`. + + +.. index:: single: / (slash); in pathnames +.. data:: altsep + + An alternative character used by the operating system to separate pathname + components, or ``None`` if only one separator character exists. This is set to + ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via + :mod:`os.path`. + + +.. index:: single: . (dot); in pathnames +.. data:: extsep + + The character which separates the base filename from the extension; for example, + the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`. + + +.. index:: single: : (colon); path separator (POSIX) + single: ; (semicolon) +.. data:: pathsep + + The character conventionally used by the operating system to separate search + path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for + Windows. Also available via :mod:`os.path`. + + +.. data:: defpath + + The default search path used by :func:`exec\*p\* ` and + :func:`spawn\*p\* ` if the environment doesn't have a ``'PATH'`` + key. Also available via :mod:`os.path`. + + +.. data:: linesep + + The string used to separate (or, rather, terminate) lines on the current + platform. This may be a single character, such as ``'\n'`` for POSIX, or + multiple characters, for example, ``'\r\n'`` for Windows. Do not use + *os.linesep* as a line terminator when writing files opened in text mode (the + default); use a single ``'\n'`` instead, on all platforms. + + +.. data:: devnull + + The file path of the null device. For example: ``'/dev/null'`` for + POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`. + +.. data:: RTLD_LAZY + RTLD_NOW + RTLD_GLOBAL + RTLD_LOCAL + RTLD_NODELETE + RTLD_NOLOAD + RTLD_DEEPBIND + + Flags for use with the :func:`~sys.setdlopenflags` and + :func:`~sys.getdlopenflags` functions. See the Unix manual page + :manpage:`dlopen(3)` for what the different flags mean. + + .. versionadded:: 3.3 + + +Random numbers +-------------- + + +.. function:: getrandom(size, flags=0) + + Get up to *size* random bytes. The function can return less bytes than + requested. + + These bytes can be used to seed user-space random number generators or for + cryptographic purposes. + + ``getrandom()`` relies on entropy gathered from device drivers and other + sources of environmental noise. Unnecessarily reading large quantities of + data will have a negative impact on other users of the ``/dev/random`` and + ``/dev/urandom`` devices. + + The flags argument is a bit mask that can contain zero or more of the + following values ORed together: :py:data:`os.GRND_RANDOM` and + :py:data:`GRND_NONBLOCK`. + + See also the `Linux getrandom() manual page + `_. + + .. availability:: Linux 3.17 and newer. + + .. versionadded:: 3.6 + +.. function:: urandom(size) + + Return a string of *size* random bytes suitable for cryptographic use. + + This function returns random bytes from an OS-specific randomness source. The + returned data should be unpredictable enough for cryptographic applications, + though its exact quality depends on the OS implementation. + + On Linux, if the ``getrandom()`` syscall is available, it is used in + blocking mode: block until the system urandom entropy pool is initialized + (128 bits of entropy are collected by the kernel). See the :pep:`524` for + the rationale. On Linux, the :func:`getrandom` function can be used to get + random bytes in non-blocking mode (using the :data:`GRND_NONBLOCK` flag) or + to poll until the system urandom entropy pool is initialized. + + On a Unix-like system, random bytes are read from the ``/dev/urandom`` + device. If the ``/dev/urandom`` device is not available or not readable, the + :exc:`NotImplementedError` exception is raised. + + On Windows, it will use ``CryptGenRandom()``. + + .. seealso:: + The :mod:`secrets` module provides higher level functions. For an + easy-to-use interface to the random number generator provided by your + platform, please see :class:`random.SystemRandom`. + + .. versionchanged:: 3.6.0 + On Linux, ``getrandom()`` is now used in blocking mode to increase the + security. + + .. versionchanged:: 3.5.2 + On Linux, if the ``getrandom()`` syscall blocks (the urandom entropy pool + is not initialized yet), fall back on reading ``/dev/urandom``. + + .. versionchanged:: 3.5 + On Linux 3.17 and newer, the ``getrandom()`` syscall is now used + when available. On OpenBSD 5.6 and newer, the C ``getentropy()`` + function is now used. These functions avoid the usage of an internal file + descriptor. + +.. data:: GRND_NONBLOCK + + By default, when reading from ``/dev/random``, :func:`getrandom` blocks if + no random bytes are available, and when reading from ``/dev/urandom``, it blocks + if the entropy pool has not yet been initialized. + + If the :py:data:`GRND_NONBLOCK` flag is set, then :func:`getrandom` does not + block in these cases, but instead immediately raises :exc:`BlockingIOError`. + + .. versionadded:: 3.6 + +.. data:: GRND_RANDOM + + If this bit is set, then random bytes are drawn from the + ``/dev/random`` pool instead of the ``/dev/urandom`` pool. + + .. versionadded:: 3.6 diff --git a/cpython_2/environment/repo/Doc/library/ossaudiodev.rst b/cpython_2/environment/repo/Doc/library/ossaudiodev.rst new file mode 100644 index 0000000000000000000000000000000000000000..a7d3dac363cdf24ae0f65e11a05eca9d444fd324 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/ossaudiodev.rst @@ -0,0 +1,448 @@ +:mod:`ossaudiodev` --- Access to OSS-compatible audio devices +============================================================= + +.. module:: ossaudiodev + :platform: Linux, FreeBSD + :synopsis: Access to OSS-compatible audio devices. + +-------------- + +This module allows you to access the OSS (Open Sound System) audio interface. +OSS is available for a wide range of open-source and commercial Unices, and is +the standard audio interface for Linux and recent versions of FreeBSD. + +.. Things will get more complicated for future Linux versions, since + ALSA is in the standard kernel as of 2.5.x. Presumably if you + use ALSA, you'll have to make sure its OSS compatibility layer + is active to use ossaudiodev, but you're going to need it for the vast + majority of Linux audio apps anyway. + + 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 : + > * 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 + +.. versionchanged:: 3.3 + Operations in this module now raise :exc:`OSError` where :exc:`IOError` + was raised. + + +.. seealso:: + + `Open Sound System Programmer's Guide `_ + the official documentation for the OSS C API + + The module defines a large number of constants supplied by the OSS device + driver; see ```` on either Linux or FreeBSD for a listing. + +:mod:`ossaudiodev` defines the following variables and functions: + + +.. exception:: OSSAudioError + + This exception is raised on certain errors. The argument is a string describing + what went wrong. + + (If :mod:`ossaudiodev` receives an error from a system call such as + :c:func:`open`, :c:func:`write`, or :c:func:`ioctl`, it raises :exc:`OSError`. + Errors detected directly by :mod:`ossaudiodev` result in :exc:`OSSAudioError`.) + + (For backwards compatibility, the exception class is also available as + ``ossaudiodev.error``.) + + +.. function:: open(mode) + open(device, mode) + + Open an audio device and return an OSS audio device object. This object + supports many file-like methods, such as :meth:`read`, :meth:`write`, and + :meth:`fileno` (although there are subtle differences between conventional Unix + read/write semantics and those of OSS audio devices). It also supports a number + of audio-specific methods; see below for the complete list of methods. + + *device* is the audio device filename to use. If it is not specified, this + module first looks in the environment variable :envvar:`AUDIODEV` for a device + to use. If not found, it falls back to :file:`/dev/dsp`. + + *mode* is one of ``'r'`` for read-only (record) access, ``'w'`` for + write-only (playback) access and ``'rw'`` for both. Since many sound cards + only allow one process to have the recorder or player open at a time, it is a + good idea to open the device only for the activity needed. Further, some + sound cards are half-duplex: they can be opened for reading or writing, but + not both at once. + + Note the unusual calling syntax: the *first* argument is optional, and the + second is required. This is a historical artifact for compatibility with the + older :mod:`linuxaudiodev` module which :mod:`ossaudiodev` supersedes. + + .. XXX it might also be motivated + by my unfounded-but-still-possibly-true belief that the default + audio device varies unpredictably across operating systems. -GW + + +.. function:: openmixer([device]) + + Open a mixer device and return an OSS mixer device object. *device* is the + mixer device filename to use. If it is not specified, this module first looks + in the environment variable :envvar:`MIXERDEV` for a device to use. If not + found, it falls back to :file:`/dev/mixer`. + + +.. _ossaudio-device-objects: + +Audio Device Objects +-------------------- + +Before you can write to or read from an audio device, you must call three +methods in the correct order: + +#. :meth:`setfmt` to set the output format + +#. :meth:`channels` to set the number of channels + +#. :meth:`speed` to set the sample rate + +Alternately, you can use the :meth:`setparameters` method to set all three audio +parameters at once. This is more convenient, but may not be as flexible in all +cases. + +The audio device objects returned by :func:`.open` define the following methods +and (read-only) attributes: + + +.. method:: oss_audio_device.close() + + Explicitly close the audio device. When you are done writing to or reading from + an audio device, you should explicitly close it. A closed device cannot be used + again. + + +.. method:: oss_audio_device.fileno() + + Return the file descriptor associated with the device. + + +.. method:: oss_audio_device.read(size) + + Read *size* bytes from the audio input and return them as a Python string. + Unlike most Unix device drivers, OSS audio devices in blocking mode (the + default) will block :func:`read` until the entire requested amount of data is + available. + + +.. method:: oss_audio_device.write(data) + + Write a :term:`bytes-like object` *data* to the audio device and return the + number of bytes written. If the audio device is in blocking mode (the + default), the entire data is always written (again, this is different from + usual Unix device semantics). If the device is in non-blocking mode, some + data may not be written---see :meth:`writeall`. + + .. versionchanged:: 3.5 + Writable :term:`bytes-like object` is now accepted. + + +.. method:: oss_audio_device.writeall(data) + + Write a :term:`bytes-like object` *data* to the audio device: waits until + the audio device is able to accept data, writes as much data as it will + accept, and repeats until *data* has been completely written. If the device + is in blocking mode (the default), this has the same effect as + :meth:`write`; :meth:`writeall` is only useful in non-blocking mode. Has + no return value, since the amount of data written is always equal to the + amount of data supplied. + + .. versionchanged:: 3.5 + Writable :term:`bytes-like object` is now accepted. + + +.. versionchanged:: 3.2 + Audio device objects also support the context management protocol, i.e. they can + be used in a :keyword:`with` statement. + + +The following methods each map to exactly one :c:func:`ioctl` system call. The +correspondence is obvious: for example, :meth:`setfmt` corresponds to the +``SNDCTL_DSP_SETFMT`` ioctl, and :meth:`sync` to ``SNDCTL_DSP_SYNC`` (this can +be useful when consulting the OSS documentation). If the underlying +:c:func:`ioctl` fails, they all raise :exc:`OSError`. + + +.. method:: oss_audio_device.nonblock() + + Put the device into non-blocking mode. Once in non-blocking mode, there is no + way to return it to blocking mode. + + +.. method:: oss_audio_device.getfmts() + + Return a bitmask of the audio output formats supported by the soundcard. Some + of the formats supported by OSS are: + + +-------------------------+---------------------------------------------+ + | Format | Description | + +=========================+=============================================+ + | :const:`AFMT_MU_LAW` | a logarithmic encoding (used by Sun ``.au`` | + | | files and :file:`/dev/audio`) | + +-------------------------+---------------------------------------------+ + | :const:`AFMT_A_LAW` | a logarithmic encoding | + +-------------------------+---------------------------------------------+ + | :const:`AFMT_IMA_ADPCM` | a 4:1 compressed format defined by the | + | | Interactive Multimedia Association | + +-------------------------+---------------------------------------------+ + | :const:`AFMT_U8` | Unsigned, 8-bit audio | + +-------------------------+---------------------------------------------+ + | :const:`AFMT_S16_LE` | Signed, 16-bit audio, little-endian byte | + | | order (as used by Intel processors) | + +-------------------------+---------------------------------------------+ + | :const:`AFMT_S16_BE` | Signed, 16-bit audio, big-endian byte order | + | | (as used by 68k, PowerPC, Sparc) | + +-------------------------+---------------------------------------------+ + | :const:`AFMT_S8` | Signed, 8 bit audio | + +-------------------------+---------------------------------------------+ + | :const:`AFMT_U16_LE` | Unsigned, 16-bit little-endian audio | + +-------------------------+---------------------------------------------+ + | :const:`AFMT_U16_BE` | Unsigned, 16-bit big-endian audio | + +-------------------------+---------------------------------------------+ + + Consult the OSS documentation for a full list of audio formats, and note that + most devices support only a subset of these formats. Some older devices only + support :const:`AFMT_U8`; the most common format used today is + :const:`AFMT_S16_LE`. + + +.. method:: oss_audio_device.setfmt(format) + + Try to set the current audio format to *format*---see :meth:`getfmts` for a + list. Returns the audio format that the device was set to, which may not be the + requested format. May also be used to return the current audio format---do this + by passing an "audio format" of :const:`AFMT_QUERY`. + + +.. method:: oss_audio_device.channels(nchannels) + + Set the number of output channels to *nchannels*. A value of 1 indicates + monophonic sound, 2 stereophonic. Some devices may have more than 2 channels, + and some high-end devices may not support mono. Returns the number of channels + the device was set to. + + +.. method:: oss_audio_device.speed(samplerate) + + Try to set the audio sampling rate to *samplerate* samples per second. Returns + the rate actually set. Most sound devices don't support arbitrary sampling + rates. Common rates are: + + +-------+-------------------------------------------+ + | Rate | Description | + +=======+===========================================+ + | 8000 | default rate for :file:`/dev/audio` | + +-------+-------------------------------------------+ + | 11025 | speech recording | + +-------+-------------------------------------------+ + | 22050 | | + +-------+-------------------------------------------+ + | 44100 | CD quality audio (at 16 bits/sample and 2 | + | | channels) | + +-------+-------------------------------------------+ + | 96000 | DVD quality audio (at 24 bits/sample) | + +-------+-------------------------------------------+ + + +.. method:: oss_audio_device.sync() + + Wait until the sound device has played every byte in its buffer. (This happens + implicitly when the device is closed.) The OSS documentation recommends closing + and re-opening the device rather than using :meth:`sync`. + + +.. method:: oss_audio_device.reset() + + Immediately stop playing or recording and return the device to a state where it + can accept commands. The OSS documentation recommends closing and re-opening + the device after calling :meth:`reset`. + + +.. method:: oss_audio_device.post() + + Tell the driver that there is likely to be a pause in the output, making it + possible for the device to handle the pause more intelligently. You might use + this after playing a spot sound effect, before waiting for user input, or before + doing disk I/O. + +The following convenience methods combine several ioctls, or one ioctl and some +simple calculations. + + +.. method:: oss_audio_device.setparameters(format, nchannels, samplerate[, strict=False]) + + Set the key audio sampling parameters---sample format, number of channels, and + sampling rate---in one method call. *format*, *nchannels*, and *samplerate* + should be as specified in the :meth:`setfmt`, :meth:`channels`, and + :meth:`speed` methods. If *strict* is true, :meth:`setparameters` checks to + see if each parameter was actually set to the requested value, and raises + :exc:`OSSAudioError` if not. Returns a tuple (*format*, *nchannels*, + *samplerate*) indicating the parameter values that were actually set by the + device driver (i.e., the same as the return values of :meth:`setfmt`, + :meth:`channels`, and :meth:`speed`). + + For example, :: + + (fmt, channels, rate) = dsp.setparameters(fmt, channels, rate) + + is equivalent to :: + + fmt = dsp.setfmt(fmt) + channels = dsp.channels(channels) + rate = dsp.rate(rate) + + +.. method:: oss_audio_device.bufsize() + + Returns the size of the hardware buffer, in samples. + + +.. method:: oss_audio_device.obufcount() + + Returns the number of samples that are in the hardware buffer yet to be played. + + +.. method:: oss_audio_device.obuffree() + + Returns the number of samples that could be queued into the hardware buffer to + be played without blocking. + +Audio device objects also support several read-only attributes: + + +.. attribute:: oss_audio_device.closed + + Boolean indicating whether the device has been closed. + + +.. attribute:: oss_audio_device.name + + String containing the name of the device file. + + +.. attribute:: oss_audio_device.mode + + The I/O mode for the file, either ``"r"``, ``"rw"``, or ``"w"``. + + +.. _mixer-device-objects: + +Mixer Device Objects +-------------------- + +The mixer object provides two file-like methods: + + +.. method:: oss_mixer_device.close() + + This method closes the open mixer device file. Any further attempts to use the + mixer after this file is closed will raise an :exc:`OSError`. + + +.. method:: oss_mixer_device.fileno() + + Returns the file handle number of the open mixer device file. + +.. versionchanged:: 3.2 + Mixer objects also support the context management protocol. + + +The remaining methods are specific to audio mixing: + + +.. method:: oss_mixer_device.controls() + + This method returns a bitmask specifying the available mixer controls ("Control" + being a specific mixable "channel", such as :const:`SOUND_MIXER_PCM` or + :const:`SOUND_MIXER_SYNTH`). This bitmask indicates a subset of all available + mixer controls---the :const:`SOUND_MIXER_\*` constants defined at module level. + To determine if, for example, the current mixer object supports a PCM mixer, use + the following Python code:: + + mixer=ossaudiodev.openmixer() + if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM): + # PCM is supported + ... code ... + + For most purposes, the :const:`SOUND_MIXER_VOLUME` (master volume) and + :const:`SOUND_MIXER_PCM` controls should suffice---but code that uses the mixer + should be flexible when it comes to choosing mixer controls. On the Gravis + Ultrasound, for example, :const:`SOUND_MIXER_VOLUME` does not exist. + + +.. method:: oss_mixer_device.stereocontrols() + + Returns a bitmask indicating stereo mixer controls. If a bit is set, the + corresponding control is stereo; if it is unset, the control is either + monophonic or not supported by the mixer (use in combination with + :meth:`controls` to determine which). + + See the code example for the :meth:`controls` function for an example of getting + data from a bitmask. + + +.. method:: oss_mixer_device.reccontrols() + + Returns a bitmask specifying the mixer controls that may be used to record. See + the code example for :meth:`controls` for an example of reading from a bitmask. + + +.. method:: oss_mixer_device.get(control) + + Returns the volume of a given mixer control. The returned volume is a 2-tuple + ``(left_volume,right_volume)``. Volumes are specified as numbers from 0 + (silent) to 100 (full volume). If the control is monophonic, a 2-tuple is still + returned, but both volumes are the same. + + Raises :exc:`OSSAudioError` if an invalid control is specified, or + :exc:`OSError` if an unsupported control is specified. + + +.. method:: oss_mixer_device.set(control, (left, right)) + + Sets the volume for a given mixer control to ``(left,right)``. ``left`` and + ``right`` must be ints and between 0 (silent) and 100 (full volume). On + success, the new volume is returned as a 2-tuple. Note that this may not be + exactly the same as the volume specified, because of the limited resolution of + some soundcard's mixers. + + Raises :exc:`OSSAudioError` if an invalid mixer control was specified, or if the + specified volumes were out-of-range. + + +.. method:: oss_mixer_device.get_recsrc() + + This method returns a bitmask indicating which control(s) are currently being + used as a recording source. + + +.. method:: oss_mixer_device.set_recsrc(bitmask) + + Call this function to specify a recording source. Returns a bitmask indicating + the new recording source (or sources) if successful; raises :exc:`OSError` if an + invalid source was specified. To set the current recording source to the + microphone input:: + + mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC) diff --git a/cpython_2/environment/repo/Doc/library/othergui.rst b/cpython_2/environment/repo/Doc/library/othergui.rst new file mode 100644 index 0000000000000000000000000000000000000000..4548459f8e261d70a56842d0e9405676aba2430d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/othergui.rst @@ -0,0 +1,56 @@ +.. _other-gui-packages: + +Other Graphical User Interface Packages +======================================= + +Major cross-platform (Windows, Mac OS X, Unix-like) GUI toolkits are +available for Python: + +.. seealso:: + + `PyGObject `_ + PyGObject provides introspection bindings for C libraries using + `GObject `_. One of + these libraries is the `GTK+ 3 `_ widget set. + GTK+ comes with many more widgets than Tkinter provides. An online + `Python GTK+ 3 Tutorial `_ + is available. + + `PyGTK `_ + PyGTK provides bindings for an older version + of the library, GTK+ 2. It provides an object oriented interface that + is slightly higher level than the C one. There are also bindings to + `GNOME `_. An online `tutorial + `_ is available. + + `PyQt `_ + PyQt is a :program:`sip`\ -wrapped binding to the Qt toolkit. Qt is an + extensive C++ GUI application development framework that is + available for Unix, Windows and Mac OS X. :program:`sip` is a tool + for generating bindings for C++ libraries as Python classes, and + is specifically designed for Python. + + `PySide `_ + PySide is a newer binding to the Qt toolkit, provided by Nokia. + Compared to PyQt, its licensing scheme is friendlier to non-open source + applications. + + `wxPython `_ + wxPython is a cross-platform GUI toolkit for Python that is built around + the popular `wxWidgets `_ (formerly wxWindows) + C++ toolkit. It provides a native look and feel for applications on + Windows, Mac OS X, and Unix systems by using each platform's native + widgets where ever possible, (GTK+ on Unix-like systems). In addition to + an extensive set of widgets, wxPython provides classes for online + documentation and context sensitive help, printing, HTML viewing, + low-level device context drawing, drag and drop, system clipboard access, + an XML-based resource format and more, including an ever growing library + of user-contributed modules. + +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 +Python, both cross-platform, and platform-specific. See the `GUI Programming +`_ page in the Python Wiki for a +much more complete list, and also for links to documents where the +different GUI toolkits are compared. + diff --git a/cpython_2/environment/repo/Doc/library/parser.rst b/cpython_2/environment/repo/Doc/library/parser.rst new file mode 100644 index 0000000000000000000000000000000000000000..79fc10d0675af48c7cfcf7954ecb0c90bca751ae --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/parser.rst @@ -0,0 +1,357 @@ +:mod:`parser` --- Access Python parse trees +=========================================== + +.. module:: parser + :synopsis: Access parse trees for Python source code. + +.. moduleauthor:: Fred L. Drake, Jr. +.. sectionauthor:: Fred L. Drake, Jr. + +.. Copyright 1995 Virginia Polytechnic Institute and State University and Fred + L. Drake, Jr. This copyright notice must be distributed on all copies, but + this document otherwise may be distributed as part of the Python + distribution. No fee may be charged for this document in any representation, + either on paper or electronically. This restriction does not affect other + elements in a distributed package in any way. + +.. index:: single: parsing; Python source code + +-------------- + +The :mod:`parser` module provides an interface to Python's internal parser and +byte-code compiler. The primary purpose for this interface is to allow Python +code to edit the parse tree of a Python expression and create executable code +from this. This is better than trying to parse and modify an arbitrary Python +code fragment as a string because parsing is performed in a manner identical to +the code forming the application. It is also faster. + +.. warning:: + + The parser module is deprecated and will be removed in future versions of + Python. For the majority of use cases you can leverage the Abstract Syntax + Tree (AST) generation and compilation stage, using the :mod:`ast` module. + +There are a few things to note about this module which are important to making +use of the data structures created. This is not a tutorial on editing the parse +trees for Python code, but some examples of using the :mod:`parser` module are +presented. + +Most importantly, a good understanding of the Python grammar processed by the +internal parser is required. For full information on the language syntax, refer +to :ref:`reference-index`. The parser +itself is created from a grammar specification defined in the file +:file:`Grammar/Grammar` in the standard Python distribution. The parse trees +stored in the ST objects created by this module are the actual output from the +internal parser when created by the :func:`expr` or :func:`suite` functions, +described below. The ST objects created by :func:`sequence2st` faithfully +simulate those structures. Be aware that the values of the sequences which are +considered "correct" will vary from one version of Python to another as the +formal grammar for the language is revised. However, transporting code from one +Python version to another as source text will always allow correct parse trees +to be created in the target version, with the only restriction being that +migrating to an older version of the interpreter will not support more recent +language constructs. The parse trees are not typically compatible from one +version to another, though source code has usually been forward-compatible within +a major release series. + +Each element of the sequences returned by :func:`st2list` or :func:`st2tuple` +has a simple form. Sequences representing non-terminal elements in the grammar +always have a length greater than one. The first element is an integer which +identifies a production in the grammar. These integers are given symbolic names +in the C header file :file:`Include/graminit.h` and the Python module +:mod:`symbol`. Each additional element of the sequence represents a component +of the production as recognized in the input string: these are always sequences +which have the same form as the parent. An important aspect of this structure +which should be noted is that keywords used to identify the parent node type, +such as the keyword :keyword:`if` in an :const:`if_stmt`, are included in the +node tree without any special treatment. For example, the :keyword:`!if` keyword +is represented by the tuple ``(1, 'if')``, where ``1`` is the numeric value +associated with all :const:`NAME` tokens, including variable and function names +defined by the user. In an alternate form returned when line number information +is requested, the same token might be represented as ``(1, 'if', 12)``, where +the ``12`` represents the line number at which the terminal symbol was found. + +Terminal elements are represented in much the same way, but without any child +elements and the addition of the source text which was identified. The example +of the :keyword:`if` keyword above is representative. The various types of +terminal symbols are defined in the C header file :file:`Include/token.h` and +the Python module :mod:`token`. + +The ST objects are not required to support the functionality of this module, +but are provided for three purposes: to allow an application to amortize the +cost of processing complex parse trees, to provide a parse tree representation +which conserves memory space when compared to the Python list or tuple +representation, and to ease the creation of additional modules in C which +manipulate parse trees. A simple "wrapper" class may be created in Python to +hide the use of ST objects. + +The :mod:`parser` module defines functions for a few distinct purposes. The +most important purposes are to create ST objects and to convert ST objects to +other representations such as parse trees and compiled code objects, but there +are also functions which serve to query the type of parse tree represented by an +ST object. + + +.. seealso:: + + Module :mod:`symbol` + Useful constants representing internal nodes of the parse tree. + + Module :mod:`token` + Useful constants representing leaf nodes of the parse tree and functions for + testing node values. + + +.. _creating-sts: + +Creating ST Objects +------------------- + +ST objects may be created from source code or from a parse tree. When creating +an ST object from source, different functions are used to create the ``'eval'`` +and ``'exec'`` forms. + + +.. function:: expr(source) + + The :func:`expr` function parses the parameter *source* as if it were an input + to ``compile(source, 'file.py', 'eval')``. If the parse succeeds, an ST object + is created to hold the internal parse tree representation, otherwise an + appropriate exception is raised. + + +.. function:: suite(source) + + The :func:`suite` function parses the parameter *source* as if it were an input + to ``compile(source, 'file.py', 'exec')``. If the parse succeeds, an ST object + is created to hold the internal parse tree representation, otherwise an + appropriate exception is raised. + + +.. function:: sequence2st(sequence) + + This function accepts a parse tree represented as a sequence and builds an + internal representation if possible. If it can validate that the tree conforms + to the Python grammar and all nodes are valid node types in the host version of + Python, an ST object is created from the internal representation and returned + to the called. If there is a problem creating the internal representation, or + if the tree cannot be validated, a :exc:`ParserError` exception is raised. An + ST object created this way should not be assumed to compile correctly; normal + exceptions raised by compilation may still be initiated when the ST object is + passed to :func:`compilest`. This may indicate problems not related to syntax + (such as a :exc:`MemoryError` exception), but may also be due to constructs such + as the result of parsing ``del f(0)``, which escapes the Python parser but is + checked by the bytecode compiler. + + Sequences representing terminal tokens may be represented as either two-element + lists of the form ``(1, 'name')`` or as three-element lists of the form ``(1, + 'name', 56)``. If the third element is present, it is assumed to be a valid + line number. The line number may be specified for any subset of the terminal + symbols in the input tree. + + +.. function:: tuple2st(sequence) + + This is the same function as :func:`sequence2st`. This entry point is + maintained for backward compatibility. + + +.. _converting-sts: + +Converting ST Objects +--------------------- + +ST objects, regardless of the input used to create them, may be converted to +parse trees represented as list- or tuple- trees, or may be compiled into +executable code objects. Parse trees may be extracted with or without line +numbering information. + + +.. function:: st2list(st, line_info=False, col_info=False) + + This function accepts an ST object from the caller in *st* and returns a + Python list representing the equivalent parse tree. The resulting list + representation can be used for inspection or the creation of a new parse tree in + list form. This function does not fail so long as memory is available to build + the list representation. If the parse tree will only be used for inspection, + :func:`st2tuple` should be used instead to reduce memory consumption and + fragmentation. When the list representation is required, this function is + significantly faster than retrieving a tuple representation and converting that + to nested lists. + + If *line_info* is true, line number information will be included for all + terminal tokens as a third element of the list representing the token. Note + that the line number provided specifies the line on which the token *ends*. + This information is omitted if the flag is false or omitted. + + +.. function:: st2tuple(st, line_info=False, col_info=False) + + This function accepts an ST object from the caller in *st* and returns a + Python tuple representing the equivalent parse tree. Other than returning a + tuple instead of a list, this function is identical to :func:`st2list`. + + If *line_info* is true, line number information will be included for all + terminal tokens as a third element of the list representing the token. This + information is omitted if the flag is false or omitted. + + +.. function:: compilest(st, filename='') + + .. index:: + builtin: exec + builtin: eval + + The Python byte compiler can be invoked on an ST object to produce code objects + which can be used as part of a call to the built-in :func:`exec` or :func:`eval` + functions. This function provides the interface to the compiler, passing the + internal parse tree from *st* to the parser, using the source file name + specified by the *filename* parameter. The default value supplied for *filename* + indicates that the source was an ST object. + + Compiling an ST object may result in exceptions related to compilation; an + example would be a :exc:`SyntaxError` caused by the parse tree for ``del f(0)``: + this statement is considered legal within the formal grammar for Python but is + not a legal language construct. The :exc:`SyntaxError` raised for this + condition is actually generated by the Python byte-compiler normally, which is + why it can be raised at this point by the :mod:`parser` module. Most causes of + compilation failure can be diagnosed programmatically by inspection of the parse + tree. + + +.. _querying-sts: + +Queries on ST Objects +--------------------- + +Two functions are provided which allow an application to determine if an ST was +created as an expression or a suite. Neither of these functions can be used to +determine if an ST was created from source code via :func:`expr` or +:func:`suite` or from a parse tree via :func:`sequence2st`. + + +.. function:: isexpr(st) + + .. index:: builtin: compile + + When *st* represents an ``'eval'`` form, this function returns ``True``, otherwise + it returns ``False``. This is useful, since code objects normally cannot be queried + for this information using existing built-in functions. Note that the code + objects created by :func:`compilest` cannot be queried like this either, and + are identical to those created by the built-in :func:`compile` function. + + +.. function:: issuite(st) + + This function mirrors :func:`isexpr` in that it reports whether an ST object + represents an ``'exec'`` form, commonly known as a "suite." It is not safe to + assume that this function is equivalent to ``not isexpr(st)``, as additional + syntactic fragments may be supported in the future. + + +.. _st-errors: + +Exceptions and Error Handling +----------------------------- + +The parser module defines a single exception, but may also pass other built-in +exceptions from other portions of the Python runtime environment. See each +function for information about the exceptions it can raise. + + +.. exception:: ParserError + + Exception raised when a failure occurs within the parser module. This is + generally produced for validation failures rather than the built-in + :exc:`SyntaxError` raised during normal parsing. The exception argument is + either a string describing the reason of the failure or a tuple containing a + sequence causing the failure from a parse tree passed to :func:`sequence2st` + and an explanatory string. Calls to :func:`sequence2st` need to be able to + handle either type of exception, while calls to other functions in the module + will only need to be aware of the simple string values. + +Note that the functions :func:`compilest`, :func:`expr`, and :func:`suite` may +raise exceptions which are normally raised by the parsing and compilation +process. These include the built in exceptions :exc:`MemoryError`, +:exc:`OverflowError`, :exc:`SyntaxError`, and :exc:`SystemError`. In these +cases, these exceptions carry all the meaning normally associated with them. +Refer to the descriptions of each function for detailed information. + + +.. _st-objects: + +ST Objects +---------- + +Ordered and equality comparisons are supported between ST objects. Pickling of +ST objects (using the :mod:`pickle` module) is also supported. + + +.. data:: STType + + The type of the objects returned by :func:`expr`, :func:`suite` and + :func:`sequence2st`. + +ST objects have the following methods: + + +.. method:: ST.compile(filename='') + + Same as ``compilest(st, filename)``. + + +.. method:: ST.isexpr() + + Same as ``isexpr(st)``. + + +.. method:: ST.issuite() + + Same as ``issuite(st)``. + + +.. method:: ST.tolist(line_info=False, col_info=False) + + Same as ``st2list(st, line_info, col_info)``. + + +.. method:: ST.totuple(line_info=False, col_info=False) + + Same as ``st2tuple(st, line_info, col_info)``. + + +Example: Emulation of :func:`compile` +------------------------------------- + +While many useful operations may take place between parsing and bytecode +generation, the simplest operation is to do nothing. For this purpose, using +the :mod:`parser` module to produce an intermediate data structure is equivalent +to the code :: + + >>> code = compile('a + 5', 'file.py', 'eval') + >>> a = 5 + >>> eval(code) + 10 + +The equivalent operation using the :mod:`parser` module is somewhat longer, and +allows the intermediate internal parse tree to be retained as an ST object:: + + >>> import parser + >>> st = parser.expr('a + 5') + >>> code = st.compile('file.py') + >>> a = 5 + >>> eval(code) + 10 + +An application which needs both ST and code objects can package this code into +readily available functions:: + + import parser + + def load_suite(source_string): + st = parser.suite(source_string) + return st, st.compile() + + def load_expression(source_string): + st = parser.expr(source_string) + return st, st.compile() diff --git a/cpython_2/environment/repo/Doc/library/pathlib-inheritance.png b/cpython_2/environment/repo/Doc/library/pathlib-inheritance.png new file mode 100644 index 0000000000000000000000000000000000000000..c8af33dda59a1e700a34dd76f6626485419e844e Binary files /dev/null and b/cpython_2/environment/repo/Doc/library/pathlib-inheritance.png differ diff --git a/cpython_2/environment/repo/Doc/library/pathlib-inheritance.svg b/cpython_2/environment/repo/Doc/library/pathlib-inheritance.svg new file mode 100644 index 0000000000000000000000000000000000000000..49057f678fd7d00e428de68c5a19a7e7833ba5e6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pathlib-inheritance.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/cpython_2/environment/repo/Doc/library/pathlib.rst b/cpython_2/environment/repo/Doc/library/pathlib.rst new file mode 100644 index 0000000000000000000000000000000000000000..83f7c836f0e71cf84a031ac7c7283a0772ddabe7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pathlib.rst @@ -0,0 +1,1210 @@ + +:mod:`pathlib` --- Object-oriented filesystem paths +=================================================== + +.. module:: pathlib + :synopsis: Object-oriented filesystem paths + +.. versionadded:: 3.4 + +**Source code:** :source:`Lib/pathlib.py` + +.. index:: single: path; operations + +-------------- + +This module offers classes representing filesystem paths with semantics +appropriate for different operating systems. Path classes are divided +between :ref:`pure paths `, which provide purely computational +operations without I/O, and :ref:`concrete paths `, which +inherit from pure paths but also provide I/O operations. + +.. image:: pathlib-inheritance.png + :align: center + +If you've never used this module before or just aren't sure which class is +right for your task, :class:`Path` is most likely what you need. It instantiates +a :ref:`concrete path ` for the platform the code is running on. + +Pure paths are useful in some special cases; for example: + +#. If you want to manipulate Windows paths on a Unix machine (or vice versa). + You cannot instantiate a :class:`WindowsPath` when running on Unix, but you + can instantiate :class:`PureWindowsPath`. +#. You want to make sure that your code only manipulates paths without actually + accessing the OS. In this case, instantiating one of the pure classes may be + useful since those simply don't have any OS-accessing operations. + +.. seealso:: + :pep:`428`: The pathlib module -- object-oriented filesystem paths. + +.. seealso:: + For low-level path manipulation on strings, you can also use the + :mod:`os.path` module. + + +Basic use +--------- + +Importing the main class:: + + >>> from pathlib import Path + +Listing subdirectories:: + + >>> p = Path('.') + >>> [x for x in p.iterdir() if x.is_dir()] + [PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'), + PosixPath('__pycache__'), PosixPath('build')] + +Listing Python source files in this directory tree:: + + >>> list(p.glob('**/*.py')) + [PosixPath('test_pathlib.py'), PosixPath('setup.py'), + PosixPath('pathlib.py'), PosixPath('docs/conf.py'), + PosixPath('build/lib/pathlib.py')] + +Navigating inside a directory tree:: + + >>> p = Path('/etc') + >>> q = p / 'init.d' / 'reboot' + >>> q + PosixPath('/etc/init.d/reboot') + >>> q.resolve() + PosixPath('/etc/rc.d/init.d/halt') + +Querying path properties:: + + >>> q.exists() + True + >>> q.is_dir() + False + +Opening a file:: + + >>> with q.open() as f: f.readline() + ... + '#!/bin/bash\n' + + +.. _pure-paths: + +Pure paths +---------- + +Pure path objects provide path-handling operations which don't actually +access a filesystem. There are three ways to access these classes, which +we also call *flavours*: + +.. class:: PurePath(*pathsegments) + + A generic class that represents the system's path flavour (instantiating + it creates either a :class:`PurePosixPath` or a :class:`PureWindowsPath`):: + + >>> PurePath('setup.py') # Running on a Unix machine + PurePosixPath('setup.py') + + Each element of *pathsegments* can be either a string representing a + path segment, an object implementing the :class:`os.PathLike` interface + which returns a string, or another path object:: + + >>> PurePath('foo', 'some/path', 'bar') + PurePosixPath('foo/some/path/bar') + >>> PurePath(Path('foo'), Path('bar')) + PurePosixPath('foo/bar') + + When *pathsegments* is empty, the current directory is assumed:: + + >>> PurePath() + PurePosixPath('.') + + When several absolute paths are given, the last is taken as an anchor + (mimicking :func:`os.path.join`'s behaviour):: + + >>> PurePath('/etc', '/usr', 'lib64') + PurePosixPath('/usr/lib64') + >>> PureWindowsPath('c:/Windows', 'd:bar') + PureWindowsPath('d:bar') + + However, in a Windows path, changing the local root doesn't discard the + previous drive setting:: + + >>> PureWindowsPath('c:/Windows', '/Program Files') + PureWindowsPath('c:/Program Files') + + Spurious slashes and single dots are collapsed, but double dots (``'..'``) + are not, since this would change the meaning of a path in the face of + symbolic links:: + + >>> PurePath('foo//bar') + PurePosixPath('foo/bar') + >>> PurePath('foo/./bar') + PurePosixPath('foo/bar') + >>> PurePath('foo/../bar') + PurePosixPath('foo/../bar') + + (a naïve approach would make ``PurePosixPath('foo/../bar')`` equivalent + to ``PurePosixPath('bar')``, which is wrong if ``foo`` is a symbolic link + to another directory) + + Pure path objects implement the :class:`os.PathLike` interface, allowing them + to be used anywhere the interface is accepted. + + .. versionchanged:: 3.6 + Added support for the :class:`os.PathLike` interface. + +.. class:: PurePosixPath(*pathsegments) + + A subclass of :class:`PurePath`, this path flavour represents non-Windows + filesystem paths:: + + >>> PurePosixPath('/etc') + PurePosixPath('/etc') + + *pathsegments* is specified similarly to :class:`PurePath`. + +.. class:: PureWindowsPath(*pathsegments) + + A subclass of :class:`PurePath`, this path flavour represents Windows + filesystem paths:: + + >>> PureWindowsPath('c:/Program Files/') + PureWindowsPath('c:/Program Files') + + *pathsegments* is specified similarly to :class:`PurePath`. + +Regardless of the system you're running on, you can instantiate all of +these classes, since they don't provide any operation that does system calls. + + +General properties +^^^^^^^^^^^^^^^^^^ + +Paths are immutable and hashable. Paths of a same flavour are comparable +and orderable. These properties respect the flavour's case-folding +semantics:: + + >>> PurePosixPath('foo') == PurePosixPath('FOO') + False + >>> PureWindowsPath('foo') == PureWindowsPath('FOO') + True + >>> PureWindowsPath('FOO') in { PureWindowsPath('foo') } + True + >>> PureWindowsPath('C:') < PureWindowsPath('d:') + True + +Paths of a different flavour compare unequal and cannot be ordered:: + + >>> PureWindowsPath('foo') == PurePosixPath('foo') + False + >>> PureWindowsPath('foo') < PurePosixPath('foo') + Traceback (most recent call last): + File "", line 1, in + TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath' + + +Operators +^^^^^^^^^ + +The slash operator helps create child paths, similarly to :func:`os.path.join`:: + + >>> p = PurePath('/etc') + >>> p + PurePosixPath('/etc') + >>> p / 'init.d' / 'apache2' + PurePosixPath('/etc/init.d/apache2') + >>> q = PurePath('bin') + >>> '/usr' / q + PurePosixPath('/usr/bin') + +A path object can be used anywhere an object implementing :class:`os.PathLike` +is accepted:: + + >>> import os + >>> p = PurePath('/etc') + >>> os.fspath(p) + '/etc' + +The string representation of a path is the raw filesystem path itself +(in native form, e.g. with backslashes under Windows), which you can +pass to any function taking a file path as a string:: + + >>> p = PurePath('/etc') + >>> str(p) + '/etc' + >>> p = PureWindowsPath('c:/Program Files') + >>> str(p) + 'c:\\Program Files' + +Similarly, calling :class:`bytes` on a path gives the raw filesystem path as a +bytes object, as encoded by :func:`os.fsencode`:: + + >>> bytes(p) + b'/etc' + +.. note:: + Calling :class:`bytes` is only recommended under Unix. Under Windows, + the unicode form is the canonical representation of filesystem paths. + + +Accessing individual parts +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To access the individual "parts" (components) of a path, use the following +property: + +.. data:: PurePath.parts + + A tuple giving access to the path's various components:: + + >>> p = PurePath('/usr/bin/python3') + >>> p.parts + ('/', 'usr', 'bin', 'python3') + + >>> p = PureWindowsPath('c:/Program Files/PSF') + >>> p.parts + ('c:\\', 'Program Files', 'PSF') + + (note how the drive and local root are regrouped in a single part) + + +Methods and properties +^^^^^^^^^^^^^^^^^^^^^^ + +.. testsetup:: + + from pathlib import PurePath, PurePosixPath, PureWindowsPath + +Pure paths provide the following methods and properties: + +.. data:: PurePath.drive + + A string representing the drive letter or name, if any:: + + >>> PureWindowsPath('c:/Program Files/').drive + 'c:' + >>> PureWindowsPath('/Program Files/').drive + '' + >>> PurePosixPath('/etc').drive + '' + + UNC shares are also considered drives:: + + >>> PureWindowsPath('//host/share/foo.txt').drive + '\\\\host\\share' + +.. data:: PurePath.root + + A string representing the (local or global) root, if any:: + + >>> PureWindowsPath('c:/Program Files/').root + '\\' + >>> PureWindowsPath('c:Program Files/').root + '' + >>> PurePosixPath('/etc').root + '/' + + UNC shares always have a root:: + + >>> PureWindowsPath('//host/share').root + '\\' + +.. data:: PurePath.anchor + + The concatenation of the drive and root:: + + >>> PureWindowsPath('c:/Program Files/').anchor + 'c:\\' + >>> PureWindowsPath('c:Program Files/').anchor + 'c:' + >>> PurePosixPath('/etc').anchor + '/' + >>> PureWindowsPath('//host/share').anchor + '\\\\host\\share\\' + + +.. data:: PurePath.parents + + An immutable sequence providing access to the logical ancestors of + the path:: + + >>> p = PureWindowsPath('c:/foo/bar/setup.py') + >>> p.parents[0] + PureWindowsPath('c:/foo/bar') + >>> p.parents[1] + PureWindowsPath('c:/foo') + >>> p.parents[2] + PureWindowsPath('c:/') + + +.. data:: PurePath.parent + + The logical parent of the path:: + + >>> p = PurePosixPath('/a/b/c/d') + >>> p.parent + PurePosixPath('/a/b/c') + + You cannot go past an anchor, or empty path:: + + >>> p = PurePosixPath('/') + >>> p.parent + PurePosixPath('/') + >>> p = PurePosixPath('.') + >>> p.parent + PurePosixPath('.') + + .. note:: + This is a purely lexical operation, hence the following behaviour:: + + >>> p = PurePosixPath('foo/..') + >>> p.parent + PurePosixPath('foo') + + If you want to walk an arbitrary filesystem path upwards, it is + recommended to first call :meth:`Path.resolve` so as to resolve + symlinks and eliminate `".."` components. + + +.. data:: PurePath.name + + A string representing the final path component, excluding the drive and + root, if any:: + + >>> PurePosixPath('my/library/setup.py').name + 'setup.py' + + UNC drive names are not considered:: + + >>> PureWindowsPath('//some/share/setup.py').name + 'setup.py' + >>> PureWindowsPath('//some/share').name + '' + + +.. data:: PurePath.suffix + + The file extension of the final component, if any:: + + >>> PurePosixPath('my/library/setup.py').suffix + '.py' + >>> PurePosixPath('my/library.tar.gz').suffix + '.gz' + >>> PurePosixPath('my/library').suffix + '' + + +.. data:: PurePath.suffixes + + A list of the path's file extensions:: + + >>> PurePosixPath('my/library.tar.gar').suffixes + ['.tar', '.gar'] + >>> PurePosixPath('my/library.tar.gz').suffixes + ['.tar', '.gz'] + >>> PurePosixPath('my/library').suffixes + [] + + +.. data:: PurePath.stem + + The final path component, without its suffix:: + + >>> PurePosixPath('my/library.tar.gz').stem + 'library.tar' + >>> PurePosixPath('my/library.tar').stem + 'library' + >>> PurePosixPath('my/library').stem + 'library' + + +.. method:: PurePath.as_posix() + + Return a string representation of the path with forward slashes (``/``):: + + >>> p = PureWindowsPath('c:\\windows') + >>> str(p) + 'c:\\windows' + >>> p.as_posix() + 'c:/windows' + + +.. method:: PurePath.as_uri() + + Represent the path as a ``file`` URI. :exc:`ValueError` is raised if + the path isn't absolute. + + >>> p = PurePosixPath('/etc/passwd') + >>> p.as_uri() + 'file:///etc/passwd' + >>> p = PureWindowsPath('c:/Windows') + >>> p.as_uri() + 'file:///c:/Windows' + + +.. method:: PurePath.is_absolute() + + Return whether the path is absolute or not. A path is considered absolute + if it has both a root and (if the flavour allows) a drive:: + + >>> PurePosixPath('/a/b').is_absolute() + True + >>> PurePosixPath('a/b').is_absolute() + False + + >>> PureWindowsPath('c:/a/b').is_absolute() + True + >>> PureWindowsPath('/a/b').is_absolute() + False + >>> PureWindowsPath('c:').is_absolute() + False + >>> PureWindowsPath('//some/share').is_absolute() + True + + +.. method:: PurePath.is_relative_to(*other) + + Return whether or not this path is relative to the *other* path. + + >>> p = PurePath('/etc/passwd') + >>> p.is_relative_to('/etc') + True + >>> p.is_relative_to('/usr') + False + + .. versionadded:: 3.9 + + +.. method:: PurePath.is_reserved() + + With :class:`PureWindowsPath`, return ``True`` if the path is considered + reserved under Windows, ``False`` otherwise. With :class:`PurePosixPath`, + ``False`` is always returned. + + >>> PureWindowsPath('nul').is_reserved() + True + >>> PurePosixPath('nul').is_reserved() + False + + File system calls on reserved paths can fail mysteriously or have + unintended effects. + + +.. method:: PurePath.joinpath(*other) + + Calling this method is equivalent to combining the path with each of + the *other* arguments in turn:: + + >>> PurePosixPath('/etc').joinpath('passwd') + PurePosixPath('/etc/passwd') + >>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd')) + PurePosixPath('/etc/passwd') + >>> PurePosixPath('/etc').joinpath('init.d', 'apache2') + PurePosixPath('/etc/init.d/apache2') + >>> PureWindowsPath('c:').joinpath('/Program Files') + PureWindowsPath('c:/Program Files') + + +.. method:: PurePath.match(pattern) + + Match this path against the provided glob-style pattern. Return ``True`` + if matching is successful, ``False`` otherwise. + + If *pattern* is relative, the path can be either relative or absolute, + and matching is done from the right:: + + >>> PurePath('a/b.py').match('*.py') + True + >>> PurePath('/a/b/c.py').match('b/*.py') + True + >>> PurePath('/a/b/c.py').match('a/*.py') + False + + If *pattern* is absolute, the path must be absolute, and the whole path + must match:: + + >>> PurePath('/a.py').match('/*.py') + True + >>> PurePath('a/b.py').match('/*.py') + False + + As with other methods, case-sensitivity follows platform defaults:: + + >>> PurePosixPath('b.py').match('*.PY') + False + >>> PureWindowsPath('b.py').match('*.PY') + True + + +.. method:: PurePath.relative_to(*other) + + Compute a version of this path relative to the path represented by + *other*. If it's impossible, ValueError is raised:: + + >>> p = PurePosixPath('/etc/passwd') + >>> p.relative_to('/') + PurePosixPath('etc/passwd') + >>> p.relative_to('/etc') + PurePosixPath('passwd') + >>> p.relative_to('/usr') + Traceback (most recent call last): + File "", line 1, in + File "pathlib.py", line 694, in relative_to + .format(str(self), str(formatted))) + ValueError: '/etc/passwd' does not start with '/usr' + + +.. method:: PurePath.with_name(name) + + Return a new path with the :attr:`name` changed. If the original path + doesn't have a name, ValueError is raised:: + + >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz') + >>> p.with_name('setup.py') + PureWindowsPath('c:/Downloads/setup.py') + >>> p = PureWindowsPath('c:/') + >>> p.with_name('setup.py') + Traceback (most recent call last): + File "", line 1, in + File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name + raise ValueError("%r has an empty name" % (self,)) + ValueError: PureWindowsPath('c:/') has an empty name + + +.. method:: PurePath.with_stem(stem) + + Return a new path with the :attr:`stem` changed. If the original path + doesn't have a name, ValueError is raised:: + + >>> p = PureWindowsPath('c:/Downloads/draft.txt') + >>> p.with_stem('final') + PureWindowsPath('c:/Downloads/final.txt') + >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz') + >>> p.with_stem('lib') + PureWindowsPath('c:/Downloads/lib.gz') + >>> p = PureWindowsPath('c:/') + >>> p.with_stem('') + Traceback (most recent call last): + File "", line 1, in + File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem + return self.with_name(stem + self.suffix) + File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name + raise ValueError("%r has an empty name" % (self,)) + ValueError: PureWindowsPath('c:/') has an empty name + + .. versionadded:: 3.9 + + +.. method:: PurePath.with_suffix(suffix) + + Return a new path with the :attr:`suffix` changed. If the original path + doesn't have a suffix, the new *suffix* is appended instead. If the + *suffix* is an empty string, the original suffix is removed:: + + >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz') + >>> p.with_suffix('.bz2') + PureWindowsPath('c:/Downloads/pathlib.tar.bz2') + >>> p = PureWindowsPath('README') + >>> p.with_suffix('.txt') + PureWindowsPath('README.txt') + >>> p = PureWindowsPath('README.txt') + >>> p.with_suffix('') + PureWindowsPath('README') + + +.. _concrete-paths: + + +Concrete paths +-------------- + +Concrete paths are subclasses of the pure path classes. In addition to +operations provided by the latter, they also provide methods to do system +calls on path objects. There are three ways to instantiate concrete paths: + +.. class:: Path(*pathsegments) + + A subclass of :class:`PurePath`, this class represents concrete paths of + the system's path flavour (instantiating it creates either a + :class:`PosixPath` or a :class:`WindowsPath`):: + + >>> Path('setup.py') + PosixPath('setup.py') + + *pathsegments* is specified similarly to :class:`PurePath`. + +.. class:: PosixPath(*pathsegments) + + A subclass of :class:`Path` and :class:`PurePosixPath`, this class + represents concrete non-Windows filesystem paths:: + + >>> PosixPath('/etc') + PosixPath('/etc') + + *pathsegments* is specified similarly to :class:`PurePath`. + +.. class:: WindowsPath(*pathsegments) + + A subclass of :class:`Path` and :class:`PureWindowsPath`, this class + represents concrete Windows filesystem paths:: + + >>> WindowsPath('c:/Program Files/') + WindowsPath('c:/Program Files') + + *pathsegments* is specified similarly to :class:`PurePath`. + +You can only instantiate the class flavour that corresponds to your system +(allowing system calls on non-compatible path flavours could lead to +bugs or failures in your application):: + + >>> import os + >>> os.name + 'posix' + >>> Path('setup.py') + PosixPath('setup.py') + >>> PosixPath('setup.py') + PosixPath('setup.py') + >>> WindowsPath('setup.py') + Traceback (most recent call last): + File "", line 1, in + File "pathlib.py", line 798, in __new__ + % (cls.__name__,)) + NotImplementedError: cannot instantiate 'WindowsPath' on your system + + +Methods +^^^^^^^ + +Concrete paths provide the following methods in addition to pure paths +methods. Many of these methods can raise an :exc:`OSError` if a system +call fails (for example because the path doesn't exist). + +.. versionchanged:: 3.8 + + :meth:`~Path.exists()`, :meth:`~Path.is_dir()`, :meth:`~Path.is_file()`, + :meth:`~Path.is_mount()`, :meth:`~Path.is_symlink()`, + :meth:`~Path.is_block_device()`, :meth:`~Path.is_char_device()`, + :meth:`~Path.is_fifo()`, :meth:`~Path.is_socket()` now return ``False`` + instead of raising an exception for paths that contain characters + unrepresentable at the OS level. + + +.. classmethod:: Path.cwd() + + Return a new path object representing the current directory (as returned + by :func:`os.getcwd`):: + + >>> Path.cwd() + PosixPath('/home/antoine/pathlib') + + +.. classmethod:: Path.home() + + Return a new path object representing the user's home directory (as + returned by :func:`os.path.expanduser` with ``~`` construct):: + + >>> Path.home() + PosixPath('/home/antoine') + + .. versionadded:: 3.5 + + +.. method:: Path.stat() + + Return a :class:`os.stat_result` object containing information about this path, like :func:`os.stat`. + The result is looked up at each call to this method. + + :: + + >>> p = Path('setup.py') + >>> p.stat().st_size + 956 + >>> p.stat().st_mtime + 1327883547.852554 + + +.. method:: Path.chmod(mode) + + Change the file mode and permissions, like :func:`os.chmod`:: + + >>> p = Path('setup.py') + >>> p.stat().st_mode + 33277 + >>> p.chmod(0o444) + >>> p.stat().st_mode + 33060 + + +.. method:: Path.exists() + + Whether the path points to an existing file or directory:: + + >>> Path('.').exists() + True + >>> Path('setup.py').exists() + True + >>> Path('/etc').exists() + True + >>> Path('nonexistentfile').exists() + False + + .. note:: + If the path points to a symlink, :meth:`exists` returns whether the + symlink *points to* an existing file or directory. + + +.. method:: Path.expanduser() + + Return a new path with expanded ``~`` and ``~user`` constructs, + as returned by :meth:`os.path.expanduser`:: + + >>> p = PosixPath('~/films/Monty Python') + >>> p.expanduser() + PosixPath('/home/eric/films/Monty Python') + + .. versionadded:: 3.5 + + +.. method:: Path.glob(pattern) + + Glob the given relative *pattern* in the directory represented by this path, + yielding all matching files (of any kind):: + + >>> sorted(Path('.').glob('*.py')) + [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')] + >>> sorted(Path('.').glob('*/*.py')) + [PosixPath('docs/conf.py')] + + The "``**``" pattern means "this directory and all subdirectories, + recursively". In other words, it enables recursive globbing:: + + >>> sorted(Path('.').glob('**/*.py')) + [PosixPath('build/lib/pathlib.py'), + PosixPath('docs/conf.py'), + PosixPath('pathlib.py'), + PosixPath('setup.py'), + PosixPath('test_pathlib.py')] + + .. note:: + Using the "``**``" pattern in large directory trees may consume + an inordinate amount of time. + + .. audit-event:: pathlib.Path.glob self,pattern pathlib.Path.glob + + +.. method:: Path.group() + + Return the name of the group owning the file. :exc:`KeyError` is raised + if the file's gid isn't found in the system database. + + +.. method:: Path.is_dir() + + Return ``True`` if the path points to a directory (or a symbolic link + pointing to a directory), ``False`` if it points to another kind of file. + + ``False`` is also returned if the path doesn't exist or is a broken symlink; + other errors (such as permission errors) are propagated. + + +.. method:: Path.is_file() + + Return ``True`` if the path points to a regular file (or a symbolic link + pointing to a regular file), ``False`` if it points to another kind of file. + + ``False`` is also returned if the path doesn't exist or is a broken symlink; + other errors (such as permission errors) are propagated. + + +.. method:: Path.is_mount() + + Return ``True`` if the path is a :dfn:`mount point`: a point in a + file system where a different file system has been mounted. On POSIX, the + function checks whether *path*'s parent, :file:`path/..`, is on a different + device than *path*, or whether :file:`path/..` and *path* point to the same + i-node on the same device --- this should detect mount points for all Unix + and POSIX variants. Not implemented on Windows. + + .. versionadded:: 3.7 + + +.. method:: Path.is_symlink() + + Return ``True`` if the path points to a symbolic link, ``False`` otherwise. + + ``False`` is also returned if the path doesn't exist; other errors (such + as permission errors) are propagated. + + +.. method:: Path.is_socket() + + Return ``True`` if the path points to a Unix socket (or a symbolic link + pointing to a Unix socket), ``False`` if it points to another kind of file. + + ``False`` is also returned if the path doesn't exist or is a broken symlink; + other errors (such as permission errors) are propagated. + + +.. method:: Path.is_fifo() + + Return ``True`` if the path points to a FIFO (or a symbolic link + pointing to a FIFO), ``False`` if it points to another kind of file. + + ``False`` is also returned if the path doesn't exist or is a broken symlink; + other errors (such as permission errors) are propagated. + + +.. method:: Path.is_block_device() + + Return ``True`` if the path points to a block device (or a symbolic link + pointing to a block device), ``False`` if it points to another kind of file. + + ``False`` is also returned if the path doesn't exist or is a broken symlink; + other errors (such as permission errors) are propagated. + + +.. method:: Path.is_char_device() + + Return ``True`` if the path points to a character device (or a symbolic link + pointing to a character device), ``False`` if it points to another kind of file. + + ``False`` is also returned if the path doesn't exist or is a broken symlink; + other errors (such as permission errors) are propagated. + + +.. method:: Path.iterdir() + + When the path points to a directory, yield path objects of the directory + contents:: + + >>> p = Path('docs') + >>> for child in p.iterdir(): child + ... + PosixPath('docs/conf.py') + PosixPath('docs/_templates') + PosixPath('docs/make.bat') + PosixPath('docs/index.rst') + PosixPath('docs/_build') + PosixPath('docs/_static') + PosixPath('docs/Makefile') + +.. method:: Path.lchmod(mode) + + Like :meth:`Path.chmod` but, if the path points to a symbolic link, the + symbolic link's mode is changed rather than its target's. + + +.. method:: Path.lstat() + + Like :meth:`Path.stat` but, if the path points to a symbolic link, return + the symbolic link's information rather than its target's. + + +.. method:: Path.mkdir(mode=0o777, parents=False, exist_ok=False) + + Create a new directory at this given path. If *mode* is given, it is + combined with the process' ``umask`` value to determine the file mode + and access flags. If the path already exists, :exc:`FileExistsError` + is raised. + + If *parents* is true, any missing parents of this path are created + as needed; they are created with the default permissions without taking + *mode* into account (mimicking the POSIX ``mkdir -p`` command). + + If *parents* is false (the default), a missing parent raises + :exc:`FileNotFoundError`. + + If *exist_ok* is false (the default), :exc:`FileExistsError` is + raised if the target directory already exists. + + If *exist_ok* is true, :exc:`FileExistsError` exceptions will be + ignored (same behavior as the POSIX ``mkdir -p`` command), but only if the + last path component is not an existing non-directory file. + + .. versionchanged:: 3.5 + The *exist_ok* parameter was added. + + +.. method:: Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None) + + Open the file pointed to by the path, like the built-in :func:`open` + function does:: + + >>> p = Path('setup.py') + >>> with p.open() as f: + ... f.readline() + ... + '#!/usr/bin/env python3\n' + + +.. method:: Path.owner() + + Return the name of the user owning the file. :exc:`KeyError` is raised + if the file's uid isn't found in the system database. + + +.. method:: Path.read_bytes() + + Return the binary contents of the pointed-to file as a bytes object:: + + >>> p = Path('my_binary_file') + >>> p.write_bytes(b'Binary file contents') + 20 + >>> p.read_bytes() + b'Binary file contents' + + .. versionadded:: 3.5 + + +.. method:: Path.read_text(encoding=None, errors=None) + + Return the decoded contents of the pointed-to file as a string:: + + >>> p = Path('my_text_file') + >>> p.write_text('Text file contents') + 18 + >>> p.read_text() + 'Text file contents' + + The file is opened and then closed. The optional parameters have the same + meaning as in :func:`open`. + + .. versionadded:: 3.5 + + +.. method:: Path.readlink() + + Return the path to which the symbolic link points (as returned by + :func:`os.readlink`):: + + >>> p = Path('mylink') + >>> p.symlink_to('setup.py') + >>> p.readlink() + PosixPath('setup.py') + + .. versionadded:: 3.9 + + +.. method:: Path.rename(target) + + Rename this file or directory to the given *target*, and return a new Path + instance pointing to *target*. On Unix, if *target* exists and is a file, + it will be replaced silently if the user has permission. *target* can be + either a string or another path object:: + + >>> p = Path('foo') + >>> p.open('w').write('some text') + 9 + >>> target = Path('bar') + >>> p.rename(target) + PosixPath('bar') + >>> target.open().read() + 'some text' + + .. versionchanged:: 3.8 + Added return value, return the new Path instance. + + +.. method:: Path.replace(target) + + Rename this file or directory to the given *target*, and return a new Path + instance pointing to *target*. If *target* points to an existing file or + directory, it will be unconditionally replaced. + + .. versionchanged:: 3.8 + Added return value, return the new Path instance. + + +.. method:: Path.resolve(strict=False) + + Make the path absolute, resolving any symlinks. A new path object is + returned:: + + >>> p = Path() + >>> p + PosixPath('.') + >>> p.resolve() + PosixPath('/home/antoine/pathlib') + + "``..``" components are also eliminated (this is the only method to do so):: + + >>> p = Path('docs/../setup.py') + >>> p.resolve() + PosixPath('/home/antoine/pathlib/setup.py') + + If the path doesn't exist and *strict* is ``True``, :exc:`FileNotFoundError` + is raised. If *strict* is ``False``, the path is resolved as far as possible + and any remainder is appended without checking whether it exists. If an + infinite loop is encountered along the resolution path, :exc:`RuntimeError` + is raised. + + .. versionadded:: 3.6 + The *strict* argument (pre-3.6 behavior is strict). + +.. method:: Path.rglob(pattern) + + This is like calling :func:`Path.glob` with "``**/``" added in front of the + given relative *pattern*:: + + >>> sorted(Path().rglob("*.py")) + [PosixPath('build/lib/pathlib.py'), + PosixPath('docs/conf.py'), + PosixPath('pathlib.py'), + PosixPath('setup.py'), + PosixPath('test_pathlib.py')] + + .. audit-event:: pathlib.Path.rglob self,pattern pathlib.Path.rglob + + +.. method:: Path.rmdir() + + Remove this directory. The directory must be empty. + + +.. method:: Path.samefile(other_path) + + Return whether this path points to the same file as *other_path*, which + can be either a Path object, or a string. The semantics are similar + to :func:`os.path.samefile` and :func:`os.path.samestat`. + + An :exc:`OSError` can be raised if either file cannot be accessed for some + reason. + + :: + + >>> p = Path('spam') + >>> q = Path('eggs') + >>> p.samefile(q) + False + >>> p.samefile('spam') + True + + .. versionadded:: 3.5 + + +.. method:: Path.symlink_to(target, target_is_directory=False) + + Make this path a symbolic link to *target*. Under Windows, + *target_is_directory* must be true (default ``False``) if the link's target + is a directory. Under POSIX, *target_is_directory*'s value is ignored. + + :: + + >>> p = Path('mylink') + >>> p.symlink_to('setup.py') + >>> p.resolve() + PosixPath('/home/antoine/pathlib/setup.py') + >>> p.stat().st_size + 956 + >>> p.lstat().st_size + 8 + + .. note:: + The order of arguments (link, target) is the reverse + of :func:`os.symlink`'s. + + +.. method:: Path.touch(mode=0o666, exist_ok=True) + + Create a file at this given path. If *mode* is given, it is combined + with the process' ``umask`` value to determine the file mode and access + flags. If the file already exists, the function succeeds if *exist_ok* + is true (and its modification time is updated to the current time), + otherwise :exc:`FileExistsError` is raised. + + +.. method:: Path.unlink(missing_ok=False) + + Remove this file or symbolic link. If the path points to a directory, + use :func:`Path.rmdir` instead. + + If *missing_ok* is false (the default), :exc:`FileNotFoundError` is + raised if the path does not exist. + + If *missing_ok* is true, :exc:`FileNotFoundError` exceptions will be + ignored (same behavior as the POSIX ``rm -f`` command). + + .. versionchanged:: 3.8 + The *missing_ok* parameter was added. + + +.. method:: Path.link_to(target) + + Create a hard link pointing to a path named *target*. + + .. versionchanged:: 3.8 + + +.. method:: Path.write_bytes(data) + + Open the file pointed to in bytes mode, write *data* to it, and close the + file:: + + >>> p = Path('my_binary_file') + >>> p.write_bytes(b'Binary file contents') + 20 + >>> p.read_bytes() + b'Binary file contents' + + An existing file of the same name is overwritten. + + .. versionadded:: 3.5 + + +.. method:: Path.write_text(data, encoding=None, errors=None) + + Open the file pointed to in text mode, write *data* to it, and close the + file:: + + >>> p = Path('my_text_file') + >>> p.write_text('Text file contents') + 18 + >>> p.read_text() + 'Text file contents' + + An existing file of the same name is overwritten. The optional parameters + have the same meaning as in :func:`open`. + + .. versionadded:: 3.5 + +Correspondence to tools in the :mod:`os` module +----------------------------------------------- + +Below is a table mapping various :mod:`os` functions to their corresponding +:class:`PurePath`/:class:`Path` equivalent. + +.. note:: + + Although :func:`os.path.relpath` and :meth:`PurePath.relative_to` have some + overlapping use-cases, their semantics differ enough to warrant not + considering them equivalent. + +==================================== ============================== +os and os.path pathlib +==================================== ============================== +:func:`os.path.abspath` :meth:`Path.resolve` +:func:`os.chmod` :meth:`Path.chmod` +:func:`os.mkdir` :meth:`Path.mkdir` +:func:`os.makedirs` :meth:`Path.mkdir` +:func:`os.rename` :meth:`Path.rename` +:func:`os.replace` :meth:`Path.replace` +:func:`os.rmdir` :meth:`Path.rmdir` +:func:`os.remove`, :func:`os.unlink` :meth:`Path.unlink` +:func:`os.getcwd` :func:`Path.cwd` +:func:`os.path.exists` :meth:`Path.exists` +:func:`os.path.expanduser` :meth:`Path.expanduser` and + :meth:`Path.home` +:func:`os.path.isdir` :meth:`Path.is_dir` +:func:`os.path.isfile` :meth:`Path.is_file` +:func:`os.path.islink` :meth:`Path.is_symlink` +:func:`os.readlink` :meth:`Path.readlink` +:func:`os.stat` :meth:`Path.stat`, + :meth:`Path.owner`, + :meth:`Path.group` +:func:`os.path.isabs` :meth:`PurePath.is_absolute` +:func:`os.path.join` :func:`PurePath.joinpath` +:func:`os.path.basename` :data:`PurePath.name` +:func:`os.path.dirname` :data:`PurePath.parent` +:func:`os.path.samefile` :meth:`Path.samefile` +:func:`os.path.splitext` :data:`PurePath.suffix` +==================================== ============================== diff --git a/cpython_2/environment/repo/Doc/library/pdb.rst b/cpython_2/environment/repo/Doc/library/pdb.rst new file mode 100644 index 0000000000000000000000000000000000000000..606e8e534577067805916d5ee5fcad4ce3876fd8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pdb.rst @@ -0,0 +1,546 @@ +.. _debugger: + +:mod:`pdb` --- The Python Debugger +================================== + +.. module:: pdb + :synopsis: The Python debugger for interactive interpreters. + +**Source code:** :source:`Lib/pdb.py` + +.. index:: single: debugging + +-------------- + +The module :mod:`pdb` defines an interactive source code debugger for Python +programs. It supports setting (conditional) breakpoints and single stepping at +the source line level, inspection of stack frames, source code listing, and +evaluation of arbitrary Python code in the context of any stack frame. It also +supports post-mortem debugging and can be called under program control. + +.. index:: + single: Pdb (class in pdb) + module: bdb + module: cmd + +The debugger is extensible -- it is actually defined as the class :class:`Pdb`. +This is currently undocumented but easily understood by reading the source. The +extension interface uses the modules :mod:`bdb` and :mod:`cmd`. + +The debugger's prompt is ``(Pdb)``. Typical usage to run a program under control +of the debugger is:: + + >>> import pdb + >>> import mymodule + >>> pdb.run('mymodule.test()') + > (0)?() + (Pdb) continue + > (1)?() + (Pdb) continue + NameError: 'spam' + > (1)?() + (Pdb) + +.. versionchanged:: 3.3 + Tab-completion via the :mod:`readline` module is available for commands and + command arguments, e.g. the current global and local names are offered as + arguments of the ``p`` command. + +:file:`pdb.py` can also be invoked as a script to debug other scripts. For +example:: + + python3 -m pdb myscript.py + +When invoked as a script, pdb will automatically enter post-mortem debugging if +the program being debugged exits abnormally. After post-mortem debugging (or +after normal exit of the program), pdb will restart the program. Automatic +restarting preserves pdb's state (such as breakpoints) and in most cases is more +useful than quitting the debugger upon program's exit. + +.. versionadded:: 3.2 + :file:`pdb.py` now accepts a ``-c`` option that executes commands as if given + in a :file:`.pdbrc` file, see :ref:`debugger-commands`. + +.. versionadded:: 3.7 + :file:`pdb.py` now accepts a ``-m`` option that execute modules similar to the way + ``python3 -m`` does. As with a script, the debugger will pause execution just + before the first line of the module. + + +The typical usage to break into the debugger from a running program is to +insert :: + + import pdb; pdb.set_trace() + +at the location you want to break into the debugger. You can then step through +the code following this statement, and continue running without the debugger +using the :pdbcmd:`continue` command. + +.. versionadded:: 3.7 + The built-in :func:`breakpoint()`, when called with defaults, can be used + instead of ``import pdb; pdb.set_trace()``. + +The typical usage to inspect a crashed program is:: + + >>> import pdb + >>> import mymodule + >>> mymodule.test() + Traceback (most recent call last): + File "", line 1, in + File "./mymodule.py", line 4, in test + test2() + File "./mymodule.py", line 3, in test2 + print(spam) + NameError: spam + >>> pdb.pm() + > ./mymodule.py(3)test2() + -> print(spam) + (Pdb) + + +The module defines the following functions; each enters the debugger in a +slightly different way: + +.. function:: run(statement, globals=None, locals=None) + + Execute the *statement* (given as a string or a code object) under debugger + control. The debugger prompt appears before any code is executed; you can + set breakpoints and type :pdbcmd:`continue`, or you can step through the + statement using :pdbcmd:`step` or :pdbcmd:`next` (all these commands are + explained below). The optional *globals* and *locals* arguments specify the + environment in which the code is executed; by default the dictionary of the + module :mod:`__main__` is used. (See the explanation of the built-in + :func:`exec` or :func:`eval` functions.) + + +.. function:: runeval(expression, globals=None, locals=None) + + Evaluate the *expression* (given as a string or a code object) under debugger + control. When :func:`runeval` returns, it returns the value of the + expression. Otherwise this function is similar to :func:`run`. + + +.. function:: runcall(function, *args, **kwds) + + Call the *function* (a function or method object, not a string) with the + given arguments. When :func:`runcall` returns, it returns whatever the + function call returned. The debugger prompt appears as soon as the function + is entered. + + +.. function:: set_trace(*, header=None) + + Enter the debugger at the calling stack frame. This is useful to hard-code + a breakpoint at a given point in a program, even if the code is not + otherwise being debugged (e.g. when an assertion fails). If given, + *header* is printed to the console just before debugging begins. + + .. versionchanged:: 3.7 + The keyword-only argument *header*. + + +.. function:: post_mortem(traceback=None) + + 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). + + +.. function:: pm() + + Enter post-mortem debugging of the traceback found in + :data:`sys.last_traceback`. + + +The ``run*`` functions and :func:`set_trace` are aliases for instantiating the +:class:`Pdb` class and calling the method of the same name. If you want to +access further features, you have to do this yourself: + +.. class:: Pdb(completekey='tab', stdin=None, stdout=None, skip=None, \ + nosigint=False, readrc=True) + + :class:`Pdb` is the debugger class. + + The *completekey*, *stdin* and *stdout* arguments are passed to the + underlying :class:`cmd.Cmd` class; see the description there. + + The *skip* argument, if given, must be an iterable of glob-style module name + patterns. The debugger will not step into frames that originate in a module + that matches one of these patterns. [1]_ + + By default, Pdb sets a handler for the SIGINT signal (which is sent when the + user presses :kbd:`Ctrl-C` on the console) when you give a ``continue`` command. + This allows you to break into the debugger again by pressing :kbd:`Ctrl-C`. If you + want Pdb not to touch the SIGINT handler, set *nosigint* to true. + + The *readrc* argument defaults to true and controls whether Pdb will load + .pdbrc files from the filesystem. + + Example call to enable tracing with *skip*:: + + import pdb; pdb.Pdb(skip=['django.*']).set_trace() + + .. audit-event:: pdb.Pdb "" pdb.Pdb + + .. versionadded:: 3.1 + The *skip* argument. + + .. versionadded:: 3.2 + The *nosigint* argument. Previously, a SIGINT handler was never set by + Pdb. + + .. versionchanged:: 3.6 + The *readrc* argument. + + .. method:: run(statement, globals=None, locals=None) + runeval(expression, globals=None, locals=None) + runcall(function, *args, **kwds) + set_trace() + + See the documentation for the functions explained above. + + +.. _debugger-commands: + +Debugger Commands +----------------- + +The commands recognized by the debugger are listed below. Most commands can be +abbreviated to one or two letters as indicated; e.g. ``h(elp)`` means that +either ``h`` or ``help`` can be used to enter the help command (but not ``he`` +or ``hel``, nor ``H`` or ``Help`` or ``HELP``). Arguments to commands must be +separated by whitespace (spaces or tabs). Optional arguments are enclosed in +square brackets (``[]``) in the command syntax; the square brackets must not be +typed. Alternatives in the command syntax are separated by a vertical bar +(``|``). + +Entering a blank line repeats the last command entered. Exception: if the last +command was a :pdbcmd:`list` command, the next 11 lines are listed. + +Commands that the debugger doesn't recognize are assumed to be Python statements +and are executed in the context of the program being debugged. Python +statements can also be prefixed with an exclamation point (``!``). This is a +powerful way to inspect the program being debugged; it is even possible to +change a variable or call a function. When an exception occurs in such a +statement, the exception name is printed but the debugger's state is not +changed. + +The debugger supports :ref:`aliases `. Aliases can have +parameters which allows one a certain level of adaptability to the context under +examination. + +Multiple commands may be entered on a single line, separated by ``;;``. (A +single ``;`` is not used as it is the separator for multiple commands in a line +that is passed to the Python parser.) No intelligence is applied to separating +the commands; the input is split at the first ``;;`` pair, even if it is in the +middle of a quoted string. + +.. index:: + pair: .pdbrc; file + triple: debugger; configuration; file + +If a file :file:`.pdbrc` exists in the user's home directory or in the current +directory, it is read in and executed as if it had been typed at the debugger +prompt. This is particularly useful for aliases. If both files exist, the one +in the home directory is read first and aliases defined there can be overridden +by the local file. + +.. versionchanged:: 3.2 + :file:`.pdbrc` can now contain commands that continue debugging, such as + :pdbcmd:`continue` or :pdbcmd:`next`. Previously, these commands had no + effect. + + +.. pdbcommand:: h(elp) [command] + + Without argument, print the list of available commands. With a *command* as + argument, print help about that command. ``help pdb`` displays the full + documentation (the docstring of the :mod:`pdb` module). Since the *command* + argument must be an identifier, ``help exec`` must be entered to get help on + the ``!`` command. + +.. pdbcommand:: w(here) + + Print a stack trace, with the most recent frame at the bottom. An arrow + indicates the current frame, which determines the context of most commands. + +.. pdbcommand:: d(own) [count] + + Move the current frame *count* (default one) levels down in the stack trace + (to a newer frame). + +.. pdbcommand:: u(p) [count] + + Move the current frame *count* (default one) levels up in the stack trace (to + an older frame). + +.. pdbcommand:: b(reak) [([filename:]lineno | function) [, condition]] + + With a *lineno* argument, set a break there in the current file. With a + *function* argument, set a break at the first executable statement within + that function. The line number may be prefixed with a filename and a colon, + to specify a breakpoint in another file (probably one that hasn't been loaded + yet). The file is searched on :data:`sys.path`. Note that each breakpoint + is assigned a number to which all the other breakpoint commands refer. + + If a second argument is present, it is an expression which must evaluate to + true before the breakpoint is honored. + + Without argument, list all breaks, including for each breakpoint, the number + of times that breakpoint has been hit, the current ignore count, and the + associated condition if any. + +.. pdbcommand:: tbreak [([filename:]lineno | function) [, condition]] + + Temporary breakpoint, which is removed automatically when it is first hit. + The arguments are the same as for :pdbcmd:`break`. + +.. pdbcommand:: cl(ear) [filename:lineno | bpnumber ...] + + With a *filename:lineno* argument, clear all the breakpoints at this line. + With a space separated list of breakpoint numbers, clear those breakpoints. + Without argument, clear all breaks (but first ask confirmation). + +.. pdbcommand:: disable [bpnumber ...] + + Disable the breakpoints given as a space separated list of breakpoint + numbers. Disabling a breakpoint means it cannot cause the program to stop + execution, but unlike clearing a breakpoint, it remains in the list of + breakpoints and can be (re-)enabled. + +.. pdbcommand:: enable [bpnumber ...] + + Enable the breakpoints specified. + +.. pdbcommand:: ignore bpnumber [count] + + Set the ignore count for the given breakpoint number. If count is omitted, + the ignore count is set to 0. A breakpoint becomes active when the ignore + count is zero. When non-zero, the count is decremented each time the + breakpoint is reached and the breakpoint is not disabled and any associated + condition evaluates to true. + +.. pdbcommand:: condition bpnumber [condition] + + Set a new *condition* for the breakpoint, an expression which must evaluate + to true before the breakpoint is honored. If *condition* is absent, any + existing condition is removed; i.e., the breakpoint is made unconditional. + +.. pdbcommand:: commands [bpnumber] + + Specify a list of commands for breakpoint number *bpnumber*. The commands + themselves appear on the following lines. Type a line containing just + ``end`` to terminate the commands. An example:: + + (Pdb) commands 1 + (com) p some_variable + (com) end + (Pdb) + + To remove all commands from a breakpoint, type ``commands`` and follow it + immediately with ``end``; that is, give no commands. + + With no *bpnumber* argument, ``commands`` refers to the last breakpoint set. + + You can use breakpoint commands to start your program up again. Simply use + the :pdbcmd:`continue` command, or :pdbcmd:`step`, + or any other command that resumes execution. + + Specifying any command resuming execution + (currently :pdbcmd:`continue`, :pdbcmd:`step`, :pdbcmd:`next`, + :pdbcmd:`return`, :pdbcmd:`jump`, :pdbcmd:`quit` and their abbreviations) + terminates the command list (as if + that command was immediately followed by end). This is because any time you + resume execution (even with a simple next or step), you may encounter another + breakpoint—which could have its own command list, leading to ambiguities about + which list to execute. + + If you use the 'silent' command in the command list, the usual message about + stopping at a breakpoint is not printed. This may be desirable for breakpoints + that are to print a specific message and then continue. If none of the other + commands print anything, you see no sign that the breakpoint was reached. + +.. pdbcommand:: s(tep) + + Execute the current line, stop at the first possible occasion (either in a + function that is called or on the next line in the current function). + +.. pdbcommand:: n(ext) + + Continue execution until the next line in the current function is reached or + it returns. (The difference between :pdbcmd:`next` and :pdbcmd:`step` is + that :pdbcmd:`step` stops inside a called function, while :pdbcmd:`next` + executes called functions at (nearly) full speed, only stopping at the next + line in the current function.) + +.. pdbcommand:: unt(il) [lineno] + + Without argument, continue execution until the line with a number greater + than the current one is reached. + + With a line number, continue execution until a line with a number greater or + equal to that is reached. In both cases, also stop when the current frame + returns. + + .. versionchanged:: 3.2 + Allow giving an explicit line number. + +.. pdbcommand:: r(eturn) + + Continue execution until the current function returns. + +.. pdbcommand:: c(ont(inue)) + + Continue execution, only stop when a breakpoint is encountered. + +.. pdbcommand:: j(ump) lineno + + Set the next line that will be executed. Only available in the bottom-most + frame. This lets you jump back and execute code again, or jump forward to + skip code that you don't want to run. + + It should be noted that not all jumps are allowed -- for instance it is not + possible to jump into the middle of a :keyword:`for` loop or out of a + :keyword:`finally` clause. + +.. pdbcommand:: l(ist) [first[, last]] + + List source code for the current file. Without arguments, list 11 lines + around the current line or continue the previous listing. With ``.`` as + argument, list 11 lines around the current line. With one argument, + list 11 lines around at that line. With two arguments, list the given range; + if the second argument is less than the first, it is interpreted as a count. + + The current line in the current frame is indicated by ``->``. If an + exception is being debugged, the line where the exception was originally + raised or propagated is indicated by ``>>``, if it differs from the current + line. + + .. versionadded:: 3.2 + The ``>>`` marker. + +.. pdbcommand:: ll | longlist + + List all source code for the current function or frame. Interesting lines + are marked as for :pdbcmd:`list`. + + .. versionadded:: 3.2 + +.. pdbcommand:: a(rgs) + + Print the argument list of the current function. + +.. pdbcommand:: p expression + + Evaluate the *expression* in the current context and print its value. + + .. note:: + + ``print()`` can also be used, but is not a debugger command --- this executes the + Python :func:`print` function. + + +.. pdbcommand:: pp expression + + Like the :pdbcmd:`p` command, except the value of the expression is + pretty-printed using the :mod:`pprint` module. + +.. pdbcommand:: whatis expression + + Print the type of the *expression*. + +.. pdbcommand:: source expression + + Try to get source code for the given object and display it. + + .. versionadded:: 3.2 + +.. pdbcommand:: display [expression] + + Display the value of the expression if it changed, each time execution stops + in the current frame. + + Without expression, list all display expressions for the current frame. + + .. versionadded:: 3.2 + +.. pdbcommand:: undisplay [expression] + + Do not display the expression any more in the current frame. Without + expression, clear all display expressions for the current frame. + + .. versionadded:: 3.2 + +.. pdbcommand:: interact + + Start an interactive interpreter (using the :mod:`code` module) whose global + namespace contains all the (global and local) names found in the current + scope. + + .. versionadded:: 3.2 + +.. _debugger-aliases: + +.. pdbcommand:: alias [name [command]] + + Create an alias called *name* that executes *command*. The command must + *not* be enclosed in quotes. Replaceable parameters can be indicated by + ``%1``, ``%2``, and so on, while ``%*`` is replaced by all the parameters. + If no command is given, the current alias for *name* is shown. If no + arguments are given, all aliases are listed. + + Aliases may be nested and can contain anything that can be legally typed at + the pdb prompt. Note that internal pdb commands *can* be overridden by + aliases. Such a command is then hidden until the alias is removed. Aliasing + is recursively applied to the first word of the command line; all other words + in the line are left alone. + + As an example, here are two useful aliases (especially when placed in the + :file:`.pdbrc` file):: + + # Print instance variables (usage "pi classInst") + alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) + # Print instance variables in self + alias ps pi self + +.. pdbcommand:: unalias name + + Delete the specified alias. + +.. pdbcommand:: ! statement + + Execute the (one-line) *statement* in the context of the current stack frame. + The exclamation point can be omitted unless the first word of the statement + resembles a debugger command. To set a global variable, you can prefix the + assignment command with a :keyword:`global` statement on the same line, + e.g.:: + + (Pdb) global list_options; list_options = ['-l'] + (Pdb) + +.. pdbcommand:: run [args ...] + restart [args ...] + + Restart the debugged Python program. If an argument is supplied, it is split + with :mod:`shlex` and the result is used as the new :data:`sys.argv`. + History, breakpoints, actions and debugger options are preserved. + :pdbcmd:`restart` is an alias for :pdbcmd:`run`. + +.. pdbcommand:: q(uit) + + Quit from the debugger. The program being executed is aborted. + +.. pdbcommand:: debug code + + Enter a recursive debugger that steps through the code + argument (which is an arbitrary expression or statement to be + executed in the current environment). + +.. pdbcommand:: retval + Print the return value for the last return of a function. + +.. rubric:: Footnotes + +.. [1] Whether a frame is considered to originate in a certain module + is determined by the ``__name__`` in the frame globals. diff --git a/cpython_2/environment/repo/Doc/library/persistence.rst b/cpython_2/environment/repo/Doc/library/persistence.rst new file mode 100644 index 0000000000000000000000000000000000000000..d5bb193fa3aa09b9a8b2ac19a31d69aabb25eb8a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/persistence.rst @@ -0,0 +1,23 @@ +.. _persistence: + +**************** +Data Persistence +**************** + +The modules described in this chapter support storing Python data in a +persistent form on disk. The :mod:`pickle` and :mod:`marshal` modules can turn +many Python data types into a stream of bytes and then recreate the objects from +the bytes. The various DBM-related modules support a family of hash-based file +formats that store a mapping of strings to other strings. + +The list of modules described in this chapter is: + + +.. toctree:: + + pickle.rst + copyreg.rst + shelve.rst + marshal.rst + dbm.rst + sqlite3.rst diff --git a/cpython_2/environment/repo/Doc/library/pickle.rst b/cpython_2/environment/repo/Doc/library/pickle.rst new file mode 100644 index 0000000000000000000000000000000000000000..b7c34527719486ccf839da564d403409dde77ab7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pickle.rst @@ -0,0 +1,1203 @@ +:mod:`pickle` --- Python object serialization +============================================= + +.. module:: pickle + :synopsis: Convert Python objects to streams of bytes and back. + +.. sectionauthor:: Jim Kerr . +.. sectionauthor:: Barry Warsaw + +**Source code:** :source:`Lib/pickle.py` + +.. index:: + single: persistence + pair: persistent; objects + pair: serializing; objects + pair: marshalling; objects + pair: flattening; objects + pair: pickling; objects + +-------------- + +The :mod:`pickle` module implements binary protocols for serializing and +de-serializing a Python object structure. *"Pickling"* is the process +whereby a Python object hierarchy is converted into a byte stream, and +*"unpickling"* is the inverse operation, whereby a byte stream +(from a :term:`binary file` or :term:`bytes-like object`) is converted +back into an object hierarchy. Pickling (and unpickling) is alternatively +known as "serialization", "marshalling," [#]_ or "flattening"; however, to +avoid confusion, the terms used here are "pickling" and "unpickling". + +.. warning:: + + The ``pickle`` module **is not secure**. Only unpickle data you trust. + + It is possible to construct malicious pickle data which will **execute + arbitrary code during unpickling**. Never unpickle data that could have come + from an untrusted source, or that could have been tampered with. + + Consider signing data with :mod:`hmac` if you need to ensure that it has not + been tampered with. + + Safer serialization formats such as :mod:`json` may be more appropriate if + you are processing untrusted data. See :ref:`comparison-with-json`. + + +Relationship to other Python modules +------------------------------------ + +Comparison with ``marshal`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Python has a more primitive serialization module called :mod:`marshal`, but in +general :mod:`pickle` should always be the preferred way to serialize Python +objects. :mod:`marshal` exists primarily to support Python's :file:`.pyc` +files. + +The :mod:`pickle` module differs from :mod:`marshal` in several significant ways: + +* The :mod:`pickle` module keeps track of the objects it has already serialized, + so that later references to the same object won't be serialized again. + :mod:`marshal` doesn't do this. + + This has implications both for recursive objects and object sharing. Recursive + objects are objects that contain references to themselves. These are not + handled by marshal, and in fact, attempting to marshal recursive objects will + crash your Python interpreter. Object sharing happens when there are multiple + references to the same object in different places in the object hierarchy being + serialized. :mod:`pickle` stores such objects only once, and ensures that all + other references point to the master copy. Shared objects remain shared, which + can be very important for mutable objects. + +* :mod:`marshal` cannot be used to serialize user-defined classes and their + instances. :mod:`pickle` can save and restore class instances transparently, + however the class definition must be importable and live in the same module as + when the object was stored. + +* The :mod:`marshal` serialization format is not guaranteed to be portable + across Python versions. Because its primary job in life is to support + :file:`.pyc` files, the Python implementers reserve the right to change the + serialization format in non-backwards compatible ways should the need arise. + The :mod:`pickle` serialization format is guaranteed to be backwards compatible + across Python releases provided a compatible pickle protocol is chosen and + pickling and unpickling code deals with Python 2 to Python 3 type differences + if your data is crossing that unique breaking change language boundary. + + +.. _comparison-with-json: + +Comparison with ``json`` +^^^^^^^^^^^^^^^^^^^^^^^^ + +There are fundamental differences between the pickle protocols and +`JSON (JavaScript Object Notation) `_: + +* JSON is a text serialization format (it outputs unicode text, although + most of the time it is then encoded to ``utf-8``), while pickle is + a binary serialization format; + +* JSON is human-readable, while pickle is not; + +* JSON is interoperable and widely used outside of the Python ecosystem, + while pickle is Python-specific; + +* JSON, by default, can only represent a subset of the Python built-in + types, and no custom classes; pickle can represent an extremely large + number of Python types (many of them automatically, by clever usage + of Python's introspection facilities; complex cases can be tackled by + implementing :ref:`specific object APIs `); + +* Unlike pickle, deserializing untrusted JSON does not in itself create an + arbitrary code execution vulnerability. + +.. seealso:: + The :mod:`json` module: a standard library module allowing JSON + serialization and deserialization. + + +.. _pickle-protocols: + +Data stream format +------------------ + +.. index:: + single: External Data Representation + +The data format used by :mod:`pickle` is Python-specific. This has the +advantage that there are no restrictions imposed by external standards such as +JSON or XDR (which can't represent pointer sharing); however it means that +non-Python programs may not be able to reconstruct pickled Python objects. + +By default, the :mod:`pickle` data format uses a relatively compact binary +representation. If you need optimal size characteristics, you can efficiently +:doc:`compress ` pickled data. + +The module :mod:`pickletools` contains tools for analyzing data streams +generated by :mod:`pickle`. :mod:`pickletools` source code has extensive +comments about opcodes used by pickle protocols. + +There are currently 6 different protocols which can be used for pickling. +The higher the protocol used, the more recent the version of Python needed +to read the pickle produced. + +* Protocol version 0 is the original "human-readable" protocol and is + backwards compatible with earlier versions of Python. + +* Protocol version 1 is an old binary format which is also compatible with + earlier versions of Python. + +* Protocol version 2 was introduced in Python 2.3. It provides much more + efficient pickling of :term:`new-style class`\es. Refer to :pep:`307` for + information about improvements brought by protocol 2. + +* Protocol version 3 was added in Python 3.0. It has explicit support for + :class:`bytes` objects and cannot be unpickled by Python 2.x. This was + the default protocol in Python 3.0--3.7. + +* Protocol version 4 was added in Python 3.4. It adds support for very large + objects, pickling more kinds of objects, and some data format + optimizations. It is the default protocol starting with Python 3.8. + Refer to :pep:`3154` for information about improvements brought by + protocol 4. + +* Protocol version 5 was added in Python 3.8. It adds support for out-of-band + data and speedup for in-band data. Refer to :pep:`574` for information about + improvements brought by protocol 5. + +.. note:: + Serialization is a more primitive notion than persistence; although + :mod:`pickle` reads and writes file objects, it does not handle the issue of + naming persistent objects, nor the (even more complicated) issue of concurrent + access to persistent objects. The :mod:`pickle` module can transform a complex + object into a byte stream and it can transform the byte stream into an object + with the same internal structure. Perhaps the most obvious thing to do with + these byte streams is to write them onto a file, but it is also conceivable to + send them across a network or store them in a database. The :mod:`shelve` + module provides a simple interface to pickle and unpickle objects on + DBM-style database files. + + +Module Interface +---------------- + +To serialize an object hierarchy, you simply call the :func:`dumps` function. +Similarly, to de-serialize a data stream, you call the :func:`loads` function. +However, if you want more control over serialization and de-serialization, +you can create a :class:`Pickler` or an :class:`Unpickler` object, respectively. + +The :mod:`pickle` module provides the following constants: + + +.. data:: HIGHEST_PROTOCOL + + An integer, the highest :ref:`protocol version ` + available. This value can be passed as a *protocol* value to functions + :func:`dump` and :func:`dumps` as well as the :class:`Pickler` + constructor. + +.. data:: DEFAULT_PROTOCOL + + An integer, the default :ref:`protocol version ` used + for pickling. May be less than :data:`HIGHEST_PROTOCOL`. Currently the + default protocol is 4, first introduced in Python 3.4 and incompatible + with previous versions. + + .. versionchanged:: 3.0 + + The default protocol is 3. + + .. versionchanged:: 3.8 + + The default protocol is 4. + +The :mod:`pickle` module provides the following functions to make the pickling +process more convenient: + +.. function:: dump(obj, file, protocol=None, \*, fix_imports=True, buffer_callback=None) + + Write the pickled representation of the object *obj* to the open + :term:`file object` *file*. This is equivalent to + ``Pickler(file, protocol).dump(obj)``. + + Arguments *file*, *protocol*, *fix_imports* and *buffer_callback* have + the same meaning as in the :class:`Pickler` constructor. + + .. versionchanged:: 3.8 + The *buffer_callback* argument was added. + +.. function:: dumps(obj, protocol=None, \*, fix_imports=True, buffer_callback=None) + + Return the pickled representation of the object *obj* as a :class:`bytes` object, + instead of writing it to a file. + + Arguments *protocol*, *fix_imports* and *buffer_callback* have the same + meaning as in the :class:`Pickler` constructor. + + .. versionchanged:: 3.8 + The *buffer_callback* argument was added. + +.. function:: load(file, \*, fix_imports=True, encoding="ASCII", errors="strict", buffers=None) + + Read the pickled representation of an object from the open :term:`file object` + *file* and return the reconstituted object hierarchy specified therein. + This is equivalent to ``Unpickler(file).load()``. + + The protocol version of the pickle is detected automatically, so no + protocol argument is needed. Bytes past the pickled representation + of the object are ignored. + + Arguments *file*, *fix_imports*, *encoding*, *errors*, *strict* and *buffers* + have the same meaning as in the :class:`Unpickler` constructor. + + .. versionchanged:: 3.8 + The *buffers* argument was added. + +.. function:: loads(data, /, \*, fix_imports=True, encoding="ASCII", errors="strict", buffers=None) + + Return the reconstituted object hierarchy of the pickled representation + *data* of an object. *data* must be a :term:`bytes-like object`. + + The protocol version of the pickle is detected automatically, so no + protocol argument is needed. Bytes past the pickled representation + of the object are ignored. + + Arguments *file*, *fix_imports*, *encoding*, *errors*, *strict* and *buffers* + have the same meaning as in the :class:`Unpickler` constructor. + + .. versionchanged:: 3.8 + The *buffers* argument was added. + + +The :mod:`pickle` module defines three exceptions: + +.. exception:: PickleError + + Common base class for the other pickling exceptions. It inherits + :exc:`Exception`. + +.. exception:: PicklingError + + Error raised when an unpicklable object is encountered by :class:`Pickler`. + It inherits :exc:`PickleError`. + + Refer to :ref:`pickle-picklable` to learn what kinds of objects can be + pickled. + +.. exception:: UnpicklingError + + Error raised when there is a problem unpickling an object, such as a data + corruption or a security violation. It inherits :exc:`PickleError`. + + Note that other exceptions may also be raised during unpickling, including + (but not necessarily limited to) AttributeError, EOFError, ImportError, and + IndexError. + + +The :mod:`pickle` module exports three classes, :class:`Pickler`, +:class:`Unpickler` and :class:`PickleBuffer`: + +.. class:: Pickler(file, protocol=None, \*, fix_imports=True, buffer_callback=None) + + This takes a binary file for writing a pickle data stream. + + The optional *protocol* argument, an integer, tells the pickler to use + the given protocol; supported protocols are 0 to :data:`HIGHEST_PROTOCOL`. + If not specified, the default is :data:`DEFAULT_PROTOCOL`. If a negative + number is specified, :data:`HIGHEST_PROTOCOL` is selected. + + The *file* argument must have a write() method that accepts a single bytes + argument. It can thus be an on-disk file opened for binary writing, an + :class:`io.BytesIO` instance, or any other custom object that meets this + interface. + + If *fix_imports* is true and *protocol* is less than 3, pickle will try to + map the new Python 3 names to the old module names used in Python 2, so + that the pickle data stream is readable with Python 2. + + If *buffer_callback* is None (the default), buffer views are + serialized into *file* as part of the pickle stream. + + If *buffer_callback* is not None, then it can be called any number + of times with a buffer view. If the callback returns a false value + (such as None), the given buffer is :ref:`out-of-band `; + otherwise the buffer is serialized in-band, i.e. inside the pickle stream. + + It is an error if *buffer_callback* is not None and *protocol* is + None or smaller than 5. + + .. versionchanged:: 3.8 + The *buffer_callback* argument was added. + + .. method:: dump(obj) + + Write the pickled representation of *obj* to the open file object given in + the constructor. + + .. method:: persistent_id(obj) + + Do nothing by default. This exists so a subclass can override it. + + If :meth:`persistent_id` returns ``None``, *obj* is pickled as usual. Any + other value causes :class:`Pickler` to emit the returned value as a + persistent ID for *obj*. The meaning of this persistent ID should be + defined by :meth:`Unpickler.persistent_load`. Note that the value + returned by :meth:`persistent_id` cannot itself have a persistent ID. + + See :ref:`pickle-persistent` for details and examples of uses. + + .. attribute:: dispatch_table + + A pickler object's dispatch table is a registry of *reduction + functions* of the kind which can be declared using + :func:`copyreg.pickle`. It is a mapping whose keys are classes + and whose values are reduction functions. A reduction function + takes a single argument of the associated class and should + conform to the same interface as a :meth:`__reduce__` + method. + + By default, a pickler object will not have a + :attr:`dispatch_table` attribute, and it will instead use the + global dispatch table managed by the :mod:`copyreg` module. + However, to customize the pickling for a specific pickler object + one can set the :attr:`dispatch_table` attribute to a dict-like + object. Alternatively, if a subclass of :class:`Pickler` has a + :attr:`dispatch_table` attribute then this will be used as the + default dispatch table for instances of that class. + + See :ref:`pickle-dispatch` for usage examples. + + .. versionadded:: 3.3 + + .. method:: reducer_override(self, obj) + + Special reducer that can be defined in :class:`Pickler` subclasses. This + method has priority over any reducer in the :attr:`dispatch_table`. It + should conform to the same interface as a :meth:`__reduce__` method, and + can optionally return ``NotImplemented`` to fallback on + :attr:`dispatch_table`-registered reducers to pickle ``obj``. + + For a detailed example, see :ref:`reducer_override`. + + .. versionadded:: 3.8 + + .. attribute:: fast + + Deprecated. Enable fast mode if set to a true value. The fast mode + disables the usage of memo, therefore speeding the pickling process by not + generating superfluous PUT opcodes. It should not be used with + self-referential objects, doing otherwise will cause :class:`Pickler` to + recurse infinitely. + + Use :func:`pickletools.optimize` if you need more compact pickles. + + +.. class:: Unpickler(file, \*, fix_imports=True, encoding="ASCII", errors="strict", buffers=None) + + This takes a binary file for reading a pickle data stream. + + The protocol version of the pickle is detected automatically, so no + protocol argument is needed. + + The argument *file* must have three methods, a read() method that takes an + integer argument, a readinto() method that takes a buffer argument + and a readline() method that requires no arguments, as in the + :class:`io.BufferedIOBase` interface. Thus *file* can be an on-disk file + opened for binary reading, an :class:`io.BytesIO` object, or any other + custom object that meets this interface. + + The optional arguments *fix_imports*, *encoding* and *errors* are used + to control compatibility support for pickle stream generated by Python 2. + If *fix_imports* is true, pickle will try to map the old Python 2 names + to the new names used in Python 3. The *encoding* and *errors* tell + pickle how to decode 8-bit string instances pickled by Python 2; + these default to 'ASCII' and 'strict', respectively. The *encoding* can + be 'bytes' to read these 8-bit string instances as bytes objects. + Using ``encoding='latin1'`` is required for unpickling NumPy arrays and + instances of :class:`~datetime.datetime`, :class:`~datetime.date` and + :class:`~datetime.time` pickled by Python 2. + + If *buffers* is None (the default), then all data necessary for + deserialization must be contained in the pickle stream. This means + that the *buffer_callback* argument was None when a :class:`Pickler` + was instantiated (or when :func:`dump` or :func:`dumps` was called). + + If *buffers* is not None, it should be an iterable of buffer-enabled + objects that is consumed each time the pickle stream references + an :ref:`out-of-band ` buffer view. Such buffers have been + given in order to the *buffer_callback* of a Pickler object. + + .. versionchanged:: 3.8 + The *buffers* argument was added. + + .. method:: load() + + Read the pickled representation of an object from the open file object + given in the constructor, and return the reconstituted object hierarchy + specified therein. Bytes past the pickled representation of the object + are ignored. + + .. method:: persistent_load(pid) + + Raise an :exc:`UnpicklingError` by default. + + If defined, :meth:`persistent_load` should return the object specified by + the persistent ID *pid*. If an invalid persistent ID is encountered, an + :exc:`UnpicklingError` should be raised. + + See :ref:`pickle-persistent` for details and examples of uses. + + .. method:: find_class(module, name) + + Import *module* if necessary and return the object called *name* from it, + where the *module* and *name* arguments are :class:`str` objects. Note, + unlike its name suggests, :meth:`find_class` is also used for finding + functions. + + Subclasses may override this to gain control over what type of objects and + how they can be loaded, potentially reducing security risks. Refer to + :ref:`pickle-restrict` for details. + + .. audit-event:: pickle.find_class module,name pickle.Unpickler.find_class + +.. class:: PickleBuffer(buffer) + + A wrapper for a buffer representing picklable data. *buffer* must be a + :ref:`buffer-providing ` object, such as a + :term:`bytes-like object` or a N-dimensional array. + + :class:`PickleBuffer` is itself a buffer provider, therefore it is + possible to pass it to other APIs expecting a buffer-providing object, + such as :class:`memoryview`. + + :class:`PickleBuffer` objects can only be serialized using pickle + protocol 5 or higher. They are eligible for + :ref:`out-of-band serialization `. + + .. versionadded:: 3.8 + + .. method:: raw() + + Return a :class:`memoryview` of the memory area underlying this buffer. + The returned object is a one-dimensional, C-contiguous memoryview + with format ``B`` (unsigned bytes). :exc:`BufferError` is raised if + the buffer is neither C- nor Fortran-contiguous. + + .. method:: release() + + Release the underlying buffer exposed by the PickleBuffer object. + + +.. _pickle-picklable: + +What can be pickled and unpickled? +---------------------------------- + +The following types can be pickled: + +* ``None``, ``True``, and ``False`` + +* integers, floating point numbers, complex numbers + +* strings, bytes, bytearrays + +* tuples, lists, sets, and dictionaries containing only picklable objects + +* functions defined at the top level of a module (using :keyword:`def`, not + :keyword:`lambda`) + +* built-in functions defined at the top level of a module + +* classes that are defined at the top level of a module + +* instances of such classes whose :attr:`~object.__dict__` or the result of + calling :meth:`__getstate__` is picklable (see section :ref:`pickle-inst` for + details). + +Attempts to pickle unpicklable objects will raise the :exc:`PicklingError` +exception; when this happens, an unspecified number of bytes may have already +been written to the underlying file. Trying to pickle a highly recursive data +structure may exceed the maximum recursion depth, a :exc:`RecursionError` will be +raised in this case. You can carefully raise this limit with +:func:`sys.setrecursionlimit`. + +Note that functions (built-in and user-defined) are pickled by "fully qualified" +name reference, not by value. [#]_ This means that only the function name is +pickled, along with the name of the module the function is defined in. Neither +the function's code, nor any of its function attributes are pickled. Thus the +defining module must be importable in the unpickling environment, and the module +must contain the named object, otherwise an exception will be raised. [#]_ + +Similarly, classes are pickled by named reference, so the same restrictions in +the unpickling environment apply. Note that none of the class's code or data is +pickled, so in the following example the class attribute ``attr`` is not +restored in the unpickling environment:: + + class Foo: + attr = 'A class attribute' + + picklestring = pickle.dumps(Foo) + +These restrictions are why picklable functions and classes must be defined in +the top level of a module. + +Similarly, when class instances are pickled, their class's code and data are not +pickled along with them. Only the instance data are pickled. This is done on +purpose, so you can fix bugs in a class or add methods to the class and still +load objects that were created with an earlier version of the class. If you +plan to have long-lived objects that will see many versions of a class, it may +be worthwhile to put a version number in the objects so that suitable +conversions can be made by the class's :meth:`__setstate__` method. + + +.. _pickle-inst: + +Pickling Class Instances +------------------------ + +.. currentmodule:: None + +In this section, we describe the general mechanisms available to you to define, +customize, and control how class instances are pickled and unpickled. + +In most cases, no additional code is needed to make instances picklable. By +default, pickle will retrieve the class and the attributes of an instance via +introspection. When a class instance is unpickled, its :meth:`__init__` method +is usually *not* invoked. The default behaviour first creates an uninitialized +instance and then restores the saved attributes. The following code shows an +implementation of this behaviour:: + + def save(obj): + return (obj.__class__, obj.__dict__) + + def load(cls, attributes): + obj = cls.__new__(cls) + obj.__dict__.update(attributes) + return obj + +Classes can alter the default behaviour by providing one or several special +methods: + +.. method:: object.__getnewargs_ex__() + + In protocols 2 and newer, classes that implements the + :meth:`__getnewargs_ex__` method can dictate the values passed to the + :meth:`__new__` method upon unpickling. The method must return a pair + ``(args, kwargs)`` where *args* is a tuple of positional arguments + and *kwargs* a dictionary of named arguments for constructing the + object. Those will be passed to the :meth:`__new__` method upon + unpickling. + + You should implement this method if the :meth:`__new__` method of your + class requires keyword-only arguments. Otherwise, it is recommended for + compatibility to implement :meth:`__getnewargs__`. + + .. versionchanged:: 3.6 + :meth:`__getnewargs_ex__` is now used in protocols 2 and 3. + + +.. method:: object.__getnewargs__() + + This method serves a similar purpose as :meth:`__getnewargs_ex__`, but + supports only positional arguments. It must return a tuple of arguments + ``args`` which will be passed to the :meth:`__new__` method upon unpickling. + + :meth:`__getnewargs__` will not be called if :meth:`__getnewargs_ex__` is + defined. + + .. versionchanged:: 3.6 + Before Python 3.6, :meth:`__getnewargs__` was called instead of + :meth:`__getnewargs_ex__` in protocols 2 and 3. + + +.. method:: object.__getstate__() + + Classes can further influence how their instances are pickled; if the class + defines the method :meth:`__getstate__`, it is called and the returned object + is pickled as the contents for the instance, instead of the contents of the + instance's dictionary. If the :meth:`__getstate__` method is absent, the + instance's :attr:`~object.__dict__` is pickled as usual. + + +.. method:: object.__setstate__(state) + + Upon unpickling, if the class defines :meth:`__setstate__`, it is called with + the unpickled state. In that case, there is no requirement for the state + object to be a dictionary. Otherwise, the pickled state must be a dictionary + and its items are assigned to the new instance's dictionary. + + .. note:: + + If :meth:`__getstate__` returns a false value, the :meth:`__setstate__` + method will not be called upon unpickling. + + +Refer to the section :ref:`pickle-state` for more information about how to use +the methods :meth:`__getstate__` and :meth:`__setstate__`. + +.. note:: + + At unpickling time, some methods like :meth:`__getattr__`, + :meth:`__getattribute__`, or :meth:`__setattr__` may be called upon the + instance. In case those methods rely on some internal invariant being + true, the type should implement :meth:`__new__` to establish such an + invariant, as :meth:`__init__` is not called when unpickling an + instance. + +.. index:: pair: copy; protocol + +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. [#]_ + +Although powerful, implementing :meth:`__reduce__` directly in your classes is +error prone. For this reason, class designers should use the high-level +interface (i.e., :meth:`__getnewargs_ex__`, :meth:`__getstate__` and +:meth:`__setstate__`) whenever possible. We will show, however, cases where +using :meth:`__reduce__` is the only option or leads to more efficient pickling +or both. + +.. method:: object.__reduce__() + + The interface is currently defined as follows. The :meth:`__reduce__` method + takes no argument and shall return either a string or preferably a tuple (the + returned object is often referred to as the "reduce value"). + + If a string is returned, the string should be interpreted as the name of a + global variable. It should be the object's local name relative to its + module; the pickle module searches the module namespace to determine the + object's module. This behaviour is typically useful for singletons. + + When a tuple is returned, it must be between two and six items long. + Optional items can either be omitted, or ``None`` can be provided as their + value. The semantics of each item are in order: + + .. XXX Mention __newobj__ special-case? + + * A callable object that will be called to create the initial version of the + object. + + * A tuple of arguments for the callable object. An empty tuple must be given + if the callable does not accept any argument. + + * Optionally, the object's state, which will be passed to the object's + :meth:`__setstate__` method as previously described. If the object has no + such method then, the value must be a dictionary and it will be added to + the object's :attr:`~object.__dict__` attribute. + + * Optionally, an iterator (and not a sequence) yielding successive items. + These items will be appended to the object either using + ``obj.append(item)`` or, in batch, using ``obj.extend(list_of_items)``. + This is primarily used for list subclasses, but may be used by other + classes as long as they have :meth:`append` and :meth:`extend` methods with + the appropriate signature. (Whether :meth:`append` or :meth:`extend` is + used depends on which pickle protocol version is used as well as the number + of items to append, so both must be supported.) + + * Optionally, an iterator (not a sequence) yielding successive key-value + pairs. These items will be stored to the object using ``obj[key] = + value``. This is primarily used for dictionary subclasses, but may be used + by other classes as long as they implement :meth:`__setitem__`. + + * Optionally, a callable with a ``(obj, state)`` signature. This + callable allows the user to programmatically control the state-updating + behavior of a specific object, instead of using ``obj``'s static + :meth:`__setstate__` method. If not ``None``, this callable will have + priority over ``obj``'s :meth:`__setstate__`. + + .. versionadded:: 3.8 + The optional sixth tuple item, ``(obj, state)``, was added. + + +.. method:: object.__reduce_ex__(protocol) + + Alternatively, a :meth:`__reduce_ex__` method may be defined. The only + difference is this method should take a single integer argument, the protocol + version. When defined, pickle will prefer it over the :meth:`__reduce__` + method. In addition, :meth:`__reduce__` automatically becomes a synonym for + the extended version. The main use for this method is to provide + backwards-compatible reduce values for older Python releases. + +.. currentmodule:: pickle + +.. _pickle-persistent: + +Persistence of External Objects +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. index:: + single: persistent_id (pickle protocol) + single: persistent_load (pickle protocol) + +For the benefit of object persistence, the :mod:`pickle` module supports the +notion of a reference to an object outside the pickled data stream. Such +objects are referenced by a persistent ID, which should be either a string of +alphanumeric characters (for protocol 0) [#]_ or just an arbitrary object (for +any newer protocol). + +The resolution of such persistent IDs is not defined by the :mod:`pickle` +module; it will delegate this resolution to the user-defined methods on the +pickler and unpickler, :meth:`~Pickler.persistent_id` and +:meth:`~Unpickler.persistent_load` respectively. + +To pickle objects that have an external persistent ID, the pickler must have a +custom :meth:`~Pickler.persistent_id` method that takes an object as an +argument and returns either ``None`` or the persistent ID for that object. +When ``None`` is returned, the pickler simply pickles the object as normal. +When a persistent ID string is returned, the pickler will pickle that object, +along with a marker so that the unpickler will recognize it as a persistent ID. + +To unpickle external objects, the unpickler must have a custom +:meth:`~Unpickler.persistent_load` method that takes a persistent ID object and +returns the referenced object. + +Here is a comprehensive example presenting how persistent ID can be used to +pickle external objects by reference. + +.. literalinclude:: ../includes/dbpickle.py + +.. _pickle-dispatch: + +Dispatch Tables +^^^^^^^^^^^^^^^ + +If one wants to customize pickling of some classes without disturbing +any other code which depends on pickling, then one can create a +pickler with a private dispatch table. + +The global dispatch table managed by the :mod:`copyreg` module is +available as :data:`copyreg.dispatch_table`. Therefore, one may +choose to use a modified copy of :data:`copyreg.dispatch_table` as a +private dispatch table. + +For example :: + + f = io.BytesIO() + p = pickle.Pickler(f) + p.dispatch_table = copyreg.dispatch_table.copy() + p.dispatch_table[SomeClass] = reduce_SomeClass + +creates an instance of :class:`pickle.Pickler` with a private dispatch +table which handles the ``SomeClass`` class specially. Alternatively, +the code :: + + class MyPickler(pickle.Pickler): + dispatch_table = copyreg.dispatch_table.copy() + dispatch_table[SomeClass] = reduce_SomeClass + f = io.BytesIO() + p = MyPickler(f) + +does the same, but all instances of ``MyPickler`` will by default +share the same dispatch table. The equivalent code using the +:mod:`copyreg` module is :: + + copyreg.pickle(SomeClass, reduce_SomeClass) + f = io.BytesIO() + p = pickle.Pickler(f) + +.. _pickle-state: + +Handling Stateful Objects +^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. index:: + single: __getstate__() (copy protocol) + single: __setstate__() (copy protocol) + +Here's an example that shows how to modify pickling behavior for a class. +The :class:`TextReader` class opens a text file, and returns the line number and +line contents each time its :meth:`!readline` method is called. If a +:class:`TextReader` instance is pickled, all attributes *except* the file object +member are saved. When the instance is unpickled, the file is reopened, and +reading resumes from the last location. The :meth:`__setstate__` and +:meth:`__getstate__` methods are used to implement this behavior. :: + + class TextReader: + """Print and number lines in a text file.""" + + def __init__(self, filename): + self.filename = filename + self.file = open(filename) + self.lineno = 0 + + def readline(self): + self.lineno += 1 + line = self.file.readline() + if not line: + return None + if line.endswith('\n'): + line = line[:-1] + return "%i: %s" % (self.lineno, line) + + def __getstate__(self): + # Copy the object's state from self.__dict__ which contains + # all our instance attributes. Always use the dict.copy() + # method to avoid modifying the original state. + state = self.__dict__.copy() + # Remove the unpicklable entries. + del state['file'] + return state + + def __setstate__(self, state): + # Restore instance attributes (i.e., filename and lineno). + self.__dict__.update(state) + # Restore the previously opened file's state. To do so, we need to + # reopen it and read from it until the line count is restored. + file = open(self.filename) + for _ in range(self.lineno): + file.readline() + # Finally, save the file. + self.file = file + + +A sample usage might be something like this:: + + >>> reader = TextReader("hello.txt") + >>> reader.readline() + '1: Hello world!' + >>> reader.readline() + '2: I am line number two.' + >>> new_reader = pickle.loads(pickle.dumps(reader)) + >>> new_reader.readline() + '3: Goodbye!' + +.. _reducer_override: + +Custom Reduction for Types, Functions, and Other Objects +-------------------------------------------------------- + +.. versionadded:: 3.8 + +Sometimes, :attr:`~Pickler.dispatch_table` may not be flexible enough. +In particular we may want to customize pickling based on another criterion +than the object's type, or we may want to customize the pickling of +functions and classes. + +For those cases, it is possible to subclass from the :class:`Pickler` class and +implement a :meth:`~Pickler.reducer_override` method. This method can return an +arbitrary reduction tuple (see :meth:`__reduce__`). It can alternatively return +``NotImplemented`` to fallback to the traditional behavior. + +If both the :attr:`~Pickler.dispatch_table` and +:meth:`~Pickler.reducer_override` are defined, then +:meth:`~Pickler.reducer_override` method takes priority. + +.. Note:: + For performance reasons, :meth:`~Pickler.reducer_override` may not be + called for the following objects: ``None``, ``True``, ``False``, and + exact instances of :class:`int`, :class:`float`, :class:`bytes`, + :class:`str`, :class:`dict`, :class:`set`, :class:`frozenset`, :class:`list` + and :class:`tuple`. + +Here is a simple example where we allow pickling and reconstructing +a given class:: + + import io + import pickle + + class MyClass: + my_attribute = 1 + + class MyPickler(pickle.Pickler): + def reducer_override(self, obj): + """Custom reducer for MyClass.""" + if getattr(obj, "__name__", None) == "MyClass": + return type, (obj.__name__, obj.__bases__, + {'my_attribute': obj.my_attribute}) + else: + # For any other object, fallback to usual reduction + return NotImplemented + + f = io.BytesIO() + p = MyPickler(f) + p.dump(MyClass) + + del MyClass + + unpickled_class = pickle.loads(f.getvalue()) + + assert isinstance(unpickled_class, type) + assert unpickled_class.__name__ == "MyClass" + assert unpickled_class.my_attribute == 1 + + +.. _pickle-oob: + +Out-of-band Buffers +------------------- + +.. versionadded:: 3.8 + +In some contexts, the :mod:`pickle` module is used to transfer massive amounts +of data. Therefore, it can be important to minimize the number of memory +copies, to preserve performance and resource consumption. However, normal +operation of the :mod:`pickle` module, as it transforms a graph-like structure +of objects into a sequential stream of bytes, intrinsically involves copying +data to and from the pickle stream. + +This constraint can be eschewed if both the *provider* (the implementation +of the object types to be transferred) and the *consumer* (the implementation +of the communications system) support the out-of-band transfer facilities +provided by pickle protocol 5 and higher. + +Provider API +^^^^^^^^^^^^ + +The large data objects to be pickled must implement a :meth:`__reduce_ex__` +method specialized for protocol 5 and higher, which returns a +:class:`PickleBuffer` instance (instead of e.g. a :class:`bytes` object) +for any large data. + +A :class:`PickleBuffer` object *signals* that the underlying buffer is +eligible for out-of-band data transfer. Those objects remain compatible +with normal usage of the :mod:`pickle` module. However, consumers can also +opt-in to tell :mod:`pickle` that they will handle those buffers by +themselves. + +Consumer API +^^^^^^^^^^^^ + +A communications system can enable custom handling of the :class:`PickleBuffer` +objects generated when serializing an object graph. + +On the sending side, it needs to pass a *buffer_callback* argument to +:class:`Pickler` (or to the :func:`dump` or :func:`dumps` function), which +will be called with each :class:`PickleBuffer` generated while pickling +the object graph. Buffers accumulated by the *buffer_callback* will not +see their data copied into the pickle stream, only a cheap marker will be +inserted. + +On the receiving side, it needs to pass a *buffers* argument to +:class:`Unpickler` (or to the :func:`load` or :func:`loads` function), +which is an iterable of the buffers which were passed to *buffer_callback*. +That iterable should produce buffers in the same order as they were passed +to *buffer_callback*. Those buffers will provide the data expected by the +reconstructors of the objects whose pickling produced the original +:class:`PickleBuffer` objects. + +Between the sending side and the receiving side, the communications system +is free to implement its own transfer mechanism for out-of-band buffers. +Potential optimizations include the use of shared memory or datatype-dependent +compression. + +Example +^^^^^^^ + +Here is a trivial example where we implement a :class:`bytearray` subclass +able to participate in out-of-band buffer pickling:: + + class ZeroCopyByteArray(bytearray): + + def __reduce_ex__(self, protocol): + if protocol >= 5: + return type(self)._reconstruct, (PickleBuffer(self),), None + else: + # PickleBuffer is forbidden with pickle protocols <= 4. + return type(self)._reconstruct, (bytearray(self),) + + @classmethod + def _reconstruct(cls, obj): + with memoryview(obj) as m: + # Get a handle over the original buffer object + obj = m.obj + if type(obj) is cls: + # Original buffer object is a ZeroCopyByteArray, return it + # as-is. + return obj + else: + return cls(obj) + +The reconstructor (the ``_reconstruct`` class method) returns the buffer's +providing object if it has the right type. This is an easy way to simulate +zero-copy behaviour on this toy example. + +On the consumer side, we can pickle those objects the usual way, which +when unserialized will give us a copy of the original object:: + + b = ZeroCopyByteArray(b"abc") + data = pickle.dumps(b, protocol=5) + new_b = pickle.loads(data) + print(b == new_b) # True + print(b is new_b) # False: a copy was made + +But if we pass a *buffer_callback* and then give back the accumulated +buffers when unserializing, we are able to get back the original object:: + + b = ZeroCopyByteArray(b"abc") + buffers = [] + data = pickle.dumps(b, protocol=5, buffer_callback=buffers.append) + new_b = pickle.loads(data, buffers=buffers) + print(b == new_b) # True + print(b is new_b) # True: no copy was made + +This example is limited by the fact that :class:`bytearray` allocates its +own memory: you cannot create a :class:`bytearray` instance that is backed +by another object's memory. However, third-party datatypes such as NumPy +arrays do not have this limitation, and allow use of zero-copy pickling +(or making as few copies as possible) when transferring between distinct +processes or systems. + +.. seealso:: :pep:`574` -- Pickle protocol 5 with out-of-band data + + +.. _pickle-restrict: + +Restricting Globals +------------------- + +.. index:: + single: find_class() (pickle protocol) + +By default, unpickling will import any class or function that it finds in the +pickle data. For many applications, this behaviour is unacceptable as it +permits the unpickler to import and invoke arbitrary code. Just consider what +this hand-crafted pickle data stream does when loaded:: + + >>> import pickle + >>> pickle.loads(b"cos\nsystem\n(S'echo hello world'\ntR.") + hello world + 0 + +In this example, the unpickler imports the :func:`os.system` function and then +apply the string argument "echo hello world". Although this example is +inoffensive, it is not difficult to imagine one that could damage your system. + +For this reason, you may want to control what gets unpickled by customizing +:meth:`Unpickler.find_class`. Unlike its name suggests, +:meth:`Unpickler.find_class` is called whenever a global (i.e., a class or +a function) is requested. Thus it is possible to either completely forbid +globals or restrict them to a safe subset. + +Here is an example of an unpickler allowing only few safe classes from the +:mod:`builtins` module to be loaded:: + + import builtins + import io + import pickle + + safe_builtins = { + 'range', + 'complex', + 'set', + 'frozenset', + 'slice', + } + + class RestrictedUnpickler(pickle.Unpickler): + + def find_class(self, module, name): + # Only allow safe classes from builtins. + if module == "builtins" and name in safe_builtins: + return getattr(builtins, name) + # Forbid everything else. + raise pickle.UnpicklingError("global '%s.%s' is forbidden" % + (module, name)) + + def restricted_loads(s): + """Helper function analogous to pickle.loads().""" + return RestrictedUnpickler(io.BytesIO(s)).load() + +A sample usage of our unpickler working has intended:: + + >>> restricted_loads(pickle.dumps([1, 2, range(15)])) + [1, 2, range(0, 15)] + >>> restricted_loads(b"cos\nsystem\n(S'echo hello world'\ntR.") + Traceback (most recent call last): + ... + pickle.UnpicklingError: global 'os.system' is forbidden + >>> restricted_loads(b'cbuiltins\neval\n' + ... b'(S\'getattr(__import__("os"), "system")' + ... b'("echo hello world")\'\ntR.') + Traceback (most recent call last): + ... + pickle.UnpicklingError: global 'builtins.eval' is forbidden + + +.. XXX Add note about how extension codes could evade our protection + 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 +alternatives such as the marshalling API in :mod:`xmlrpc.client` or +third-party solutions. + + +Performance +----------- + +Recent versions of the pickle protocol (from protocol 2 and upwards) feature +efficient binary encodings for several common features and built-in types. +Also, the :mod:`pickle` module has a transparent optimizer written in C. + + +.. _pickle-example: + +Examples +-------- + +For the simplest code, use the :func:`dump` and :func:`load` functions. :: + + import pickle + + # An arbitrary collection of objects supported by pickle. + data = { + 'a': [1, 2.0, 3, 4+6j], + 'b': ("character string", b"byte string"), + 'c': {None, True, False} + } + + with open('data.pickle', 'wb') as f: + # Pickle the 'data' dictionary using the highest protocol available. + pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) + + +The following example reads the resulting pickled data. :: + + import pickle + + with open('data.pickle', 'rb') as f: + # The protocol version used is detected automatically, so we do not + # have to specify it. + data = pickle.load(f) + + +.. XXX: Add examples showing how to optimize pickles for size (like using +.. pickletools.optimize() or the gzip module). + + +.. seealso:: + + Module :mod:`copyreg` + Pickle interface constructor registration for extension types. + + Module :mod:`pickletools` + Tools for working with and analyzing pickled data. + + Module :mod:`shelve` + Indexed databases of objects; uses :mod:`pickle`. + + Module :mod:`copy` + Shallow and deep object copying. + + Module :mod:`marshal` + High-performance serialization of built-in types. + + +.. rubric:: Footnotes + +.. [#] Don't confuse this with the :mod:`marshal` module + +.. [#] This is why :keyword:`lambda` functions cannot be pickled: all + :keyword:`!lambda` functions share the same name: ````. + +.. [#] The exception raised will likely be an :exc:`ImportError` or an + :exc:`AttributeError` but it could be something else. + +.. [#] The :mod:`copy` module uses this protocol for shallow and deep copying + operations. + +.. [#] The limitation on alphanumeric characters is due to the fact + the persistent IDs, in protocol 0, are delimited by the newline + character. Therefore if any kind of newline characters occurs in + persistent IDs, the resulting pickle will become unreadable. diff --git a/cpython_2/environment/repo/Doc/library/pickletools.rst b/cpython_2/environment/repo/Doc/library/pickletools.rst new file mode 100644 index 0000000000000000000000000000000000000000..480f4a6d3208156f0add93d636045592ca35bc9c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pickletools.rst @@ -0,0 +1,110 @@ +:mod:`pickletools` --- Tools for pickle developers +================================================== + +.. module:: pickletools + :synopsis: Contains extensive comments about the pickle protocols and + pickle-machine opcodes, as well as some useful functions. + +**Source code:** :source:`Lib/pickletools.py` + +-------------- + + +This module contains various constants relating to the intimate details of the +:mod:`pickle` module, some lengthy comments about the implementation, and a +few useful functions for analyzing pickled data. The contents of this module +are useful for Python core developers who are working on the :mod:`pickle`; +ordinary users of the :mod:`pickle` module probably won't find the +:mod:`pickletools` module relevant. + +Command line usage +------------------ + +.. versionadded:: 3.2 + +When invoked from the command line, ``python -m pickletools`` will +disassemble the contents of one or more pickle files. Note that if +you want to see the Python object stored in the pickle rather than the +details of pickle format, you may want to use ``-m pickle`` instead. +However, when the pickle file that you want to examine comes from an +untrusted source, ``-m pickletools`` is a safer option because it does +not execute pickle bytecode. + +For example, with a tuple ``(1, 2)`` pickled in file ``x.pickle``: + +.. code-block:: shell-session + + $ python -m pickle x.pickle + (1, 2) + + $ python -m pickletools x.pickle + 0: \x80 PROTO 3 + 2: K BININT1 1 + 4: K BININT1 2 + 6: \x86 TUPLE2 + 7: q BINPUT 0 + 9: . STOP + highest protocol among opcodes = 2 + +Command line options +^^^^^^^^^^^^^^^^^^^^ + +.. program:: pickletools + +.. cmdoption:: -a, --annotate + + Annotate each line with a short opcode description. + +.. cmdoption:: -o, --output= + + Name of a file where the output should be written. + +.. cmdoption:: -l, --indentlevel= + + The number of blanks by which to indent a new MARK level. + +.. cmdoption:: -m, --memo + + When multiple objects are disassembled, preserve memo between + disassemblies. + +.. cmdoption:: -p, --preamble= + + When more than one pickle file are specified, print given preamble + before each disassembly. + + + +Programmatic Interface +---------------------- + + +.. function:: dis(pickle, out=None, memo=None, indentlevel=4, annotate=0) + + Outputs a symbolic disassembly of the pickle to the file-like + object *out*, defaulting to ``sys.stdout``. *pickle* can be a + string or a file-like object. *memo* can be a Python dictionary + that will be used as the pickle's memo; it can be used to perform + disassemblies across multiple pickles created by the same + pickler. Successive levels, indicated by ``MARK`` opcodes in the + stream, are indented by *indentlevel* spaces. If a nonzero value + is given to *annotate*, each opcode in the output is annotated with + a short description. The value of *annotate* is used as a hint for + the column where annotation should start. + + .. versionadded:: 3.2 + The *annotate* argument. + +.. function:: genops(pickle) + + Provides an :term:`iterator` over all of the opcodes in a pickle, returning a + sequence of ``(opcode, arg, pos)`` triples. *opcode* is an instance of an + :class:`OpcodeInfo` class; *arg* is the decoded value, as a Python object, of + the opcode's argument; *pos* is the position at which this opcode is located. + *pickle* can be a string or a file-like object. + +.. function:: optimize(picklestring) + + Returns a new equivalent pickle string after eliminating unused ``PUT`` + opcodes. The optimized pickle is shorter, takes less transmission time, + requires less storage space, and unpickles more efficiently. diff --git a/cpython_2/environment/repo/Doc/library/pipes.rst b/cpython_2/environment/repo/Doc/library/pipes.rst new file mode 100644 index 0000000000000000000000000000000000000000..0a22da1f555bc285906f54250954f11ebf3af95d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pipes.rst @@ -0,0 +1,95 @@ +:mod:`pipes` --- Interface to shell pipelines +============================================= + +.. module:: pipes + :platform: Unix + :synopsis: A Python interface to Unix shell pipelines. + +.. sectionauthor:: Moshe Zadka + +**Source code:** :source:`Lib/pipes.py` + +-------------- + +The :mod:`pipes` module defines a class to abstract the concept of a *pipeline* +--- a sequence of converters from one file to another. + +Because the module uses :program:`/bin/sh` command lines, a POSIX or compatible +shell for :func:`os.system` and :func:`os.popen` is required. + +The :mod:`pipes` module defines the following class: + + +.. class:: Template() + + An abstraction of a pipeline. + +Example:: + + >>> import pipes + >>> t = pipes.Template() + >>> t.append('tr a-z A-Z', '--') + >>> f = t.open('pipefile', 'w') + >>> f.write('hello world') + >>> f.close() + >>> open('pipefile').read() + 'HELLO WORLD' + + +.. _template-objects: + +Template Objects +---------------- + +Template objects following methods: + + +.. method:: Template.reset() + + Restore a pipeline template to its initial state. + + +.. method:: Template.clone() + + Return a new, equivalent, pipeline template. + + +.. method:: Template.debug(flag) + + If *flag* is true, turn debugging on. Otherwise, turn debugging off. When + debugging is on, commands to be executed are printed, and the shell is given + ``set -x`` command to be more verbose. + + +.. method:: Template.append(cmd, kind) + + Append a new action at the end. The *cmd* variable must be a valid bourne shell + command. The *kind* variable consists of two letters. + + The first letter can be either of ``'-'`` (which means the command reads its + standard input), ``'f'`` (which means the commands reads a given file on the + command line) or ``'.'`` (which means the commands reads no input, and hence + must be first.) + + Similarly, the second letter can be either of ``'-'`` (which means the command + writes to standard output), ``'f'`` (which means the command writes a file on + the command line) or ``'.'`` (which means the command does not write anything, + and hence must be last.) + + +.. method:: Template.prepend(cmd, kind) + + Add a new action at the beginning. See :meth:`append` for explanations of the + arguments. + + +.. method:: Template.open(file, mode) + + Return a file-like object, open to *file*, but read from or written to by the + pipeline. Note that only one of ``'r'``, ``'w'`` may be given. + + +.. method:: Template.copy(infile, outfile) + + Copy *infile* to *outfile* through the pipe. + diff --git a/cpython_2/environment/repo/Doc/library/pkgutil.rst b/cpython_2/environment/repo/Doc/library/pkgutil.rst new file mode 100644 index 0000000000000000000000000000000000000000..2066cbb9fc57cee3c6ff327de22cc8e3aab82885 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pkgutil.rst @@ -0,0 +1,270 @@ +:mod:`pkgutil` --- Package extension utility +============================================ + +.. module:: pkgutil + :synopsis: Utilities for the import system. + +**Source code:** :source:`Lib/pkgutil.py` + +-------------- + +This module provides utilities for the import system, in particular package +support. + +.. class:: ModuleInfo(module_finder, name, ispkg) + + A namedtuple that holds a brief summary of a module's info. + + .. versionadded:: 3.6 + +.. function:: extend_path(path, name) + + Extend the search path for the modules which comprise a package. Intended + use is to place the following code in a package's :file:`__init__.py`:: + + from pkgutil import extend_path + __path__ = extend_path(__path__, __name__) + + This will add to the package's ``__path__`` all subdirectories of directories + on ``sys.path`` named after the package. This is useful if one wants to + distribute different parts of a single logical package as multiple + directories. + + It also looks for :file:`\*.pkg` files beginning where ``*`` matches the + *name* argument. This feature is similar to :file:`\*.pth` files (see the + :mod:`site` module for more information), except that it doesn't special-case + lines starting with ``import``. A :file:`\*.pkg` file is trusted at face + value: apart from checking for duplicates, all entries found in a + :file:`\*.pkg` file are added to the path, regardless of whether they exist + on the filesystem. (This is a feature.) + + If the input path is not a list (as is the case for frozen packages) it is + returned unchanged. The input path is not modified; an extended copy is + returned. Items are only appended to the copy at the end. + + It is assumed that :data:`sys.path` is a sequence. Items of :data:`sys.path` + that are not strings referring to existing directories are ignored. Unicode + items on :data:`sys.path` that cause errors when used as filenames may cause + this function to raise an exception (in line with :func:`os.path.isdir` + behavior). + + +.. class:: ImpImporter(dirname=None) + + :pep:`302` Finder that wraps Python's "classic" import algorithm. + + If *dirname* is a string, a :pep:`302` finder is created that searches that + directory. If *dirname* is ``None``, a :pep:`302` finder is created that + searches the current :data:`sys.path`, plus any modules that are frozen or + built-in. + + Note that :class:`ImpImporter` does not currently support being used by + placement on :data:`sys.meta_path`. + + .. deprecated:: 3.3 + This emulation is no longer needed, as the standard import mechanism + is now fully :pep:`302` compliant and available in :mod:`importlib`. + + +.. class:: ImpLoader(fullname, file, filename, etc) + + :term:`Loader` that wraps Python's "classic" import algorithm. + + .. deprecated:: 3.3 + This emulation is no longer needed, as the standard import mechanism + is now fully :pep:`302` compliant and available in :mod:`importlib`. + + +.. function:: find_loader(fullname) + + Retrieve a module :term:`loader` for the given *fullname*. + + This is a backwards compatibility wrapper around + :func:`importlib.util.find_spec` that converts most failures to + :exc:`ImportError` and only returns the loader rather than the full + :class:`ModuleSpec`. + + .. versionchanged:: 3.3 + Updated to be based directly on :mod:`importlib` rather than relying + on the package internal :pep:`302` import emulation. + + .. versionchanged:: 3.4 + Updated to be based on :pep:`451` + +.. function:: get_importer(path_item) + + Retrieve a :term:`finder` for the given *path_item*. + + The returned finder is cached in :data:`sys.path_importer_cache` if it was + newly created by a path hook. + + The cache (or part of it) can be cleared manually if a rescan of + :data:`sys.path_hooks` is necessary. + + .. versionchanged:: 3.3 + Updated to be based directly on :mod:`importlib` rather than relying + on the package internal :pep:`302` import emulation. + + +.. function:: get_loader(module_or_name) + + Get a :term:`loader` object for *module_or_name*. + + If the module or package is accessible via the normal import mechanism, a + wrapper around the relevant part of that machinery is returned. Returns + ``None`` if the module cannot be found or imported. If the named module is + not already imported, its containing package (if any) is imported, in order + to establish the package ``__path__``. + + .. versionchanged:: 3.3 + Updated to be based directly on :mod:`importlib` rather than relying + on the package internal :pep:`302` import emulation. + + .. versionchanged:: 3.4 + Updated to be based on :pep:`451` + + +.. function:: iter_importers(fullname='') + + Yield :term:`finder` objects for the given module name. + + If fullname contains a '.', the finders will be for the package + containing fullname, otherwise they will be all registered top level + finders (i.e. those on both sys.meta_path and sys.path_hooks). + + If the named module is in a package, that package is imported as a side + effect of invoking this function. + + If no module name is specified, all top level finders are produced. + + .. versionchanged:: 3.3 + Updated to be based directly on :mod:`importlib` rather than relying + on the package internal :pep:`302` import emulation. + + +.. function:: iter_modules(path=None, prefix='') + + Yields :class:`ModuleInfo` for all submodules on *path*, or, if + *path* is ``None``, all top-level modules on ``sys.path``. + + *path* should be either ``None`` or a list of paths to look for modules in. + + *prefix* is a string to output on the front of every module name on output. + + .. note:: + + Only works for a :term:`finder` which defines an ``iter_modules()`` + method. This interface is non-standard, so the module also provides + implementations for :class:`importlib.machinery.FileFinder` and + :class:`zipimport.zipimporter`. + + .. versionchanged:: 3.3 + Updated to be based directly on :mod:`importlib` rather than relying + on the package internal :pep:`302` import emulation. + + +.. function:: walk_packages(path=None, prefix='', onerror=None) + + Yields :class:`ModuleInfo` for all modules recursively on + *path*, or, if *path* is ``None``, all accessible modules. + + *path* should be either ``None`` or a list of paths to look for modules in. + + *prefix* is a string to output on the front of every module name on output. + + Note that this function must import all *packages* (*not* all modules!) on + the given *path*, in order to access the ``__path__`` attribute to find + submodules. + + *onerror* is a function which gets called with one argument (the name of the + package which was being imported) if any exception occurs while trying to + import a package. If no *onerror* function is supplied, :exc:`ImportError`\s + are caught and ignored, while all other exceptions are propagated, + terminating the search. + + Examples:: + + # list all modules python can access + walk_packages() + + # list all submodules of ctypes + walk_packages(ctypes.__path__, ctypes.__name__ + '.') + + .. note:: + + Only works for a :term:`finder` which defines an ``iter_modules()`` + method. This interface is non-standard, so the module also provides + implementations for :class:`importlib.machinery.FileFinder` and + :class:`zipimport.zipimporter`. + + .. versionchanged:: 3.3 + Updated to be based directly on :mod:`importlib` rather than relying + on the package internal :pep:`302` import emulation. + + +.. function:: get_data(package, resource) + + Get a resource from a package. + + This is a wrapper for the :term:`loader` + :meth:`get_data ` API. The + *package* argument should be the name of a package, in standard module format + (``foo.bar``). The *resource* argument should be in the form of a relative + filename, using ``/`` as the path separator. The parent directory name + ``..`` is not allowed, and nor is a rooted name (starting with a ``/``). + + The function returns a binary string that is the contents of the specified + resource. + + For packages located in the filesystem, which have already been imported, + this is the rough equivalent of:: + + d = os.path.dirname(sys.modules[package].__file__) + data = open(os.path.join(d, resource), 'rb').read() + + If the package cannot be located or loaded, or it uses a :term:`loader` + which does not support :meth:`get_data `, + then ``None`` is returned. In particular, the :term:`loader` for + :term:`namespace packages ` does not support + :meth:`get_data `. + + +.. function:: resolve_name(name) + + Resolve a name to an object. + + This functionality is used in numerous places in the standard library (see + :issue:`12915`) - and equivalent functionality is also in widely used + third-party packages such as setuptools, Django and Pyramid. + + It is expected that *name* will be a string in one of the following + formats, where W is shorthand for a valid Python identifier and dot stands + for a literal period in these pseudo-regexes: + + * ``W(.W)*`` + * ``W(.W)*:(W(.W)*)?`` + + The first form is intended for backward compatibility only. It assumes that + some part of the dotted name is a package, and the rest is an object + somewhere within that package, possibly nested inside other objects. + Because the place where the package stops and the object hierarchy starts + can't be inferred by inspection, repeated attempts to import must be done + with this form. + + In the second form, the caller makes the division point clear through the + provision of a single colon: the dotted name to the left of the colon is a + package to be imported, and the dotted name to the right is the object + hierarchy within that package. Only one import is needed in this form. If + it ends with the colon, then a module object is returned. + + The function will return an object (which might be a module), or raise one + of the following exceptions: + + :exc:`ValueError` -- if *name* isn't in a recognised format. + + :exc:`ImportError` -- if an import failed when it shouldn't have. + + :exc:`AttributeError` -- If a failure occurred when traversing the object + hierarchy within the imported package to get to the desired object. + + .. versionadded:: 3.9 diff --git a/cpython_2/environment/repo/Doc/library/platform.rst b/cpython_2/environment/repo/Doc/library/platform.rst new file mode 100644 index 0000000000000000000000000000000000000000..8e8e3775aaff4a11c187a9d595fbacf3c8ee3356 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/platform.rst @@ -0,0 +1,262 @@ +:mod:`platform` --- Access to underlying platform's identifying data +===================================================================== + +.. module:: platform + :synopsis: Retrieves as much platform identifying data as possible. + +.. moduleauthor:: Marc-André Lemburg +.. sectionauthor:: Bjorn Pettersen + +**Source code:** :source:`Lib/platform.py` + +-------------- + +.. note:: + + Specific platforms listed alphabetically, with Linux included in the Unix + section. + + +Cross Platform +-------------- + + +.. function:: architecture(executable=sys.executable, bits='', linkage='') + + Queries the given executable (defaults to the Python interpreter binary) for + various architecture information. + + Returns a tuple ``(bits, linkage)`` which contain information about the bit + architecture and the linkage format used for the executable. Both values are + returned as strings. + + Values that cannot be determined are returned as given by the parameter presets. + If bits is given as ``''``, the ``sizeof(pointer)`` (or + ``sizeof(long)`` on Python version < 1.5.2) is used as indicator for the + supported pointer size. + + The function relies on the system's :file:`file` command to do the actual work. + This is available on most if not all Unix platforms and some non-Unix platforms + and then only if the executable points to the Python interpreter. Reasonable + defaults are used when the above needs are not met. + + .. note:: + + On Mac OS X (and perhaps other platforms), executable files may be + universal files containing multiple architectures. + + To get at the "64-bitness" of the current interpreter, it is more + reliable to query the :attr:`sys.maxsize` attribute:: + + is_64bits = sys.maxsize > 2**32 + + +.. function:: machine() + + Returns the machine type, e.g. ``'i386'``. An empty string is returned if the + value cannot be determined. + + +.. function:: node() + + Returns the computer's network name (may not be fully qualified!). An empty + string is returned if the value cannot be determined. + + +.. function:: platform(aliased=0, terse=0) + + Returns a single string identifying the underlying platform with as much useful + information as possible. + + The output is intended to be *human readable* rather than machine parseable. It + may look different on different platforms and this is intended. + + If *aliased* is true, the function will use aliases for various platforms that + report system names which differ from their common names, for example SunOS will + be reported as Solaris. The :func:`system_alias` function is used to implement + this. + + Setting *terse* to true causes the function to return only the absolute minimum + information needed to identify the platform. + + .. versionchanged:: 3.8 + On macOS, the function now uses :func:`mac_ver`, if it returns a + non-empty release string, to get the macOS version rather than the darwin + version. + + +.. function:: processor() + + Returns the (real) processor name, e.g. ``'amdk6'``. + + An empty string is returned if the value cannot be determined. Note that many + platforms do not provide this information or simply return the same value as for + :func:`machine`. NetBSD does this. + + +.. function:: python_build() + + Returns a tuple ``(buildno, builddate)`` stating the Python build number and + date as strings. + + +.. function:: python_compiler() + + Returns a string identifying the compiler used for compiling Python. + + +.. function:: python_branch() + + Returns a string identifying the Python implementation SCM branch. + + +.. function:: python_implementation() + + Returns a string identifying the Python implementation. Possible return values + are: 'CPython', 'IronPython', 'Jython', 'PyPy'. + + +.. function:: python_revision() + + Returns a string identifying the Python implementation SCM revision. + + +.. function:: python_version() + + Returns the Python version as string ``'major.minor.patchlevel'``. + + Note that unlike the Python ``sys.version``, the returned value will always + include the patchlevel (it defaults to 0). + + +.. function:: python_version_tuple() + + Returns the Python version as tuple ``(major, minor, patchlevel)`` of strings. + + Note that unlike the Python ``sys.version``, the returned value will always + include the patchlevel (it defaults to ``'0'``). + + +.. function:: release() + + Returns the system's release, e.g. ``'2.2.0'`` or ``'NT'`` An empty string is + returned if the value cannot be determined. + + +.. function:: system() + + Returns the system/OS name, such as ``'Linux'``, ``'Darwin'``, ``'Java'``, + ``'Windows'``. An empty string is returned if the value cannot be determined. + + +.. function:: system_alias(system, release, version) + + Returns ``(system, release, version)`` aliased to common marketing names used + for some systems. It also does some reordering of the information in some cases + where it would otherwise cause confusion. + + +.. function:: version() + + Returns the system's release version, e.g. ``'#3 on degas'``. An empty string is + returned if the value cannot be determined. + + +.. function:: uname() + + Fairly portable uname interface. Returns a :func:`~collections.namedtuple` + containing six attributes: :attr:`system`, :attr:`node`, :attr:`release`, + :attr:`version`, :attr:`machine`, and :attr:`processor`. + + Note that this adds a sixth attribute (:attr:`processor`) not present + in the :func:`os.uname` result. Also, the attribute names are different + for the first two attributes; :func:`os.uname` names them + :attr:`sysname` and :attr:`nodename`. + + Entries which cannot be determined are set to ``''``. + + .. versionchanged:: 3.3 + Result changed from a tuple to a namedtuple. + + +Java Platform +------------- + + +.. function:: java_ver(release='', vendor='', vminfo=('','',''), osinfo=('','','')) + + Version interface for Jython. + + Returns a tuple ``(release, vendor, vminfo, osinfo)`` with *vminfo* being a + tuple ``(vm_name, vm_release, vm_vendor)`` and *osinfo* being a tuple + ``(os_name, os_version, os_arch)``. Values which cannot be determined are set to + the defaults given as parameters (which all default to ``''``). + + +Windows Platform +---------------- + + +.. function:: win32_ver(release='', version='', csd='', ptype='') + + Get additional version information from the Windows Registry and return a tuple + ``(release, version, csd, ptype)`` referring to OS release, version number, + CSD level (service pack) and OS type (multi/single processor). + + As a hint: *ptype* is ``'Uniprocessor Free'`` on single processor NT machines + and ``'Multiprocessor Free'`` on multi processor machines. The *'Free'* refers + to the OS version being free of debugging code. It could also state *'Checked'* + which means the OS version uses debugging code, i.e. code that checks arguments, + ranges, etc. + + .. note:: + + This function works best with Mark Hammond's + :mod:`win32all` package installed, but also on Python 2.3 and + later (support for this was added in Python 2.6). It obviously + only runs on Win32 compatible platforms. + +.. function:: win32_edition() + + Returns a string representing the current Windows edition. Possible + values include but are not limited to ``'Enterprise'``, ``'IoTUAP'``, + ``'ServerStandard'``, and ``'nanoserver'``. + + .. versionadded:: 3.8 + +.. function:: win32_is_iot() + + Return ``True`` if the Windows edition returned by :func:`win32_edition` + is recognized as an IoT edition. + + .. versionadded:: 3.8 + + +Mac OS Platform +--------------- + + +.. function:: mac_ver(release='', versioninfo=('','',''), machine='') + + Get Mac OS version information and return it as tuple ``(release, versioninfo, + machine)`` with *versioninfo* being a tuple ``(version, dev_stage, + non_release_version)``. + + Entries which cannot be determined are set to ``''``. All tuple entries are + strings. + + +Unix Platforms +-------------- + +.. function:: libc_ver(executable=sys.executable, lib='', version='', chunksize=16384) + + Tries to determine the libc version against which the file executable (defaults + to the Python interpreter) is linked. Returns a tuple of strings ``(lib, + version)`` which default to the given parameters in case the lookup fails. + + Note that this function has intimate knowledge of how different libc versions + add symbols to the executable is probably only usable for executables compiled + using :program:`gcc`. + + The file is read and scanned in chunks of *chunksize* bytes. diff --git a/cpython_2/environment/repo/Doc/library/plistlib.rst b/cpython_2/environment/repo/Doc/library/plistlib.rst new file mode 100644 index 0000000000000000000000000000000000000000..6def72b3736b91d6290a054d0f0f2922ed824758 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/plistlib.rst @@ -0,0 +1,184 @@ +:mod:`plistlib` --- Generate and parse Apple ``.plist`` files +============================================================= + +.. module:: plistlib + :synopsis: Generate and parse Apple plist files. + +.. moduleauthor:: Jack Jansen +.. sectionauthor:: Georg Brandl +.. (harvested from docstrings in the original file) + +**Source code:** :source:`Lib/plistlib.py` + +.. index:: + pair: plist; file + single: property list + +-------------- + +This module provides an interface for reading and writing the "property list" +files used by Apple, primarily on macOS and iOS. This module supports both binary +and XML plist files. + +The property list (``.plist``) file format is a simple serialization supporting +basic object types, like dictionaries, lists, numbers and strings. Usually the +top level object is a dictionary. + +To write out and to parse a plist file, use the :func:`dump` and +:func:`load` functions. + +To work with plist data in bytes objects, use :func:`dumps` +and :func:`loads`. + +Values can be strings, integers, floats, booleans, tuples, lists, dictionaries +(but only with string keys), :class:`bytes`, :class:`bytearray` +or :class:`datetime.datetime` objects. + +.. versionchanged:: 3.4 + New API, old API deprecated. Support for binary format plists added. + +.. versionchanged:: 3.8 + Support added for reading and writing :class:`UID` tokens in binary plists as used + by NSKeyedArchiver and NSKeyedUnarchiver. + +.. versionchanged:: 3.9 + Old API removed. + +.. seealso:: + + `PList manual page `_ + Apple's documentation of the file format. + + +This module defines the following functions: + +.. function:: load(fp, \*, fmt=None, dict_type=dict) + + Read a plist file. *fp* should be a readable and binary file object. + Return the unpacked root object (which usually is a + dictionary). + + The *fmt* is the format of the file and the following values are valid: + + * :data:`None`: Autodetect the file format + + * :data:`FMT_XML`: XML file format + + * :data:`FMT_BINARY`: Binary plist format + + The *dict_type* is the type used for dictionaries that are read from the + plist file. + + XML data for the :data:`FMT_XML` format is parsed using the Expat parser + from :mod:`xml.parsers.expat` -- see its documentation for possible + exceptions on ill-formed XML. Unknown elements will simply be ignored + by the plist parser. + + The parser for the binary format raises :exc:`InvalidFileException` + when the file cannot be parsed. + + .. versionadded:: 3.4 + + +.. function:: loads(data, \*, fmt=None, dict_type=dict) + + Load a plist from a bytes object. See :func:`load` for an explanation of + the keyword arguments. + + .. versionadded:: 3.4 + + +.. function:: dump(value, fp, \*, fmt=FMT_XML, sort_keys=True, skipkeys=False) + + Write *value* to a plist file. *Fp* should be a writable, binary + file object. + + The *fmt* argument specifies the format of the plist file and can be + one of the following values: + + * :data:`FMT_XML`: XML formatted plist file + + * :data:`FMT_BINARY`: Binary formatted plist file + + When *sort_keys* is true (the default) the keys for dictionaries will be + written to the plist in sorted order, otherwise they will be written in + the iteration order of the dictionary. + + When *skipkeys* is false (the default) the function raises :exc:`TypeError` + when a key of a dictionary is not a string, otherwise such keys are skipped. + + A :exc:`TypeError` will be raised if the object is of an unsupported type or + a container that contains objects of unsupported types. + + An :exc:`OverflowError` will be raised for integer values that cannot + be represented in (binary) plist files. + + .. versionadded:: 3.4 + + +.. function:: dumps(value, \*, fmt=FMT_XML, sort_keys=True, skipkeys=False) + + Return *value* as a plist-formatted bytes object. See + the documentation for :func:`dump` for an explanation of the keyword + arguments of this function. + + .. versionadded:: 3.4 + + +The following classes are available: + +.. class:: UID(data) + + Wraps an :class:`int`. This is used when reading or writing NSKeyedArchiver + encoded data, which contains UID (see PList manual). + + It has one attribute, :attr:`data`, which can be used to retrieve the int value + of the UID. :attr:`data` must be in the range `0 <= data < 2**64`. + + .. versionadded:: 3.8 + + +The following constants are available: + +.. data:: FMT_XML + + The XML format for plist files. + + .. versionadded:: 3.4 + + +.. data:: FMT_BINARY + + The binary format for plist files + + .. versionadded:: 3.4 + + +Examples +-------- + +Generating a plist:: + + pl = dict( + aString = "Doodah", + aList = ["A", "B", 12, 32.1, [1, 2, 3]], + aFloat = 0.1, + anInt = 728, + aDict = dict( + anotherString = "", + aThirdString = "M\xe4ssig, Ma\xdf", + aTrueValue = True, + aFalseValue = False, + ), + someData = b"", + someMoreData = b"" * 10, + aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())), + ) + with open(fileName, 'wb') as fp: + dump(pl, fp) + +Parsing a plist:: + + with open(fileName, 'rb') as fp: + pl = load(fp) + print(pl["aKey"]) diff --git a/cpython_2/environment/repo/Doc/library/poplib.rst b/cpython_2/environment/repo/Doc/library/poplib.rst new file mode 100644 index 0000000000000000000000000000000000000000..2f349b35b7e0ff393031de21b9154d7782a9ba6a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/poplib.rst @@ -0,0 +1,277 @@ +:mod:`poplib` --- POP3 protocol client +====================================== + +.. module:: poplib + :synopsis: POP3 protocol client (requires sockets). + +.. sectionauthor:: Andrew T. Csillag +.. revised by ESR, January 2000 + +**Source code:** :source:`Lib/poplib.py` + +.. index:: pair: POP3; protocol + +-------------- + +This module defines a class, :class:`POP3`, which encapsulates a connection to a +POP3 server and implements the protocol as defined in :rfc:`1939`. The +:class:`POP3` class supports both the minimal and optional command sets from +:rfc:`1939`. The :class:`POP3` class also supports the ``STLS`` command introduced +in :rfc:`2595` to enable encrypted communication on an already established connection. + +Additionally, this module provides a class :class:`POP3_SSL`, which provides +support for connecting to POP3 servers that use SSL as an underlying protocol +layer. + +Note that POP3, though widely supported, is obsolescent. The implementation +quality of POP3 servers varies widely, and too many are quite poor. If your +mailserver supports IMAP, you would be better off using the +:class:`imaplib.IMAP4` class, as IMAP servers tend to be better implemented. + +The :mod:`poplib` module provides two classes: + + +.. class:: POP3(host, port=POP3_PORT[, timeout]) + + This class implements the actual POP3 protocol. The connection is created when + the instance is initialized. If *port* is omitted, the standard POP3 port (110) + is used. The optional *timeout* parameter specifies a timeout in seconds for the + connection attempt (if not specified, the global default timeout setting will + be used). + + .. audit-event:: poplib.connect self,host,port poplib.POP3 + + .. audit-event:: poplib.putline self,line poplib.POP3 + + All commands will raise an :ref:`auditing event ` + ``poplib.putline`` with arguments ``self`` and ``line``, + where ``line`` is the bytes about to be sent to the remote host. + + .. versionchanged:: 3.9 + If the *timeout* parameter is set to be zero, it will raise a + :class:`ValueError` to prevent the creation of a non-blocking socket. + +.. class:: POP3_SSL(host, port=POP3_SSL_PORT, keyfile=None, certfile=None, timeout=None, context=None) + + This is a subclass of :class:`POP3` that connects to the server over an SSL + encrypted socket. If *port* is not specified, 995, the standard POP3-over-SSL + port is used. *timeout* works as in the :class:`POP3` constructor. + *context* is an optional :class:`ssl.SSLContext` object which allows + bundling SSL configuration options, certificates and private keys into a + single (potentially long-lived) structure. Please read :ref:`ssl-security` + for best practices. + + *keyfile* and *certfile* are a legacy alternative to *context* - they can + point to PEM-formatted private key and certificate chain files, + respectively, for the SSL connection. + + .. audit-event:: poplib.connect self,host,port poplib.POP3_SSL + + .. audit-event:: poplib.putline self,line popplib.POP3_SSL + + All commands will raise an :ref:`auditing event ` + ``poplib.putline`` with arguments ``self`` and ``line``, + where ``line`` is the bytes about to be sent to the remote host. + + .. versionchanged:: 3.2 + *context* parameter added. + + .. versionchanged:: 3.4 + The class now supports hostname check with + :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see + :data:`ssl.HAS_SNI`). + + .. deprecated:: 3.6 + + *keyfile* and *certfile* are deprecated in favor of *context*. + Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let + :func:`ssl.create_default_context` select the system's trusted CA + certificates for you. + + .. versionchanged:: 3.9 + If the *timeout* parameter is set to be zero, it will raise a + :class:`ValueError` to prevent the creation of a non-blocking socket. + +One exception is defined as an attribute of the :mod:`poplib` module: + + +.. exception:: error_proto + + Exception raised on any errors from this module (errors from :mod:`socket` + module are not caught). The reason for the exception is passed to the + constructor as a string. + + +.. seealso:: + + Module :mod:`imaplib` + The standard Python IMAP module. + + `Frequently Asked Questions About Fetchmail `_ + The FAQ for the :program:`fetchmail` POP/IMAP client collects information on + POP3 server variations and RFC noncompliance that may be useful if you need to + write an application based on the POP protocol. + + +.. _pop3-objects: + +POP3 Objects +------------ + +All POP3 commands are represented by methods of the same name, in lower-case; +most return the response text sent by the server. + +An :class:`POP3` instance has the following methods: + + +.. method:: POP3.set_debuglevel(level) + + Set the instance's debugging level. This controls the amount of debugging + output printed. The default, ``0``, produces no debugging output. A value of + ``1`` produces a moderate amount of debugging output, generally a single line + per request. A value of ``2`` or higher produces the maximum amount of + debugging output, logging each line sent and received on the control connection. + + +.. method:: POP3.getwelcome() + + Returns the greeting string sent by the POP3 server. + + +.. method:: POP3.capa() + + Query the server's capabilities as specified in :rfc:`2449`. + Returns a dictionary in the form ``{'name': ['param'...]}``. + + .. versionadded:: 3.4 + + +.. method:: POP3.user(username) + + Send user command, response should indicate that a password is required. + + +.. method:: POP3.pass_(password) + + Send password, response includes message count and mailbox size. Note: the + mailbox on the server is locked until :meth:`~poplib.quit` is called. + + +.. method:: POP3.apop(user, secret) + + Use the more secure APOP authentication to log into the POP3 server. + + +.. method:: POP3.rpop(user) + + Use RPOP authentication (similar to UNIX r-commands) to log into POP3 server. + + +.. method:: POP3.stat() + + Get mailbox status. The result is a tuple of 2 integers: ``(message count, + mailbox size)``. + + +.. method:: POP3.list([which]) + + Request message list, result is in the form ``(response, ['mesg_num octets', + ...], octets)``. If *which* is set, it is the message to list. + + +.. method:: POP3.retr(which) + + Retrieve whole message number *which*, and set its seen flag. Result is in form + ``(response, ['line', ...], octets)``. + + +.. method:: POP3.dele(which) + + Flag message number *which* for deletion. On most servers deletions are not + actually performed until QUIT (the major exception is Eudora QPOP, which + deliberately violates the RFCs by doing pending deletes on any disconnect). + + +.. method:: POP3.rset() + + Remove any deletion marks for the mailbox. + + +.. method:: POP3.noop() + + Do nothing. Might be used as a keep-alive. + + +.. method:: POP3.quit() + + Signoff: commit changes, unlock mailbox, drop connection. + + +.. method:: POP3.top(which, howmuch) + + Retrieves the message header plus *howmuch* lines of the message after the + header of message number *which*. Result is in form ``(response, ['line', ...], + octets)``. + + The POP3 TOP command this method uses, unlike the RETR command, doesn't set the + message's seen flag; unfortunately, TOP is poorly specified in the RFCs and is + frequently broken in off-brand servers. Test this method by hand against the + POP3 servers you will use before trusting it. + + +.. method:: POP3.uidl(which=None) + + Return message digest (unique id) list. If *which* is specified, result contains + the unique id for that message in the form ``'response mesgnum uid``, otherwise + result is list ``(response, ['mesgnum uid', ...], octets)``. + + +.. method:: POP3.utf8() + + Try to switch to UTF-8 mode. Returns the server response if successful, + raises :class:`error_proto` if not. Specified in :RFC:`6856`. + + .. versionadded:: 3.5 + + +.. method:: POP3.stls(context=None) + + Start a TLS session on the active connection as specified in :rfc:`2595`. + This is only allowed before user authentication + + *context* parameter is a :class:`ssl.SSLContext` object which allows + bundling SSL configuration options, certificates and private keys into + a single (potentially long-lived) structure. Please read :ref:`ssl-security` + for best practices. + + This method supports hostname checking via + :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see + :data:`ssl.HAS_SNI`). + + .. versionadded:: 3.4 + + +Instances of :class:`POP3_SSL` have no additional methods. The interface of this +subclass is identical to its parent. + + +.. _pop3-example: + +POP3 Example +------------ + +Here is a minimal example (without error checking) that opens a mailbox and +retrieves and prints all messages:: + + import getpass, poplib + + M = poplib.POP3('localhost') + M.user(getpass.getuser()) + M.pass_(getpass.getpass()) + numMessages = len(M.list()[1]) + for i in range(numMessages): + for j in M.retr(i+1)[1]: + print(j) + +At the end of the module, there is a test section that contains a more extensive +example of usage. diff --git a/cpython_2/environment/repo/Doc/library/posix.rst b/cpython_2/environment/repo/Doc/library/posix.rst new file mode 100644 index 0000000000000000000000000000000000000000..2105af9215f7694065e7fcb237e76f875afcb41e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/posix.rst @@ -0,0 +1,92 @@ +:mod:`posix` --- The most common POSIX system calls +=================================================== + +.. module:: posix + :platform: Unix + :synopsis: The most common POSIX system calls (normally used via module os). + +-------------- + +This module provides access to operating system functionality that is +standardized by the C Standard and the POSIX standard (a thinly disguised Unix +interface). + +.. index:: module: os + +**Do not import this module directly.** Instead, import the module :mod:`os`, +which provides a *portable* version of this interface. On Unix, the :mod:`os` +module provides a superset of the :mod:`posix` interface. On non-Unix operating +systems the :mod:`posix` module is not available, but a subset is always +available through the :mod:`os` interface. Once :mod:`os` is imported, there is +*no* performance penalty in using it instead of :mod:`posix`. In addition, +:mod:`os` provides some additional functionality, such as automatically calling +:func:`~os.putenv` when an entry in ``os.environ`` is changed. + +Errors are reported as exceptions; the usual exceptions are given for type +errors, while errors reported by the system calls raise :exc:`OSError`. + + +.. _posix-large-files: + +Large File Support +------------------ + +.. index:: + single: large files + single: file; large files + +.. sectionauthor:: Steve Clift + +Several operating systems (including AIX, HP-UX, Irix and Solaris) provide +support for files that are larger than 2 GiB from a C programming model where +:c:type:`int` and :c:type:`long` are 32-bit values. This is typically accomplished +by defining the relevant size and offset types as 64-bit values. Such files are +sometimes referred to as :dfn:`large files`. + +Large file support is enabled in Python when the size of an :c:type:`off_t` is +larger than a :c:type:`long` and the :c:type:`long long` is at least as large +as an :c:type:`off_t`. +It may be necessary to configure and compile Python with certain compiler flags +to enable this mode. For example, it is enabled by default with recent versions +of Irix, but with Solaris 2.6 and 2.7 you need to do something like:: + + CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \ + ./configure + +On large-file-capable Linux systems, this might work:: + + CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" \ + ./configure + + +.. _posix-contents: + +Notable Module Contents +----------------------- + +In addition to many functions described in the :mod:`os` module documentation, +:mod:`posix` defines the following data item: + +.. data:: environ + + A dictionary representing the string environment at the time the interpreter + was started. Keys and values are bytes on Unix and str on Windows. For + example, ``environ[b'HOME']`` (``environ['HOME']`` on Windows) is the + pathname of your home directory, equivalent to ``getenv("HOME")`` in C. + + Modifying this dictionary does not affect the string environment passed on by + :func:`~os.execv`, :func:`~os.popen` or :func:`~os.system`; if you need to + change the environment, pass ``environ`` to :func:`~os.execve` or add + variable assignments and export statements to the command string for + :func:`~os.system` or :func:`~os.popen`. + + .. versionchanged:: 3.2 + On Unix, keys and values are bytes. + + .. note:: + + The :mod:`os` module provides an alternate implementation of ``environ`` + which updates the environment on modification. Note also that updating + :data:`os.environ` will render this dictionary obsolete. Use of the + :mod:`os` module version of this is recommended over direct access to the + :mod:`posix` module. diff --git a/cpython_2/environment/repo/Doc/library/pprint.rst b/cpython_2/environment/repo/Doc/library/pprint.rst new file mode 100644 index 0000000000000000000000000000000000000000..16256c549208fcac975935029bbe613e4e4cce01 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pprint.rst @@ -0,0 +1,401 @@ +:mod:`pprint` --- Data pretty printer +===================================== + +.. module:: pprint + :synopsis: Data pretty printer. + +.. moduleauthor:: Fred L. Drake, Jr. +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/pprint.py` + +-------------- + +The :mod:`pprint` module provides a capability to "pretty-print" arbitrary +Python data structures in a form which can be used as input to the interpreter. +If the formatted structures include objects which are not fundamental Python +types, the representation may not be loadable. This may be the case if objects +such as files, sockets or classes are included, as well as many other +objects which are not representable as Python literals. + +The formatted representation keeps objects on a single line if it can, and +breaks them onto multiple lines if they don't fit within the allowed width. +Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the +width constraint. + +Dictionaries are sorted by key before the display is computed. + +.. versionchanged:: 3.9 + Added support for pretty-printing :class:`types.SimpleNamespace`. + +The :mod:`pprint` module defines one class: + +.. First the implementation class: + + +.. index:: single: ...; placeholder + +.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, \ + compact=False, sort_dicts=True) + + Construct a :class:`PrettyPrinter` instance. This constructor understands + several keyword parameters. An output stream may be set using the *stream* + keyword; the only method used on the stream object is the file protocol's + :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts + ``sys.stdout``. The + amount of indentation added for each recursive level is specified by *indent*; + the default is one. Other values can cause output to look a little odd, but can + make nesting easier to spot. The number of levels which may be printed is + controlled by *depth*; if the data structure being printed is too deep, the next + contained level is replaced by ``...``. By default, there is no constraint on + the depth of the objects being formatted. The desired output width is + constrained using the *width* parameter; the default is 80 characters. If a + structure cannot be formatted within the constrained width, a best effort will + be made. If *compact* is false (the default) each item of a long sequence + will be formatted on a separate line. If *compact* is true, as many items + as will fit within the *width* will be formatted on each output line. If + *sort_dicts* is true (the default), dictionaries will be formatted with their + keys sorted, otherwise they will display in insertion order. + + .. versionchanged:: 3.4 + Added the *compact* parameter. + + .. versionchanged:: 3.8 + Added the *sort_dicts* parameter. + + + >>> import pprint + >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] + >>> stuff.insert(0, stuff[:]) + >>> pp = pprint.PrettyPrinter(indent=4) + >>> pp.pprint(stuff) + [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'], + 'spam', + 'eggs', + 'lumberjack', + 'knights', + 'ni'] + >>> pp = pprint.PrettyPrinter(width=41, compact=True) + >>> pp.pprint(stuff) + [['spam', 'eggs', 'lumberjack', + 'knights', 'ni'], + 'spam', 'eggs', 'lumberjack', 'knights', + 'ni'] + >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', + ... ('parrot', ('fresh fruit',)))))))) + >>> pp = pprint.PrettyPrinter(depth=6) + >>> pp.pprint(tup) + ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...))))))) + + +The :mod:`pprint` module also provides several shortcut functions: + +.. function:: pformat(object, indent=1, width=80, depth=None, *, \ + compact=False, sort_dicts=True) + + Return the formatted representation of *object* as a string. *indent*, + *width*, *depth*, *compact* and *sort_dicts* will be passed to the + :class:`PrettyPrinter` constructor as formatting parameters. + + .. versionchanged:: 3.4 + Added the *compact* parameter. + + .. versionchanged:: 3.8 + Added the *sort_dicts* parameter. + + +.. function:: pp(object, *args, sort_dicts=False, **kwargs) + + Prints the formatted representation of *object* followed by a newline. + If *sort_dicts* is false (the default), dictionaries will be displayed with + their keys in insertion order, otherwise the dict keys will be sorted. + *args* and *kwargs* will be passed to :func:`pprint` as formatting + parameters. + + .. versionadded:: 3.8 + + +.. function:: pprint(object, stream=None, indent=1, width=80, depth=None, *, \ + compact=False, sort_dicts=True) + + Prints the formatted representation of *object* on *stream*, followed by a + newline. If *stream* is ``None``, ``sys.stdout`` is used. This may be used + in the interactive interpreter instead of the :func:`print` function for + inspecting values (you can even reassign ``print = pprint.pprint`` for use + within a scope). *indent*, *width*, *depth*, *compact* and *sort_dicts* will + be passed to the :class:`PrettyPrinter` constructor as formatting parameters. + + .. versionchanged:: 3.4 + Added the *compact* parameter. + + .. versionchanged:: 3.8 + Added the *sort_dicts* parameter. + + >>> import pprint + >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] + >>> stuff.insert(0, stuff) + >>> pprint.pprint(stuff) + [, + 'spam', + 'eggs', + 'lumberjack', + 'knights', + 'ni'] + + +.. function:: isreadable(object) + + .. index:: builtin: eval + + Determine if the formatted representation of *object* is "readable", or can be + used to reconstruct the value using :func:`eval`. This always returns ``False`` + for recursive objects. + + >>> pprint.isreadable(stuff) + False + + +.. function:: isrecursive(object) + + Determine if *object* requires a recursive representation. + + +One more support function is also defined: + +.. function:: saferepr(object) + + Return a string representation of *object*, protected against recursive data + structures. If the representation of *object* exposes a recursive entry, the + recursive reference will be represented as ````. The representation is not otherwise formatted. + + >>> pprint.saferepr(stuff) + "[, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']" + + +.. _prettyprinter-objects: + +PrettyPrinter Objects +--------------------- + +:class:`PrettyPrinter` instances have the following methods: + + +.. method:: PrettyPrinter.pformat(object) + + Return the formatted representation of *object*. This takes into account the + options passed to the :class:`PrettyPrinter` constructor. + + +.. method:: PrettyPrinter.pprint(object) + + Print the formatted representation of *object* on the configured stream, + followed by a newline. + +The following methods provide the implementations for the corresponding +functions of the same names. Using these methods on an instance is slightly +more efficient since new :class:`PrettyPrinter` objects don't need to be +created. + + +.. method:: PrettyPrinter.isreadable(object) + + .. index:: builtin: eval + + Determine if the formatted representation of the object is "readable," or can be + used to reconstruct the value using :func:`eval`. Note that this returns + ``False`` for recursive objects. If the *depth* parameter of the + :class:`PrettyPrinter` is set and the object is deeper than allowed, this + returns ``False``. + + +.. method:: PrettyPrinter.isrecursive(object) + + Determine if the object requires a recursive representation. + +This method is provided as a hook to allow subclasses to modify the way objects +are converted to strings. The default implementation uses the internals of the +:func:`saferepr` implementation. + + +.. method:: PrettyPrinter.format(object, context, maxlevels, level) + + Returns three values: the formatted version of *object* as a string, a flag + indicating whether the result is readable, and a flag indicating whether + recursion was detected. The first argument is the object to be presented. The + second is a dictionary which contains the :func:`id` of objects that are part of + the current presentation context (direct and indirect containers for *object* + that are affecting the presentation) as the keys; if an object needs to be + presented which is already represented in *context*, the third return value + should be ``True``. Recursive calls to the :meth:`.format` method should add + additional entries for containers to this dictionary. The third argument, + *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there + is no requested limit. This argument should be passed unmodified to recursive + calls. The fourth argument, *level*, gives the current level; recursive calls + should be passed a value less than that of the current call. + + +.. _pprint-example: + +Example +------- + +To demonstrate several uses of the :func:`pprint` function and its parameters, +let's fetch information about a project from `PyPI `_:: + + >>> import json + >>> import pprint + >>> from urllib.request import urlopen + >>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp: + ... project_info = json.load(resp)['info'] + +In its basic form, :func:`pprint` shows the whole object:: + + >>> pprint.pprint(project_info) + {'author': 'The Python Packaging Authority', + 'author_email': 'pypa-dev@googlegroups.com', + 'bugtrack_url': None, + 'classifiers': ['Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.2', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Topic :: Software Development :: Build Tools'], + 'description': 'A sample Python project\n' + '=======================\n' + '\n' + 'This is the description file for the project.\n' + '\n' + 'The file should use UTF-8 encoding and be written using ' + 'ReStructured Text. It\n' + 'will be used to generate the project webpage on PyPI, and ' + 'should be written for\n' + 'that purpose.\n' + '\n' + 'Typical contents for this file would include an overview of ' + 'the project, basic\n' + 'usage examples, etc. Generally, including the project ' + 'changelog in here is not\n' + 'a good idea, although a simple "What\'s New" section for the ' + 'most recent version\n' + 'may be appropriate.', + 'description_content_type': None, + 'docs_url': None, + 'download_url': 'UNKNOWN', + 'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1}, + 'home_page': 'https://github.com/pypa/sampleproject', + 'keywords': 'sample setuptools development', + 'license': 'MIT', + 'maintainer': None, + 'maintainer_email': None, + 'name': 'sampleproject', + 'package_url': 'https://pypi.org/project/sampleproject/', + 'platform': 'UNKNOWN', + 'project_url': 'https://pypi.org/project/sampleproject/', + 'project_urls': {'Download': 'UNKNOWN', + 'Homepage': 'https://github.com/pypa/sampleproject'}, + 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/', + 'requires_dist': None, + 'requires_python': None, + 'summary': 'A sample Python project', + 'version': '1.2.0'} + +The result can be limited to a certain *depth* (ellipsis is used for deeper +contents):: + + >>> pprint.pprint(project_info, depth=1) + {'author': 'The Python Packaging Authority', + 'author_email': 'pypa-dev@googlegroups.com', + 'bugtrack_url': None, + 'classifiers': [...], + 'description': 'A sample Python project\n' + '=======================\n' + '\n' + 'This is the description file for the project.\n' + '\n' + 'The file should use UTF-8 encoding and be written using ' + 'ReStructured Text. It\n' + 'will be used to generate the project webpage on PyPI, and ' + 'should be written for\n' + 'that purpose.\n' + '\n' + 'Typical contents for this file would include an overview of ' + 'the project, basic\n' + 'usage examples, etc. Generally, including the project ' + 'changelog in here is not\n' + 'a good idea, although a simple "What\'s New" section for the ' + 'most recent version\n' + 'may be appropriate.', + 'description_content_type': None, + 'docs_url': None, + 'download_url': 'UNKNOWN', + 'downloads': {...}, + 'home_page': 'https://github.com/pypa/sampleproject', + 'keywords': 'sample setuptools development', + 'license': 'MIT', + 'maintainer': None, + 'maintainer_email': None, + 'name': 'sampleproject', + 'package_url': 'https://pypi.org/project/sampleproject/', + 'platform': 'UNKNOWN', + 'project_url': 'https://pypi.org/project/sampleproject/', + 'project_urls': {...}, + 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/', + 'requires_dist': None, + 'requires_python': None, + 'summary': 'A sample Python project', + 'version': '1.2.0'} + +Additionally, maximum character *width* can be suggested. If a long object +cannot be split, the specified width will be exceeded:: + + >>> pprint.pprint(project_info, depth=1, width=60) + {'author': 'The Python Packaging Authority', + 'author_email': 'pypa-dev@googlegroups.com', + 'bugtrack_url': None, + 'classifiers': [...], + 'description': 'A sample Python project\n' + '=======================\n' + '\n' + 'This is the description file for the ' + 'project.\n' + '\n' + 'The file should use UTF-8 encoding and be ' + 'written using ReStructured Text. It\n' + 'will be used to generate the project ' + 'webpage on PyPI, and should be written ' + 'for\n' + 'that purpose.\n' + '\n' + 'Typical contents for this file would ' + 'include an overview of the project, ' + 'basic\n' + 'usage examples, etc. Generally, including ' + 'the project changelog in here is not\n' + 'a good idea, although a simple "What\'s ' + 'New" section for the most recent version\n' + 'may be appropriate.', + 'description_content_type': None, + 'docs_url': None, + 'download_url': 'UNKNOWN', + 'downloads': {...}, + 'home_page': 'https://github.com/pypa/sampleproject', + 'keywords': 'sample setuptools development', + 'license': 'MIT', + 'maintainer': None, + 'maintainer_email': None, + 'name': 'sampleproject', + 'package_url': 'https://pypi.org/project/sampleproject/', + 'platform': 'UNKNOWN', + 'project_url': 'https://pypi.org/project/sampleproject/', + 'project_urls': {...}, + 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/', + 'requires_dist': None, + 'requires_python': None, + 'summary': 'A sample Python project', + 'version': '1.2.0'} diff --git a/cpython_2/environment/repo/Doc/library/profile.rst b/cpython_2/environment/repo/Doc/library/profile.rst new file mode 100644 index 0000000000000000000000000000000000000000..34525a96f55c43682a770b601896d82edc59afc3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/profile.rst @@ -0,0 +1,696 @@ +.. _profile: + +******************** +The Python Profilers +******************** + +**Source code:** :source:`Lib/profile.py` and :source:`Lib/pstats.py` + +-------------- + +.. _profiler-introduction: + +Introduction to the profilers +============================= + +.. index:: + single: deterministic profiling + single: profiling, deterministic + +:mod:`cProfile` and :mod:`profile` provide :dfn:`deterministic profiling` of +Python programs. A :dfn:`profile` is a set of statistics that describes how +often and for how long various parts of the program executed. These statistics +can be formatted into reports via the :mod:`pstats` module. + +The Python standard library provides two different implementations of the same +profiling interface: + +1. :mod:`cProfile` is recommended for most users; it's a C extension with + reasonable overhead that makes it suitable for profiling long-running + programs. Based on :mod:`lsprof`, contributed by Brett Rosen and Ted + Czotter. + +2. :mod:`profile`, a pure Python module whose interface is imitated by + :mod:`cProfile`, but which 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. Originally designed and written by Jim Roskind. + +.. note:: + + The profiler modules are designed to provide an execution profile for a given + program, not for benchmarking purposes (for that, there is :mod:`timeit` for + reasonably accurate results). This particularly applies to benchmarking + Python code against C code: the profilers introduce overhead for Python code, + but not for C-level functions, and so the C code would seem faster than any + Python one. + + +.. _profile-instant: + +Instant User's Manual +===================== + +This section is provided for users that "don't want to read the manual." It +provides a very brief overview, and allows a user to rapidly perform profiling +on an existing application. + +To profile a function that takes a single argument, you can do:: + + import cProfile + import re + cProfile.run('re.compile("foo|bar")') + +(Use :mod:`profile` instead of :mod:`cProfile` if the latter is not available on +your system.) + +The above action would run :func:`re.compile` and print profile results like +the following:: + + 197 function calls (192 primitive calls) in 0.002 seconds + + Ordered by: standard name + + ncalls tottime percall cumtime percall filename:lineno(function) + 1 0.000 0.000 0.001 0.001 :1() + 1 0.000 0.000 0.001 0.001 re.py:212(compile) + 1 0.000 0.000 0.001 0.001 re.py:268(_compile) + 1 0.000 0.000 0.000 0.000 sre_compile.py:172(_compile_charset) + 1 0.000 0.000 0.000 0.000 sre_compile.py:201(_optimize_charset) + 4 0.000 0.000 0.000 0.000 sre_compile.py:25(_identityfunction) + 3/1 0.000 0.000 0.000 0.000 sre_compile.py:33(_compile) + +The first line indicates that 197 calls were monitored. Of those calls, 192 +were :dfn:`primitive`, meaning that the call was not induced via recursion. The +next line: ``Ordered by: standard name``, indicates that the text string in the +far right column was used to sort the output. The column headings include: + +ncalls + for the number of calls. + +tottime + for the total time spent in the given function (and excluding time made in + calls to sub-functions) + +percall + is the quotient of ``tottime`` divided by ``ncalls`` + +cumtime + is the cumulative time spent in this and all subfunctions (from invocation + till exit). This figure is accurate *even* for recursive functions. + +percall + is the quotient of ``cumtime`` divided by primitive calls + +filename:lineno(function) + provides the respective data of each function + +When there are two numbers in the first column (for example ``3/1``), it means +that the function recursed. The second value is the number of primitive calls +and the former is the total number of calls. Note that when the function does +not recurse, these two values are the same, and only the single figure is +printed. + +Instead of printing the output at the end of the profile run, you can save the +results to a file by specifying a filename to the :func:`run` function:: + + import cProfile + import re + cProfile.run('re.compile("foo|bar")', 'restats') + +The :class:`pstats.Stats` class reads profile results from a file and formats +them in various ways. + +The files :mod:`cProfile` and :mod:`profile` can also be invoked as a script to +profile another script. For example:: + + python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py) + +``-o`` writes the profile results to a file instead of to stdout + +``-s`` specifies one of the :func:`~pstats.Stats.sort_stats` sort values to sort +the output by. This only applies when ``-o`` is not supplied. + +``-m`` specifies that a module is being profiled instead of a script. + + .. versionadded:: 3.7 + Added the ``-m`` option to :mod:`cProfile`. + + .. versionadded:: 3.8 + Added the ``-m`` option to :mod:`profile`. + +The :mod:`pstats` module's :class:`~pstats.Stats` class has a variety of methods +for manipulating and printing the data saved into a profile results file:: + + import pstats + from pstats import SortKey + p = pstats.Stats('restats') + p.strip_dirs().sort_stats(-1).print_stats() + +The :meth:`~pstats.Stats.strip_dirs` method removed the extraneous path from all +the module names. The :meth:`~pstats.Stats.sort_stats` method sorted all the +entries according to the standard module/line/name string that is printed. The +:meth:`~pstats.Stats.print_stats` method printed out all the statistics. You +might try the following sort calls:: + + p.sort_stats(SortKey.NAME) + p.print_stats() + +The first call will actually sort the list by function name, and the second call +will print out the statistics. The following are some interesting calls to +experiment with:: + + p.sort_stats(SortKey.CUMULATIVE).print_stats(10) + +This sorts the profile by cumulative time in a function, and then only prints +the ten most significant lines. If you want to understand what algorithms are +taking time, the above line is what you would use. + +If you were looking to see what functions were looping a lot, and taking a lot +of time, you would do:: + + p.sort_stats(SortKey.TIME).print_stats(10) + +to sort according to time spent within each function, and then print the +statistics for the top ten functions. + +You might also try:: + + p.sort_stats(SortKey.FILENAME).print_stats('__init__') + +This will sort all the statistics by file name, and then print out statistics +for only the class init methods (since they are spelled with ``__init__`` in +them). As one final example, you could try:: + + p.sort_stats(SortKey.TIME, SortKey.CUMULATIVE).print_stats(.5, 'init') + +This line sorts statistics with a primary key of time, and a secondary key of +cumulative time, and then prints out some of the statistics. To be specific, the +list is first culled down to 50% (re: ``.5``) of its original size, then only +lines containing ``init`` are maintained, and that sub-sub-list is printed. + +If you wondered what functions called the above functions, you could now (``p`` +is still sorted according to the last criteria) do:: + + p.print_callers(.5, 'init') + +and you would get a list of callers for each of the listed functions. + +If you want more functionality, you're going to have to read the manual, or +guess what the following functions do:: + + p.print_callees() + p.add('restats') + +Invoked as a script, the :mod:`pstats` module is a statistics browser for +reading and examining profile dumps. It has a simple line-oriented interface +(implemented using :mod:`cmd`) and interactive help. + +:mod:`profile` and :mod:`cProfile` Module Reference +======================================================= + +.. module:: cProfile +.. module:: profile + :synopsis: Python source profiler. + +Both the :mod:`profile` and :mod:`cProfile` modules provide the following +functions: + +.. function:: run(command, filename=None, sort=-1) + + This function takes a single argument that can be passed to the :func:`exec` + function, and an optional file name. In all cases this routine executes:: + + exec(command, __main__.__dict__, __main__.__dict__) + + and gathers profiling statistics from the execution. If no file name is + present, then this function automatically creates a :class:`~pstats.Stats` + instance and prints a simple profiling report. If the sort value is specified, + it is passed to this :class:`~pstats.Stats` instance to control how the + results are sorted. + +.. function:: runctx(command, globals, locals, filename=None, sort=-1) + + This function is similar to :func:`run`, with added arguments to supply the + globals and locals dictionaries for the *command* string. This routine + executes:: + + exec(command, globals, locals) + + and gathers profiling statistics as in the :func:`run` function above. + +.. class:: Profile(timer=None, timeunit=0.0, subcalls=True, builtins=True) + + This class is normally only used if more precise control over profiling is + needed than what the :func:`cProfile.run` function provides. + + A custom timer can be supplied for measuring how long code takes to run via + the *timer* argument. This must be a function that returns a single number + representing the current time. If the number is an integer, the *timeunit* + specifies a multiplier that specifies the duration of each unit of time. For + example, if the timer returns times measured in thousands of seconds, the + time unit would be ``.001``. + + Directly using the :class:`Profile` class allows formatting profile results + without writing the profile data to a file:: + + import cProfile, pstats, io + from pstats import SortKey + pr = cProfile.Profile() + pr.enable() + # ... do something ... + pr.disable() + s = io.StringIO() + sortby = SortKey.CUMULATIVE + ps = pstats.Stats(pr, stream=s).sort_stats(sortby) + ps.print_stats() + print(s.getvalue()) + + The :class:`Profile` class can also be used as a context manager (supported + only in :mod:`cProfile` module. see :ref:`typecontextmanager`):: + + import cProfile + + with cProfile.Profile() as pr: + # ... do something ... + + pr.print_stats() + + .. versionchanged:: 3.8 + Added context manager support. + + .. method:: enable() + + Start collecting profiling data. Only in :mod:`cProfile`. + + .. method:: disable() + + Stop collecting profiling data. Only in :mod:`cProfile`. + + .. method:: create_stats() + + Stop collecting profiling data and record the results internally + as the current profile. + + .. method:: print_stats(sort=-1) + + Create a :class:`~pstats.Stats` object based on the current + profile and print the results to stdout. + + .. method:: dump_stats(filename) + + Write the results of the current profile to *filename*. + + .. method:: run(cmd) + + Profile the cmd via :func:`exec`. + + .. method:: runctx(cmd, globals, locals) + + Profile the cmd via :func:`exec` with the specified global and + local environment. + + .. method:: runcall(func, /, *args, **kwargs) + + Profile ``func(*args, **kwargs)`` + +Note that profiling will only work if the called command/function actually +returns. If the interpreter is terminated (e.g. via a :func:`sys.exit` call +during the called command/function execution) no profiling results will be +printed. + +.. _profile-stats: + +The :class:`Stats` Class +======================== + +Analysis of the profiler data is done using the :class:`~pstats.Stats` class. + +.. module:: pstats + :synopsis: Statistics object for use with the profiler. + +.. class:: Stats(*filenames or profile, stream=sys.stdout) + + This class constructor creates an instance of a "statistics object" from a + *filename* (or list of filenames) or from a :class:`Profile` instance. Output + will be printed to the stream specified by *stream*. + + The file selected by the above constructor must have been created by the + corresponding version of :mod:`profile` or :mod:`cProfile`. To be specific, + there is *no* file compatibility guaranteed with future versions of this + profiler, and there is no compatibility with files produced by other + profilers, or the same profiler run on a different operating system. If + several files are provided, all the statistics for identical functions will + be coalesced, so that an overall view of several processes can be considered + in a single report. If additional files need to be combined with data in an + existing :class:`~pstats.Stats` object, the :meth:`~pstats.Stats.add` method + can be used. + + Instead of reading the profile data from a file, a :class:`cProfile.Profile` + or :class:`profile.Profile` object can be used as the profile data source. + + :class:`Stats` objects have the following methods: + + .. method:: strip_dirs() + + This method for the :class:`Stats` class removes all leading path + information from file names. It is very useful in reducing the size of + the printout to fit within (close to) 80 columns. This method modifies + the object, and the stripped information is lost. After performing a + strip operation, the object is considered to have its entries in a + "random" order, as it was just after object initialization and loading. + If :meth:`~pstats.Stats.strip_dirs` causes two function names to be + indistinguishable (they are on the same line of the same filename, and + have the same function name), then the statistics for these two entries + are accumulated into a single entry. + + + .. method:: add(*filenames) + + This method of the :class:`Stats` class accumulates additional profiling + information into the current profiling object. Its arguments should refer + to filenames created by the corresponding version of :func:`profile.run` + or :func:`cProfile.run`. Statistics for identically named (re: file, line, + name) functions are automatically accumulated into single function + statistics. + + + .. method:: dump_stats(filename) + + Save the data loaded into the :class:`Stats` object to a file named + *filename*. The file is created if it does not exist, and is overwritten + if it already exists. This is equivalent to the method of the same name + on the :class:`profile.Profile` and :class:`cProfile.Profile` classes. + + + .. method:: sort_stats(*keys) + + This method modifies the :class:`Stats` object by sorting it according to + the supplied criteria. The argument can be either a string or a SortKey + enum identifying the basis of a sort (example: ``'time'``, ``'name'``, + ``SortKey.TIME`` or ``SortKey.NAME``). The SortKey enums argument have + advantage over the string argument in that it is more robust and less + error prone. + + When more than one key is provided, then additional keys are used as + secondary criteria when there is equality in all keys selected before + them. For example, ``sort_stats(SortKey.NAME, SortKey.FILE)`` will sort + all the entries according to their function name, and resolve all ties + (identical function names) by sorting by file name. + + For the string argument, abbreviations can be used for any key names, as + long as the abbreviation is unambiguous. + + The following are the valid string and SortKey: + + +------------------+---------------------+----------------------+ + | Valid String Arg | Valid enum Arg | Meaning | + +==================+=====================+======================+ + | ``'calls'`` | SortKey.CALLS | call count | + +------------------+---------------------+----------------------+ + | ``'cumulative'`` | SortKey.CUMULATIVE | cumulative time | + +------------------+---------------------+----------------------+ + | ``'cumtime'`` | N/A | cumulative time | + +------------------+---------------------+----------------------+ + | ``'file'`` | N/A | file name | + +------------------+---------------------+----------------------+ + | ``'filename'`` | SortKey.FILENAME | file name | + +------------------+---------------------+----------------------+ + | ``'module'`` | N/A | file name | + +------------------+---------------------+----------------------+ + | ``'ncalls'`` | N/A | call count | + +------------------+---------------------+----------------------+ + | ``'pcalls'`` | SortKey.PCALLS | primitive call count | + +------------------+---------------------+----------------------+ + | ``'line'`` | SortKey.LINE | line number | + +------------------+---------------------+----------------------+ + | ``'name'`` | SortKey.NAME | function name | + +------------------+---------------------+----------------------+ + | ``'nfl'`` | SortKey.NFL | name/file/line | + +------------------+---------------------+----------------------+ + | ``'stdname'`` | SortKey.STDNAME | standard name | + +------------------+---------------------+----------------------+ + | ``'time'`` | SortKey.TIME | internal time | + +------------------+---------------------+----------------------+ + | ``'tottime'`` | N/A | internal time | + +------------------+---------------------+----------------------+ + + Note that all sorts on statistics are in descending order (placing most + time consuming items first), where as name, file, and line number searches + are in ascending order (alphabetical). The subtle distinction between + ``SortKey.NFL`` and ``SortKey.STDNAME`` is that the standard name is a + sort of the name as printed, which means that the embedded line numbers + get compared in an odd way. For example, lines 3, 20, and 40 would (if + the file names were the same) appear in the string order 20, 3 and 40. + In contrast, ``SortKey.NFL`` does a numeric compare of the line numbers. + In fact, ``sort_stats(SortKey.NFL)`` is the same as + ``sort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE)``. + + For backward-compatibility reasons, the numeric arguments ``-1``, ``0``, + ``1``, and ``2`` are permitted. They are interpreted as ``'stdname'``, + ``'calls'``, ``'time'``, and ``'cumulative'`` respectively. If this old + style format (numeric) is used, only one sort key (the numeric key) will + be used, and additional arguments will be silently ignored. + + .. For compatibility with the old profiler. + + .. versionadded:: 3.7 + Added the SortKey enum. + + .. method:: reverse_order() + + This method for the :class:`Stats` class reverses the ordering of the + basic list within the object. Note that by default ascending vs + descending order is properly selected based on the sort key of choice. + + .. This method is provided primarily for compatibility with the old + profiler. + + + .. method:: print_stats(*restrictions) + + This method for the :class:`Stats` class prints out a report as described + in the :func:`profile.run` definition. + + The order of the printing is based on the last + :meth:`~pstats.Stats.sort_stats` operation done on the object (subject to + caveats in :meth:`~pstats.Stats.add` and + :meth:`~pstats.Stats.strip_dirs`). + + The arguments provided (if any) can be used to limit the list down to the + significant entries. Initially, the list is taken to be the complete set + of profiled functions. Each restriction is either an integer (to select a + count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to + select a percentage of lines), or a string that will interpreted as a + regular expression (to pattern match the standard name that is printed). + If several restrictions are provided, then they are applied sequentially. + For example:: + + print_stats(.1, 'foo:') + + would first limit the printing to first 10% of list, and then only print + functions that were part of filename :file:`.\*foo:`. In contrast, the + command:: + + print_stats('foo:', .1) + + would limit the list to all functions having file names :file:`.\*foo:`, + and then proceed to only print the first 10% of them. + + + .. method:: print_callers(*restrictions) + + This method for the :class:`Stats` class prints a list of all functions + that called each function in the profiled database. The ordering is + identical to that provided by :meth:`~pstats.Stats.print_stats`, and the + definition of the restricting argument is also identical. Each caller is + reported on its own line. The format differs slightly depending on the + profiler that produced the stats: + + * With :mod:`profile`, a number is shown in parentheses after each caller + to show how many times this specific call was made. For convenience, a + second non-parenthesized number repeats the cumulative time spent in the + function at the right. + + * With :mod:`cProfile`, each caller is preceded by three numbers: the + number of times this specific call was made, and the total and + cumulative times spent in the current function while it was invoked by + this specific caller. + + + .. method:: print_callees(*restrictions) + + This method for the :class:`Stats` class prints a list of all function + that were called by the indicated function. Aside from this reversal of + direction of calls (re: called vs was called by), the arguments and + ordering are identical to the :meth:`~pstats.Stats.print_callers` method. + + + .. method:: get_stats_profile() + + This method returns an instance of StatsProfile, which contains a mapping + of function names to instances of FunctionProfile. Each FunctionProfile + instance holds information related to the function's profile such as how + long the function took to run, how many times it was called, etc... + + .. versionadded:: 3.9 + Added the following dataclasses: StatsProfile, FunctionProfile. + Added the following function: get_stats_profile. + +.. _deterministic-profiling: + +What Is Deterministic Profiling? +================================ + +:dfn:`Deterministic profiling` is meant to reflect the fact that all *function +call*, *function return*, and *exception* events are monitored, and precise +timings are made for the intervals between these events (during which time the +user's code is executing). In contrast, :dfn:`statistical profiling` (which is +not done by this module) randomly samples the effective instruction pointer, and +deduces where time is being spent. The latter technique traditionally involves +less overhead (as the code does not need to be instrumented), but provides only +relative indications of where time is being spent. + +In Python, since there is an interpreter active during execution, the presence +of instrumented code is not required in order to do deterministic profiling. +Python automatically provides a :dfn:`hook` (optional callback) for each event. +In addition, the interpreted nature of Python tends to add so much overhead to +execution, that deterministic profiling tends to only add small processing +overhead in typical applications. The result is that deterministic profiling is +not that expensive, yet provides extensive run time statistics about the +execution of a Python program. + +Call count statistics can be used to identify bugs in code (surprising counts), +and to identify possible inline-expansion points (high call counts). Internal +time statistics can be used to identify "hot loops" that should be carefully +optimized. Cumulative time statistics should be used to identify high level +errors in the selection of algorithms. Note that the unusual handling of +cumulative times in this profiler allows statistics for recursive +implementations of algorithms to be directly compared to iterative +implementations. + + +.. _profile-limitations: + +Limitations +=========== + +One limitation has to do with accuracy of timing information. There is a +fundamental problem with deterministic profilers involving accuracy. The most +obvious restriction is that the underlying "clock" is only ticking at a rate +(typically) of about .001 seconds. Hence no measurements will be more accurate +than the underlying clock. If enough measurements are taken, then the "error" +will tend to average out. Unfortunately, removing this first error induces a +second source of error. + +The second problem is that it "takes a while" from when an event is dispatched +until the profiler's call to get the time actually *gets* the state of the +clock. Similarly, there is a certain lag when exiting the profiler event +handler from the time that the clock's value was obtained (and then squirreled +away), until the user's code is once again executing. As a result, functions +that are called many times, or call many functions, will typically accumulate +this error. The error that accumulates in this fashion is typically less than +the accuracy of the clock (less than one clock tick), but it *can* accumulate +and become very significant. + +The problem is more important with :mod:`profile` than with the lower-overhead +:mod:`cProfile`. For this reason, :mod:`profile` provides a means of +calibrating itself for a given platform so that this error can be +probabilistically (on the average) removed. After the profiler is calibrated, it +will be more accurate (in a least square sense), but it will sometimes produce +negative numbers (when call counts are exceptionally low, and the gods of +probability work against you :-). ) Do *not* be alarmed by negative numbers in +the profile. They should *only* appear if you have calibrated your profiler, +and the results are actually better than without calibration. + + +.. _profile-calibration: + +Calibration +=========== + +The profiler of the :mod:`profile` module subtracts a constant from each event +handling time to compensate for the overhead of calling the time function, and +socking away the results. By default, the constant is 0. The following +procedure can be used to obtain a better constant for a given platform (see +:ref:`profile-limitations`). :: + + import profile + pr = profile.Profile() + for i in range(5): + print(pr.calibrate(10000)) + +The method executes the number of Python calls given by the argument, directly +and again under the profiler, measuring the time for both. It then computes the +hidden overhead per profiler event, and returns that as a float. For example, +on a 1.8Ghz Intel Core i5 running Mac OS X, and using Python's time.process_time() as +the timer, the magical number is about 4.04e-6. + +The object of this exercise is to get a fairly consistent result. If your +computer is *very* fast, or your timer function has poor resolution, you might +have to pass 100000, or even 1000000, to get consistent results. + +When you have a consistent answer, there are three ways you can use it:: + + import profile + + # 1. Apply computed bias to all Profile instances created hereafter. + profile.Profile.bias = your_computed_bias + + # 2. Apply computed bias to a specific Profile instance. + pr = profile.Profile() + pr.bias = your_computed_bias + + # 3. Specify computed bias in instance constructor. + pr = profile.Profile(bias=your_computed_bias) + +If you have a choice, you are better off choosing a smaller constant, and then +your results will "less often" show up as negative in profile statistics. + +.. _profile-timers: + +Using a custom timer +==================== + +If you want to change how current time is determined (for example, to force use +of wall-clock time or elapsed process time), pass the timing function you want +to the :class:`Profile` class constructor:: + + pr = profile.Profile(your_time_func) + +The resulting profiler will then call ``your_time_func``. Depending on whether +you are using :class:`profile.Profile` or :class:`cProfile.Profile`, +``your_time_func``'s return value will be interpreted differently: + +:class:`profile.Profile` + ``your_time_func`` should return a single number, or a list of numbers whose + sum is the current time (like what :func:`os.times` returns). If the + function returns a single time number, or the list of returned numbers has + length 2, then you will get an especially fast version of the dispatch + routine. + + Be warned that you should calibrate the profiler class for the timer function + that you choose (see :ref:`profile-calibration`). For most machines, a timer + that returns a lone integer value will provide the best results in terms of + low overhead during profiling. (:func:`os.times` is *pretty* bad, as it + returns a tuple of floating point values). If you want to substitute a + better timer in the cleanest fashion, derive a class and hardwire a + replacement dispatch method that best handles your timer call, along with the + appropriate calibration constant. + +:class:`cProfile.Profile` + ``your_time_func`` should return a single number. If it returns integers, + you can also invoke the class constructor with a second argument specifying + the real duration of one unit of time. For example, if + ``your_integer_time_func`` returns times measured in thousands of seconds, + you would construct the :class:`Profile` instance as follows:: + + pr = cProfile.Profile(your_integer_time_func, 0.001) + + As the :class:`cProfile.Profile` class cannot be calibrated, custom timer + functions should be used with care and should be as fast as possible. For + the best results with a custom timer, it might be necessary to hard-code it + in the C source of the internal :mod:`_lsprof` module. + +Python 3.3 adds several new functions in :mod:`time` that can be used to make +precise measurements of process or wall-clock time. For example, see +:func:`time.perf_counter`. diff --git a/cpython_2/environment/repo/Doc/library/pty.rst b/cpython_2/environment/repo/Doc/library/pty.rst new file mode 100644 index 0000000000000000000000000000000000000000..73d4f102fd4d8e2f57c994f55adc2925f17fa314 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pty.rst @@ -0,0 +1,120 @@ +:mod:`pty` --- Pseudo-terminal utilities +======================================== + +.. module:: pty + :platform: Linux + :synopsis: Pseudo-Terminal Handling for Linux. + +.. moduleauthor:: Steen Lumholt +.. sectionauthor:: Moshe Zadka + +**Source code:** :source:`Lib/pty.py` + +-------------- + +The :mod:`pty` module defines operations for handling the pseudo-terminal +concept: starting another process and being able to write to and read from its +controlling terminal programmatically. + +Because pseudo-terminal handling is highly platform dependent, there is code to +do it only for Linux. (The Linux code is supposed to work on other platforms, +but hasn't been tested yet.) + +The :mod:`pty` module defines the following functions: + + +.. function:: fork() + + Fork. Connect the child's controlling terminal to a pseudo-terminal. Return + value is ``(pid, fd)``. Note that the child gets *pid* 0, and the *fd* is + *invalid*. The parent's return value is the *pid* of the child, and *fd* is a + file descriptor connected to the child's controlling terminal (and also to the + child's standard input and output). + + +.. function:: openpty() + + Open a new pseudo-terminal pair, using :func:`os.openpty` if possible, or + emulation code for generic Unix systems. Return a pair of file descriptors + ``(master, slave)``, for the master and the slave end, respectively. + + +.. function:: spawn(argv[, master_read[, stdin_read]]) + + Spawn a process, and connect its controlling terminal with the current + process's standard io. This is often used to baffle programs which insist on + reading from the controlling terminal. It is expected that the process + spawned behind the pty will eventually terminate, and when it does *spawn* + will return. + + The functions *master_read* and *stdin_read* are passed a file descriptor + which they should read from, and they should always return a byte string. In + order to force spawn to return before the child process exits an + :exc:`OSError` should be thrown. + + The default implementation for both functions will read and return up to 1024 + bytes each time the function is called. The *master_read* callback is passed + the pseudoterminal’s master file descriptor to read output from the child + process, and *stdin_read* is passed file descriptor 0, to read from the + parent process's standard input. + + Returning an empty byte string from either callback is interpreted as an + end-of-file (EOF) condition, and that callback will not be called after + that. If *stdin_read* signals EOF the controlling terminal can no longer + communicate with the parent process OR the child process. Unless the child + process will quit without any input, *spawn* will then loop forever. If + *master_read* signals EOF the same behavior results (on linux at least). + + If both callbacks signal EOF then *spawn* will probably never return, unless + *select* throws an error on your platform when passed three empty lists. This + is a bug, documented in `issue 26228 `_. + + Return the exit status value from :func:`os.waitpid` on the child process. + + :func:`waitstatus_to_exitcode` can be used to convert the exit status into + an exit code. + + .. audit-event:: pty.spawn argv pty.spawn + + .. versionchanged:: 3.4 + :func:`spawn` now returns the status value from :func:`os.waitpid` + on the child process. + +Example +------- + +.. sectionauthor:: Steen Lumholt + +The following program acts like the Unix command :manpage:`script(1)`, using a +pseudo-terminal to record all input and output of a terminal session in a +"typescript". :: + + import argparse + import os + import pty + import sys + import time + + parser = argparse.ArgumentParser() + parser.add_argument('-a', dest='append', action='store_true') + parser.add_argument('-p', dest='use_python', action='store_true') + parser.add_argument('filename', nargs='?', default='typescript') + options = parser.parse_args() + + shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh') + filename = options.filename + mode = 'ab' if options.append else 'wb' + + with open(filename, mode) as script: + def read(fd): + data = os.read(fd, 1024) + script.write(data) + return data + + print('Script started, file is', filename) + script.write(('Script started on %s\n' % time.asctime()).encode()) + + pty.spawn(shell, read) + + script.write(('Script done on %s\n' % time.asctime()).encode()) + print('Script done, file is', filename) diff --git a/cpython_2/environment/repo/Doc/library/pwd.rst b/cpython_2/environment/repo/Doc/library/pwd.rst new file mode 100644 index 0000000000000000000000000000000000000000..03ebb02e4e5136ffda973dae3d651af513c65927 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pwd.rst @@ -0,0 +1,76 @@ +:mod:`pwd` --- The password database +==================================== + +.. module:: pwd + :platform: Unix + :synopsis: The password database (getpwnam() and friends). + +-------------- + +This module provides access to the Unix user account and password database. It +is available on all Unix versions. + +Password database entries are reported as a tuple-like object, whose attributes +correspond to the members of the ``passwd`` structure (Attribute field below, +see ````): + ++-------+---------------+-----------------------------+ +| Index | Attribute | Meaning | ++=======+===============+=============================+ +| 0 | ``pw_name`` | Login name | ++-------+---------------+-----------------------------+ +| 1 | ``pw_passwd`` | Optional encrypted password | ++-------+---------------+-----------------------------+ +| 2 | ``pw_uid`` | Numerical user ID | ++-------+---------------+-----------------------------+ +| 3 | ``pw_gid`` | Numerical group ID | ++-------+---------------+-----------------------------+ +| 4 | ``pw_gecos`` | User name or comment field | ++-------+---------------+-----------------------------+ +| 5 | ``pw_dir`` | User home directory | ++-------+---------------+-----------------------------+ +| 6 | ``pw_shell`` | User command interpreter | ++-------+---------------+-----------------------------+ + +The uid and gid items are integers, all others are strings. :exc:`KeyError` is +raised if the entry asked for cannot be found. + +.. note:: + + .. index:: module: crypt + + In traditional Unix the field ``pw_passwd`` usually contains a password + encrypted with a DES derived algorithm (see module :mod:`crypt`). However most + modern unices use a so-called *shadow password* system. On those unices the + *pw_passwd* field only contains an asterisk (``'*'``) or the letter ``'x'`` + where the encrypted password is stored in a file :file:`/etc/shadow` which is + not world readable. Whether the *pw_passwd* field contains anything useful is + system-dependent. If available, the :mod:`spwd` module should be used where + access to the encrypted password is required. + +It defines the following items: + + +.. function:: getpwuid(uid) + + Return the password database entry for the given numeric user ID. + + +.. function:: getpwnam(name) + + Return the password database entry for the given user name. + + +.. function:: getpwall() + + Return a list of all available password database entries, in arbitrary order. + + +.. seealso:: + + Module :mod:`grp` + An interface to the group database, similar to this. + + Module :mod:`spwd` + An interface to the shadow password database, similar to this. + diff --git a/cpython_2/environment/repo/Doc/library/py_compile.rst b/cpython_2/environment/repo/Doc/library/py_compile.rst new file mode 100644 index 0000000000000000000000000000000000000000..a12a5bb0b1aa2c0c5c290d5c619ac1cd08be11c1 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/py_compile.rst @@ -0,0 +1,148 @@ +:mod:`py_compile` --- Compile Python source files +================================================= + +.. module:: py_compile + :synopsis: Generate byte-code files from Python source files. + +.. sectionauthor:: Fred L. Drake, Jr. +.. documentation based on module docstrings + +**Source code:** :source:`Lib/py_compile.py` + +.. index:: pair: file; byte-code + +-------------- + +The :mod:`py_compile` module provides a function to generate a byte-code file +from a source file, and another function used when the module source file is +invoked as a script. + +Though not often needed, this function can be useful when installing modules for +shared use, especially if some of the users may not have permission to write the +byte-code cache files in the directory containing the source code. + + +.. exception:: PyCompileError + + Exception raised when an error occurs while attempting to compile the file. + + +.. function:: compile(file, cfile=None, dfile=None, doraise=False, optimize=-1, invalidation_mode=PycInvalidationMode.TIMESTAMP, quiet=0) + + Compile a source file to byte-code and write out the byte-code cache file. + The source code is loaded from the file named *file*. The byte-code is + written to *cfile*, which defaults to the :pep:`3147`/:pep:`488` path, ending + in ``.pyc``. + For example, if *file* is ``/foo/bar/baz.py`` *cfile* will default to + ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2. If *dfile* is + specified, it is used as the name of the source file in error messages when + instead of *file*. If *doraise* is true, a :exc:`PyCompileError` is raised + when an error is encountered while compiling *file*. If *doraise* is false + (the default), an error string is written to ``sys.stderr``, but no exception + is raised. This function returns the path to byte-compiled file, i.e. + whatever *cfile* value was used. + + The *doraise* and *quiet* arguments determine how errors are handled while + compiling file. If *quiet* is 0 or 1, and *doraise* is false, the default + behaviour is enabled: an error string is written to ``sys.stderr``, and the + function returns ``None`` instead of a path. If *doraise* is true, + a :exc:`PyCompileError` is raised instead. However if *quiet* is 2, + no message is written, and *doraise* has no effect. + + If the path that *cfile* becomes (either explicitly specified or computed) + is a symlink or non-regular file, :exc:`FileExistsError` will be raised. + This is to act as a warning that import will turn those paths into regular + files if it is allowed to write byte-compiled files to those paths. This is + a side-effect of import using file renaming to place the final byte-compiled + file into place to prevent concurrent file writing issues. + + *optimize* controls the optimization level and is passed to the built-in + :func:`compile` function. The default of ``-1`` selects the optimization + level of the current interpreter. + + *invalidation_mode* should be a member of the :class:`PycInvalidationMode` + enum and controls how the generated bytecode cache is invalidated at + runtime. The default is :attr:`PycInvalidationMode.CHECKED_HASH` if + the :envvar:`SOURCE_DATE_EPOCH` environment variable is set, otherwise + the default is :attr:`PycInvalidationMode.TIMESTAMP`. + + .. versionchanged:: 3.2 + Changed default value of *cfile* to be :PEP:`3147`-compliant. Previous + default was *file* + ``'c'`` (``'o'`` if optimization was enabled). + Also added the *optimize* parameter. + + .. versionchanged:: 3.4 + Changed code to use :mod:`importlib` for the byte-code cache file writing. + This means file creation/writing semantics now match what :mod:`importlib` + does, e.g. permissions, write-and-move semantics, etc. Also added the + caveat that :exc:`FileExistsError` is raised if *cfile* is a symlink or + non-regular file. + + .. versionchanged:: 3.7 + The *invalidation_mode* parameter was added as specified in :pep:`552`. + If the :envvar:`SOURCE_DATE_EPOCH` environment variable is set, + *invalidation_mode* will be forced to + :attr:`PycInvalidationMode.CHECKED_HASH`. + + .. versionchanged:: 3.7.2 + The :envvar:`SOURCE_DATE_EPOCH` environment variable no longer + overrides the value of the *invalidation_mode* argument, and determines + its default value instead. + + .. versionchanged:: 3.8 + The *quiet* parameter was added. + + +.. class:: PycInvalidationMode + + A enumeration of possible methods the interpreter can use to determine + whether a bytecode file is up to date with a source file. The ``.pyc`` file + indicates the desired invalidation mode in its header. See + :ref:`pyc-invalidation` for more information on how Python invalidates + ``.pyc`` files at runtime. + + .. versionadded:: 3.7 + + .. attribute:: TIMESTAMP + + The ``.pyc`` file includes the timestamp and size of the source file, + which Python will compare against the metadata of the source file at + runtime to determine if the ``.pyc`` file needs to be regenerated. + + .. attribute:: CHECKED_HASH + + The ``.pyc`` file includes a hash of the source file content, which Python + will compare against the source at runtime to determine if the ``.pyc`` + file needs to be regenerated. + + .. attribute:: UNCHECKED_HASH + + Like :attr:`CHECKED_HASH`, the ``.pyc`` file includes a hash of the source + file content. However, Python will at runtime assume the ``.pyc`` file is + up to date and not validate the ``.pyc`` against the source file at all. + + This option is useful when the ``.pycs`` are kept up to date by some + system external to Python like a build system. + + +.. function:: main(args=None) + + Compile several source files. The files named in *args* (or on the command + line, if *args* is ``None``) are compiled and the resulting byte-code is + cached in the normal manner. This function does not search a directory + structure to locate source files; it only compiles files named explicitly. + If ``'-'`` is the only parameter in args, the list of files is taken from + standard input. + + .. versionchanged:: 3.2 + Added support for ``'-'``. + +When this module is run as a script, the :func:`main` is used to compile all the +files named on the command line. The exit status is nonzero if one of the files +could not be compiled. + + +.. seealso:: + + Module :mod:`compileall` + Utilities to compile all Python source files in a directory tree. diff --git a/cpython_2/environment/repo/Doc/library/pyclbr.rst b/cpython_2/environment/repo/Doc/library/pyclbr.rst new file mode 100644 index 0000000000000000000000000000000000000000..36e83e85c23141fded94d3d362c7d75a60f0dafd --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pyclbr.rst @@ -0,0 +1,156 @@ +:mod:`pyclbr` --- Python module browser support +=============================================== + +.. module:: pyclbr + :synopsis: Supports information extraction for a Python module browser. + +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/pyclbr.py` + +-------------- + +The :mod:`pyclbr` module provides limited information about the +functions, classes, and methods defined in a Python-coded module. The +information is sufficient to implement a module browser. The +information is extracted from the Python source code rather than by +importing the module, so this module is safe to use with untrusted code. +This restriction makes it impossible to use this module with modules not +implemented in Python, including all standard and optional extension +modules. + + +.. function:: readmodule(module, path=None) + + Return a dictionary mapping module-level class names to class + descriptors. If possible, descriptors for imported base classes are + included. Parameter *module* is a string with the name of the module + to read; it may be the name of a module within a package. If given, + *path* is a sequence of directory paths prepended to ``sys.path``, + which is used to locate the module source code. + + This function is the original interface and is only kept for back + compatibility. It returns a filtered version of the following. + + +.. function:: readmodule_ex(module, path=None) + + Return a dictionary-based tree containing a function or class + descriptors for each function and class defined in the module with a + ``def`` or ``class`` statement. The returned dictionary maps + module-level function and class names to their descriptors. Nested + objects are entered into the children dictionary of their parent. As + with readmodule, *module* names the module to be read and *path* is + prepended to sys.path. If the module being read is a package, the + returned dictionary has a key ``'__path__'`` whose value is a list + containing the package search path. + +.. versionadded:: 3.7 + Descriptors for nested definitions. They are accessed through the + new children attribute. Each has a new parent attribute. + +The descriptors returned by these functions are instances of +Function and Class classes. Users are not expected to create instances +of these classes. + + +.. _pyclbr-function-objects: + +Function Objects +---------------- +Class :class:`Function` instances describe functions defined by def +statements. They have the following attributes: + + +.. attribute:: Function.file + + Name of the file in which the function is defined. + + +.. attribute:: Function.module + + The name of the module defining the function described. + + +.. attribute:: Function.name + + The name of the function. + + +.. attribute:: Function.lineno + + The line number in the file where the definition starts. + + +.. attribute:: Function.parent + + For top-level functions, None. For nested functions, the parent. + + .. versionadded:: 3.7 + + +.. attribute:: Function.children + + A dictionary mapping names to descriptors for nested functions and + classes. + + .. versionadded:: 3.7 + + +.. _pyclbr-class-objects: + +Class Objects +------------- +Class :class:`Class` instances describe classes defined by class +statements. They have the same attributes as Functions and two more. + + +.. attribute:: Class.file + + Name of the file in which the class is defined. + + +.. attribute:: Class.module + + The name of the module defining the class described. + + +.. attribute:: Class.name + + The name of the class. + + +.. attribute:: Class.lineno + + The line number in the file where the definition starts. + + +.. attribute:: Class.parent + + For top-level classes, None. For nested classes, the parent. + + .. versionadded:: 3.7 + + +.. attribute:: Class.children + + A dictionary mapping names to descriptors for nested functions and + classes. + + .. versionadded:: 3.7 + + +.. attribute:: Class.super + + A list of :class:`Class` objects which describe the immediate base + classes of the class being described. Classes which are named as + superclasses but which are not discoverable by :func:`readmodule_ex` + are listed as a string with the class name instead of as + :class:`Class` objects. + + +.. attribute:: Class.methods + + A dictionary mapping method names to line numbers. This can be + derived from the newer children dictionary, but remains for + back-compatibility. diff --git a/cpython_2/environment/repo/Doc/library/pydoc.rst b/cpython_2/environment/repo/Doc/library/pydoc.rst new file mode 100644 index 0000000000000000000000000000000000000000..f956b9d2176187524009069259256e64fe425997 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pydoc.rst @@ -0,0 +1,109 @@ +:mod:`pydoc` --- Documentation generator and online help system +=============================================================== + +.. module:: pydoc + :synopsis: Documentation generator and online help system. + +.. moduleauthor:: Ka-Ping Yee +.. sectionauthor:: Ka-Ping Yee + +**Source code:** :source:`Lib/pydoc.py` + +.. index:: + single: documentation; generation + single: documentation; online + single: help; online + +-------------- + +The :mod:`pydoc` module automatically generates documentation from Python +modules. The documentation can be presented as pages of text on the console, +served to a Web browser, or saved to HTML files. + +For modules, classes, functions and methods, the displayed documentation is +derived from the docstring (i.e. the :attr:`__doc__` attribute) of the object, +and recursively of its documentable members. If there is no docstring, +:mod:`pydoc` tries to obtain a description from the block of comment lines just +above the definition of the class, function or method in the source file, or at +the top of the module (see :func:`inspect.getcomments`). + +The built-in function :func:`help` invokes the online help system in the +interactive interpreter, which uses :mod:`pydoc` to generate its documentation +as text on the console. The same text documentation can also be viewed from +outside the Python interpreter by running :program:`pydoc` as a script at the +operating system's command prompt. For example, running :: + + pydoc sys + +at a shell prompt will display documentation on the :mod:`sys` module, in a +style similar to the manual pages shown by the Unix :program:`man` command. The +argument to :program:`pydoc` can be the name of a function, module, or package, +or a dotted reference to a class, method, or function within a module or module +in a package. If the argument to :program:`pydoc` looks like a path (that is, +it contains the path separator for your operating system, such as a slash in +Unix), and refers to an existing Python source file, then documentation is +produced for that file. + +.. note:: + + In order to find objects and their documentation, :mod:`pydoc` imports the + module(s) to be documented. Therefore, any code on module level will be + executed on that occasion. Use an ``if __name__ == '__main__':`` guard to + only execute code when a file is invoked as a script and not just imported. + +When printing output to the console, :program:`pydoc` attempts to paginate the +output for easier reading. If the :envvar:`PAGER` environment variable is set, +:program:`pydoc` will use its value as a pagination program. + +Specifying a ``-w`` flag before the argument will cause HTML documentation +to be written out to a file in the current directory, instead of displaying text +on the console. + +Specifying a ``-k`` flag before the argument will search the synopsis +lines of all available modules for the keyword given as the argument, again in a +manner similar to the Unix :program:`man` command. The synopsis line of a +module is the first line of its documentation string. + +You can also use :program:`pydoc` to start an HTTP server on the local machine +that will serve documentation to visiting Web browsers. :program:`pydoc -p 1234` +will start a HTTP server on port 1234, allowing you to browse the +documentation at ``http://localhost:1234/`` in your preferred Web browser. +Specifying ``0`` as the port number will select an arbitrary unused port. + +:program:`pydoc -n ` will start the server listening at the given +hostname. By default the hostname is 'localhost' but if you want the server to +be reached from other machines, you may want to change the host name that the +server responds to. During development this is especially useful if you want +to run pydoc from within a container. + +:program:`pydoc -b` will start the server and additionally open a web +browser to a module index page. Each served page has a navigation bar at the +top where you can *Get* help on an individual item, *Search* all modules with a +keyword in their synopsis line, and go to the *Module index*, *Topics* and +*Keywords* pages. + +When :program:`pydoc` generates documentation, it uses the current environment +and path to locate modules. Thus, invoking :program:`pydoc spam` +documents precisely the version of the module you would get if you started the +Python interpreter and typed ``import spam``. + +Module docs for core modules are assumed to reside in +``https://docs.python.org/X.Y/library/`` where ``X`` and ``Y`` are the +major and minor version numbers of the Python interpreter. This can +be overridden by setting the :envvar:`PYTHONDOCS` environment variable +to a different URL or to a local directory containing the Library +Reference Manual pages. + +.. versionchanged:: 3.2 + Added the ``-b`` option. + +.. versionchanged:: 3.3 + The ``-g`` command line option was removed. + +.. versionchanged:: 3.4 + :mod:`pydoc` now uses :func:`inspect.signature` rather than + :func:`inspect.getfullargspec` to extract signature information from + callables. + +.. versionchanged:: 3.7 + Added the ``-n`` option. diff --git a/cpython_2/environment/repo/Doc/library/pyexpat.rst b/cpython_2/environment/repo/Doc/library/pyexpat.rst new file mode 100644 index 0000000000000000000000000000000000000000..e43b9aecd86835a212b9bfa2367c4bc388f149d5 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/pyexpat.rst @@ -0,0 +1,876 @@ +:mod:`xml.parsers.expat` --- Fast XML parsing using Expat +========================================================= + +.. module:: xml.parsers.expat + :synopsis: An interface to the Expat non-validating XML parser. + +.. moduleauthor:: Paul Prescod + +-------------- + +.. Markup notes: + + Many of the attributes of the XMLParser objects are callbacks. Since + signature information must be presented, these are described using the method + directive. Since they are attributes which are set by client code, in-text + references to these attributes should be marked using the :member: role. + + +.. warning:: + + The :mod:`pyexpat` module is not secure against maliciously + constructed data. If you need to parse untrusted or unauthenticated data see + :ref:`xml-vulnerabilities`. + + +.. index:: single: Expat + +The :mod:`xml.parsers.expat` module is a Python interface to the Expat +non-validating XML parser. The module provides a single extension type, +:class:`xmlparser`, that represents the current state of an XML parser. After +an :class:`xmlparser` object has been created, various attributes of the object +can be set to handler functions. When an XML document is then fed to the +parser, the handler functions are called for the character data and markup in +the XML document. + +.. index:: module: pyexpat + +This module uses the :mod:`pyexpat` module to provide access to the Expat +parser. Direct use of the :mod:`pyexpat` module is deprecated. + +This module provides one exception and one type object: + + +.. exception:: ExpatError + + The exception raised when Expat reports an error. See section + :ref:`expaterror-objects` for more information on interpreting Expat errors. + + +.. exception:: error + + Alias for :exc:`ExpatError`. + + +.. data:: XMLParserType + + The type of the return values from the :func:`ParserCreate` function. + +The :mod:`xml.parsers.expat` module contains two functions: + + +.. function:: ErrorString(errno) + + Returns an explanatory string for a given error number *errno*. + + +.. function:: ParserCreate(encoding=None, namespace_separator=None) + + Creates and returns a new :class:`xmlparser` object. *encoding*, if specified, + must be a string naming the encoding used by the XML data. Expat doesn't + support as many encodings as Python does, and its repertoire of encodings can't + be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII. If + *encoding* [1]_ is given it will override the implicit or explicit encoding of the + document. + + Expat can optionally do XML namespace processing for you, enabled by providing a + value for *namespace_separator*. The value must be a one-character string; a + :exc:`ValueError` will be raised if the string has an illegal length (``None`` + is considered the same as omission). When namespace processing is enabled, + element type names and attribute names that belong to a namespace will be + expanded. The element name passed to the element handlers + :attr:`StartElementHandler` and :attr:`EndElementHandler` will be the + concatenation of the namespace URI, the namespace separator character, and the + local part of the name. If the namespace separator is a zero byte (``chr(0)``) + then the namespace URI and the local part will be concatenated without any + separator. + + For example, if *namespace_separator* is set to a space character (``' '``) and + the following document is parsed: + + .. code-block:: xml + + + + + + + + :attr:`StartElementHandler` will receive the following strings for each + element:: + + http://default-namespace.org/ root + http://www.python.org/ns/ elem1 + elem2 + + Due to limitations in the ``Expat`` library used by :mod:`pyexpat`, + the :class:`xmlparser` instance returned can only be used to parse a single + XML document. Call ``ParserCreate`` for each document to provide unique + parser instances. + + +.. seealso:: + + `The Expat XML Parser `_ + Home page of the Expat project. + + +.. _xmlparser-objects: + +XMLParser Objects +----------------- + +:class:`xmlparser` objects have the following methods: + + +.. method:: xmlparser.Parse(data[, isfinal]) + + Parses the contents of the string *data*, calling the appropriate handler + functions to process the parsed data. *isfinal* must be true on the final call + to this method; it allows the parsing of a single file in fragments, + not the submission of multiple files. + *data* can be the empty string at any time. + + +.. method:: xmlparser.ParseFile(file) + + Parse XML data reading from the object *file*. *file* only needs to provide + the ``read(nbytes)`` method, returning the empty string when there's no more + data. + + +.. method:: xmlparser.SetBase(base) + + Sets the base to be used for resolving relative URIs in system identifiers in + declarations. Resolving relative identifiers is left to the application: this + value will be passed through as the *base* argument to the + :func:`ExternalEntityRefHandler`, :func:`NotationDeclHandler`, and + :func:`UnparsedEntityDeclHandler` functions. + + +.. method:: xmlparser.GetBase() + + Returns a string containing the base set by a previous call to :meth:`SetBase`, + or ``None`` if :meth:`SetBase` hasn't been called. + + +.. method:: xmlparser.GetInputContext() + + Returns the input data that generated the current event as a string. The data is + in the encoding of the entity which contains the text. When called while an + event handler is not active, the return value is ``None``. + + +.. method:: xmlparser.ExternalEntityParserCreate(context[, encoding]) + + Create a "child" parser which can be used to parse an external parsed entity + referred to by content parsed by the parent parser. The *context* parameter + should be the string passed to the :meth:`ExternalEntityRefHandler` handler + function, described below. The child parser is created with the + :attr:`ordered_attributes` and :attr:`specified_attributes` set to the values of + this parser. + +.. method:: xmlparser.SetParamEntityParsing(flag) + + Control parsing of parameter entities (including the external DTD subset). + Possible *flag* values are :const:`XML_PARAM_ENTITY_PARSING_NEVER`, + :const:`XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE` and + :const:`XML_PARAM_ENTITY_PARSING_ALWAYS`. Return true if setting the flag + was successful. + +.. method:: xmlparser.UseForeignDTD([flag]) + + Calling this with a true value for *flag* (the default) will cause Expat to call + the :attr:`ExternalEntityRefHandler` with :const:`None` for all arguments to + allow an alternate DTD to be loaded. If the document does not contain a + document type declaration, the :attr:`ExternalEntityRefHandler` will still be + called, but the :attr:`StartDoctypeDeclHandler` and + :attr:`EndDoctypeDeclHandler` will not be called. + + Passing a false value for *flag* will cancel a previous call that passed a true + value, but otherwise has no effect. + + This method can only be called before the :meth:`Parse` or :meth:`ParseFile` + methods are called; calling it after either of those have been called causes + :exc:`ExpatError` to be raised with the :attr:`code` attribute set to + ``errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]``. + +:class:`xmlparser` objects have the following attributes: + + +.. 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. + When the size is changed, the buffer will be flushed. + + +.. attribute:: xmlparser.buffer_text + + Setting this to true causes the :class:`xmlparser` object to buffer textual + content returned by Expat to avoid multiple calls to the + :meth:`CharacterDataHandler` callback whenever possible. This can improve + performance substantially since Expat normally breaks character data into chunks + at every line ending. This attribute is false by default, and may be changed at + any time. + + +.. attribute:: xmlparser.buffer_used + + If :attr:`buffer_text` is enabled, the number of bytes stored in the buffer. + These bytes represent UTF-8 encoded text. This attribute has no meaningful + interpretation when :attr:`buffer_text` is false. + + +.. attribute:: xmlparser.ordered_attributes + + Setting this attribute to a non-zero integer causes the attributes to be + reported as a list rather than a dictionary. The attributes are presented in + the order found in the document text. For each attribute, two list entries are + presented: the attribute name and the attribute value. (Older versions of this + module also used this format.) By default, this attribute is false; it may be + changed at any time. + + +.. attribute:: xmlparser.specified_attributes + + If set to a non-zero integer, the parser will report only those attributes which + were specified in the document instance and not those which were derived from + attribute declarations. Applications which set this need to be especially + careful to use what additional information is available from the declarations as + needed to comply with the standards for the behavior of XML processors. By + default, this attribute is false; it may be changed at any time. + + +The following attributes contain values relating to the most recent error +encountered by an :class:`xmlparser` object, and will only have correct values +once a call to :meth:`Parse` or :meth:`ParseFile` has raised an +:exc:`xml.parsers.expat.ExpatError` exception. + + +.. attribute:: xmlparser.ErrorByteIndex + + Byte index at which an error occurred. + + +.. attribute:: xmlparser.ErrorCode + + Numeric code specifying the problem. This value can be passed to the + :func:`ErrorString` function, or compared to one of the constants defined in the + ``errors`` object. + + +.. attribute:: xmlparser.ErrorColumnNumber + + Column number at which an error occurred. + + +.. attribute:: xmlparser.ErrorLineNumber + + Line number at which an error occurred. + +The following attributes contain values relating to the current parse location +in an :class:`xmlparser` object. During a callback reporting a parse event they +indicate the location of the first of the sequence of characters that generated +the event. When called outside of a callback, the position indicated will be +just past the last parse event (regardless of whether there was an associated +callback). + + +.. attribute:: xmlparser.CurrentByteIndex + + Current byte index in the parser input. + + +.. attribute:: xmlparser.CurrentColumnNumber + + Current column number in the parser input. + + +.. attribute:: xmlparser.CurrentLineNumber + + Current line number in the parser input. + +Here is the list of handlers that can be set. To set a handler on an +:class:`xmlparser` object *o*, use ``o.handlername = func``. *handlername* must +be taken from the following list, and *func* must be a callable object accepting +the correct number of arguments. The arguments are all strings, unless +otherwise stated. + + +.. method:: xmlparser.XmlDeclHandler(version, encoding, standalone) + + Called when the XML declaration is parsed. The XML declaration is the + (optional) declaration of the applicable version of the XML recommendation, the + encoding of the document text, and an optional "standalone" declaration. + *version* and *encoding* will be strings, and *standalone* will be ``1`` if the + document is declared standalone, ``0`` if it is declared not to be standalone, + or ``-1`` if the standalone clause was omitted. This is only available with + Expat version 1.95.0 or newer. + + +.. method:: xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset) + + Called when Expat begins parsing the document type declaration (``'``. + + +.. method:: xmlparser.StartCdataSectionHandler() + + Called at the start of a CDATA section. This and :attr:`EndCdataSectionHandler` + are needed to be able to identify the syntactical start and end for CDATA + sections. + + +.. method:: xmlparser.EndCdataSectionHandler() + + Called at the end of a CDATA section. + + +.. method:: xmlparser.DefaultHandler(data) + + Called for any characters in the XML document for which no applicable handler + has been specified. This means characters that are part of a construct which + could be reported, but for which no handler has been supplied. + + +.. method:: xmlparser.DefaultHandlerExpand(data) + + This is the same as the :func:`DefaultHandler`, but doesn't inhibit expansion + of internal entities. The entity reference will not be passed to the default + handler. + + +.. method:: xmlparser.NotStandaloneHandler() + + Called if the XML document hasn't been declared as being a standalone document. + This happens when there is an external subset or a reference to a parameter + entity, but the XML declaration does not set standalone to ``yes`` in an XML + declaration. If this handler returns ``0``, then the parser will raise an + :const:`XML_ERROR_NOT_STANDALONE` error. If this handler is not set, no + exception is raised by the parser for this condition. + + +.. method:: xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId) + + Called for references to external entities. *base* is the current base, as set + by a previous call to :meth:`SetBase`. The public and system identifiers, + *systemId* and *publicId*, are strings if given; if the public identifier is not + given, *publicId* will be ``None``. The *context* value is opaque and should + only be used as described below. + + For external entities to be parsed, this handler must be implemented. It is + responsible for creating the sub-parser using + ``ExternalEntityParserCreate(context)``, initializing it with the appropriate + callbacks, and parsing the entity. This handler should return an integer; if it + returns ``0``, the parser will raise an + :const:`XML_ERROR_EXTERNAL_ENTITY_HANDLING` error, otherwise parsing will + continue. + + If this handler is not provided, external entities are reported by the + :attr:`DefaultHandler` callback, if provided. + + +.. _expaterror-objects: + +ExpatError Exceptions +--------------------- + +.. sectionauthor:: Fred L. Drake, Jr. + + +:exc:`ExpatError` exceptions have a number of interesting attributes: + + +.. attribute:: ExpatError.code + + Expat's internal error number for the specific error. The + :data:`errors.messages ` dictionary maps + these error numbers to Expat's error messages. For example:: + + from xml.parsers.expat import ParserCreate, ExpatError, errors + + p = ParserCreate() + try: + p.Parse(some_xml_document) + except ExpatError as err: + print("Error:", errors.messages[err.code]) + + The :mod:`~xml.parsers.expat.errors` module also provides error message + constants and a dictionary :data:`~xml.parsers.expat.errors.codes` mapping + these messages back to the error codes, see below. + + +.. attribute:: ExpatError.lineno + + Line number on which the error was detected. The first line is numbered ``1``. + + +.. attribute:: ExpatError.offset + + Character offset into the line where the error occurred. The first column is + numbered ``0``. + + +.. _expat-example: + +Example +------- + +The following program defines three handlers that just print out their +arguments. :: + + import xml.parsers.expat + + # 3 handler functions + def start_element(name, attrs): + print('Start element:', name, attrs) + def end_element(name): + print('End element:', name) + def char_data(data): + print('Character data:', repr(data)) + + p = xml.parsers.expat.ParserCreate() + + p.StartElementHandler = start_element + p.EndElementHandler = end_element + p.CharacterDataHandler = char_data + + p.Parse(""" + Text goes here + More text + """, 1) + +The output from this program is:: + + Start element: parent {'id': 'top'} + Start element: child1 {'name': 'paul'} + Character data: 'Text goes here' + End element: child1 + Character data: '\n' + Start element: child2 {'name': 'fred'} + Character data: 'More text' + End element: child2 + Character data: '\n' + End element: parent + + +.. _expat-content-models: + +Content Model Descriptions +-------------------------- + +.. module:: xml.parsers.expat.model + +.. sectionauthor:: Fred L. Drake, Jr. + +Content models are described using nested tuples. Each tuple contains four +values: the type, the quantifier, the name, and a tuple of children. Children +are simply additional content model descriptions. + +The values of the first two fields are constants defined in the +:mod:`xml.parsers.expat.model` module. These constants can be collected in two +groups: the model type group and the quantifier group. + +The constants in the model type group are: + + +.. data:: XML_CTYPE_ANY + :noindex: + + The element named by the model name was declared to have a content model of + ``ANY``. + + +.. data:: XML_CTYPE_CHOICE + :noindex: + + The named element allows a choice from a number of options; this is used for + content models such as ``(A | B | C)``. + + +.. data:: XML_CTYPE_EMPTY + :noindex: + + Elements which are declared to be ``EMPTY`` have this model type. + + +.. data:: XML_CTYPE_MIXED + :noindex: + + +.. data:: XML_CTYPE_NAME + :noindex: + + +.. data:: XML_CTYPE_SEQ + :noindex: + + Models which represent a series of models which follow one after the other are + indicated with this model type. This is used for models such as ``(A, B, C)``. + +The constants in the quantifier group are: + + +.. data:: XML_CQUANT_NONE + :noindex: + + No modifier is given, so it can appear exactly once, as for ``A``. + + +.. data:: XML_CQUANT_OPT + :noindex: + + The model is optional: it can appear once or not at all, as for ``A?``. + + +.. data:: XML_CQUANT_PLUS + :noindex: + + The model must occur one or more times (like ``A+``). + + +.. data:: XML_CQUANT_REP + :noindex: + + The model must occur zero or more times, as for ``A*``. + + +.. _expat-errors: + +Expat error constants +--------------------- + +.. module:: xml.parsers.expat.errors + +The following constants are provided in the :mod:`xml.parsers.expat.errors` +module. These constants are useful in interpreting some of the attributes of +the :exc:`ExpatError` exception objects raised when an error has occurred. +Since for backwards compatibility reasons, the constants' value is the error +*message* and not the numeric error *code*, you do this by comparing its +:attr:`code` attribute with +:samp:`errors.codes[errors.XML_ERROR_{CONSTANT_NAME}]`. + +The ``errors`` module has the following attributes: + +.. data:: codes + + A dictionary mapping numeric error codes to their string descriptions. + + .. versionadded:: 3.2 + + +.. data:: messages + + A dictionary mapping string descriptions to their error codes. + + .. versionadded:: 3.2 + + +.. data:: XML_ERROR_ASYNC_ENTITY + + +.. data:: XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF + + An entity reference in an attribute value referred to an external entity instead + of an internal entity. + + +.. data:: XML_ERROR_BAD_CHAR_REF + + A character reference referred to a character which is illegal in XML (for + example, character ``0``, or '``�``'). + + +.. data:: XML_ERROR_BINARY_ENTITY_REF + + An entity reference referred to an entity which was declared with a notation, so + cannot be parsed. + + +.. data:: XML_ERROR_DUPLICATE_ATTRIBUTE + + An attribute was used more than once in a start tag. + + +.. data:: XML_ERROR_INCORRECT_ENCODING + + +.. data:: XML_ERROR_INVALID_TOKEN + + Raised when an input byte could not properly be assigned to a character; for + example, a NUL byte (value ``0``) in a UTF-8 input stream. + + +.. data:: XML_ERROR_JUNK_AFTER_DOC_ELEMENT + + Something other than whitespace occurred after the document element. + + +.. data:: XML_ERROR_MISPLACED_XML_PI + + An XML declaration was found somewhere other than the start of the input data. + + +.. data:: XML_ERROR_NO_ELEMENTS + + The document contains no elements (XML requires all documents to contain exactly + one top-level element).. + + +.. data:: XML_ERROR_NO_MEMORY + + Expat was not able to allocate memory internally. + + +.. data:: XML_ERROR_PARAM_ENTITY_REF + + A parameter entity reference was found where it was not allowed. + + +.. data:: XML_ERROR_PARTIAL_CHAR + + An incomplete character was found in the input. + + +.. data:: XML_ERROR_RECURSIVE_ENTITY_REF + + An entity reference contained another reference to the same entity; possibly via + a different name, and possibly indirectly. + + +.. data:: XML_ERROR_SYNTAX + + Some unspecified syntax error was encountered. + + +.. data:: XML_ERROR_TAG_MISMATCH + + An end tag did not match the innermost open start tag. + + +.. data:: XML_ERROR_UNCLOSED_TOKEN + + Some token (such as a start tag) was not closed before the end of the stream or + the next token was encountered. + + +.. data:: XML_ERROR_UNDEFINED_ENTITY + + A reference was made to an entity which was not defined. + + +.. data:: XML_ERROR_UNKNOWN_ENCODING + + The document encoding is not supported by Expat. + + +.. data:: XML_ERROR_UNCLOSED_CDATA_SECTION + + A CDATA marked section was not closed. + + +.. data:: XML_ERROR_EXTERNAL_ENTITY_HANDLING + + +.. data:: XML_ERROR_NOT_STANDALONE + + The parser determined that the document was not "standalone" though it declared + itself to be in the XML declaration, and the :attr:`NotStandaloneHandler` was + set and returned ``0``. + + +.. data:: XML_ERROR_UNEXPECTED_STATE + + +.. data:: XML_ERROR_ENTITY_DECLARED_IN_PE + + +.. data:: XML_ERROR_FEATURE_REQUIRES_XML_DTD + + An operation was requested that requires DTD support to be compiled in, but + Expat was configured without DTD support. This should never be reported by a + standard build of the :mod:`xml.parsers.expat` module. + + +.. data:: XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING + + A behavioral change was requested after parsing started that can only be changed + before parsing has started. This is (currently) only raised by + :meth:`UseForeignDTD`. + + +.. data:: XML_ERROR_UNBOUND_PREFIX + + An undeclared prefix was found when namespace processing was enabled. + + +.. data:: XML_ERROR_UNDECLARING_PREFIX + + The document attempted to remove the namespace declaration associated with a + prefix. + + +.. data:: XML_ERROR_INCOMPLETE_PE + + A parameter entity contained incomplete markup. + + +.. data:: XML_ERROR_XML_DECL + + The document contained no document element at all. + + +.. data:: XML_ERROR_TEXT_DECL + + There was an error parsing a text declaration in an external entity. + + +.. data:: XML_ERROR_PUBLICID + + Characters were found in the public id that are not allowed. + + +.. data:: XML_ERROR_SUSPENDED + + The requested operation was made on a suspended parser, but isn't allowed. This + includes attempts to provide additional input or to stop the parser. + + +.. data:: XML_ERROR_NOT_SUSPENDED + + An attempt to resume the parser was made when the parser had not been suspended. + + +.. data:: XML_ERROR_ABORTED + + This should not be reported to Python applications. + + +.. data:: XML_ERROR_FINISHED + + The requested operation was made on a parser which was finished parsing input, + but isn't allowed. This includes attempts to provide additional input or to + stop the parser. + + +.. data:: XML_ERROR_SUSPEND_PE + + +.. rubric:: Footnotes + +.. [1] The encoding string included in XML output should conform to the + appropriate standards. For example, "UTF-8" is valid, but "UTF8" is + not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl + and https://www.iana.org/assignments/character-sets/character-sets.xhtml. + diff --git a/cpython_2/environment/repo/Doc/library/python.rst b/cpython_2/environment/repo/Doc/library/python.rst new file mode 100644 index 0000000000000000000000000000000000000000..f39613f572884f07641e0e77a0aae2f5942287c2 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/python.rst @@ -0,0 +1,27 @@ +.. _python: + +*********************** +Python Runtime Services +*********************** + +The modules described in this chapter provide a wide range of services related +to the Python interpreter and its interaction with its environment. Here's an +overview: + + +.. toctree:: + + sys.rst + sysconfig.rst + builtins.rst + __main__.rst + warnings.rst + dataclasses.rst + contextlib.rst + abc.rst + atexit.rst + traceback.rst + __future__.rst + gc.rst + inspect.rst + site.rst diff --git a/cpython_2/environment/repo/Doc/library/queue.rst b/cpython_2/environment/repo/Doc/library/queue.rst new file mode 100644 index 0000000000000000000000000000000000000000..0ec5900bef5bbff6da218e066b9d4f1ac8998876 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/queue.rst @@ -0,0 +1,280 @@ +:mod:`queue` --- A synchronized queue class +=========================================== + +.. module:: queue + :synopsis: A synchronized queue class. + +**Source code:** :source:`Lib/queue.py` + +-------------- + +The :mod:`queue` module implements multi-producer, multi-consumer queues. +It is especially useful in threaded programming when information must be +exchanged safely between multiple threads. The :class:`Queue` class in this +module implements all the required locking semantics. + +The module implements three types of queue, which differ only in the order in +which the entries are retrieved. In a :abbr:`FIFO (first-in, first-out)` +queue, the first tasks added are the first retrieved. In a +:abbr:`LIFO (last-in, first-out)` queue, the most recently added entry is +the first retrieved (operating like a stack). With a priority queue, +the entries are kept sorted (using the :mod:`heapq` module) and the +lowest valued entry is retrieved first. + +Internally, those three types of queues use locks to temporarily block +competing threads; however, they are not designed to handle reentrancy +within a thread. + +In addition, the module implements a "simple" +:abbr:`FIFO (first-in, first-out)` queue type, :class:`SimpleQueue`, whose +specific implementation provides additional guarantees +in exchange for the smaller functionality. + +The :mod:`queue` module defines the following classes and exceptions: + +.. class:: Queue(maxsize=0) + + Constructor for a :abbr:`FIFO (first-in, first-out)` queue. *maxsize* is + an integer that sets the upperbound + limit on the number of items that can be placed in the queue. Insertion will + block once this size has been reached, until queue items are consumed. If + *maxsize* is less than or equal to zero, the queue size is infinite. + +.. class:: LifoQueue(maxsize=0) + + Constructor for a :abbr:`LIFO (last-in, first-out)` queue. *maxsize* is + an integer that sets the upperbound + limit on the number of items that can be placed in the queue. Insertion will + block once this size has been reached, until queue items are consumed. If + *maxsize* is less than or equal to zero, the queue size is infinite. + + +.. class:: PriorityQueue(maxsize=0) + + Constructor for a priority queue. *maxsize* is an integer that sets the upperbound + limit on the number of items that can be placed in the queue. Insertion will + block once this size has been reached, until queue items are consumed. If + *maxsize* is less than or equal to zero, the queue size is infinite. + + The lowest valued entries are retrieved first (the lowest valued entry is the + one returned by ``sorted(list(entries))[0]``). A typical pattern for entries + is a tuple in the form: ``(priority_number, data)``. + + If the *data* elements are not comparable, the data can be wrapped in a class + that ignores the data item and only compares the priority number:: + + from dataclasses import dataclass, field + from typing import Any + + @dataclass(order=True) + class PrioritizedItem: + priority: int + item: Any=field(compare=False) + +.. class:: SimpleQueue() + + Constructor for an unbounded :abbr:`FIFO (first-in, first-out)` queue. + Simple queues lack advanced functionality such as task tracking. + + .. versionadded:: 3.7 + + +.. exception:: Empty + + Exception raised when non-blocking :meth:`~Queue.get` (or + :meth:`~Queue.get_nowait`) is called + on a :class:`Queue` object which is empty. + + +.. exception:: Full + + Exception raised when non-blocking :meth:`~Queue.put` (or + :meth:`~Queue.put_nowait`) is called + on a :class:`Queue` object which is full. + + +.. _queueobjects: + +Queue Objects +------------- + +Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`) +provide the public methods described below. + + +.. method:: Queue.qsize() + + Return the approximate size of the queue. Note, qsize() > 0 doesn't + guarantee that a subsequent get() will not block, nor will qsize() < maxsize + guarantee that put() will not block. + + +.. method:: Queue.empty() + + Return ``True`` if the queue is empty, ``False`` otherwise. If empty() + returns ``True`` it doesn't guarantee that a subsequent call to put() + will not block. Similarly, if empty() returns ``False`` it doesn't + guarantee that a subsequent call to get() will not block. + + +.. method:: Queue.full() + + Return ``True`` if the queue is full, ``False`` otherwise. If full() + returns ``True`` it doesn't guarantee that a subsequent call to get() + will not block. Similarly, if full() returns ``False`` it doesn't + guarantee that a subsequent call to put() will not block. + + +.. method:: Queue.put(item, block=True, timeout=None) + + Put *item* into the queue. If optional args *block* is true 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:`Full` exception if no free slot was available within that time. + Otherwise (*block* is false), put an item on the queue if a free slot is + immediately available, else raise the :exc:`Full` exception (*timeout* is + ignored in that case). + + +.. method:: Queue.put_nowait(item) + + Equivalent to ``put(item, False)``. + + +.. method:: Queue.get(block=True, timeout=None) + + Remove and return an item from the queue. If optional args *block* is true and + *timeout* is ``None`` (the default), block if necessary until an item is available. + If *timeout* is a positive number, it blocks at most *timeout* seconds and + raises the :exc:`Empty` exception if no item was available within that time. + Otherwise (*block* is false), return an item if one is immediately available, + else raise the :exc:`Empty` exception (*timeout* is ignored in that case). + + Prior to 3.0 on POSIX systems, and for all versions on Windows, if + *block* is true and *timeout* is ``None``, this operation goes into + an uninterruptible wait on an underlying lock. This means that no exceptions + can occur, and in particular a SIGINT will not trigger a :exc:`KeyboardInterrupt`. + + +.. method:: Queue.get_nowait() + + Equivalent to ``get(False)``. + +Two methods are offered to support tracking whether enqueued tasks have been +fully processed by daemon consumer threads. + + +.. method:: Queue.task_done() + + Indicate that a formerly enqueued task is complete. Used by queue consumer + threads. For each :meth:`get` used to fetch a task, a subsequent call to + :meth:`task_done` tells the queue that the processing on the task is complete. + + If a :meth:`join` is currently blocking, it will resume when all items have been + processed (meaning that a :meth:`task_done` call was received for every item + that had been :meth:`put` into the queue). + + Raises a :exc:`ValueError` if called more times than there were items placed in + the queue. + + +.. method:: Queue.join() + + Blocks until all items in the queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the queue. + The count goes down whenever a consumer thread calls :meth:`task_done` to + indicate that the item was retrieved and all work on it is complete. When the + count of unfinished tasks drops to zero, :meth:`join` unblocks. + + +Example of how to wait for enqueued tasks to be completed:: + + import threading, queue + + q = queue.Queue() + + def worker(): + while True: + item = q.get() + print(f'Working on {item}') + print(f'Finished {item}') + q.task_done() + + # turn-on the worker thread + threading.Thread(target=worker, daemon=True).start() + + # send thirty task requests to the worker + for item in range(30): + q.put(item) + print('All task requests sent\n', end='') + + # block until all tasks are done + q.join() + print('All work completed') + + +SimpleQueue Objects +------------------- + +:class:`SimpleQueue` objects provide the public methods described below. + +.. method:: SimpleQueue.qsize() + + Return the approximate size of the queue. Note, qsize() > 0 doesn't + guarantee that a subsequent get() will not block. + + +.. method:: SimpleQueue.empty() + + Return ``True`` if the queue is empty, ``False`` otherwise. If empty() + returns ``False`` it doesn't guarantee that a subsequent call to get() + will not block. + + +.. method:: SimpleQueue.put(item, block=True, timeout=None) + + Put *item* into the queue. The method never blocks and always succeeds + (except for potential low-level errors such as failure to allocate memory). + The optional args *block* and *timeout* are ignored and only provided + for compatibility with :meth:`Queue.put`. + + .. impl-detail:: + This method has a C implementation which is reentrant. That is, a + ``put()`` or ``get()`` call can be interrupted by another ``put()`` + call in the same thread without deadlocking or corrupting internal + state inside the queue. This makes it appropriate for use in + destructors such as ``__del__`` methods or :mod:`weakref` callbacks. + + +.. method:: SimpleQueue.put_nowait(item) + + Equivalent to ``put(item)``, provided for compatibility with + :meth:`Queue.put_nowait`. + + +.. method:: SimpleQueue.get(block=True, timeout=None) + + Remove and return an item from the queue. If optional args *block* is true and + *timeout* is ``None`` (the default), block if necessary until an item is available. + If *timeout* is a positive number, it blocks at most *timeout* seconds and + raises the :exc:`Empty` exception if no item was available within that time. + Otherwise (*block* is false), return an item if one is immediately available, + else raise the :exc:`Empty` exception (*timeout* is ignored in that case). + + +.. method:: SimpleQueue.get_nowait() + + Equivalent to ``get(False)``. + + +.. seealso:: + + Class :class:`multiprocessing.Queue` + A queue class for use in a multi-processing (rather than multi-threading) + context. + + :class:`collections.deque` is an alternative implementation of unbounded + queues with fast atomic :meth:`~collections.deque.append` and + :meth:`~collections.deque.popleft` operations that do not require locking + and also support indexing. diff --git a/cpython_2/environment/repo/Doc/library/quopri.rst b/cpython_2/environment/repo/Doc/library/quopri.rst new file mode 100644 index 0000000000000000000000000000000000000000..86717c00c3c1366cb2a5aa58e95dd984e88ebafa --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/quopri.rst @@ -0,0 +1,63 @@ +:mod:`quopri` --- Encode and decode MIME quoted-printable data +============================================================== + +.. module:: quopri + :synopsis: Encode and decode files using the MIME quoted-printable encoding. + +**Source code:** :source:`Lib/quopri.py` + +.. index:: + pair: quoted-printable; encoding + single: MIME; quoted-printable encoding + +-------------- + +This module performs quoted-printable transport encoding and decoding, as +defined in :rfc:`1521`: "MIME (Multipurpose Internet Mail Extensions) Part One: +Mechanisms for Specifying and Describing the Format of Internet Message Bodies". +The quoted-printable encoding is designed for data where there are relatively +few nonprintable characters; the base64 encoding scheme available via the +:mod:`base64` module is more compact if there are many such characters, as when +sending a graphics file. + +.. function:: decode(input, output, header=False) + + Decode the contents of the *input* file and write the resulting decoded binary + data to the *output* file. *input* and *output* must be :term:`binary file objects + `. If the optional argument *header* is present and true, underscore + will be decoded as space. This is used to decode "Q"-encoded headers as + described in :rfc:`1522`: "MIME (Multipurpose Internet Mail Extensions) + Part Two: Message Header Extensions for Non-ASCII Text". + + +.. function:: encode(input, output, quotetabs, header=False) + + Encode the contents of the *input* file and write the resulting quoted-printable + data to the *output* file. *input* and *output* must be + :term:`binary file objects `. *quotetabs*, a + non-optional flag which controls whether to encode embedded spaces + and tabs; when true it encodes such embedded whitespace, and when + false it leaves them unencoded. + Note that spaces and tabs appearing at the end of lines are always encoded, + as per :rfc:`1521`. *header* is a flag which controls if spaces are encoded + as underscores as per :rfc:`1522`. + + +.. function:: decodestring(s, header=False) + + Like :func:`decode`, except that it accepts a source :class:`bytes` and + returns the corresponding decoded :class:`bytes`. + + +.. function:: encodestring(s, quotetabs=False, header=False) + + Like :func:`encode`, except that it accepts a source :class:`bytes` and + returns the corresponding encoded :class:`bytes`. By default, it sends a + ``False`` value to *quotetabs* parameter of the :func:`encode` function. + + + +.. seealso:: + + Module :mod:`base64` + Encode and decode MIME base64 data diff --git a/cpython_2/environment/repo/Doc/library/random.rst b/cpython_2/environment/repo/Doc/library/random.rst new file mode 100644 index 0000000000000000000000000000000000000000..90366f499cae6a2a3ddb8c220bc4d0c559067e0c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/random.rst @@ -0,0 +1,538 @@ +:mod:`random` --- Generate pseudo-random numbers +================================================ + +.. module:: random + :synopsis: Generate pseudo-random numbers with various common distributions. + +**Source code:** :source:`Lib/random.py` + +-------------- + +This module implements pseudo-random number generators for various +distributions. + +For integers, there is uniform selection from a range. For sequences, there is +uniform selection of a random element, a function to generate a random +permutation of a list in-place, and a function for random sampling without +replacement. + +On the real line, there are functions to compute uniform, normal (Gaussian), +lognormal, negative exponential, gamma, and beta distributions. For generating +distributions of angles, the von Mises distribution is available. + +Almost all module functions depend on the basic function :func:`.random`, which +generates a random float uniformly in the semi-open range [0.0, 1.0). Python +uses the Mersenne Twister as the core generator. It produces 53-bit precision +floats and has a period of 2\*\*19937-1. The underlying implementation in C is +both fast and threadsafe. The Mersenne Twister is one of the most extensively +tested random number generators in existence. However, being completely +deterministic, it is not suitable for all purposes, and is completely unsuitable +for cryptographic purposes. + +The functions supplied by this module are actually bound methods of a hidden +instance of the :class:`random.Random` class. You can instantiate your own +instances of :class:`Random` to get generators that don't share state. + +Class :class:`Random` can also be subclassed if you want to use a different +basic generator of your own devising: in that case, override the :meth:`~Random.random`, +:meth:`~Random.seed`, :meth:`~Random.getstate`, and :meth:`~Random.setstate` methods. +Optionally, a new generator can supply a :meth:`~Random.getrandbits` method --- this +allows :meth:`randrange` to produce selections over an arbitrarily large range. + +The :mod:`random` module also provides the :class:`SystemRandom` class which +uses the system function :func:`os.urandom` to generate random numbers +from sources provided by the operating system. + +.. warning:: + + The pseudo-random generators of this module should not be used for + security purposes. For security or cryptographic uses, see the + :mod:`secrets` module. + +.. seealso:: + + M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally + equidistributed uniform pseudorandom number generator", ACM Transactions on + Modeling and Computer Simulation Vol. 8, No. 1, January pp.3--30 1998. + + + `Complementary-Multiply-with-Carry recipe + `_ for a compatible alternative + random number generator with a long period and comparatively simple update + operations. + + +Bookkeeping functions +--------------------- + +.. function:: seed(a=None, version=2) + + Initialize the random number generator. + + If *a* is omitted or ``None``, the current system time is used. If + randomness sources are provided by the operating system, they are used + instead of the system time (see the :func:`os.urandom` function for details + on availability). + + If *a* is an int, it is used directly. + + With version 2 (the default), a :class:`str`, :class:`bytes`, or :class:`bytearray` + object gets converted to an :class:`int` and all of its bits are used. + + With version 1 (provided for reproducing random sequences from older versions + of Python), the algorithm for :class:`str` and :class:`bytes` generates a + narrower range of seeds. + + .. versionchanged:: 3.2 + Moved to the version 2 scheme which uses all of the bits in a string seed. + + .. deprecated:: 3.9 + In the future, the *seed* must be one of the following types: + *NoneType*, :class:`int`, :class:`float`, :class:`str`, + :class:`bytes`, or :class:`bytearray`. + +.. function:: getstate() + + Return an object capturing the current internal state of the generator. This + object can be passed to :func:`setstate` to restore the state. + + +.. function:: setstate(state) + + *state* should have been obtained from a previous call to :func:`getstate`, and + :func:`setstate` restores the internal state of the generator to what it was at + the time :func:`getstate` was called. + + +Functions for bytes +------------------- + +.. function:: randbytes(n) + + Generate *n* random bytes. + + This method should not be used for generating security tokens. + Use :func:`secrets.token_bytes` instead. + + .. versionadded:: 3.9 + + +Functions for integers +---------------------- + +.. function:: randrange(stop) + randrange(start, stop[, step]) + + Return a randomly selected element from ``range(start, stop, step)``. This is + equivalent to ``choice(range(start, stop, step))``, but doesn't actually build a + range object. + + The positional argument pattern matches that of :func:`range`. Keyword arguments + should not be used because the function may use them in unexpected ways. + + .. versionchanged:: 3.2 + :meth:`randrange` is more sophisticated about producing equally distributed + values. Formerly it used a style like ``int(random()*n)`` which could produce + slightly uneven distributions. + +.. function:: randint(a, b) + + Return a random integer *N* such that ``a <= N <= b``. Alias for + ``randrange(a, b+1)``. + +.. function:: getrandbits(k) + + Returns a Python integer with *k* random bits. This method is supplied with + the MersenneTwister generator and some other generators may also provide it + as an optional part of the API. When available, :meth:`getrandbits` enables + :meth:`randrange` to handle arbitrarily large ranges. + + .. versionchanged:: 3.9 + This method now accepts zero for *k*. + + +Functions for sequences +----------------------- + +.. function:: choice(seq) + + Return a random element from the non-empty sequence *seq*. If *seq* is empty, + raises :exc:`IndexError`. + +.. function:: choices(population, weights=None, *, cum_weights=None, k=1) + + Return a *k* sized list of elements chosen from the *population* with replacement. + If the *population* is empty, raises :exc:`IndexError`. + + If a *weights* sequence is specified, selections are made according to the + relative weights. Alternatively, if a *cum_weights* sequence is given, the + selections are made according to the cumulative weights (perhaps computed + using :func:`itertools.accumulate`). For example, the relative weights + ``[10, 5, 30, 5]`` are equivalent to the cumulative weights + ``[10, 15, 45, 50]``. Internally, the relative weights are converted to + cumulative weights before making selections, so supplying the cumulative + weights saves work. + + If neither *weights* nor *cum_weights* are specified, selections are made + with equal probability. If a weights sequence is supplied, it must be + the same length as the *population* sequence. It is a :exc:`TypeError` + to specify both *weights* and *cum_weights*. + + The *weights* or *cum_weights* can use any numeric type that interoperates + with the :class:`float` values returned by :func:`random` (that includes + integers, floats, and fractions but excludes decimals). Behavior is + undefined if any weight is negative. A :exc:`ValueError` is raised if all + weights are zero. + + For a given seed, the :func:`choices` function with equal weighting + typically produces a different sequence than repeated calls to + :func:`choice`. The algorithm used by :func:`choices` uses floating + point arithmetic for internal consistency and speed. The algorithm used + by :func:`choice` defaults to integer arithmetic with repeated selections + to avoid small biases from round-off error. + + .. versionadded:: 3.6 + + .. versionchanged:: 3.9 + Raises a :exc:`ValueError` if all weights are zero. + + +.. function:: shuffle(x[, random]) + + Shuffle the sequence *x* in place. + + The optional argument *random* is a 0-argument function returning a random + float in [0.0, 1.0); by default, this is the function :func:`.random`. + + To shuffle an immutable sequence and return a new shuffled list, use + ``sample(x, k=len(x))`` instead. + + Note that even for small ``len(x)``, the total number of permutations of *x* + can quickly grow larger than the period of most random number generators. + This implies that most permutations of a long sequence can never be + generated. For example, a sequence of length 2080 is the largest that + can fit within the period of the Mersenne Twister random number generator. + + .. deprecated-removed:: 3.9 3.11 + The optional parameter *random*. + + +.. function:: sample(population, k, *, counts=None) + + Return a *k* length list of unique elements chosen from the population sequence + or set. Used for random sampling without replacement. + + Returns a new list containing elements from the population while leaving the + original population unchanged. The resulting list is in selection order so that + all sub-slices will also be valid random samples. This allows raffle winners + (the sample) to be partitioned into grand prize and second place winners (the + subslices). + + Members of the population need not be :term:`hashable` or unique. If the population + contains repeats, then each occurrence is a possible selection in the sample. + + Repeated elements can be specified one at a time or with the optional + keyword-only *counts* parameter. For example, ``sample(['red', 'blue'], + counts=[4, 2], k=5)`` is equivalent to ``sample(['red', 'red', 'red', 'red', + 'blue', 'blue'], k=5)``. + + To choose a sample from a range of integers, use a :func:`range` object as an + argument. This is especially fast and space efficient for sampling from a large + population: ``sample(range(10000000), k=60)``. + + If the sample size is larger than the population size, a :exc:`ValueError` + is raised. + + .. versionchanged:: 3.9 + Added the *counts* parameter. + + .. deprecated:: 3.9 + In the future, the *population* must be a sequence. Instances of + :class:`set` are no longer supported. The set must first be converted + to a :class:`list` or :class:`tuple`, preferably in a deterministic + order so that the sample is reproducible. + + +Real-valued distributions +------------------------- + +The following functions generate specific real-valued distributions. Function +parameters are named after the corresponding variables in the distribution's +equation, as used in common mathematical practice; most of these equations can +be found in any statistics text. + + +.. function:: random() + + Return the next random floating point number in the range [0.0, 1.0). + + +.. function:: uniform(a, b) + + Return a random floating point number *N* such that ``a <= N <= b`` for + ``a <= b`` and ``b <= N <= a`` for ``b < a``. + + The end-point value ``b`` may or may not be included in the range + depending on floating-point rounding in the equation ``a + (b-a) * random()``. + + +.. function:: triangular(low, high, mode) + + Return a random floating point number *N* such that ``low <= N <= high`` and + with the specified *mode* between those bounds. The *low* and *high* bounds + default to zero and one. The *mode* argument defaults to the midpoint + between the bounds, giving a symmetric distribution. + + +.. function:: betavariate(alpha, beta) + + Beta distribution. Conditions on the parameters are ``alpha > 0`` and + ``beta > 0``. Returned values range between 0 and 1. + + +.. function:: expovariate(lambd) + + Exponential distribution. *lambd* is 1.0 divided by the desired + mean. It should be nonzero. (The parameter would be called + "lambda", but that is a reserved word in Python.) Returned values + range from 0 to positive infinity if *lambd* is positive, and from + negative infinity to 0 if *lambd* is negative. + + +.. function:: gammavariate(alpha, beta) + + Gamma distribution. (*Not* the gamma function!) Conditions on the + parameters are ``alpha > 0`` and ``beta > 0``. + + The probability distribution function is:: + + x ** (alpha - 1) * math.exp(-x / beta) + pdf(x) = -------------------------------------- + math.gamma(alpha) * beta ** alpha + + +.. function:: gauss(mu, sigma) + + Gaussian distribution. *mu* is the mean, and *sigma* is the standard + deviation. This is slightly faster than the :func:`normalvariate` function + defined below. + + +.. function:: lognormvariate(mu, sigma) + + Log normal distribution. If you take the natural logarithm of this + distribution, you'll get a normal distribution with mean *mu* and standard + deviation *sigma*. *mu* can have any value, and *sigma* must be greater than + zero. + + +.. function:: normalvariate(mu, sigma) + + Normal distribution. *mu* is the mean, and *sigma* is the standard deviation. + + +.. function:: vonmisesvariate(mu, kappa) + + *mu* is the mean angle, expressed in radians between 0 and 2\*\ *pi*, and *kappa* + is the concentration parameter, which must be greater than or equal to zero. If + *kappa* is equal to zero, this distribution reduces to a uniform random angle + over the range 0 to 2\*\ *pi*. + + +.. function:: paretovariate(alpha) + + Pareto distribution. *alpha* is the shape parameter. + + +.. function:: weibullvariate(alpha, beta) + + Weibull distribution. *alpha* is the scale parameter and *beta* is the shape + parameter. + + +Alternative Generator +--------------------- + +.. class:: Random([seed]) + + Class that implements the default pseudo-random number generator used by the + :mod:`random` module. + + .. deprecated:: 3.9 + In the future, the *seed* must be one of the following types: + :class:`NoneType`, :class:`int`, :class:`float`, :class:`str`, + :class:`bytes`, or :class:`bytearray`. + +.. class:: SystemRandom([seed]) + + Class that uses the :func:`os.urandom` function for generating random numbers + from sources provided by the operating system. Not available on all systems. + Does not rely on software state, and sequences are not reproducible. Accordingly, + the :meth:`seed` method has no effect and is ignored. + The :meth:`getstate` and :meth:`setstate` methods raise + :exc:`NotImplementedError` if called. + + +Notes on Reproducibility +------------------------ + +Sometimes it is useful to be able to reproduce the sequences given by a +pseudo-random number generator. By re-using a seed value, the same sequence should be +reproducible from run to run as long as multiple threads are not running. + +Most of the random module's algorithms and seeding functions are subject to +change across Python versions, but two aspects are guaranteed not to change: + +* If a new seeding method is added, then a backward compatible seeder will be + offered. + +* The generator's :meth:`~Random.random` method will continue to produce the same + sequence when the compatible seeder is given the same seed. + +.. _random-examples: + +Examples and Recipes +-------------------- + +Basic examples:: + + >>> random() # Random float: 0.0 <= x < 1.0 + 0.37444887175646646 + + >>> uniform(2.5, 10.0) # Random float: 2.5 <= x < 10.0 + 3.1800146073117523 + + >>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds + 5.148957571865031 + + >>> randrange(10) # Integer from 0 to 9 inclusive + 7 + + >>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive + 26 + + >>> choice(['win', 'lose', 'draw']) # Single random element from a sequence + 'draw' + + >>> deck = 'ace two three four'.split() + >>> shuffle(deck) # Shuffle a list + >>> deck + ['four', 'two', 'ace', 'three'] + + >>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement + [40, 10, 50, 30] + +Simulations:: + + >>> # Six roulette wheel spins (weighted sampling with replacement) + >>> choices(['red', 'black', 'green'], [18, 18, 2], k=6) + ['red', 'green', 'black', 'black', 'red', 'black'] + + >>> # Deal 20 cards without replacement from a deck + >>> # of 52 playing cards, and determine the proportion of cards + >>> # with a ten-value: ten, jack, queen, or king. + >>> dealt = sample(['tens', 'low cards'], counts=[16, 36], k=20) + >>> dealt.count('tens') / 20 + 0.15 + + >>> # Estimate the probability of getting 5 or more heads from 7 spins + >>> # of a biased coin that settles on heads 60% of the time. + >>> def trial(): + ... return choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5 + ... + >>> sum(trial() for i in range(10_000)) / 10_000 + 0.4169 + + >>> # Probability of the median of 5 samples being in middle two quartiles + >>> def trial(): + ... return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500 + ... + >>> sum(trial() for i in range(10_000)) / 10_000 + 0.7958 + +Example of `statistical bootstrapping +`_ using resampling +with replacement to estimate a confidence interval for the mean of a sample:: + + # http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm + from statistics import fmean as mean + from random import choices + + data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95] + means = sorted(mean(choices(data, k=len(data))) for i in range(100)) + print(f'The sample mean of {mean(data):.1f} has a 90% confidence ' + f'interval from {means[5]:.1f} to {means[94]:.1f}') + +Example of a `resampling permutation test +`_ +to determine the statistical significance or `p-value +`_ of an observed difference +between the effects of a drug versus a placebo:: + + # Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson + from statistics import fmean as mean + from random import shuffle + + drug = [54, 73, 53, 70, 73, 68, 52, 65, 65] + placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46] + observed_diff = mean(drug) - mean(placebo) + + n = 10_000 + count = 0 + combined = drug + placebo + for i in range(n): + shuffle(combined) + new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):]) + count += (new_diff >= observed_diff) + + print(f'{n} label reshufflings produced only {count} instances with a difference') + print(f'at least as extreme as the observed difference of {observed_diff:.1f}.') + print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null') + print(f'hypothesis that there is no difference between the drug and the placebo.') + +Simulation of arrival times and service deliveries for a multiserver queue:: + + from heapq import heappush, heappop + from random import expovariate, gauss + from statistics import mean, median, stdev + + average_arrival_interval = 5.6 + average_service_time = 15.0 + stdev_service_time = 3.5 + num_servers = 3 + + waits = [] + arrival_time = 0.0 + servers = [0.0] * num_servers # time when each server becomes available + for i in range(100_000): + arrival_time += expovariate(1.0 / average_arrival_interval) + next_server_available = heappop(servers) + wait = max(0.0, next_server_available - arrival_time) + waits.append(wait) + service_duration = gauss(average_service_time, stdev_service_time) + service_completed = arrival_time + wait + service_duration + heappush(servers, service_completed) + + print(f'Mean wait: {mean(waits):.1f}. Stdev wait: {stdev(waits):.1f}.') + print(f'Median wait: {median(waits):.1f}. Max wait: {max(waits):.1f}.') + +.. seealso:: + + `Statistics for Hackers `_ + a video tutorial by + `Jake Vanderplas `_ + on statistical analysis using just a few fundamental concepts + including simulation, sampling, shuffling, and cross-validation. + + `Economics Simulation + `_ + a simulation of a marketplace by + `Peter Norvig `_ that shows effective + use of many of the tools and distributions provided by this module + (gauss, uniform, sample, betavariate, choice, triangular, and randrange). + + `A Concrete Introduction to Probability (using Python) + `_ + a tutorial by `Peter Norvig `_ covering + the basics of probability theory, how to write simulations, and + how to perform data analysis using Python. diff --git a/cpython_2/environment/repo/Doc/library/re.rst b/cpython_2/environment/repo/Doc/library/re.rst new file mode 100644 index 0000000000000000000000000000000000000000..9abbd8ba73616eeceae8adb72abf884a34a33aae --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/re.rst @@ -0,0 +1,1698 @@ +:mod:`re` --- Regular expression operations +=========================================== + +.. module:: re + :synopsis: Regular expression operations. + +.. moduleauthor:: Fredrik Lundh +.. sectionauthor:: Andrew M. Kuchling + +**Source code:** :source:`Lib/re.py` + +-------------- + +This module provides regular expression matching operations similar to +those found in Perl. + +Both patterns and strings to be searched can be Unicode strings (:class:`str`) +as well as 8-bit strings (:class:`bytes`). +However, Unicode strings and 8-bit strings cannot be mixed: +that is, you cannot match a Unicode string with a byte pattern or +vice-versa; similarly, when asking for a substitution, the replacement +string must be of the same type as both the pattern and the search string. + +Regular expressions use the backslash character (``'\'``) to indicate +special forms or to allow special characters to be used without invoking +their special meaning. This collides with Python's usage of the same +character for the same purpose in string literals; for example, to match +a literal backslash, one might have to write ``'\\\\'`` as the pattern +string, because the regular expression must be ``\\``, and each +backslash must be expressed as ``\\`` inside a regular Python string +literal. Also, please note that any invalid escape sequences in Python's +usage of the backslash in string literals now generate a :exc:`DeprecationWarning` +and in the future this will become a :exc:`SyntaxError`. This behaviour +will happen even if it is a valid escape sequence for a regular expression. + +The solution is to use Python's raw string notation for regular expression +patterns; backslashes are not handled in any special way in a string literal +prefixed with ``'r'``. So ``r"\n"`` is a two-character string containing +``'\'`` and ``'n'``, while ``"\n"`` is a one-character string containing a +newline. Usually patterns will be expressed in Python code using this raw +string notation. + +It is important to note that most regular expression operations are available as +module-level functions and methods on +:ref:`compiled regular expressions `. The functions are shortcuts +that don't require you to compile a regex object first, but miss some +fine-tuning parameters. + +.. seealso:: + + The third-party `regex `_ module, + which has an API compatible with the standard library :mod:`re` module, + but offers additional functionality and a more thorough Unicode support. + + +.. _re-syntax: + +Regular Expression Syntax +------------------------- + +A regular expression (or RE) specifies a set of strings that matches it; the +functions in this module let you check if a particular string matches a given +regular expression (or if a given regular expression matches a particular +string, which comes down to the same thing). + +Regular expressions can be concatenated to form new regular expressions; if *A* +and *B* are both regular expressions, then *AB* is also a regular expression. +In general, if a string *p* matches *A* and another string *q* matches *B*, the +string *pq* will match AB. This holds unless *A* or *B* contain low precedence +operations; boundary conditions between *A* and *B*; or have numbered group +references. Thus, complex expressions can easily be constructed from simpler +primitive expressions like the ones described here. For details of the theory +and implementation of regular expressions, consult the Friedl book [Frie09]_, +or almost any textbook about compiler construction. + +A brief explanation of the format of regular expressions follows. For further +information and a gentler presentation, consult the :ref:`regex-howto`. + +Regular expressions can contain both special and ordinary characters. Most +ordinary characters, like ``'A'``, ``'a'``, or ``'0'``, are the simplest regular +expressions; they simply match themselves. You can concatenate ordinary +characters, so ``last`` matches the string ``'last'``. (In the rest of this +section, we'll write RE's in ``this special style``, usually without quotes, and +strings to be matched ``'in single quotes'``.) + +Some characters, like ``'|'`` or ``'('``, are special. Special +characters either stand for classes of ordinary characters, or affect +how the regular expressions around them are interpreted. + +Repetition qualifiers (``*``, ``+``, ``?``, ``{m,n}``, etc) cannot be +directly nested. This avoids ambiguity with the non-greedy modifier suffix +``?``, and with other modifiers in other implementations. To apply a second +repetition to an inner repetition, parentheses may be used. For example, +the expression ``(?:a{6})*`` matches any multiple of six ``'a'`` characters. + + +The special characters are: + +.. index:: single: . (dot); in regular expressions + +``.`` + (Dot.) In the default mode, this matches any character except a newline. If + the :const:`DOTALL` flag has been specified, this matches any character + including a newline. + +.. index:: single: ^ (caret); in regular expressions + +``^`` + (Caret.) Matches the start of the string, and in :const:`MULTILINE` mode also + matches immediately after each newline. + +.. index:: single: $ (dollar); in regular expressions + +``$`` + Matches the end of the string or just before the newline at the end of the + string, and in :const:`MULTILINE` mode also matches before a newline. ``foo`` + matches both 'foo' and 'foobar', while the regular expression ``foo$`` matches + only 'foo'. More interestingly, searching for ``foo.$`` in ``'foo1\nfoo2\n'`` + matches 'foo2' normally, but 'foo1' in :const:`MULTILINE` mode; searching for + a single ``$`` in ``'foo\n'`` will find two (empty) matches: one just before + the newline, and one at the end of the string. + +.. index:: single: * (asterisk); in regular expressions + +``*`` + Causes the resulting RE to match 0 or more repetitions of the preceding RE, as + many repetitions as are possible. ``ab*`` will match 'a', 'ab', or 'a' followed + by any number of 'b's. + +.. index:: single: + (plus); in regular expressions + +``+`` + Causes the resulting RE to match 1 or more repetitions of the preceding RE. + ``ab+`` will match 'a' followed by any non-zero number of 'b's; it will not + match just 'a'. + +.. index:: single: ? (question mark); in regular expressions + +``?`` + Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. + ``ab?`` will match either 'a' or 'ab'. + +.. index:: + single: *?; in regular expressions + single: +?; in regular expressions + single: ??; in regular expressions + +``*?``, ``+?``, ``??`` + The ``'*'``, ``'+'``, and ``'?'`` qualifiers are all :dfn:`greedy`; they match + as much text as possible. Sometimes this behaviour isn't desired; if the RE + ``<.*>`` is matched against ``' b '``, it will match the entire + string, and not just ``''``. Adding ``?`` after the qualifier makes it + perform the match in :dfn:`non-greedy` or :dfn:`minimal` fashion; as *few* + characters as possible will be matched. Using the RE ``<.*?>`` will match + only ``''``. + +.. index:: + single: {} (curly brackets); in regular expressions + +``{m}`` + Specifies that exactly *m* copies of the previous RE should be matched; fewer + matches cause the entire RE not to match. For example, ``a{6}`` will match + exactly six ``'a'`` characters, but not five. + +``{m,n}`` + Causes the resulting RE to match from *m* to *n* repetitions of the preceding + RE, attempting to match as many repetitions as possible. For example, + ``a{3,5}`` will match from 3 to 5 ``'a'`` characters. Omitting *m* specifies a + lower bound of zero, and omitting *n* specifies an infinite upper bound. As an + example, ``a{4,}b`` will match ``'aaaab'`` or a thousand ``'a'`` characters + followed by a ``'b'``, but not ``'aaab'``. The comma may not be omitted or the + modifier would be confused with the previously described form. + +``{m,n}?`` + Causes the resulting RE to match from *m* to *n* repetitions of the preceding + RE, attempting to match as *few* repetitions as possible. This is the + non-greedy version of the previous qualifier. For example, on the + 6-character string ``'aaaaaa'``, ``a{3,5}`` will match 5 ``'a'`` characters, + while ``a{3,5}?`` will only match 3 characters. + +.. index:: single: \ (backslash); in regular expressions + +``\`` + Either escapes special characters (permitting you to match characters like + ``'*'``, ``'?'``, and so forth), or signals a special sequence; special + sequences are discussed below. + + If you're not using a raw string to express the pattern, remember that Python + also uses the backslash as an escape sequence in string literals; if the escape + sequence isn't recognized by Python's parser, the backslash and subsequent + character are included in the resulting string. However, if Python would + recognize the resulting sequence, the backslash should be repeated twice. This + is complicated and hard to understand, so it's highly recommended that you use + raw strings for all but the simplest expressions. + +.. index:: + single: [] (square brackets); in regular expressions + +``[]`` + Used to indicate a set of characters. In a set: + + * Characters can be listed individually, e.g. ``[amk]`` will match ``'a'``, + ``'m'``, or ``'k'``. + + .. index:: single: - (minus); in regular expressions + + * Ranges of characters can be indicated by giving two characters and separating + them by a ``'-'``, for example ``[a-z]`` will match any lowercase ASCII letter, + ``[0-5][0-9]`` will match all the two-digits numbers from ``00`` to ``59``, and + ``[0-9A-Fa-f]`` will match any hexadecimal digit. If ``-`` is escaped (e.g. + ``[a\-z]``) or if it's placed as the first or last character + (e.g. ``[-a]`` or ``[a-]``), it will match a literal ``'-'``. + + * Special characters lose their special meaning inside sets. For example, + ``[(+*)]`` will match any of the literal characters ``'('``, ``'+'``, + ``'*'``, or ``')'``. + + .. index:: single: \ (backslash); in regular expressions + + * Character classes such as ``\w`` or ``\S`` (defined below) are also accepted + inside a set, although the characters they match depends on whether + :const:`ASCII` or :const:`LOCALE` mode is in force. + + .. index:: single: ^ (caret); in regular expressions + + * Characters that are not within a range can be matched by :dfn:`complementing` + the set. If the first character of the set is ``'^'``, all the characters + that are *not* in the set will be matched. For example, ``[^5]`` will match + any character except ``'5'``, and ``[^^]`` will match any character except + ``'^'``. ``^`` has no special meaning if it's not the first character in + the set. + + * To match a literal ``']'`` inside a set, precede it with a backslash, or + place it at the beginning of the set. For example, both ``[()[\]{}]`` and + ``[]()[{}]`` will both match a parenthesis. + + .. .. index:: single: --; in regular expressions + .. .. index:: single: &&; in regular expressions + .. .. index:: single: ~~; in regular expressions + .. .. index:: single: ||; in regular expressions + + * Support of nested sets and set operations as in `Unicode Technical + Standard #18`_ might be added in the future. This would change the + syntax, so to facilitate this change a :exc:`FutureWarning` will be raised + in ambiguous cases for the time being. + That includes sets starting with a literal ``'['`` or containing literal + character sequences ``'--'``, ``'&&'``, ``'~~'``, and ``'||'``. To + avoid a warning escape them with a backslash. + + .. _Unicode Technical Standard #18: https://unicode.org/reports/tr18/ + + .. versionchanged:: 3.7 + :exc:`FutureWarning` is raised if a character set contains constructs + that will change semantically in the future. + +.. index:: single: | (vertical bar); in regular expressions + +``|`` + ``A|B``, where *A* and *B* can be arbitrary REs, creates a regular expression that + will match either *A* or *B*. An arbitrary number of REs can be separated by the + ``'|'`` in this way. This can be used inside groups (see below) as well. As + the target string is scanned, REs separated by ``'|'`` are tried from left to + right. When one pattern completely matches, that branch is accepted. This means + that once *A* matches, *B* will not be tested further, even if it would + produce a longer overall match. In other words, the ``'|'`` operator is never + greedy. To match a literal ``'|'``, use ``\|``, or enclose it inside a + character class, as in ``[|]``. + +.. index:: + single: () (parentheses); in regular expressions + +``(...)`` + Matches whatever regular expression is inside the parentheses, and indicates the + start and end of a group; the contents of a group can be retrieved after a match + has been performed, and can be matched later in the string with the ``\number`` + special sequence, described below. To match the literals ``'('`` or ``')'``, + use ``\(`` or ``\)``, or enclose them inside a character class: ``[(]``, ``[)]``. + +.. index:: single: (?; in regular expressions + +``(?...)`` + This is an extension notation (a ``'?'`` following a ``'('`` is not meaningful + otherwise). The first character after the ``'?'`` determines what the meaning + and further syntax of the construct is. Extensions usually do not create a new + group; ``(?P...)`` is the only exception to this rule. Following are the + currently supported extensions. + +``(?aiLmsux)`` + (One or more letters from the set ``'a'``, ``'i'``, ``'L'``, ``'m'``, + ``'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.U` (Unicode matching), 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 expression, instead of passing a *flag* argument to the + :func:`re.compile` function. Flags should be used first in the + expression string. + +.. index:: single: (?:; in regular expressions + +``(?:...)`` + A non-capturing version of regular parentheses. Matches whatever regular + expression is inside the parentheses, but the substring matched by the group + *cannot* be retrieved after performing a match or referenced later in the + pattern. + +``(?aiLmsux-imsx:...)`` + (Zero or more letters from the set ``'a'``, ``'i'``, ``'L'``, ``'m'``, + ``'s'``, ``'u'``, ``'x'``, optionally followed by ``'-'`` followed by + one or more letters from the ``'i'``, ``'m'``, ``'s'``, ``'x'``.) + The letters set or remove 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.U` (Unicode matching), + and :const:`re.X` (verbose), for the part of the expression. + (The flags are described in :ref:`contents-of-module-re`.) + + The letters ``'a'``, ``'L'`` and ``'u'`` are mutually exclusive when used + as inline flags, so they can't be combined or follow ``'-'``. Instead, + when one of them appears in an inline group, it overrides the matching mode + in the enclosing group. In Unicode patterns ``(?a:...)`` switches to + ASCII-only matching, and ``(?u:...)`` switches to Unicode matching + (default). In byte pattern ``(?L:...)`` switches to locale depending + matching, and ``(?a:...)`` switches to ASCII-only matching (default). + This override is only in effect for the narrow inline group, and the + original matching mode is restored outside of the group. + + .. versionadded:: 3.6 + + .. versionchanged:: 3.7 + The letters ``'a'``, ``'L'`` and ``'u'`` also can be used in a group. + +.. index:: single: (?P<; in regular expressions + +``(?P...)`` + Similar to regular parentheses, but the substring matched by the group is + accessible via the symbolic group name *name*. Group names must be valid + Python identifiers, and each group name must be defined only once within a + regular expression. A symbolic group is also a numbered group, just as if + the group were not named. + + Named groups can be referenced in three contexts. If the pattern is + ``(?P['"]).*?(?P=quote)`` (i.e. matching a string quoted with either + single or double quotes): + + +---------------------------------------+----------------------------------+ + | Context of reference to group "quote" | Ways to reference it | + +=======================================+==================================+ + | in the same pattern itself | * ``(?P=quote)`` (as shown) | + | | * ``\1`` | + +---------------------------------------+----------------------------------+ + | when processing match object *m* | * ``m.group('quote')`` | + | | * ``m.end('quote')`` (etc.) | + +---------------------------------------+----------------------------------+ + | in a string passed to the *repl* | * ``\g`` | + | argument of ``re.sub()`` | * ``\g<1>`` | + | | * ``\1`` | + +---------------------------------------+----------------------------------+ + +.. index:: single: (?P=; in regular expressions + +``(?P=name)`` + A backreference to a named group; it matches whatever text was matched by the + earlier group named *name*. + +.. index:: single: (?#; in regular expressions + +``(?#...)`` + A comment; the contents of the parentheses are simply ignored. + +.. index:: single: (?=; in regular expressions + +``(?=...)`` + Matches if ``...`` matches next, but doesn't consume any of the string. This is + called a :dfn:`lookahead assertion`. For example, ``Isaac (?=Asimov)`` will match + ``'Isaac '`` only if it's followed by ``'Asimov'``. + +.. index:: single: (?!; in regular expressions + +``(?!...)`` + Matches if ``...`` doesn't match next. This is a :dfn:`negative lookahead assertion`. + For example, ``Isaac (?!Asimov)`` will match ``'Isaac '`` only if it's *not* + followed by ``'Asimov'``. + +.. index:: single: (?<=; in regular expressions + +``(?<=...)`` + Matches if the current position in the string is preceded by a match for ``...`` + that ends at the current position. This is called a :dfn:`positive lookbehind + assertion`. ``(?<=abc)def`` will find a match in ``'abcdef'``, since the + lookbehind will back up 3 characters and check if the contained pattern matches. + The contained pattern must only match strings of some fixed length, meaning that + ``abc`` or ``a|b`` are allowed, but ``a*`` and ``a{3,4}`` are not. Note that + patterns which start with positive lookbehind assertions will not match at the + beginning of the string being searched; you will most likely want to use the + :func:`search` function rather than the :func:`match` function: + + >>> import re + >>> m = re.search('(?<=abc)def', 'abcdef') + >>> m.group(0) + 'def' + + This example looks for a word following a hyphen: + + >>> m = re.search(r'(?<=-)\w+', 'spam-egg') + >>> m.group(0) + 'egg' + + .. versionchanged:: 3.5 + Added support for group references of fixed length. + +.. index:: single: (?|$)`` is a poor email matching pattern, which + will match with ``''`` as well as ``'user@host.com'``, but + not with ``''``. + + +The special sequences consist of ``'\'`` and a character from the list below. +If the ordinary character is not an ASCII digit or an ASCII letter, then the +resulting RE will match the second character. For example, ``\$`` matches the +character ``'$'``. + +.. index:: single: \ (backslash); in regular expressions + +``\number`` + Matches the contents of the group of the same number. Groups are numbered + starting from 1. For example, ``(.+) \1`` matches ``'the the'`` or ``'55 55'``, + but not ``'thethe'`` (note the space after the group). This special sequence + can only be used to match one of the first 99 groups. If the first digit of + *number* is 0, or *number* is 3 octal digits long, it will not be interpreted as + a group match, but as the character with octal value *number*. Inside the + ``'['`` and ``']'`` of a character class, all numeric escapes are treated as + characters. + +.. index:: single: \A; in regular expressions + +``\A`` + Matches only at the start of the string. + +.. index:: single: \b; in regular expressions + +``\b`` + Matches the empty string, but only at the beginning or end of a word. + A word is defined as a sequence of word characters. Note that formally, + ``\b`` is defined as the boundary between a ``\w`` and a ``\W`` character + (or vice versa), or between ``\w`` and the beginning/end of the string. + This means that ``r'\bfoo\b'`` matches ``'foo'``, ``'foo.'``, ``'(foo)'``, + ``'bar foo baz'`` but not ``'foobar'`` or ``'foo3'``. + + By default Unicode alphanumerics are the ones used in Unicode patterns, but + this can be changed by using the :const:`ASCII` flag. Word boundaries are + determined by the current locale if the :const:`LOCALE` flag is used. + Inside a character range, ``\b`` represents the backspace character, for + compatibility with Python's string literals. + +.. index:: single: \B; in regular expressions + +``\B`` + Matches the empty string, but only when it is *not* at the beginning or end + of a word. This means that ``r'py\B'`` matches ``'python'``, ``'py3'``, + ``'py2'``, but not ``'py'``, ``'py.'``, or ``'py!'``. + ``\B`` is just the opposite of ``\b``, so word characters in Unicode + patterns are Unicode alphanumerics or the underscore, although this can + be changed by using the :const:`ASCII` flag. Word boundaries are + determined by the current locale if the :const:`LOCALE` flag is used. + +.. index:: single: \d; in regular expressions + +``\d`` + For Unicode (str) patterns: + Matches any Unicode decimal digit (that is, any character in + Unicode character category [Nd]). This includes ``[0-9]``, and + also many other digit characters. If the :const:`ASCII` flag is + used only ``[0-9]`` is matched. + + For 8-bit (bytes) patterns: + Matches any decimal digit; this is equivalent to ``[0-9]``. + +.. index:: single: \D; in regular expressions + +``\D`` + Matches any character which is not a decimal digit. This is + the opposite of ``\d``. If the :const:`ASCII` flag is used this + becomes the equivalent of ``[^0-9]``. + +.. index:: single: \s; in regular expressions + +``\s`` + For Unicode (str) patterns: + Matches Unicode whitespace characters (which includes + ``[ \t\n\r\f\v]``, and also many other characters, for example the + non-breaking spaces mandated by typography rules in many + languages). If the :const:`ASCII` flag is used, only + ``[ \t\n\r\f\v]`` is matched. + + For 8-bit (bytes) patterns: + Matches characters considered whitespace in the ASCII character set; + this is equivalent to ``[ \t\n\r\f\v]``. + +.. index:: single: \S; in regular expressions + +``\S`` + Matches any character which is not a whitespace character. This is + the opposite of ``\s``. If the :const:`ASCII` flag is used this + becomes the equivalent of ``[^ \t\n\r\f\v]``. + +.. index:: single: \w; in regular expressions + +``\w`` + For Unicode (str) patterns: + Matches Unicode word characters; this includes most characters + that can be part of a word in any language, as well as numbers and + the underscore. If the :const:`ASCII` flag is used, only + ``[a-zA-Z0-9_]`` is matched. + + For 8-bit (bytes) patterns: + Matches characters considered alphanumeric in the ASCII character set; + this is equivalent to ``[a-zA-Z0-9_]``. If the :const:`LOCALE` flag is + used, matches characters considered alphanumeric in the current locale + and the underscore. + +.. index:: single: \W; in regular expressions + +``\W`` + Matches any character which is not a word character. This is + the opposite of ``\w``. If the :const:`ASCII` flag is used this + becomes the equivalent of ``[^a-zA-Z0-9_]``. If the :const:`LOCALE` flag is + used, matches characters which are neither alphanumeric in the current locale + nor the underscore. + +.. index:: single: \Z; in regular expressions + +``\Z`` + Matches only at the end of the string. + +.. index:: + single: \a; in regular expressions + single: \b; in regular expressions + single: \f; in regular expressions + single: \n; in regular expressions + single: \N; in regular expressions + single: \r; in regular expressions + single: \t; in regular expressions + single: \u; in regular expressions + single: \U; in regular expressions + single: \v; in regular expressions + single: \x; in regular expressions + single: \\; in regular expressions + +Most of the standard escapes supported by Python string literals are also +accepted by the regular expression parser:: + + \a \b \f \n + \N \r \t \u + \U \v \x \\ + +(Note that ``\b`` is used to represent word boundaries, and means "backspace" +only inside character classes.) + +``'\u'``, ``'\U'``, and ``'\N'`` escape sequences are only recognized in Unicode +patterns. In bytes patterns they are errors. Unknown escapes of ASCII +letters are reserved for future use and treated as errors. + +Octal escapes are included in a limited form. If the first digit is a 0, or if +there are three octal digits, it is considered an octal escape. Otherwise, it is +a group reference. As for string literals, octal escapes are always at most +three digits in length. + +.. versionchanged:: 3.3 + The ``'\u'`` and ``'\U'`` escape sequences have been added. + +.. versionchanged:: 3.6 + Unknown escapes consisting of ``'\'`` and an ASCII letter now are errors. + +.. versionchanged:: 3.8 + The ``'\N{name}'`` escape sequence has been added. As in string literals, + it expands to the named Unicode character (e.g. ``'\N{EM DASH}'``). + + +.. _contents-of-module-re: + +Module Contents +--------------- + +The module defines several functions, constants, and an exception. Some of the +functions are simplified versions of the full featured methods for compiled +regular expressions. Most non-trivial applications always use the compiled +form. + +.. versionchanged:: 3.6 + Flag constants are now instances of :class:`RegexFlag`, which is a subclass of + :class:`enum.IntFlag`. + +.. function:: compile(pattern, flags=0) + + Compile a regular expression pattern into a :ref:`regular expression object + `, which can be used for matching using its + :func:`~Pattern.match`, :func:`~Pattern.search` and other methods, described + below. + + The expression's behaviour can be modified by specifying a *flags* value. + Values can be any of the following variables, combined using bitwise OR (the + ``|`` operator). + + The sequence :: + + prog = re.compile(pattern) + result = prog.match(string) + + is equivalent to :: + + result = re.match(pattern, string) + + but using :func:`re.compile` and saving the resulting regular expression + object for reuse is more efficient when the expression will be used several + times in a single program. + + .. note:: + + The compiled versions of the most recent patterns passed to + :func:`re.compile` and the module-level matching functions are cached, so + programs that use only a few regular expressions at a time needn't worry + about compiling regular expressions. + + +.. data:: A + ASCII + + Make ``\w``, ``\W``, ``\b``, ``\B``, ``\d``, ``\D``, ``\s`` and ``\S`` + perform ASCII-only matching instead of full Unicode matching. This is only + meaningful for Unicode patterns, and is ignored for byte patterns. + Corresponds to the inline flag ``(?a)``. + + Note that for backward compatibility, the :const:`re.U` flag still + exists (as well as its synonym :const:`re.UNICODE` and its embedded + counterpart ``(?u)``), but these are redundant in Python 3 since + matches are Unicode by default for strings (and Unicode matching + isn't allowed for bytes). + + +.. data:: DEBUG + + Display debug information about compiled expression. + No corresponding inline flag. + + +.. data:: I + IGNORECASE + + Perform case-insensitive matching; expressions like ``[A-Z]`` will also + match lowercase letters. Full Unicode matching (such as ``Ü`` matching + ``ü``) also works unless the :const:`re.ASCII` flag is used to disable + non-ASCII matches. The current locale does not change the effect of this + flag unless the :const:`re.LOCALE` flag is also used. + Corresponds to the inline flag ``(?i)``. + + Note that when the Unicode patterns ``[a-z]`` or ``[A-Z]`` are used in + combination with the :const:`IGNORECASE` flag, they will match the 52 ASCII + letters and 4 additional non-ASCII letters: 'İ' (U+0130, Latin capital + letter I with dot above), 'ı' (U+0131, Latin small letter dotless i), + 'ſ' (U+017F, Latin small letter long s) and 'K' (U+212A, Kelvin sign). + If the :const:`ASCII` flag is used, only letters 'a' to 'z' + and 'A' to 'Z' are matched. + +.. data:: L + LOCALE + + Make ``\w``, ``\W``, ``\b``, ``\B`` and case-insensitive matching + dependent on the current locale. This flag can be used only with bytes + patterns. The use of this flag is discouraged as the locale mechanism + is very unreliable, it only handles one "culture" at a time, and it only + works with 8-bit locales. Unicode matching is already enabled by default + in Python 3 for Unicode (str) patterns, and it is able to handle different + locales/languages. + Corresponds to the inline flag ``(?L)``. + + .. versionchanged:: 3.6 + :const:`re.LOCALE` can be used only with bytes patterns and is + not compatible with :const:`re.ASCII`. + + .. versionchanged:: 3.7 + Compiled regular expression objects with the :const:`re.LOCALE` flag no + longer depend on the locale at compile time. Only the locale at + matching time affects the result of matching. + + +.. data:: M + MULTILINE + + When specified, the pattern character ``'^'`` matches at the beginning of the + string and at the beginning of each line (immediately following each newline); + and the pattern character ``'$'`` matches at the end of the string and at the + end of each line (immediately preceding each newline). By default, ``'^'`` + matches only at the beginning of the string, and ``'$'`` only at the end of the + string and immediately before the newline (if any) at the end of the string. + Corresponds to the inline flag ``(?m)``. + + +.. data:: S + DOTALL + + Make the ``'.'`` special character match any character at all, including a + newline; without this flag, ``'.'`` will match anything *except* a newline. + Corresponds to the inline flag ``(?s)``. + + +.. data:: X + VERBOSE + + .. index:: single: # (hash); in regular expressions + + This flag allows you to write regular expressions that look nicer and are + more readable by allowing you to visually separate logical sections of the + pattern and add comments. Whitespace within the pattern is ignored, except + when in a character class, or when preceded by an unescaped backslash, + or within tokens like ``*?``, ``(?:`` or ``(?P<...>``. + When a line contains a ``#`` that is not in a character class and is not + preceded by an unescaped backslash, all characters from the leftmost such + ``#`` through the end of the line are ignored. + + This means that the two following regular expression objects that match a + decimal number are functionally equal:: + + a = re.compile(r"""\d + # the integral part + \. # the decimal point + \d * # some fractional digits""", re.X) + b = re.compile(r"\d+\.\d*") + + Corresponds to the inline flag ``(?x)``. + + +.. function:: search(pattern, string, flags=0) + + Scan through *string* looking for the first location where the regular expression + *pattern* produces a match, and return a corresponding :ref:`match object + `. Return ``None`` if no position in the string matches the + pattern; note that this is different from finding a zero-length match at some + point in the string. + + +.. function:: match(pattern, string, flags=0) + + If zero or more characters at the beginning of *string* match the regular + expression *pattern*, return a corresponding :ref:`match object + `. Return ``None`` if the string does not match the pattern; + note that this is different from a zero-length match. + + Note that even in :const:`MULTILINE` mode, :func:`re.match` will only match + at the beginning of the string and not at the beginning of each line. + + If you want to locate a match anywhere in *string*, use :func:`search` + instead (see also :ref:`search-vs-match`). + + +.. function:: fullmatch(pattern, string, flags=0) + + If the whole *string* matches the regular expression *pattern*, return a + corresponding :ref:`match object `. Return ``None`` if the + string does not match the pattern; note that this is different from a + zero-length match. + + .. versionadded:: 3.4 + + +.. function:: split(pattern, string, maxsplit=0, flags=0) + + Split *string* by the occurrences of *pattern*. If capturing parentheses are + used in *pattern*, then the text of all groups in the pattern are also returned + as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* + splits occur, and the remainder of the string is returned as the final element + of the list. :: + + >>> re.split(r'\W+', 'Words, words, words.') + ['Words', 'words', 'words', ''] + >>> re.split(r'(\W+)', 'Words, words, words.') + ['Words', ', ', 'words', ', ', 'words', '.', ''] + >>> re.split(r'\W+', 'Words, words, words.', 1) + ['Words', 'words, words.'] + >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE) + ['0', '3', '9'] + + If there are capturing groups in the separator and it matches at the start of + the string, the result will start with an empty string. The same holds for + the end of the string:: + + >>> re.split(r'(\W+)', '...words, words...') + ['', '...', 'words', ', ', 'words', '...', ''] + + That way, separator components are always found at the same relative + indices within the result list. + + Empty matches for the pattern split the string only when not adjacent + to a previous empty match. + + >>> re.split(r'\b', 'Words, words, words.') + ['', 'Words', ', ', 'words', ', ', 'words', '.'] + >>> re.split(r'\W*', '...words...') + ['', '', 'w', 'o', 'r', 'd', 's', '', ''] + >>> re.split(r'(\W*)', '...words...') + ['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', ''] + + .. versionchanged:: 3.1 + Added the optional flags argument. + + .. versionchanged:: 3.7 + Added support of splitting on a pattern that could match an empty string. + + +.. function:: findall(pattern, string, flags=0) + + Return all non-overlapping matches of *pattern* in *string*, as a list of + strings. The *string* is scanned left-to-right, and matches are returned in + the order found. If one or more groups are present in the pattern, return a + list of groups; this will be a list of tuples if the pattern has more than + one group. Empty matches are included in the result. + + .. versionchanged:: 3.7 + Non-empty matches can now start just after a previous empty match. + + +.. function:: finditer(pattern, string, flags=0) + + Return an :term:`iterator` yielding :ref:`match objects ` over + all non-overlapping matches for the RE *pattern* in *string*. The *string* + is scanned left-to-right, and matches are returned in the order found. Empty + matches are included in the result. + + .. versionchanged:: 3.7 + Non-empty matches can now start just after a previous empty match. + + +.. function:: sub(pattern, repl, string, count=0, flags=0) + + Return the string obtained by replacing the leftmost non-overlapping occurrences + of *pattern* in *string* by the replacement *repl*. If the pattern isn't found, + *string* is returned unchanged. *repl* can be a string or a function; if it is + a string, any backslash escapes in it are processed. That is, ``\n`` is + converted to a single newline character, ``\r`` is converted to a carriage return, and + so forth. Unknown escapes of ASCII letters are reserved for future use and + treated as errors. Other unknown escapes such as ``\&`` are left alone. + Backreferences, such + as ``\6``, are replaced with the substring matched by group 6 in the pattern. + For example:: + + >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', + ... r'static PyObject*\npy_\1(void)\n{', + ... 'def myfunc():') + 'static PyObject*\npy_myfunc(void)\n{' + + If *repl* is a function, it is called for every non-overlapping occurrence of + *pattern*. The function takes a single :ref:`match object ` + argument, and returns the replacement string. For example:: + + >>> def dashrepl(matchobj): + ... if matchobj.group(0) == '-': return ' ' + ... else: return '-' + >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files') + 'pro--gram files' + >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) + 'Baked Beans & Spam' + + The pattern may be a string or a :ref:`pattern object `. + + The optional argument *count* is the maximum number of pattern occurrences to be + replaced; *count* must be a non-negative integer. If omitted or zero, all + occurrences will be replaced. Empty matches for the pattern are replaced only + when not adjacent to a previous empty match, so ``sub('x*', '-', 'abxd')`` returns + ``'-a-b--d-'``. + + .. index:: single: \g; in regular expressions + + In string-type *repl* arguments, in addition to the character escapes and + backreferences described above, + ``\g`` will use the substring matched by the group named ``name``, as + defined by the ``(?P...)`` syntax. ``\g`` uses the corresponding + group number; ``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous + in a replacement such as ``\g<2>0``. ``\20`` would be interpreted as a + reference to group 20, not a reference to group 2 followed by the literal + character ``'0'``. The backreference ``\g<0>`` substitutes in the entire + substring matched by the RE. + + .. versionchanged:: 3.1 + Added the optional flags argument. + + .. versionchanged:: 3.5 + Unmatched groups are replaced with an empty string. + + .. versionchanged:: 3.6 + Unknown escapes in *pattern* consisting of ``'\'`` and an ASCII letter + now are errors. + + .. versionchanged:: 3.7 + Unknown escapes in *repl* consisting of ``'\'`` and an ASCII letter + now are errors. + + .. versionchanged:: 3.7 + Empty matches for the pattern are replaced when adjacent to a previous + non-empty match. + + +.. function:: subn(pattern, repl, string, count=0, flags=0) + + Perform the same operation as :func:`sub`, but return a tuple ``(new_string, + number_of_subs_made)``. + + .. versionchanged:: 3.1 + Added the optional flags argument. + + .. versionchanged:: 3.5 + Unmatched groups are replaced with an empty string. + + +.. function:: escape(pattern) + + Escape special characters in *pattern*. + This is useful if you want to match an arbitrary literal string that may + have regular expression metacharacters in it. For example:: + + >>> print(re.escape('http://www.python.org')) + http://www\.python\.org + + >>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:" + >>> print('[%s]+' % re.escape(legal_chars)) + [abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&'\*\+\-\.\^_`\|\~:]+ + + >>> operators = ['+', '-', '*', '/', '**'] + >>> print('|'.join(map(re.escape, sorted(operators, reverse=True)))) + /|\-|\+|\*\*|\* + + This function must not be used for the replacement string in :func:`sub` + and :func:`subn`, only backslashes should be escaped. For example:: + + >>> digits_re = r'\d+' + >>> sample = '/usr/sbin/sendmail - 0 errors, 12 warnings' + >>> print(re.sub(digits_re, digits_re.replace('\\', r'\\'), sample)) + /usr/sbin/sendmail - \d+ errors, \d+ warnings + + .. versionchanged:: 3.3 + The ``'_'`` character is no longer escaped. + + .. versionchanged:: 3.7 + Only characters that can have special meaning in a regular expression + are escaped. As a result, ``'!'``, ``'"'``, ``'%'``, ``"'"``, ``','``, + ``'/'``, ``':'``, ``';'``, ``'<'``, ``'='``, ``'>'``, ``'@'``, and + ``"`"`` are no longer escaped. + + +.. function:: purge() + + Clear the regular expression cache. + + +.. exception:: error(msg, pattern=None, pos=None) + + Exception raised when a string passed to one of the functions here is not a + valid regular expression (for example, it might contain unmatched parentheses) + or when some other error occurs during compilation or matching. It is never an + error if a string contains no match for a pattern. The error instance has + the following additional attributes: + + .. attribute:: msg + + The unformatted error message. + + .. attribute:: pattern + + The regular expression pattern. + + .. attribute:: pos + + The index in *pattern* where compilation failed (may be ``None``). + + .. attribute:: lineno + + The line corresponding to *pos* (may be ``None``). + + .. attribute:: colno + + The column corresponding to *pos* (may be ``None``). + + .. versionchanged:: 3.5 + Added additional attributes. + +.. _re-objects: + +Regular Expression Objects +-------------------------- + +Compiled regular expression objects support the following methods and +attributes: + +.. method:: Pattern.search(string[, pos[, endpos]]) + + Scan through *string* looking for the first location where this regular + expression produces a match, and return a corresponding :ref:`match object + `. Return ``None`` if no position in the string matches the + pattern; note that this is different from finding a zero-length match at some + point in the string. + + The optional second parameter *pos* gives an index in the string where the + search is to start; it defaults to ``0``. This is not completely equivalent to + slicing the string; the ``'^'`` pattern character matches at the real beginning + of the string and at positions just after a newline, but not necessarily at the + index where the search is to start. + + The optional parameter *endpos* limits how far the string will be searched; it + will be as if the string is *endpos* characters long, so only the characters + from *pos* to ``endpos - 1`` will be searched for a match. If *endpos* is less + than *pos*, no match will be found; otherwise, if *rx* is a compiled regular + expression object, ``rx.search(string, 0, 50)`` is equivalent to + ``rx.search(string[:50], 0)``. :: + + >>> pattern = re.compile("d") + >>> pattern.search("dog") # Match at index 0 + + >>> pattern.search("dog", 1) # No match; search doesn't include the "d" + + +.. method:: Pattern.match(string[, pos[, endpos]]) + + If zero or more characters at the *beginning* of *string* match this regular + expression, return a corresponding :ref:`match object `. + Return ``None`` if the string does not match the pattern; note that this is + different from a zero-length match. + + The optional *pos* and *endpos* parameters have the same meaning as for the + :meth:`~Pattern.search` method. :: + + >>> pattern = re.compile("o") + >>> pattern.match("dog") # No match as "o" is not at the start of "dog". + >>> pattern.match("dog", 1) # Match as "o" is the 2nd character of "dog". + + + If you want to locate a match anywhere in *string*, use + :meth:`~Pattern.search` instead (see also :ref:`search-vs-match`). + + +.. method:: Pattern.fullmatch(string[, pos[, endpos]]) + + If the whole *string* matches this regular expression, return a corresponding + :ref:`match object `. Return ``None`` if the string does not + match the pattern; note that this is different from a zero-length match. + + The optional *pos* and *endpos* parameters have the same meaning as for the + :meth:`~Pattern.search` method. :: + + >>> pattern = re.compile("o[gh]") + >>> pattern.fullmatch("dog") # No match as "o" is not at the start of "dog". + >>> pattern.fullmatch("ogre") # No match as not the full string matches. + >>> pattern.fullmatch("doggie", 1, 3) # Matches within given limits. + + + .. versionadded:: 3.4 + + +.. method:: Pattern.split(string, maxsplit=0) + + Identical to the :func:`split` function, using the compiled pattern. + + +.. method:: Pattern.findall(string[, pos[, endpos]]) + + Similar to the :func:`findall` function, using the compiled pattern, but + also accepts optional *pos* and *endpos* parameters that limit the search + region like for :meth:`search`. + + +.. method:: Pattern.finditer(string[, pos[, endpos]]) + + Similar to the :func:`finditer` function, using the compiled pattern, but + also accepts optional *pos* and *endpos* parameters that limit the search + region like for :meth:`search`. + + +.. method:: Pattern.sub(repl, string, count=0) + + Identical to the :func:`sub` function, using the compiled pattern. + + +.. method:: Pattern.subn(repl, string, count=0) + + Identical to the :func:`subn` function, using the compiled pattern. + + +.. attribute:: Pattern.flags + + The regex matching flags. This is a combination of the flags given to + :func:`.compile`, any ``(?...)`` inline flags in the pattern, and implicit + flags such as :data:`UNICODE` if the pattern is a Unicode string. + + +.. attribute:: Pattern.groups + + The number of capturing groups in the pattern. + + +.. attribute:: Pattern.groupindex + + A dictionary mapping any symbolic group names defined by ``(?P)`` to group + numbers. The dictionary is empty if no symbolic groups were used in the + pattern. + + +.. attribute:: Pattern.pattern + + The pattern string from which the pattern object was compiled. + + +.. versionchanged:: 3.7 + Added support of :func:`copy.copy` and :func:`copy.deepcopy`. Compiled + regular expression objects are considered atomic. + + +.. _match-objects: + +Match Objects +------------- + +Match objects always have a boolean value of ``True``. +Since :meth:`~Pattern.match` and :meth:`~Pattern.search` return ``None`` +when there is no match, you can test whether there was a match with a simple +``if`` statement:: + + match = re.search(pattern, string) + if match: + process(match) + +Match objects support the following methods and attributes: + + +.. method:: Match.expand(template) + + Return the string obtained by doing backslash substitution on the template + string *template*, as done by the :meth:`~Pattern.sub` method. + Escapes such as ``\n`` are converted to the appropriate characters, + and numeric backreferences (``\1``, ``\2``) and named backreferences + (``\g<1>``, ``\g``) are replaced by the contents of the + corresponding group. + + .. versionchanged:: 3.5 + Unmatched groups are replaced with an empty string. + +.. method:: Match.group([group1, ...]) + + Returns one or more subgroups of the match. If there is a single argument, the + result is a single string; if there are multiple arguments, the result is a + tuple with one item per argument. Without arguments, *group1* defaults to zero + (the whole match is returned). If a *groupN* argument is zero, the corresponding + return value is the entire matching string; if it is in the inclusive range + [1..99], it is the string matching the corresponding parenthesized group. If a + group number is negative or larger than the number of groups defined in the + pattern, an :exc:`IndexError` exception is raised. If a group is contained in a + part of the pattern that did not match, the corresponding result is ``None``. + If a group is contained in a part of the pattern that matched multiple times, + the last match is returned. :: + + >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") + >>> m.group(0) # The entire match + 'Isaac Newton' + >>> m.group(1) # The first parenthesized subgroup. + 'Isaac' + >>> m.group(2) # The second parenthesized subgroup. + 'Newton' + >>> m.group(1, 2) # Multiple arguments give us a tuple. + ('Isaac', 'Newton') + + If the regular expression uses the ``(?P...)`` syntax, the *groupN* + arguments may also be strings identifying groups by their group name. If a + string argument is not used as a group name in the pattern, an :exc:`IndexError` + exception is raised. + + A moderately complicated example:: + + >>> m = re.match(r"(?P\w+) (?P\w+)", "Malcolm Reynolds") + >>> m.group('first_name') + 'Malcolm' + >>> m.group('last_name') + 'Reynolds' + + Named groups can also be referred to by their index:: + + >>> m.group(1) + 'Malcolm' + >>> m.group(2) + 'Reynolds' + + If a group matches multiple times, only the last match is accessible:: + + >>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times. + >>> m.group(1) # Returns only the last match. + 'c3' + + +.. method:: Match.__getitem__(g) + + This is identical to ``m.group(g)``. This allows easier access to + an individual group from a match:: + + >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") + >>> m[0] # The entire match + 'Isaac Newton' + >>> m[1] # The first parenthesized subgroup. + 'Isaac' + >>> m[2] # The second parenthesized subgroup. + 'Newton' + + .. versionadded:: 3.6 + + +.. method:: Match.groups(default=None) + + Return a tuple containing all the subgroups of the match, from 1 up to however + many groups are in the pattern. The *default* argument is used for groups that + did not participate in the match; it defaults to ``None``. + + For example:: + + >>> m = re.match(r"(\d+)\.(\d+)", "24.1632") + >>> m.groups() + ('24', '1632') + + If we make the decimal place and everything after it optional, not all groups + might participate in the match. These groups will default to ``None`` unless + the *default* argument is given:: + + >>> m = re.match(r"(\d+)\.?(\d+)?", "24") + >>> m.groups() # Second group defaults to None. + ('24', None) + >>> m.groups('0') # Now, the second group defaults to '0'. + ('24', '0') + + +.. method:: Match.groupdict(default=None) + + Return a dictionary containing all the *named* subgroups of the match, keyed by + the subgroup name. The *default* argument is used for groups that did not + participate in the match; it defaults to ``None``. For example:: + + >>> m = re.match(r"(?P\w+) (?P\w+)", "Malcolm Reynolds") + >>> m.groupdict() + {'first_name': 'Malcolm', 'last_name': 'Reynolds'} + + +.. method:: Match.start([group]) + Match.end([group]) + + Return the indices of the start and end of the substring matched by *group*; + *group* defaults to zero (meaning the whole matched substring). Return ``-1`` if + *group* exists but did not contribute to the match. For a match object *m*, and + a group *g* that did contribute to the match, the substring matched by group *g* + (equivalent to ``m.group(g)``) is :: + + m.string[m.start(g):m.end(g)] + + Note that ``m.start(group)`` will equal ``m.end(group)`` if *group* matched a + null string. For example, after ``m = re.search('b(c?)', 'cba')``, + ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both + 2, and ``m.start(2)`` raises an :exc:`IndexError` exception. + + An example that will remove *remove_this* from email addresses:: + + >>> email = "tony@tiremove_thisger.net" + >>> m = re.search("remove_this", email) + >>> email[:m.start()] + email[m.end():] + 'tony@tiger.net' + + +.. method:: Match.span([group]) + + For a match *m*, return the 2-tuple ``(m.start(group), m.end(group))``. Note + that if *group* did not contribute to the match, this is ``(-1, -1)``. + *group* defaults to zero, the entire match. + + +.. attribute:: Match.pos + + The value of *pos* which was passed to the :meth:`~Pattern.search` or + :meth:`~Pattern.match` method of a :ref:`regex object `. This is + the index into the string at which the RE engine started looking for a match. + + +.. attribute:: Match.endpos + + The value of *endpos* which was passed to the :meth:`~Pattern.search` or + :meth:`~Pattern.match` method of a :ref:`regex object `. This is + the index into the string beyond which the RE engine will not go. + + +.. attribute:: Match.lastindex + + The integer index of the last matched capturing group, or ``None`` if no group + was matched at all. For example, the expressions ``(a)b``, ``((a)(b))``, and + ``((ab))`` will have ``lastindex == 1`` if applied to the string ``'ab'``, while + the expression ``(a)(b)`` will have ``lastindex == 2``, if applied to the same + string. + + +.. attribute:: Match.lastgroup + + The name of the last matched capturing group, or ``None`` if the group didn't + have a name, or if no group was matched at all. + + +.. attribute:: Match.re + + The :ref:`regular expression object ` whose :meth:`~Pattern.match` or + :meth:`~Pattern.search` method produced this match instance. + + +.. attribute:: Match.string + + The string passed to :meth:`~Pattern.match` or :meth:`~Pattern.search`. + + +.. versionchanged:: 3.7 + Added support of :func:`copy.copy` and :func:`copy.deepcopy`. Match objects + are considered atomic. + + +.. _re-examples: + +Regular Expression Examples +--------------------------- + + +Checking for a Pair +^^^^^^^^^^^^^^^^^^^ + +In this example, we'll use the following helper function to display match +objects a little more gracefully:: + + def displaymatch(match): + if match is None: + return None + return '' % (match.group(), match.groups()) + +Suppose you are writing a poker program where a player's hand is represented as +a 5-character string with each character representing a card, "a" for ace, "k" +for king, "q" for queen, "j" for jack, "t" for 10, and "2" through "9" +representing the card with that value. + +To see if a given string is a valid hand, one could do the following:: + + >>> valid = re.compile(r"^[a2-9tjqk]{5}$") + >>> displaymatch(valid.match("akt5q")) # Valid. + "" + >>> displaymatch(valid.match("akt5e")) # Invalid. + >>> displaymatch(valid.match("akt")) # Invalid. + >>> displaymatch(valid.match("727ak")) # Valid. + "" + +That last hand, ``"727ak"``, contained a pair, or two of the same valued cards. +To match this with a regular expression, one could use backreferences as such:: + + >>> pair = re.compile(r".*(.).*\1") + >>> displaymatch(pair.match("717ak")) # Pair of 7s. + "" + >>> displaymatch(pair.match("718ak")) # No pairs. + >>> displaymatch(pair.match("354aa")) # Pair of aces. + "" + +To find out what card the pair consists of, one could use the +:meth:`~Match.group` method of the match object in the following manner:: + + >>> pair = re.compile(r".*(.).*\1") + >>> 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 "", line 1, in + re.match(r".*(.).*\1", "718ak").group(1) + AttributeError: 'NoneType' object has no attribute 'group' + + >>> pair.match("354aa").group(1) + 'a' + + +Simulating scanf() +^^^^^^^^^^^^^^^^^^ + +.. index:: single: scanf() + +Python does not currently have an equivalent to :c:func:`scanf`. Regular +expressions are generally more powerful, though also more verbose, than +:c:func:`scanf` format strings. The table below offers some more-or-less +equivalent mappings between :c:func:`scanf` format tokens and regular +expressions. + ++--------------------------------+---------------------------------------------+ +| :c:func:`scanf` Token | Regular Expression | ++================================+=============================================+ +| ``%c`` | ``.`` | ++--------------------------------+---------------------------------------------+ +| ``%5c`` | ``.{5}`` | ++--------------------------------+---------------------------------------------+ +| ``%d`` | ``[-+]?\d+`` | ++--------------------------------+---------------------------------------------+ +| ``%e``, ``%E``, ``%f``, ``%g`` | ``[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?`` | ++--------------------------------+---------------------------------------------+ +| ``%i`` | ``[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)`` | ++--------------------------------+---------------------------------------------+ +| ``%o`` | ``[-+]?[0-7]+`` | ++--------------------------------+---------------------------------------------+ +| ``%s`` | ``\S+`` | ++--------------------------------+---------------------------------------------+ +| ``%u`` | ``\d+`` | ++--------------------------------+---------------------------------------------+ +| ``%x``, ``%X`` | ``[-+]?(0[xX])?[\dA-Fa-f]+`` | ++--------------------------------+---------------------------------------------+ + +To extract the filename and numbers from a string like :: + + /usr/sbin/sendmail - 0 errors, 4 warnings + +you would use a :c:func:`scanf` format like :: + + %s - %d errors, %d warnings + +The equivalent regular expression would be :: + + (\S+) - (\d+) errors, (\d+) warnings + + +.. _search-vs-match: + +search() vs. match() +^^^^^^^^^^^^^^^^^^^^ + +.. sectionauthor:: Fred L. Drake, Jr. + +Python offers two different primitive operations based on regular expressions: +:func:`re.match` checks for a match only at the beginning of the string, while +:func:`re.search` checks for a match anywhere in the string (this is what Perl +does by default). + +For example:: + + >>> re.match("c", "abcdef") # No match + >>> re.search("c", "abcdef") # Match + + +Regular expressions beginning with ``'^'`` can be used with :func:`search` to +restrict the match at the beginning of the string:: + + >>> re.match("c", "abcdef") # No match + >>> re.search("^c", "abcdef") # No match + >>> re.search("^a", "abcdef") # Match + + +Note however that in :const:`MULTILINE` mode :func:`match` only matches at the +beginning of the string, whereas using :func:`search` with a regular expression +beginning with ``'^'`` will match at the beginning of each line. :: + + >>> re.match('X', 'A\nB\nX', re.MULTILINE) # No match + >>> re.search('^X', 'A\nB\nX', re.MULTILINE) # Match + + + +Making a Phonebook +^^^^^^^^^^^^^^^^^^ + +: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. + +First, here is the input. Normally it may come from a file, here we are using +triple-quoted string syntax + +.. doctest:: + + >>> text = """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 + ... + ... + ... Heather Albrecht: 548.326.4584 919 Park Place""" + +The entries are separated by one or more newlines. Now we convert the string +into a list with each nonempty line having its own entry: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> entries = re.split("\n+", text) + >>> entries + ['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', + 'Heather Albrecht: 548.326.4584 919 Park Place'] + +Finally, split each entry into a list with first name, last name, telephone +number, and address. We use the ``maxsplit`` parameter of :func:`split` +because the address has spaces, our splitting pattern, in it: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> [re.split(":? ", entry, 3) for entry in entries] + [['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'], + ['Heather', 'Albrecht', '548.326.4584', '919 Park Place']] + +The ``:?`` pattern matches the colon after the last name, so that it does not +occur in the result list. With a ``maxsplit`` of ``4``, we could separate the +house number from the street name: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> [re.split(":? ", entry, 4) for entry in entries] + [['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'], + ['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']] + + +Text Munging +^^^^^^^^^^^^ + +:func:`sub` replaces every occurrence of a pattern with a string or the +result of a function. This example demonstrates using :func:`sub` with +a function to "munge" text, or randomize the order of all the characters +in each word of a sentence except for the first and last characters:: + + >>> def repl(m): + ... inner_word = list(m.group(2)) + ... random.shuffle(inner_word) + ... return m.group(1) + "".join(inner_word) + m.group(3) + >>> text = "Professor Abdolmalek, please report your absences promptly." + >>> re.sub(r"(\w)(\w+)(\w)", repl, text) + 'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.' + >>> re.sub(r"(\w)(\w+)(\w)", repl, text) + 'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.' + + +Finding all Adverbs +^^^^^^^^^^^^^^^^^^^ + +:func:`findall` matches *all* occurrences of a pattern, not just the first +one as :func:`search` does. For example, if a writer wanted to +find all of the adverbs in some text, they might use :func:`findall` in +the following manner:: + + >>> text = "He was carefully disguised but captured quickly by police." + >>> re.findall(r"\w+ly", text) + ['carefully', 'quickly'] + + +Finding all Adverbs and their Positions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If one wants more information about all matches of a pattern than the matched +text, :func:`finditer` is useful as it provides :ref:`match objects +` instead of strings. Continuing with the previous example, if +a writer wanted to find all of the adverbs *and their positions* in +some text, they would use :func:`finditer` in the following manner:: + + >>> text = "He was carefully disguised but captured quickly by police." + >>> for m in re.finditer(r"\w+ly", text): + ... print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) + 07-16: carefully + 40-47: quickly + + +Raw String Notation +^^^^^^^^^^^^^^^^^^^ + +Raw string notation (``r"text"``) keeps regular expressions sane. Without it, +every backslash (``'\'``) in a regular expression would have to be prefixed with +another one to escape it. For example, the two following lines of code are +functionally identical:: + + >>> re.match(r"\W(.)\1\W", " ff ") + + >>> re.match("\\W(.)\\1\\W", " ff ") + + +When one wants to match a literal backslash, it must be escaped in the regular +expression. With raw string notation, this means ``r"\\"``. Without raw string +notation, one must use ``"\\\\"``, making the following lines of code +functionally identical:: + + >>> re.match(r"\\", r"\\") + + >>> re.match("\\\\", r"\\") + + + +Writing a Tokenizer +^^^^^^^^^^^^^^^^^^^ + +A `tokenizer or scanner `_ +analyzes a string to categorize groups of characters. This is a useful first +step in writing a compiler or interpreter. + +The text categories are specified with regular expressions. The technique is +to combine those into a single master regular expression and to loop over +successive matches:: + + from typing import NamedTuple + import re + + class Token(NamedTuple): + type: str + value: str + line: int + column: int + + def tokenize(code): + keywords = {'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'} + token_specification = [ + ('NUMBER', r'\d+(\.\d*)?'), # Integer or decimal number + ('ASSIGN', r':='), # Assignment operator + ('END', r';'), # Statement terminator + ('ID', r'[A-Za-z]+'), # Identifiers + ('OP', r'[+\-*/]'), # Arithmetic operators + ('NEWLINE', r'\n'), # Line endings + ('SKIP', r'[ \t]+'), # Skip over spaces and tabs + ('MISMATCH', r'.'), # Any other character + ] + tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification) + line_num = 1 + line_start = 0 + for mo in re.finditer(tok_regex, code): + kind = mo.lastgroup + value = mo.group() + column = mo.start() - line_start + if kind == 'NUMBER': + value = float(value) if '.' in value else int(value) + elif kind == 'ID' and value in keywords: + kind = value + elif kind == 'NEWLINE': + line_start = mo.end() + line_num += 1 + continue + elif kind == 'SKIP': + continue + elif kind == 'MISMATCH': + raise RuntimeError(f'{value!r} unexpected on line {line_num}') + yield Token(kind, value, line_num, column) + + statements = ''' + IF quantity THEN + total := total + price * quantity; + tax := price * 0.05; + ENDIF; + ''' + + for token in tokenize(statements): + print(token) + +The tokenizer produces the following output:: + + Token(type='IF', value='IF', line=2, column=4) + Token(type='ID', value='quantity', line=2, column=7) + Token(type='THEN', value='THEN', line=2, column=16) + Token(type='ID', value='total', line=3, column=8) + Token(type='ASSIGN', value=':=', line=3, column=14) + Token(type='ID', value='total', line=3, column=17) + Token(type='OP', value='+', line=3, column=23) + Token(type='ID', value='price', line=3, column=25) + Token(type='OP', value='*', line=3, column=31) + Token(type='ID', value='quantity', line=3, column=33) + Token(type='END', value=';', line=3, column=41) + Token(type='ID', value='tax', line=4, column=8) + Token(type='ASSIGN', value=':=', line=4, column=12) + Token(type='ID', value='price', line=4, column=15) + Token(type='OP', value='*', line=4, column=21) + Token(type='NUMBER', value=0.05, line=4, column=23) + Token(type='END', value=';', line=4, column=27) + Token(type='ENDIF', value='ENDIF', line=5, column=4) + Token(type='END', value=';', line=5, column=9) + + +.. [Frie09] Friedl, Jeffrey. Mastering Regular Expressions. 3rd ed., O'Reilly + Media, 2009. The third edition of the book no longer covers Python at all, + but the first edition covered writing good regular expression patterns in + great detail. diff --git a/cpython_2/environment/repo/Doc/library/readline.rst b/cpython_2/environment/repo/Doc/library/readline.rst new file mode 100644 index 0000000000000000000000000000000000000000..eae0a6df45f30e153a18861036bfbc2162622fe3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/readline.rst @@ -0,0 +1,359 @@ +:mod:`readline` --- GNU readline interface +========================================== + +.. module:: readline + :platform: Unix + :synopsis: GNU readline support for Python. + +.. sectionauthor:: Skip Montanaro + +-------------- + +The :mod:`readline` module defines a number of functions to facilitate +completion and reading/writing of history files from the Python interpreter. +This module can be used directly, or via the :mod:`rlcompleter` module, which +supports completion of Python identifiers at the interactive prompt. Settings +made using this module affect the behaviour of both the interpreter's +interactive prompt and the prompts offered by the built-in :func:`input` +function. + +Readline keybindings may be configured via an initialization file, typically +``.inputrc`` in your home directory. See `Readline Init File +`_ +in the GNU Readline manual for information about the format and +allowable constructs of that file, and the capabilities of the +Readline library in general. + +.. note:: + + The underlying Readline library API may be implemented by + the ``libedit`` library instead of GNU readline. + On macOS the :mod:`readline` module detects which library is being used + at run time. + + The configuration file for ``libedit`` is different from that + of GNU readline. If you programmatically load configuration strings + you can check for the text "libedit" in :const:`readline.__doc__` + to differentiate between GNU readline and libedit. + + If you use *editline*/``libedit`` readline emulation on macOS, the + initialization file located in your home directory is named + ``.editrc``. For example, the following content in ``~/.editrc`` will + turn ON *vi* keybindings and TAB completion:: + + python:bind -v + python:bind ^I rl_complete + + +Init file +--------- + +The following functions relate to the init file and user configuration: + + +.. function:: parse_and_bind(string) + + Execute the init line provided in the *string* argument. This calls + :c:func:`rl_parse_and_bind` in the underlying library. + + +.. function:: read_init_file([filename]) + + Execute a readline initialization file. The default filename is the last filename + used. This calls :c:func:`rl_read_init_file` in the underlying library. + + +Line buffer +----------- + +The following functions operate on the line buffer: + + +.. function:: get_line_buffer() + + Return the current contents of the line buffer (:c:data:`rl_line_buffer` + in the underlying library). + + +.. function:: insert_text(string) + + Insert text into the line buffer at the cursor position. This calls + :c:func:`rl_insert_text` in the underlying library, but ignores + the return value. + + +.. function:: redisplay() + + Change what's displayed on the screen to reflect the current contents of the + line buffer. This calls :c:func:`rl_redisplay` in the underlying library. + + +History file +------------ + +The following functions operate on a history file: + + +.. function:: read_history_file([filename]) + + Load a readline history file, and append it to the history list. + The default filename is :file:`~/.history`. This calls + :c:func:`read_history` in the underlying library. + + +.. function:: write_history_file([filename]) + + Save the history list to a readline history file, overwriting any + existing file. The default filename is :file:`~/.history`. This calls + :c:func:`write_history` in the underlying library. + + +.. function:: append_history_file(nelements[, filename]) + + Append the last *nelements* items of history to a file. The default filename is + :file:`~/.history`. The file must already exist. This calls + :c:func:`append_history` in the underlying library. This function + only exists if Python was compiled for a version of the library + that supports it. + + .. versionadded:: 3.5 + + +.. function:: get_history_length() + set_history_length(length) + + Set or return the desired number of lines to save in the history file. + The :func:`write_history_file` function uses this value to truncate + the history file, by calling :c:func:`history_truncate_file` in + the underlying library. Negative values imply + unlimited history file size. + + +History list +------------ + +The following functions operate on a global history list: + + +.. function:: clear_history() + + Clear the current history. This calls :c:func:`clear_history` in the + underlying library. The Python function only exists if Python was + compiled for a version of the library that supports it. + + +.. function:: get_current_history_length() + + Return the number of items currently in the history. (This is different from + :func:`get_history_length`, which returns the maximum number of lines that will + be written to a history file.) + + +.. function:: get_history_item(index) + + Return the current contents of history item at *index*. The item index + is one-based. This calls :c:func:`history_get` in the underlying library. + + +.. function:: remove_history_item(pos) + + Remove history item specified by its position from the history. + The position is zero-based. This calls :c:func:`remove_history` in + the underlying library. + + +.. function:: replace_history_item(pos, line) + + Replace history item specified by its position with *line*. + The position is zero-based. This calls :c:func:`replace_history_entry` + in the underlying library. + + +.. function:: add_history(line) + + Append *line* to the history buffer, as if it was the last line typed. + This calls :c:func:`add_history` in the underlying library. + + +.. function:: set_auto_history(enabled) + + Enable or disable automatic calls to :c:func:`add_history` when reading + input via readline. The *enabled* argument should be a Boolean value + that when true, enables auto history, and that when false, disables + auto history. + + .. versionadded:: 3.6 + + .. impl-detail:: + Auto history is enabled by default, and changes to this do not persist + across multiple sessions. + + +Startup hooks +------------- + + +.. function:: set_startup_hook([function]) + + Set or remove the function invoked by the :c:data:`rl_startup_hook` + callback of the underlying library. If *function* is specified, it will + be used as the new hook function; if omitted or ``None``, any function + already installed is removed. The hook is called with no + arguments just before readline prints the first prompt. + + +.. function:: set_pre_input_hook([function]) + + Set or remove the function invoked by the :c:data:`rl_pre_input_hook` + callback of the underlying library. If *function* is specified, it will + be used as the new hook function; if omitted or ``None``, any + function already installed is removed. The hook is called + with no arguments after the first prompt has been printed and just before + readline starts reading input characters. This function only exists + if Python was compiled for a version of the library that supports it. + + +Completion +---------- + +The following functions relate to implementing a custom word completion +function. This is typically operated by the Tab key, and can suggest and +automatically complete a word being typed. By default, Readline is set up +to be used by :mod:`rlcompleter` to complete Python identifiers for +the interactive interpreter. If the :mod:`readline` module is to be used +with a custom completer, a different set of word delimiters should be set. + + +.. function:: set_completer([function]) + + Set or remove the completer function. If *function* is specified, it will be + used as the new completer function; if omitted or ``None``, any completer + function already installed is removed. The completer function is called as + ``function(text, state)``, for *state* in ``0``, ``1``, ``2``, ..., until it + returns a non-string value. It should return the next possible completion + starting with *text*. + + The installed completer function is invoked by the *entry_func* callback + passed to :c:func:`rl_completion_matches` in the underlying library. + The *text* string comes from the first parameter to the + :c:data:`rl_attempted_completion_function` callback of the + underlying library. + + +.. function:: get_completer() + + Get the completer function, or ``None`` if no completer function has been set. + + +.. function:: get_completion_type() + + Get the type of completion being attempted. This returns the + :c:data:`rl_completion_type` variable in the underlying library as + an integer. + + +.. function:: get_begidx() + get_endidx() + + Get the beginning or ending index of the completion scope. + These indexes are the *start* and *end* arguments passed to the + :c:data:`rl_attempted_completion_function` callback of the + underlying library. + + +.. function:: set_completer_delims(string) + get_completer_delims() + + Set or get the word delimiters for completion. These determine the + start of the word to be considered for completion (the completion scope). + These functions access the :c:data:`rl_completer_word_break_characters` + variable in the underlying library. + + +.. function:: set_completion_display_matches_hook([function]) + + Set or remove the completion display function. If *function* is + specified, it will be used as the new completion display function; + if omitted or ``None``, any completion display function already + installed is removed. This sets or clears the + :c:data:`rl_completion_display_matches_hook` callback in the + underlying library. The completion display function is called as + ``function(substitution, [matches], longest_match_length)`` once + each time matches need to be displayed. + + +.. _readline-example: + +Example +------- + +The following example demonstrates how to use the :mod:`readline` module's +history reading and writing functions to automatically load and save a history +file named :file:`.python_history` from the user's home directory. The code +below would normally be executed automatically during interactive sessions +from the user's :envvar:`PYTHONSTARTUP` file. :: + + import atexit + import os + import readline + + histfile = os.path.join(os.path.expanduser("~"), ".python_history") + try: + readline.read_history_file(histfile) + # default history len is -1 (infinite), which may grow unruly + readline.set_history_length(1000) + except FileNotFoundError: + pass + + atexit.register(readline.write_history_file, histfile) + +This code is actually automatically run when Python is run in +:ref:`interactive mode ` (see :ref:`rlcompleter-config`). + +The following example achieves the same goal but supports concurrent interactive +sessions, by only appending the new history. :: + + import atexit + import os + import readline + histfile = os.path.join(os.path.expanduser("~"), ".python_history") + + try: + readline.read_history_file(histfile) + h_len = readline.get_current_history_length() + except FileNotFoundError: + open(histfile, 'wb').close() + h_len = 0 + + def save(prev_h_len, histfile): + new_h_len = readline.get_current_history_length() + readline.set_history_length(1000) + readline.append_history_file(new_h_len - prev_h_len, histfile) + atexit.register(save, h_len, histfile) + +The following example extends the :class:`code.InteractiveConsole` class to +support history save/restore. :: + + import atexit + import code + import os + import readline + + class HistoryConsole(code.InteractiveConsole): + def __init__(self, locals=None, filename="", + histfile=os.path.expanduser("~/.console-history")): + code.InteractiveConsole.__init__(self, locals, filename) + self.init_history(histfile) + + def init_history(self, histfile): + readline.parse_and_bind("tab: complete") + if hasattr(readline, "read_history_file"): + try: + readline.read_history_file(histfile) + except FileNotFoundError: + pass + atexit.register(self.save_history, histfile) + + def save_history(self, histfile): + readline.set_history_length(1000) + readline.write_history_file(histfile) diff --git a/cpython_2/environment/repo/Doc/library/reprlib.rst b/cpython_2/environment/repo/Doc/library/reprlib.rst new file mode 100644 index 0000000000000000000000000000000000000000..1a0c1b0dcd1aa9c04760250f4fa60f15be39b33f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/reprlib.rst @@ -0,0 +1,163 @@ +:mod:`reprlib` --- Alternate :func:`repr` implementation +======================================================== + +.. module:: reprlib + :synopsis: Alternate repr() implementation with size limits. + +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/reprlib.py` + +-------------- + +The :mod:`reprlib` module provides a means for producing object representations +with limits on the size of the resulting strings. This is used in the Python +debugger and may be useful in other contexts as well. + +This module provides a class, an instance, and a function: + + +.. class:: Repr() + + Class which provides formatting services useful in implementing functions + similar to the built-in :func:`repr`; size limits for different object types + are added to avoid the generation of representations which are excessively long. + + +.. data:: aRepr + + This is an instance of :class:`Repr` which is used to provide the + :func:`.repr` function described below. Changing the attributes of this + object will affect the size limits used by :func:`.repr` and the Python + debugger. + + +.. function:: repr(obj) + + This is the :meth:`~Repr.repr` method of ``aRepr``. It returns a string + similar to that returned by the built-in function of the same name, but with + limits on most sizes. + +In addition to size-limiting tools, the module also provides a decorator for +detecting recursive calls to :meth:`__repr__` and substituting a placeholder +string instead. + + +.. index:: single: ...; placeholder + +.. decorator:: recursive_repr(fillvalue="...") + + Decorator for :meth:`__repr__` methods to detect recursive calls within the + same thread. If a recursive call is made, the *fillvalue* is returned, + otherwise, the usual :meth:`__repr__` call is made. For example: + + >>> from reprlib import recursive_repr + >>> class MyList(list): + ... @recursive_repr() + ... def __repr__(self): + ... return '<' + '|'.join(map(repr, self)) + '>' + ... + >>> m = MyList('abc') + >>> m.append(m) + >>> m.append('x') + >>> print(m) + <'a'|'b'|'c'|...|'x'> + + .. versionadded:: 3.2 + + +.. _repr-objects: + +Repr Objects +------------ + +:class:`Repr` instances provide several attributes which can be used to provide +size limits for the representations of different object types, and methods +which format specific object types. + + +.. attribute:: Repr.maxlevel + + Depth limit on the creation of recursive representations. The default is ``6``. + + +.. attribute:: Repr.maxdict + Repr.maxlist + Repr.maxtuple + Repr.maxset + Repr.maxfrozenset + Repr.maxdeque + Repr.maxarray + + Limits on the number of entries represented for the named object type. The + default is ``4`` for :attr:`maxdict`, ``5`` for :attr:`maxarray`, and ``6`` for + the others. + + +.. attribute:: Repr.maxlong + + Maximum number of characters in the representation for an integer. Digits + are dropped from the middle. The default is ``40``. + + +.. attribute:: Repr.maxstring + + Limit on the number of characters in the representation of the string. Note + that the "normal" representation of the string is used as the character source: + if escape sequences are needed in the representation, these may be mangled when + the representation is shortened. The default is ``30``. + + +.. attribute:: Repr.maxother + + This limit is used to control the size of object types for which no specific + formatting method is available on the :class:`Repr` object. It is applied in a + similar manner as :attr:`maxstring`. The default is ``20``. + + +.. method:: Repr.repr(obj) + + The equivalent to the built-in :func:`repr` that uses the formatting imposed by + the instance. + + +.. method:: Repr.repr1(obj, level) + + Recursive implementation used by :meth:`.repr`. This uses the type of *obj* to + determine which formatting method to call, passing it *obj* and *level*. The + type-specific methods should call :meth:`repr1` to perform recursive formatting, + with ``level - 1`` for the value of *level* in the recursive call. + + +.. method:: Repr.repr_TYPE(obj, level) + :noindex: + + Formatting methods for specific types are implemented as methods with a name + based on the type name. In the method name, **TYPE** is replaced by + ``'_'.join(type(obj).__name__.split())``. Dispatch to these methods is + handled by :meth:`repr1`. Type-specific methods which need to recursively + format a value should call ``self.repr1(subobj, level - 1)``. + + +.. _subclassing-reprs: + +Subclassing Repr Objects +------------------------ + +The use of dynamic dispatching by :meth:`Repr.repr1` allows subclasses of +:class:`Repr` to add support for additional built-in object types or to modify +the handling of types already supported. This example shows how special support +for file objects could be added:: + + import reprlib + import sys + + class MyRepr(reprlib.Repr): + + def repr_TextIOWrapper(self, obj, level): + if obj.name in {'', '', ''}: + return obj.name + return repr(obj) + + aRepr = MyRepr() + print(aRepr.repr(sys.stdin)) # prints '' diff --git a/cpython_2/environment/repo/Doc/library/resource.rst b/cpython_2/environment/repo/Doc/library/resource.rst new file mode 100644 index 0000000000000000000000000000000000000000..e4eac43642d14de7e64e3a6415ac0ff79f0a784d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/resource.rst @@ -0,0 +1,371 @@ +:mod:`resource` --- Resource usage information +============================================== + +.. module:: resource + :platform: Unix + :synopsis: An interface to provide resource usage information on the current process. + +.. moduleauthor:: Jeremy Hylton +.. sectionauthor:: Jeremy Hylton + +-------------- + +This module provides basic mechanisms for measuring and controlling system +resources utilized by a program. + +Symbolic constants are used to specify particular system resources and to +request usage information about either the current process or its children. + +An :exc:`OSError` is raised on syscall failure. + + +.. exception:: error + + A deprecated alias of :exc:`OSError`. + + .. versionchanged:: 3.3 + Following :pep:`3151`, this class was made an alias of :exc:`OSError`. + + +Resource Limits +--------------- + +Resources usage can be limited using the :func:`setrlimit` function described +below. Each resource is controlled by a pair of limits: a soft limit and a hard +limit. The soft limit is the current limit, and may be lowered or raised by a +process over time. The soft limit can never exceed the hard limit. The hard +limit can be lowered to any value greater than the soft limit, but not raised. +(Only processes with the effective UID of the super-user can raise a hard +limit.) + +The specific resources that can be limited are system dependent. They are +described in the :manpage:`getrlimit(2)` man page. The resources listed below +are supported when the underlying operating system supports them; resources +which cannot be checked or controlled by the operating system are not defined in +this module for those platforms. + + +.. data:: RLIM_INFINITY + + Constant used to represent the limit for an unlimited resource. + + +.. function:: getrlimit(resource) + + Returns a tuple ``(soft, hard)`` with the current soft and hard limits of + *resource*. Raises :exc:`ValueError` if an invalid resource is specified, or + :exc:`error` if the underlying system call fails unexpectedly. + + +.. function:: setrlimit(resource, limits) + + Sets new limits of consumption of *resource*. The *limits* argument must be a + tuple ``(soft, hard)`` of two integers describing the new limits. A value of + :data:`~resource.RLIM_INFINITY` can be used to request a limit that is + unlimited. + + Raises :exc:`ValueError` if an invalid resource is specified, if the new soft + limit exceeds the hard limit, or if a process tries to raise its hard limit. + Specifying a limit of :data:`~resource.RLIM_INFINITY` when the hard or + system limit for that resource is not unlimited will result in a + :exc:`ValueError`. A process with the effective UID of super-user can + request any valid limit value, including unlimited, but :exc:`ValueError` + will still be raised if the requested limit exceeds the system imposed + limit. + + ``setrlimit`` may also raise :exc:`error` if the underlying system call + fails. + + VxWorks only supports setting :data:`RLIMIT_NOFILE`. + + .. audit-event:: resource.setrlimit resource,limits resource.setrlimit + + +.. function:: prlimit(pid, resource[, limits]) + + Combines :func:`setrlimit` and :func:`getrlimit` in one function and + supports to get and set the resources limits of an arbitrary process. If + *pid* is 0, then the call applies to the current process. *resource* and + *limits* have the same meaning as in :func:`setrlimit`, except that + *limits* is optional. + + When *limits* is not given the function returns the *resource* limit of the + process *pid*. When *limits* is given the *resource* limit of the process is + set and the former resource limit is returned. + + Raises :exc:`ProcessLookupError` when *pid* can't be found and + :exc:`PermissionError` when the user doesn't have ``CAP_SYS_RESOURCE`` for + the process. + + .. audit-event:: resource.prlimit pid,resource,limits resource.prlimit + + .. availability:: Linux 2.6.36 or later with glibc 2.13 or later. + + .. versionadded:: 3.4 + + +These symbols define resources whose consumption can be controlled using the +:func:`setrlimit` and :func:`getrlimit` functions described below. The values of +these symbols are exactly the constants used by C programs. + +The Unix man page for :manpage:`getrlimit(2)` lists the available resources. +Note that not all systems use the same symbol or same value to denote the same +resource. This module does not attempt to mask platform differences --- symbols +not defined for a platform will not be available from this module on that +platform. + + +.. data:: RLIMIT_CORE + + The maximum size (in bytes) of a core file that the current process can create. + This may result in the creation of a partial core file if a larger core would be + required to contain the entire process image. + + +.. data:: RLIMIT_CPU + + The maximum amount of processor time (in seconds) that a process can use. If + this limit is exceeded, a :const:`SIGXCPU` signal is sent to the process. (See + the :mod:`signal` module documentation for information about how to catch this + signal and do something useful, e.g. flush open files to disk.) + + +.. data:: RLIMIT_FSIZE + + The maximum size of a file which the process may create. + + +.. data:: RLIMIT_DATA + + The maximum size (in bytes) of the process's heap. + + +.. data:: RLIMIT_STACK + + The maximum size (in bytes) of the call stack for the current process. This only + affects the stack of the main thread in a multi-threaded process. + + +.. data:: RLIMIT_RSS + + The maximum resident set size that should be made available to the process. + + +.. data:: RLIMIT_NPROC + + The maximum number of processes the current process may create. + + +.. data:: RLIMIT_NOFILE + + The maximum number of open file descriptors for the current process. + + +.. data:: RLIMIT_OFILE + + The BSD name for :const:`RLIMIT_NOFILE`. + + +.. data:: RLIMIT_MEMLOCK + + The maximum address space which may be locked in memory. + + +.. data:: RLIMIT_VMEM + + The largest area of mapped memory which the process may occupy. + + +.. data:: RLIMIT_AS + + The maximum area (in bytes) of address space which may be taken by the process. + + +.. data:: RLIMIT_MSGQUEUE + + The number of bytes that can be allocated for POSIX message queues. + + .. availability:: Linux 2.6.8 or later. + + .. versionadded:: 3.4 + + +.. data:: RLIMIT_NICE + + The ceiling for the process's nice level (calculated as 20 - rlim_cur). + + .. availability:: Linux 2.6.12 or later. + + .. versionadded:: 3.4 + + +.. data:: RLIMIT_RTPRIO + + The ceiling of the real-time priority. + + .. availability:: Linux 2.6.12 or later. + + .. versionadded:: 3.4 + + +.. data:: RLIMIT_RTTIME + + The time limit (in microseconds) on CPU time that a process can spend + under real-time scheduling without making a blocking syscall. + + .. availability:: Linux 2.6.25 or later. + + .. versionadded:: 3.4 + + +.. data:: RLIMIT_SIGPENDING + + The number of signals which the process may queue. + + .. availability:: Linux 2.6.8 or later. + + .. versionadded:: 3.4 + +.. data:: RLIMIT_SBSIZE + + The maximum size (in bytes) of socket buffer usage for this user. + This limits the amount of network memory, and hence the amount of mbufs, + that this user may hold at any time. + + .. availability:: FreeBSD 9 or later. + + .. versionadded:: 3.4 + +.. data:: RLIMIT_SWAP + + The maximum size (in bytes) of the swap space that may be reserved or + used by all of this user id's processes. + This limit is enforced only if bit 1 of the vm.overcommit sysctl is set. + Please see :manpage:`tuning(7)` for a complete description of this sysctl. + + .. availability:: FreeBSD 9 or later. + + .. versionadded:: 3.4 + +.. data:: RLIMIT_NPTS + + The maximum number of pseudo-terminals created by this user id. + + .. availability:: FreeBSD 9 or later. + + .. versionadded:: 3.4 + +Resource Usage +-------------- + +These functions are used to retrieve resource usage information: + + +.. function:: getrusage(who) + + This function returns an object that describes the resources consumed by either + the current process or its children, as specified by the *who* parameter. The + *who* parameter should be specified using one of the :const:`RUSAGE_\*` + constants described below. + + A simple example:: + + from resource import * + import time + + # a non CPU-bound task + time.sleep(3) + print(getrusage(RUSAGE_SELF)) + + # a CPU-bound task + for i in range(10 ** 8): + _ = 1 + 1 + print(getrusage(RUSAGE_SELF)) + + The fields of the return value each describe how a particular system resource + has been used, e.g. amount of time spent running is user mode or number of times + the process was swapped out of main memory. Some values are dependent on the + clock tick internal, e.g. the amount of memory the process is using. + + For backward compatibility, the return value is also accessible as a tuple of 16 + elements. + + The fields :attr:`ru_utime` and :attr:`ru_stime` of the return value are + floating point values representing the amount of time spent executing in user + mode and the amount of time spent executing in system mode, respectively. The + remaining values are integers. Consult the :manpage:`getrusage(2)` man page for + detailed information about these values. A brief summary is presented here: + + +--------+---------------------+---------------------------------------+ + | Index | Field | Resource | + +========+=====================+=======================================+ + | ``0`` | :attr:`ru_utime` | time in user mode (float seconds) | + +--------+---------------------+---------------------------------------+ + | ``1`` | :attr:`ru_stime` | time in system mode (float seconds) | + +--------+---------------------+---------------------------------------+ + | ``2`` | :attr:`ru_maxrss` | maximum resident set size | + +--------+---------------------+---------------------------------------+ + | ``3`` | :attr:`ru_ixrss` | shared memory size | + +--------+---------------------+---------------------------------------+ + | ``4`` | :attr:`ru_idrss` | unshared memory size | + +--------+---------------------+---------------------------------------+ + | ``5`` | :attr:`ru_isrss` | unshared stack size | + +--------+---------------------+---------------------------------------+ + | ``6`` | :attr:`ru_minflt` | page faults not requiring I/O | + +--------+---------------------+---------------------------------------+ + | ``7`` | :attr:`ru_majflt` | page faults requiring I/O | + +--------+---------------------+---------------------------------------+ + | ``8`` | :attr:`ru_nswap` | number of swap outs | + +--------+---------------------+---------------------------------------+ + | ``9`` | :attr:`ru_inblock` | block input operations | + +--------+---------------------+---------------------------------------+ + | ``10`` | :attr:`ru_oublock` | block output operations | + +--------+---------------------+---------------------------------------+ + | ``11`` | :attr:`ru_msgsnd` | messages sent | + +--------+---------------------+---------------------------------------+ + | ``12`` | :attr:`ru_msgrcv` | messages received | + +--------+---------------------+---------------------------------------+ + | ``13`` | :attr:`ru_nsignals` | signals received | + +--------+---------------------+---------------------------------------+ + | ``14`` | :attr:`ru_nvcsw` | voluntary context switches | + +--------+---------------------+---------------------------------------+ + | ``15`` | :attr:`ru_nivcsw` | involuntary context switches | + +--------+---------------------+---------------------------------------+ + + This function will raise a :exc:`ValueError` if an invalid *who* parameter is + specified. It may also raise :exc:`error` exception in unusual circumstances. + + +.. function:: getpagesize() + + Returns the number of bytes in a system page. (This need not be the same as the + hardware page size.) + +The following :const:`RUSAGE_\*` symbols are passed to the :func:`getrusage` +function to specify which processes information should be provided for. + + +.. data:: RUSAGE_SELF + + Pass to :func:`getrusage` to request resources consumed by the calling + process, which is the sum of resources used by all threads in the process. + + +.. data:: RUSAGE_CHILDREN + + Pass to :func:`getrusage` to request resources consumed by child processes + of the calling process which have been terminated and waited for. + + +.. data:: RUSAGE_BOTH + + Pass to :func:`getrusage` to request resources consumed by both the current + process and child processes. May not be available on all systems. + + +.. data:: RUSAGE_THREAD + + Pass to :func:`getrusage` to request resources consumed by the current + thread. May not be available on all systems. + + .. versionadded:: 3.2 diff --git a/cpython_2/environment/repo/Doc/library/rlcompleter.rst b/cpython_2/environment/repo/Doc/library/rlcompleter.rst new file mode 100644 index 0000000000000000000000000000000000000000..40b09ce897880edd450c99fef939d8f5fed55028 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/rlcompleter.rst @@ -0,0 +1,61 @@ +:mod:`rlcompleter` --- Completion function for GNU readline +=========================================================== + +.. module:: rlcompleter + :synopsis: Python identifier completion, suitable for the GNU readline library. + +.. sectionauthor:: Moshe Zadka + +**Source code:** :source:`Lib/rlcompleter.py` + +-------------- + +The :mod:`rlcompleter` module defines a completion function suitable for the +:mod:`readline` module by completing valid Python identifiers and keywords. + +When this module is imported on a Unix platform with the :mod:`readline` module +available, an instance of the :class:`Completer` class is automatically created +and its :meth:`complete` method is set as the :mod:`readline` completer. + +Example:: + + >>> import rlcompleter + >>> import readline + >>> readline.parse_and_bind("tab: complete") + >>> readline. + readline.__doc__ readline.get_line_buffer( readline.read_init_file( + readline.__file__ readline.insert_text( readline.set_completer( + readline.__name__ readline.parse_and_bind( + >>> readline. + +The :mod:`rlcompleter` module is designed for use with Python's +:ref:`interactive mode `. Unless Python is run with the +:option:`-S` option, the module is automatically imported and configured +(see :ref:`rlcompleter-config`). + +On platforms without :mod:`readline`, the :class:`Completer` class defined by +this module can still be used for custom purposes. + + +.. _completer-objects: + +Completer Objects +----------------- + +Completer objects have the following method: + + +.. method:: Completer.complete(text, state) + + Return the *state*\ th completion for *text*. + + If called for *text* that doesn't include a period character (``'.'``), it will + complete from names currently defined in :mod:`__main__`, :mod:`builtins` and + keywords (as defined by the :mod:`keyword` module). + + 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 + expression is caught, silenced and :const:`None` is returned. + diff --git a/cpython_2/environment/repo/Doc/library/runpy.rst b/cpython_2/environment/repo/Doc/library/runpy.rst new file mode 100644 index 0000000000000000000000000000000000000000..af35e81a2d4523996250adb4f54de031a5a7b168 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/runpy.rst @@ -0,0 +1,179 @@ +:mod:`runpy` --- Locating and executing Python modules +====================================================== + +.. module:: runpy + :synopsis: Locate and run Python modules without importing them first. + +.. moduleauthor:: Nick Coghlan + +**Source code:** :source:`Lib/runpy.py` + +-------------- + +The :mod:`runpy` module is used to locate and run Python modules without +importing them first. Its main use is to implement the :option:`-m` command +line switch that allows scripts to be located using the Python module +namespace rather than the filesystem. + +Note that this is *not* a sandbox module - all code is executed in the +current process, and any side effects (such as cached imports of other +modules) will remain in place after the functions have returned. + +Furthermore, any functions and classes defined by the executed code are not +guaranteed to work correctly after a :mod:`runpy` function has returned. +If that limitation is not acceptable for a given use case, :mod:`importlib` +is likely to be a more suitable choice than this module. + +The :mod:`runpy` module provides two functions: + + +.. function:: run_module(mod_name, init_globals=None, run_name=None, alter_sys=False) + + .. index:: + module: __main__ + + Execute the code of the specified module and return the resulting module + globals dictionary. The module's code is first located using the standard + import mechanism (refer to :pep:`302` for details) and then executed in a + fresh module namespace. + + The *mod_name* argument should be an absolute module name. + If the module name refers to a package rather than a normal + module, then that package is imported and the ``__main__`` submodule within + that package is then executed and the resulting module globals dictionary + returned. + + The optional dictionary argument *init_globals* may be used to pre-populate + the module's globals dictionary before the code is executed. The supplied + dictionary will not be modified. If any of the special global variables + below are defined in the supplied dictionary, those definitions are + overridden by :func:`run_module`. + + The special global variables ``__name__``, ``__spec__``, ``__file__``, + ``__cached__``, ``__loader__`` and ``__package__`` are set in the globals + dictionary before the module code is executed (Note that this is a + minimal set of variables - other variables may be set implicitly as an + interpreter implementation detail). + + ``__name__`` is set to *run_name* if this optional argument is not + :const:`None`, to ``mod_name + '.__main__'`` if the named module is a + package and to the *mod_name* argument otherwise. + + ``__spec__`` will be set appropriately for the *actually* imported + module (that is, ``__spec__.name`` will always be *mod_name* or + ``mod_name + '.__main__``, never *run_name*). + + ``__file__``, ``__cached__``, ``__loader__`` and ``__package__`` are + :ref:`set as normal ` based on the module spec. + + If the argument *alter_sys* is supplied and evaluates to :const:`True`, + then ``sys.argv[0]`` is updated with the value of ``__file__`` and + ``sys.modules[__name__]`` is updated with a temporary module object for the + module being executed. Both ``sys.argv[0]`` and ``sys.modules[__name__]`` + are restored to their original values before the function returns. + + Note that this manipulation of :mod:`sys` is not thread-safe. Other threads + may see the partially initialised module, as well as the altered list of + arguments. It is recommended that the :mod:`sys` module be left alone when + invoking this function from threaded code. + + .. seealso:: + The :option:`-m` option offering equivalent functionality from the + command line. + + .. versionchanged:: 3.1 + Added ability to execute packages by looking for a ``__main__`` submodule. + + .. versionchanged:: 3.2 + Added ``__cached__`` global variable (see :pep:`3147`). + + .. versionchanged:: 3.4 + Updated to take advantage of the module spec feature added by + :pep:`451`. This allows ``__cached__`` to be set correctly for modules + run this way, as well as ensuring the real module name is always + accessible as ``__spec__.name``. + +.. function:: run_path(file_path, init_globals=None, run_name=None) + + .. index:: + module: __main__ + + Execute the code at the named filesystem location and return the resulting + module globals dictionary. As with a script name supplied to the CPython + command line, the supplied path may refer to a Python source file, a + compiled bytecode file or a valid sys.path entry containing a ``__main__`` + module (e.g. a zipfile containing a top-level ``__main__.py`` file). + + For a simple script, the specified code is simply executed in a fresh + module namespace. For a valid sys.path entry (typically a zipfile or + directory), the entry is first added to the beginning of ``sys.path``. The + function then looks for and executes a :mod:`__main__` module using the + updated path. Note that there is no special protection against invoking + an existing :mod:`__main__` entry located elsewhere on ``sys.path`` if + there is no such module at the specified location. + + The optional dictionary argument *init_globals* may be used to pre-populate + the module's globals dictionary before the code is executed. The supplied + dictionary will not be modified. If any of the special global variables + below are defined in the supplied dictionary, those definitions are + overridden by :func:`run_path`. + + The special global variables ``__name__``, ``__spec__``, ``__file__``, + ``__cached__``, ``__loader__`` and ``__package__`` are set in the globals + dictionary before the module code is executed (Note that this is a + minimal set of variables - other variables may be set implicitly as an + interpreter implementation detail). + + ``__name__`` is set to *run_name* if this optional argument is not + :const:`None` and to ``''`` otherwise. + + If the supplied path directly references a script file (whether as source + or as precompiled byte code), then ``__file__`` will be set to the + supplied path, and ``__spec__``, ``__cached__``, ``__loader__`` and + ``__package__`` will all be set to :const:`None`. + + If the supplied path is a reference to a valid sys.path entry, then + ``__spec__`` will be set appropriately for the imported ``__main__`` + module (that is, ``__spec__.name`` will always be ``__main__``). + ``__file__``, ``__cached__``, ``__loader__`` and ``__package__`` will be + :ref:`set as normal ` based on the module spec. + + A number of alterations are also made to the :mod:`sys` module. Firstly, + ``sys.path`` may be altered as described above. ``sys.argv[0]`` is updated + with the value of ``file_path`` and ``sys.modules[__name__]`` is updated + with a temporary module object for the module being executed. All + modifications to items in :mod:`sys` are reverted before the function + returns. + + Note that, unlike :func:`run_module`, the alterations made to :mod:`sys` + are not optional in this function as these adjustments are essential to + allowing the execution of sys.path entries. As the thread-safety + limitations still apply, use of this function in threaded code should be + either serialised with the import lock or delegated to a separate process. + + .. seealso:: + :ref:`using-on-interface-options` for equivalent functionality on the + command line (``python path/to/script``). + + .. versionadded:: 3.2 + + .. versionchanged:: 3.4 + Updated to take advantage of the module spec feature added by + :pep:`451`. This allows ``__cached__`` to be set correctly in the + case where ``__main__`` is imported from a valid sys.path entry rather + than being executed directly. + +.. seealso:: + + :pep:`338` -- Executing modules as scripts + PEP written and implemented by Nick Coghlan. + + :pep:`366` -- Main module explicit relative imports + PEP written and implemented by Nick Coghlan. + + :pep:`451` -- A ModuleSpec Type for the Import System + PEP written and implemented by Eric Snow + + :ref:`using-on-general` - CPython command line details + + The :func:`importlib.import_module` function diff --git a/cpython_2/environment/repo/Doc/library/sched.rst b/cpython_2/environment/repo/Doc/library/sched.rst new file mode 100644 index 0000000000000000000000000000000000000000..a4ba2848f11ddea5bead75617bbee35ae086bee8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/sched.rst @@ -0,0 +1,137 @@ +:mod:`sched` --- Event scheduler +================================ + +.. module:: sched + :synopsis: General purpose event scheduler. + +.. sectionauthor:: Moshe Zadka + +**Source code:** :source:`Lib/sched.py` + +.. index:: single: event scheduling + +-------------- + +The :mod:`sched` module defines a class which implements a general purpose event +scheduler: + +.. class:: scheduler(timefunc=time.monotonic, delayfunc=time.sleep) + + The :class:`scheduler` class defines a generic interface to scheduling events. + It needs two functions to actually deal with the "outside world" --- *timefunc* + should be callable without arguments, and return a number (the "time", in any + units whatsoever). The *delayfunc* function should be callable with one + argument, compatible with the output of *timefunc*, and should delay that many + time units. *delayfunc* will also be called with the argument ``0`` after each + event is run to allow other threads an opportunity to run in multi-threaded + applications. + + .. versionchanged:: 3.3 + *timefunc* and *delayfunc* parameters are optional. + + .. versionchanged:: 3.3 + :class:`scheduler` class can be safely used in multi-threaded + environments. + +Example:: + + >>> import sched, time + >>> s = sched.scheduler(time.time, time.sleep) + >>> def print_time(a='default'): + ... print("From print_time", time.time(), a) + ... + >>> def print_some_times(): + ... print(time.time()) + ... s.enter(10, 1, print_time) + ... s.enter(5, 2, print_time, argument=('positional',)) + ... s.enter(5, 1, print_time, kwargs={'a': 'keyword'}) + ... s.run() + ... print(time.time()) + ... + >>> print_some_times() + 930343690.257 + From print_time 930343695.274 positional + From print_time 930343695.275 keyword + From print_time 930343700.273 default + 930343700.276 + +.. _scheduler-objects: + +Scheduler Objects +----------------- + +:class:`scheduler` instances have the following methods and attributes: + + +.. method:: scheduler.enterabs(time, priority, action, argument=(), kwargs={}) + + Schedule a new event. The *time* argument should be a numeric type compatible + with the return value of the *timefunc* function passed to the constructor. + Events scheduled for the same *time* will be executed in the order of their + *priority*. A lower number represents a higher priority. + + Executing the event means executing ``action(*argument, **kwargs)``. + *argument* is a sequence holding the positional arguments for *action*. + *kwargs* is a dictionary holding the keyword arguments for *action*. + + Return value is an event which may be used for later cancellation of the event + (see :meth:`cancel`). + + .. versionchanged:: 3.3 + *argument* parameter is optional. + + .. versionchanged:: 3.3 + *kwargs* parameter was added. + + +.. method:: scheduler.enter(delay, priority, action, argument=(), kwargs={}) + + Schedule an event for *delay* more time units. Other than the relative time, the + other arguments, the effect and the return value are the same as those for + :meth:`enterabs`. + + .. versionchanged:: 3.3 + *argument* parameter is optional. + + .. versionchanged:: 3.3 + *kwargs* parameter was added. + +.. method:: scheduler.cancel(event) + + Remove the event from the queue. If *event* is not an event currently in the + queue, this method will raise a :exc:`ValueError`. + + +.. method:: scheduler.empty() + + Return ``True`` if the event queue is empty. + + +.. method:: scheduler.run(blocking=True) + + Run all scheduled events. This method will wait (using the :func:`delayfunc` + function passed to the constructor) for the next event, then execute it and so + on until there are no more scheduled events. + + If *blocking* is false executes the scheduled events due to expire soonest + (if any) and then return the deadline of the next scheduled call in the + scheduler (if any). + + Either *action* or *delayfunc* can raise an exception. In either case, the + scheduler will maintain a consistent state and propagate the exception. If an + exception is raised by *action*, the event will not be attempted in future calls + to :meth:`run`. + + If a sequence of events takes longer to run than the time available before the + next event, the scheduler will simply fall behind. No events will be dropped; + the calling code is responsible for canceling events which are no longer + pertinent. + + .. versionchanged:: 3.3 + *blocking* parameter was added. + +.. attribute:: scheduler.queue + + Read-only attribute returning a list of upcoming events in the order they + will be run. Each event is shown as a :term:`named tuple` with the + following fields: time, priority, action, argument, kwargs. diff --git a/cpython_2/environment/repo/Doc/library/secrets.rst b/cpython_2/environment/repo/Doc/library/secrets.rst new file mode 100644 index 0000000000000000000000000000000000000000..bc4766da2785b36dfe8b0621abb5389d3138f197 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/secrets.rst @@ -0,0 +1,202 @@ +:mod:`secrets` --- Generate secure random numbers for managing secrets +====================================================================== + +.. module:: secrets + :synopsis: Generate secure random numbers for managing secrets. + +.. moduleauthor:: Steven D'Aprano +.. sectionauthor:: Steven D'Aprano +.. versionadded:: 3.6 + +.. testsetup:: + + from secrets import * + __name__ = '' + +**Source code:** :source:`Lib/secrets.py` + +------------- + +The :mod:`secrets` module is used for generating cryptographically strong +random numbers suitable for managing data such as passwords, account +authentication, security tokens, and related secrets. + +In particularly, :mod:`secrets` should be used in preference to the +default pseudo-random number generator in the :mod:`random` module, which +is designed for modelling and simulation, not security or cryptography. + +.. seealso:: + + :pep:`506` + + +Random numbers +-------------- + +The :mod:`secrets` module provides access to the most secure source of +randomness that your operating system provides. + +.. class:: SystemRandom + + A class for generating random numbers using the highest-quality + sources provided by the operating system. See + :class:`random.SystemRandom` for additional details. + +.. function:: choice(sequence) + + Return a randomly-chosen element from a non-empty sequence. + +.. function:: randbelow(n) + + Return a random int in the range [0, *n*). + +.. function:: randbits(k) + + Return an int with *k* random bits. + + +Generating tokens +----------------- + +The :mod:`secrets` module provides functions for generating secure +tokens, suitable for applications such as password resets, +hard-to-guess URLs, and similar. + +.. function:: token_bytes([nbytes=None]) + + Return a random byte string containing *nbytes* number of bytes. + If *nbytes* is ``None`` or not supplied, a reasonable default is + used. + + .. doctest:: + + >>> token_bytes(16) #doctest:+SKIP + b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b' + + +.. function:: token_hex([nbytes=None]) + + Return a random text string, in hexadecimal. The string has *nbytes* + random bytes, each byte converted to two hex digits. If *nbytes* is + ``None`` or not supplied, a reasonable default is used. + + .. doctest:: + + >>> token_hex(16) #doctest:+SKIP + 'f9bf78b9a18ce6d46a0cd2b0b86df9da' + +.. function:: token_urlsafe([nbytes=None]) + + Return a random URL-safe text string, containing *nbytes* random + bytes. The text is Base64 encoded, so on average each byte results + in approximately 1.3 characters. If *nbytes* is ``None`` or not + supplied, a reasonable default is used. + + .. doctest:: + + >>> token_urlsafe(16) #doctest:+SKIP + 'Drmhze6EPcv0fN_81Bj-nA' + + +How many bytes should tokens use? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To be secure against +`brute-force attacks `_, +tokens need to have sufficient randomness. Unfortunately, what is +considered sufficient will necessarily increase as computers get more +powerful and able to make more guesses in a shorter period. As of 2015, +it is believed that 32 bytes (256 bits) of randomness is sufficient for +the typical use-case expected for the :mod:`secrets` module. + +For those who want to manage their own token length, you can explicitly +specify how much randomness is used for tokens by giving an :class:`int` +argument to the various ``token_*`` functions. That argument is taken +as the number of bytes of randomness to use. + +Otherwise, if no argument is provided, or if the argument is ``None``, +the ``token_*`` functions will use a reasonable default instead. + +.. note:: + + That default is subject to change at any time, including during + maintenance releases. + + +Other functions +--------------- + +.. function:: compare_digest(a, b) + + Return ``True`` if strings *a* and *b* are equal, otherwise ``False``, + in such a way as to reduce the risk of + `timing attacks `_. + See :func:`hmac.compare_digest` for additional details. + + +Recipes and best practices +-------------------------- + +This section shows recipes and best practices for using :mod:`secrets` +to manage a basic level of security. + +Generate an eight-character alphanumeric password: + +.. testcode:: + + import string + import secrets + alphabet = string.ascii_letters + string.digits + password = ''.join(secrets.choice(alphabet) for i in range(8)) + + +.. note:: + + Applications should not + `store passwords in a recoverable format `_, + whether plain text or encrypted. They should be salted and hashed + using a cryptographically-strong one-way (irreversible) hash function. + + +Generate a ten-character alphanumeric password with at least one +lowercase character, at least one uppercase character, and at least +three digits: + +.. testcode:: + + import string + import secrets + alphabet = string.ascii_letters + string.digits + while True: + password = ''.join(secrets.choice(alphabet) for i in range(10)) + if (any(c.islower() for c in password) + and any(c.isupper() for c in password) + and sum(c.isdigit() for c in password) >= 3): + break + + +Generate an `XKCD-style passphrase `_: + +.. testcode:: + + import secrets + # On standard Linux systems, use a convenient dictionary file. + # Other platforms may need to provide their own word-list. + with open('/usr/share/dict/words') as f: + words = [word.strip() for word in f] + password = ' '.join(secrets.choice(words) for i in range(4)) + + +Generate a hard-to-guess temporary URL containing a security token +suitable for password recovery applications: + +.. testcode:: + + import secrets + url = 'https://mydomain.com/reset=' + secrets.token_urlsafe() + + + +.. + # This modeline must appear within the last ten lines of the file. + kate: indent-width 3; remove-trailing-space on; replace-tabs on; encoding utf-8; diff --git a/cpython_2/environment/repo/Doc/library/select.rst b/cpython_2/environment/repo/Doc/library/select.rst new file mode 100644 index 0000000000000000000000000000000000000000..bb2809580d0401fef6d02c14bad6eef106fe5517 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/select.rst @@ -0,0 +1,649 @@ +:mod:`select` --- Waiting for I/O completion +============================================ + +.. module:: select + :synopsis: Wait for I/O completion on multiple streams. + +-------------- + +This module provides access to the :c:func:`select` and :c:func:`poll` functions +available in most operating systems, :c:func:`devpoll` available on +Solaris and derivatives, :c:func:`epoll` available on Linux 2.5+ and +:c:func:`kqueue` available on most BSD. +Note that on Windows, it only works for sockets; on other operating systems, +it also works for other file types (in particular, on Unix, it works on pipes). +It cannot be used on regular files to determine whether a file has grown since +it was last read. + +.. note:: + + The :mod:`selectors` module allows high-level and efficient I/O + multiplexing, built upon the :mod:`select` module primitives. Users are + encouraged to use the :mod:`selectors` module instead, unless they want + precise control over the OS-level primitives used. + + +The module defines the following: + + +.. exception:: error + + A deprecated alias of :exc:`OSError`. + + .. versionchanged:: 3.3 + Following :pep:`3151`, this class was made an alias of :exc:`OSError`. + + +.. function:: devpoll() + + (Only supported on Solaris and derivatives.) Returns a ``/dev/poll`` + polling object; see section :ref:`devpoll-objects` below for the + methods supported by devpoll objects. + + :c:func:`devpoll` objects are linked to the number of file + descriptors allowed at the time of instantiation. If your program + reduces this value, :c:func:`devpoll` will fail. If your program + increases this value, :c:func:`devpoll` may return an + incomplete list of active file descriptors. + + The new file descriptor is :ref:`non-inheritable `. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.4 + The new file descriptor is now non-inheritable. + +.. function:: epoll(sizehint=-1, flags=0) + + (Only supported on Linux 2.5.44 and newer.) Return an edge polling object, + which can be used as Edge or Level Triggered interface for I/O + events. + + *sizehint* informs epoll about the expected number of events to be + registered. It must be positive, or `-1` to use the default. It is only + used on older systems where :c:func:`epoll_create1` is not available; + otherwise it has no effect (though its value is still checked). + + *flags* is deprecated and completely ignored. However, when supplied, its + value must be ``0`` or ``select.EPOLL_CLOEXEC``, otherwise ``OSError`` is + raised. + + See the :ref:`epoll-objects` section below for the methods supported by + epolling objects. + + ``epoll`` objects support the context management protocol: when used in a + :keyword:`with` statement, the new file descriptor is automatically closed + at the end of the block. + + The new file descriptor is :ref:`non-inheritable `. + + .. versionchanged:: 3.3 + Added the *flags* parameter. + + .. versionchanged:: 3.4 + Support for the :keyword:`with` statement was added. + The new file descriptor is now non-inheritable. + + .. deprecated:: 3.4 + The *flags* parameter. ``select.EPOLL_CLOEXEC`` is used by default now. + Use :func:`os.set_inheritable` to make the file descriptor inheritable. + + +.. function:: poll() + + (Not supported by all operating systems.) Returns a polling object, which + supports registering and unregistering file descriptors, and then polling them + for I/O events; see section :ref:`poll-objects` below for the methods supported + by polling objects. + + +.. function:: kqueue() + + (Only supported on BSD.) Returns a kernel queue object; see section + :ref:`kqueue-objects` below for the methods supported by kqueue objects. + + The new file descriptor is :ref:`non-inheritable `. + + .. versionchanged:: 3.4 + The new file descriptor is now non-inheritable. + + +.. function:: kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0) + + (Only supported on BSD.) Returns a kernel event object; see section + :ref:`kevent-objects` below for the methods supported by kevent objects. + + +.. function:: select(rlist, wlist, xlist[, timeout]) + + This is a straightforward interface to the Unix :c:func:`select` system call. + The first three arguments are sequences of 'waitable objects': either + integers representing file descriptors or objects with a parameterless method + named :meth:`~io.IOBase.fileno` returning such an integer: + + * *rlist*: wait until ready for reading + * *wlist*: wait until ready for writing + * *xlist*: wait for an "exceptional condition" (see the manual page for what + your system considers such a condition) + + Empty sequences are allowed, but acceptance of three empty sequences is + platform-dependent. (It is known to work on Unix but not on Windows.) The + optional *timeout* argument specifies a time-out as a floating point number + in seconds. When the *timeout* argument is omitted the function blocks until + at least one file descriptor is ready. A time-out value of zero specifies a + poll and never blocks. + + The return value is a triple of lists of objects that are ready: subsets of the + first three arguments. When the time-out is reached without a file descriptor + becoming ready, three empty lists are returned. + + .. index:: + single: socket() (in module socket) + single: popen() (in module os) + + Among the acceptable object types in the sequences are Python :term:`file + objects ` (e.g. ``sys.stdin``, or objects returned by + :func:`open` or :func:`os.popen`), socket objects returned by + :func:`socket.socket`. You may also define a :dfn:`wrapper` class yourself, + as long as it has an appropriate :meth:`~io.IOBase.fileno` method (that + really returns a file descriptor, not just a random integer). + + .. note:: + + .. index:: single: WinSock + + File objects on Windows are not acceptable, but sockets are. On Windows, + the underlying :c:func:`select` function is provided by the WinSock + library, and does not handle file descriptors that don't originate from + WinSock. + + .. versionchanged:: 3.5 + The function is now retried with a recomputed timeout when interrupted by + a signal, except if the signal handler raises an exception (see + :pep:`475` for the rationale), instead of raising + :exc:`InterruptedError`. + + +.. attribute:: PIPE_BUF + + The minimum number of bytes which can be written without blocking to a pipe + when the pipe has been reported as ready for writing by :func:`~select.select`, + :func:`poll` or another interface in this module. This doesn't apply + to other kind of file-like objects such as sockets. + + This value is guaranteed by POSIX to be at least 512. + + .. availability:: Unix + + .. versionadded:: 3.2 + + +.. _devpoll-objects: + +``/dev/poll`` Polling Objects +----------------------------- + +Solaris and derivatives have ``/dev/poll``. While :c:func:`select` is +O(highest file descriptor) and :c:func:`poll` is O(number of file +descriptors), ``/dev/poll`` is O(active file descriptors). + +``/dev/poll`` behaviour is very close to the standard :c:func:`poll` +object. + + +.. method:: devpoll.close() + + Close the file descriptor of the polling object. + + .. versionadded:: 3.4 + + +.. attribute:: devpoll.closed + + ``True`` if the polling object is closed. + + .. versionadded:: 3.4 + + +.. method:: devpoll.fileno() + + Return the file descriptor number of the polling object. + + .. versionadded:: 3.4 + + +.. method:: devpoll.register(fd[, eventmask]) + + Register a file descriptor with the polling object. Future calls to the + :meth:`poll` method will then check whether the file descriptor has any + pending I/O events. *fd* can be either an integer, or an object with a + :meth:`~io.IOBase.fileno` method that returns an integer. File objects + implement :meth:`!fileno`, so they can also be used as the argument. + + *eventmask* is an optional bitmask describing the type of events you want to + check for. The constants are the same that with :c:func:`poll` + object. The default value is a combination of the constants :const:`POLLIN`, + :const:`POLLPRI`, and :const:`POLLOUT`. + + .. warning:: + + Registering a file descriptor that's already registered is not an + error, but the result is undefined. The appropriate action is to + unregister or modify it first. This is an important difference + compared with :c:func:`poll`. + + +.. method:: devpoll.modify(fd[, eventmask]) + + This method does an :meth:`unregister` followed by a + :meth:`register`. It is (a bit) more efficient that doing the same + explicitly. + + +.. method:: devpoll.unregister(fd) + + Remove a file descriptor being tracked by a polling object. Just like the + :meth:`register` method, *fd* can be an integer or an object with a + :meth:`~io.IOBase.fileno` method that returns an integer. + + Attempting to remove a file descriptor that was never registered is + safely ignored. + + +.. method:: devpoll.poll([timeout]) + + Polls the set of registered file descriptors, and returns a possibly-empty list + containing ``(fd, event)`` 2-tuples for the descriptors that have events or + errors to report. *fd* is the file descriptor, and *event* is a bitmask with + bits set for the reported events for that descriptor --- :const:`POLLIN` for + waiting input, :const:`POLLOUT` to indicate that the descriptor can be written + to, and so forth. An empty list indicates that the call timed out and no file + descriptors had any events to report. If *timeout* is given, it specifies the + length of time in milliseconds which the system will wait for events before + returning. If *timeout* is omitted, -1, or :const:`None`, the call will + block until there is an event for this poll object. + + .. versionchanged:: 3.5 + The function is now retried with a recomputed timeout when interrupted by + a signal, except if the signal handler raises an exception (see + :pep:`475` for the rationale), instead of raising + :exc:`InterruptedError`. + + +.. _epoll-objects: + +Edge and Level Trigger Polling (epoll) Objects +---------------------------------------------- + + https://linux.die.net/man/4/epoll + + *eventmask* + + +-------------------------+-----------------------------------------------+ + | Constant | Meaning | + +=========================+===============================================+ + | :const:`EPOLLIN` | Available for read | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLOUT` | Available for write | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLPRI` | Urgent data for read | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLERR` | Error condition happened on the assoc. fd | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLHUP` | Hang up happened on the assoc. fd | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLET` | Set Edge Trigger behavior, the default is | + | | Level Trigger behavior | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLONESHOT` | Set one-shot behavior. After one event is | + | | pulled out, the fd is internally disabled | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLEXCLUSIVE` | Wake only one epoll object when the | + | | associated fd has an event. The default (if | + | | this flag is not set) is to wake all epoll | + | | objects polling on a fd. | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLRDHUP` | Stream socket peer closed connection or shut | + | | down writing half of connection. | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLRDNORM` | Equivalent to :const:`EPOLLIN` | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLRDBAND` | Priority data band can be read. | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLWRNORM` | Equivalent to :const:`EPOLLOUT` | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLWRBAND` | Priority data may be written. | + +-------------------------+-----------------------------------------------+ + | :const:`EPOLLMSG` | Ignored. | + +-------------------------+-----------------------------------------------+ + + .. versionadded:: 3.6 + :const:`EPOLLEXCLUSIVE` was added. It's only supported by Linux Kernel 4.5 + or later. + +.. method:: epoll.close() + + Close the control file descriptor of the epoll object. + + +.. attribute:: epoll.closed + + ``True`` if the epoll object is closed. + + +.. method:: epoll.fileno() + + Return the file descriptor number of the control fd. + + +.. method:: epoll.fromfd(fd) + + Create an epoll object from a given file descriptor. + + +.. method:: epoll.register(fd[, eventmask]) + + Register a fd descriptor with the epoll object. + + +.. method:: epoll.modify(fd, eventmask) + + Modify a registered file descriptor. + + +.. method:: epoll.unregister(fd) + + Remove a registered file descriptor from the epoll object. + + .. versionchanged:: 3.9 + The method no longer ignores the :data:`~errno.EBADF` error. + + +.. method:: epoll.poll(timeout=None, maxevents=-1) + + Wait for events. timeout in seconds (float) + + .. versionchanged:: 3.5 + The function is now retried with a recomputed timeout when interrupted by + a signal, except if the signal handler raises an exception (see + :pep:`475` for the rationale), instead of raising + :exc:`InterruptedError`. + + +.. _poll-objects: + +Polling Objects +--------------- + +The :c:func:`poll` system call, supported on most Unix systems, provides better +scalability for network servers that service many, many clients at the same +time. :c:func:`poll` scales better because the system call only requires listing +the file descriptors of interest, while :c:func:`select` builds a bitmap, turns +on bits for the fds of interest, and then afterward the whole bitmap has to be +linearly scanned again. :c:func:`select` is O(highest file descriptor), while +:c:func:`poll` is O(number of file descriptors). + + +.. method:: poll.register(fd[, eventmask]) + + Register a file descriptor with the polling object. Future calls to the + :meth:`poll` method will then check whether the file descriptor has any + pending I/O events. *fd* can be either an integer, or an object with a + :meth:`~io.IOBase.fileno` method that returns an integer. File objects + implement :meth:`!fileno`, so they can also be used as the argument. + + *eventmask* is an optional bitmask describing the type of events you want to + check for, and can be a combination of the constants :const:`POLLIN`, + :const:`POLLPRI`, and :const:`POLLOUT`, described in the table below. If not + specified, the default value used will check for all 3 types of events. + + +-------------------+------------------------------------------+ + | Constant | Meaning | + +===================+==========================================+ + | :const:`POLLIN` | There is data to read | + +-------------------+------------------------------------------+ + | :const:`POLLPRI` | There is urgent data to read | + +-------------------+------------------------------------------+ + | :const:`POLLOUT` | Ready for output: writing will not block | + +-------------------+------------------------------------------+ + | :const:`POLLERR` | Error condition of some sort | + +-------------------+------------------------------------------+ + | :const:`POLLHUP` | Hung up | + +-------------------+------------------------------------------+ + | :const:`POLLRDHUP`| Stream socket peer closed connection, or | + | | shut down writing half of connection | + +-------------------+------------------------------------------+ + | :const:`POLLNVAL` | Invalid request: descriptor not open | + +-------------------+------------------------------------------+ + + Registering a file descriptor that's already registered is not an error, and has + the same effect as registering the descriptor exactly once. + + +.. method:: poll.modify(fd, eventmask) + + Modifies an already registered fd. This has the same effect as + ``register(fd, eventmask)``. Attempting to modify a file descriptor + that was never registered causes an :exc:`OSError` exception with errno + :const:`ENOENT` to be raised. + + +.. method:: poll.unregister(fd) + + Remove a file descriptor being tracked by a polling object. Just like the + :meth:`register` method, *fd* can be an integer or an object with a + :meth:`~io.IOBase.fileno` method that returns an integer. + + Attempting to remove a file descriptor that was never registered causes a + :exc:`KeyError` exception to be raised. + + +.. method:: poll.poll([timeout]) + + Polls the set of registered file descriptors, and returns a possibly-empty list + containing ``(fd, event)`` 2-tuples for the descriptors that have events or + errors to report. *fd* is the file descriptor, and *event* is a bitmask with + bits set for the reported events for that descriptor --- :const:`POLLIN` for + waiting input, :const:`POLLOUT` to indicate that the descriptor can be written + to, and so forth. An empty list indicates that the call timed out and no file + descriptors had any events to report. If *timeout* is given, it specifies the + length of time in milliseconds which the system will wait for events before + returning. If *timeout* is omitted, negative, or :const:`None`, the call will + block until there is an event for this poll object. + + .. versionchanged:: 3.5 + The function is now retried with a recomputed timeout when interrupted by + a signal, except if the signal handler raises an exception (see + :pep:`475` for the rationale), instead of raising + :exc:`InterruptedError`. + + +.. _kqueue-objects: + +Kqueue Objects +-------------- + +.. method:: kqueue.close() + + Close the control file descriptor of the kqueue object. + + +.. attribute:: kqueue.closed + + ``True`` if the kqueue object is closed. + + +.. method:: kqueue.fileno() + + Return the file descriptor number of the control fd. + + +.. method:: kqueue.fromfd(fd) + + Create a kqueue object from a given file descriptor. + + +.. method:: kqueue.control(changelist, max_events[, timeout]) -> eventlist + + Low level interface to kevent + + - changelist must be an iterable of kevent objects or ``None`` + - max_events must be 0 or a positive integer + - timeout in seconds (floats possible); the default is ``None``, + to wait forever + + .. versionchanged:: 3.5 + The function is now retried with a recomputed timeout when interrupted by + a signal, except if the signal handler raises an exception (see + :pep:`475` for the rationale), instead of raising + :exc:`InterruptedError`. + + +.. _kevent-objects: + +Kevent Objects +-------------- + +https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2 + +.. attribute:: kevent.ident + + Value used to identify the event. The interpretation depends on the filter + but it's usually the file descriptor. In the constructor ident can either + be an int or an object with a :meth:`~io.IOBase.fileno` method. kevent + stores the integer internally. + +.. attribute:: kevent.filter + + Name of the kernel filter. + + +---------------------------+---------------------------------------------+ + | Constant | Meaning | + +===========================+=============================================+ + | :const:`KQ_FILTER_READ` | Takes a descriptor and returns whenever | + | | there is data available to read | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_WRITE` | Takes a descriptor and returns whenever | + | | there is data available to write | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_AIO` | AIO requests | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_VNODE` | Returns when one or more of the requested | + | | events watched in *fflag* occurs | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_PROC` | Watch for events on a process id | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_NETDEV` | Watch for events on a network device | + | | [not available on Mac OS X] | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_SIGNAL` | Returns whenever the watched signal is | + | | delivered to the process | + +---------------------------+---------------------------------------------+ + | :const:`KQ_FILTER_TIMER` | Establishes an arbitrary timer | + +---------------------------+---------------------------------------------+ + +.. attribute:: kevent.flags + + Filter action. + + +---------------------------+---------------------------------------------+ + | Constant | Meaning | + +===========================+=============================================+ + | :const:`KQ_EV_ADD` | Adds or modifies an event | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_DELETE` | Removes an event from the queue | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_ENABLE` | Permitscontrol() to returns the event | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_DISABLE` | Disablesevent | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_ONESHOT` | Removes event after first occurrence | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_CLEAR` | Reset the state after an event is retrieved | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_SYSFLAGS` | internal event | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_FLAG1` | internal event | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_EOF` | Filter specific EOF condition | + +---------------------------+---------------------------------------------+ + | :const:`KQ_EV_ERROR` | See return values | + +---------------------------+---------------------------------------------+ + + +.. attribute:: kevent.fflags + + Filter specific flags. + + :const:`KQ_FILTER_READ` and :const:`KQ_FILTER_WRITE` filter flags: + + +----------------------------+--------------------------------------------+ + | Constant | Meaning | + +============================+============================================+ + | :const:`KQ_NOTE_LOWAT` | low water mark of a socket buffer | + +----------------------------+--------------------------------------------+ + + :const:`KQ_FILTER_VNODE` filter flags: + + +----------------------------+--------------------------------------------+ + | Constant | Meaning | + +============================+============================================+ + | :const:`KQ_NOTE_DELETE` | *unlink()* was called | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_WRITE` | a write occurred | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_EXTEND` | the file was extended | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_ATTRIB` | an attribute was changed | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_LINK` | the link count has changed | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_RENAME` | the file was renamed | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_REVOKE` | access to the file was revoked | + +----------------------------+--------------------------------------------+ + + :const:`KQ_FILTER_PROC` filter flags: + + +----------------------------+--------------------------------------------+ + | Constant | Meaning | + +============================+============================================+ + | :const:`KQ_NOTE_EXIT` | the process has exited | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_FORK` | the process has called *fork()* | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_EXEC` | the process has executed a new process | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_PCTRLMASK` | internal filter flag | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_PDATAMASK` | internal filter flag | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_TRACK` | follow a process across *fork()* | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_CHILD` | returned on the child process for | + | | *NOTE_TRACK* | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_TRACKERR` | unable to attach to a child | + +----------------------------+--------------------------------------------+ + + :const:`KQ_FILTER_NETDEV` filter flags (not available on Mac OS X): + + +----------------------------+--------------------------------------------+ + | Constant | Meaning | + +============================+============================================+ + | :const:`KQ_NOTE_LINKUP` | link is up | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_LINKDOWN` | link is down | + +----------------------------+--------------------------------------------+ + | :const:`KQ_NOTE_LINKINV` | link state is invalid | + +----------------------------+--------------------------------------------+ + + +.. attribute:: kevent.data + + Filter specific data. + + +.. attribute:: kevent.udata + + User defined value. diff --git a/cpython_2/environment/repo/Doc/library/selectors.rst b/cpython_2/environment/repo/Doc/library/selectors.rst new file mode 100644 index 0000000000000000000000000000000000000000..6d864a836de075462b3aacce630d180ab2e84a55 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/selectors.rst @@ -0,0 +1,277 @@ +:mod:`selectors` --- High-level I/O multiplexing +================================================ + +.. module:: selectors + :synopsis: High-level I/O multiplexing. + +.. versionadded:: 3.4 + +**Source code:** :source:`Lib/selectors.py` + +-------------- + +Introduction +------------ + +This module allows high-level and efficient I/O multiplexing, built upon the +:mod:`select` module primitives. Users are encouraged to use this module +instead, unless they want precise control over the OS-level primitives used. + +It defines a :class:`BaseSelector` abstract base class, along with several +concrete implementations (:class:`KqueueSelector`, :class:`EpollSelector`...), +that can be used to wait for I/O readiness notification on multiple file +objects. In the following, "file object" refers to any object with a +:meth:`fileno()` method, or a raw file descriptor. See :term:`file object`. + +:class:`DefaultSelector` is an alias to the most efficient implementation +available on the current platform: this should be the default choice for most +users. + +.. note:: + The type of file objects supported depends on the platform: on Windows, + sockets are supported, but not pipes, whereas on Unix, both are supported + (some other types may be supported as well, such as fifos or special file + devices). + +.. seealso:: + + :mod:`select` + Low-level I/O multiplexing module. + + +Classes +------- + +Classes hierarchy:: + + BaseSelector + +-- SelectSelector + +-- PollSelector + +-- EpollSelector + +-- DevpollSelector + +-- KqueueSelector + + +In the following, *events* is a bitwise mask indicating which I/O events should +be waited for on a given file object. It can be a combination of the modules +constants below: + + +-----------------------+-----------------------------------------------+ + | Constant | Meaning | + +=======================+===============================================+ + | :const:`EVENT_READ` | Available for read | + +-----------------------+-----------------------------------------------+ + | :const:`EVENT_WRITE` | Available for write | + +-----------------------+-----------------------------------------------+ + + +.. class:: SelectorKey + + A :class:`SelectorKey` is a :class:`~collections.namedtuple` used to + associate a file object to its underlying file descriptor, selected event + mask and attached data. It is returned by several :class:`BaseSelector` + methods. + + .. attribute:: fileobj + + File object registered. + + .. attribute:: fd + + Underlying file descriptor. + + .. attribute:: events + + Events that must be waited for on this file object. + + .. attribute:: data + + Optional opaque data associated to this file object: for example, this + could be used to store a per-client session ID. + + +.. class:: BaseSelector + + A :class:`BaseSelector` is used to wait for I/O event readiness on multiple + file objects. It supports file stream registration, unregistration, and a + method to wait for I/O events on those streams, with an optional timeout. + It's an abstract base class, so cannot be instantiated. Use + :class:`DefaultSelector` instead, or one of :class:`SelectSelector`, + :class:`KqueueSelector` etc. if you want to specifically use an + implementation, and your platform supports it. + :class:`BaseSelector` and its concrete implementations support the + :term:`context manager` protocol. + + .. abstractmethod:: register(fileobj, events, data=None) + + Register a file object for selection, monitoring it for I/O events. + + *fileobj* is the file object to monitor. It may either be an integer + file descriptor or an object with a ``fileno()`` method. + *events* is a bitwise mask of events to monitor. + *data* is an opaque object. + + This returns a new :class:`SelectorKey` instance, or raises a + :exc:`ValueError` in case of invalid event mask or file descriptor, or + :exc:`KeyError` if the file object is already registered. + + .. abstractmethod:: unregister(fileobj) + + Unregister a file object from selection, removing it from monitoring. A + file object shall be unregistered prior to being closed. + + *fileobj* must be a file object previously registered. + + This returns the associated :class:`SelectorKey` instance, or raises a + :exc:`KeyError` if *fileobj* is not registered. It will raise + :exc:`ValueError` if *fileobj* is invalid (e.g. it has no ``fileno()`` + method or its ``fileno()`` method has an invalid return value). + + .. method:: modify(fileobj, events, data=None) + + Change a registered file object's monitored events or attached data. + + This is equivalent to :meth:`BaseSelector.unregister(fileobj)` followed + by :meth:`BaseSelector.register(fileobj, events, data)`, except that it + can be implemented more efficiently. + + This returns a new :class:`SelectorKey` instance, or raises a + :exc:`ValueError` in case of invalid event mask or file descriptor, or + :exc:`KeyError` if the file object is not registered. + + .. abstractmethod:: select(timeout=None) + + Wait until some registered file objects become ready, or the timeout + expires. + + If ``timeout > 0``, this specifies the maximum wait time, in seconds. + If ``timeout <= 0``, the call won't block, and will report the currently + ready file objects. + If *timeout* is ``None``, the call will block until a monitored file object + becomes ready. + + This returns a list of ``(key, events)`` tuples, one for each ready file + object. + + *key* is the :class:`SelectorKey` instance corresponding to a ready file + object. + *events* is a bitmask of events ready on this file object. + + .. note:: + This method can return before any file object becomes ready or the + timeout has elapsed if the current process receives a signal: in this + case, an empty list will be returned. + + .. versionchanged:: 3.5 + The selector is now retried with a recomputed timeout when interrupted + by a signal if the signal handler did not raise an exception (see + :pep:`475` for the rationale), instead of returning an empty list + of events before the timeout. + + .. method:: close() + + Close the selector. + + This must be called to make sure that any underlying resource is freed. + The selector shall not be used once it has been closed. + + .. method:: get_key(fileobj) + + Return the key associated with a registered file object. + + This returns the :class:`SelectorKey` instance associated to this file + object, or raises :exc:`KeyError` if the file object is not registered. + + .. abstractmethod:: get_map() + + Return a mapping of file objects to selector keys. + + This returns a :class:`~collections.abc.Mapping` instance mapping + registered file objects to their associated :class:`SelectorKey` + instance. + + +.. class:: DefaultSelector() + + The default selector class, using the most efficient implementation + available on the current platform. This should be the default choice for + most users. + + +.. class:: SelectSelector() + + :func:`select.select`-based selector. + + +.. class:: PollSelector() + + :func:`select.poll`-based selector. + + +.. class:: EpollSelector() + + :func:`select.epoll`-based selector. + + .. method:: fileno() + + This returns the file descriptor used by the underlying + :func:`select.epoll` object. + +.. class:: DevpollSelector() + + :func:`select.devpoll`-based selector. + + .. method:: fileno() + + This returns the file descriptor used by the underlying + :func:`select.devpoll` object. + + .. versionadded:: 3.5 + +.. class:: KqueueSelector() + + :func:`select.kqueue`-based selector. + + .. method:: fileno() + + This returns the file descriptor used by the underlying + :func:`select.kqueue` object. + + +Examples +-------- + +Here is a simple echo server implementation:: + + import selectors + import socket + + sel = selectors.DefaultSelector() + + def accept(sock, mask): + conn, addr = sock.accept() # Should be ready + print('accepted', conn, 'from', addr) + conn.setblocking(False) + sel.register(conn, selectors.EVENT_READ, read) + + def read(conn, mask): + data = conn.recv(1000) # Should be ready + if data: + print('echoing', repr(data), 'to', conn) + conn.send(data) # Hope it won't block + else: + print('closing', conn) + sel.unregister(conn) + conn.close() + + sock = socket.socket() + sock.bind(('localhost', 1234)) + sock.listen(100) + sock.setblocking(False) + sel.register(sock, selectors.EVENT_READ, accept) + + while True: + events = sel.select() + for key, mask in events: + callback = key.data + callback(key.fileobj, mask) diff --git a/cpython_2/environment/repo/Doc/library/shelve.rst b/cpython_2/environment/repo/Doc/library/shelve.rst new file mode 100644 index 0000000000000000000000000000000000000000..f08c58179a2f9f071371b4e7bf8217bc47f569ef --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/shelve.rst @@ -0,0 +1,203 @@ +:mod:`shelve` --- Python object persistence +=========================================== + +.. module:: shelve + :synopsis: Python object persistence. + +**Source code:** :source:`Lib/shelve.py` + +.. index:: module: pickle + +-------------- + +A "shelf" is a persistent, dictionary-like object. The difference with "dbm" +databases is that the values (not the keys!) in a shelf can be essentially +arbitrary Python objects --- anything that the :mod:`pickle` module can handle. +This includes most class instances, recursive data types, and objects containing +lots of shared sub-objects. The keys are ordinary strings. + + +.. function:: open(filename, flag='c', protocol=None, writeback=False) + + Open a persistent dictionary. The filename specified is the base filename for + the underlying database. As a side-effect, an extension may be added to the + filename and more than one file may be created. By default, the underlying + database file is opened for reading and writing. The optional *flag* parameter + has the same interpretation as the *flag* parameter of :func:`dbm.open`. + + By default, version 3 pickles are used to serialize values. The version of the + pickle protocol can be specified with the *protocol* parameter. + + Because of Python semantics, a shelf cannot know when a mutable + persistent-dictionary entry is modified. By default modified objects are + written *only* when assigned to the shelf (see :ref:`shelve-example`). If the + optional *writeback* parameter is set to ``True``, all entries accessed are also + cached in memory, and written back on :meth:`~Shelf.sync` and + :meth:`~Shelf.close`; this can make it handier to mutate mutable entries in + the persistent dictionary, but, if many entries are accessed, it can consume + vast amounts of memory for the cache, and it can make the close operation + very slow since all accessed entries are written back (there is no way to + determine which accessed entries are mutable, nor which ones were actually + mutated). + + .. note:: + + Do not rely on the shelf being closed automatically; always call + :meth:`~Shelf.close` explicitly when you don't need it any more, or + use :func:`shelve.open` as a context manager:: + + with shelve.open('spam') as db: + db['eggs'] = 'eggs' + +.. warning:: + + Because the :mod:`shelve` module is backed by :mod:`pickle`, it is insecure + to load a shelf from an untrusted source. Like with pickle, loading a shelf + can execute arbitrary code. + +Shelf objects support all methods supported by dictionaries. This eases the +transition from dictionary based scripts to those requiring persistent storage. + +Two additional methods are supported: + +.. method:: Shelf.sync() + + Write back all entries in the cache if the shelf was opened with *writeback* + set to :const:`True`. Also empty the cache and synchronize the persistent + dictionary on disk, if feasible. This is called automatically when the shelf + is closed with :meth:`close`. + +.. method:: Shelf.close() + + Synchronize and close the persistent *dict* object. Operations on a closed + shelf will fail with a :exc:`ValueError`. + + +.. seealso:: + + `Persistent dictionary recipe `_ + with widely supported storage formats and having the speed of native + dictionaries. + + +Restrictions +------------ + + .. index:: + module: dbm.ndbm + module: dbm.gnu + +* The choice of which database package will be used (such as :mod:`dbm.ndbm` or + :mod:`dbm.gnu`) depends on which interface is available. Therefore it is not + safe to open the database directly using :mod:`dbm`. The database is also + (unfortunately) subject to the limitations of :mod:`dbm`, if it is used --- + this means that (the pickled representation of) the objects stored in the + database should be fairly small, and in rare cases key collisions may cause + the database to refuse updates. + +* The :mod:`shelve` module does not support *concurrent* read/write access to + shelved objects. (Multiple simultaneous read accesses are safe.) When a + program has a shelf open for writing, no other program should have it open for + reading or writing. Unix file locking can be used to solve this, but this + differs across Unix versions and requires knowledge about the database + implementation used. + + +.. class:: Shelf(dict, protocol=None, writeback=False, keyencoding='utf-8') + + A subclass of :class:`collections.abc.MutableMapping` which stores pickled + values in the *dict* object. + + By default, version 3 pickles are used to serialize values. The version of the + pickle protocol can be specified with the *protocol* parameter. See the + :mod:`pickle` documentation for a discussion of the pickle protocols. + + If the *writeback* parameter is ``True``, the object will hold a cache of all + entries accessed and write them back to the *dict* at sync and close times. + This allows natural operations on mutable entries, but can consume much more + memory and make sync and close take a long time. + + The *keyencoding* parameter is the encoding used to encode keys before they + are used with the underlying dict. + + A :class:`Shelf` object can also be used as a context manager, in which + case it will be automatically closed when the :keyword:`with` block ends. + + .. versionchanged:: 3.2 + Added the *keyencoding* parameter; previously, keys were always encoded in + UTF-8. + + .. versionchanged:: 3.4 + Added context manager support. + + +.. class:: BsdDbShelf(dict, protocol=None, writeback=False, keyencoding='utf-8') + + A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`!next`, + :meth:`previous`, :meth:`last` and :meth:`set_location` which are available + in the third-party :mod:`bsddb` module from `pybsddb + `_ but not in other database + modules. The *dict* object passed to the constructor must support those + methods. This is generally accomplished by calling one of + :func:`bsddb.hashopen`, :func:`bsddb.btopen` or :func:`bsddb.rnopen`. The + optional *protocol*, *writeback*, and *keyencoding* parameters have the same + interpretation as for the :class:`Shelf` class. + + +.. class:: DbfilenameShelf(filename, flag='c', protocol=None, writeback=False) + + A subclass of :class:`Shelf` which accepts a *filename* instead of a dict-like + object. The underlying file will be opened using :func:`dbm.open`. By + default, the file will be created and opened for both read and write. The + optional *flag* parameter has the same interpretation as for the :func:`.open` + function. The optional *protocol* and *writeback* parameters have the same + interpretation as for the :class:`Shelf` class. + + +.. _shelve-example: + +Example +------- + +To summarize the interface (``key`` is a string, ``data`` is an arbitrary +object):: + + import shelve + + d = shelve.open(filename) # open -- file may get suffix added by low-level + # library + + d[key] = data # store data at key (overwrites old data if + # using an existing key) + data = d[key] # retrieve a COPY of data at key (raise KeyError + # if no such key) + del d[key] # delete data stored at key (raises KeyError + # if no such key) + + flag = key in d # true if the key exists + klist = list(d.keys()) # a list of all existing keys (slow!) + + # as d was opened WITHOUT writeback=True, beware: + d['xx'] = [0, 1, 2] # this works as expected, but... + d['xx'].append(3) # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]! + + # having opened d without writeback=True, you need to code carefully: + temp = d['xx'] # extracts the copy + temp.append(5) # mutates the copy + d['xx'] = temp # stores the copy right back, to persist it + + # or, d=shelve.open(filename,writeback=True) would let you just code + # d['xx'].append(5) and have it work as expected, BUT it would also + # consume more memory and make the d.close() operation slower. + + d.close() # close it + + +.. seealso:: + + Module :mod:`dbm` + Generic interface to ``dbm``-style databases. + + Module :mod:`pickle` + Object serialization used by :mod:`shelve`. + diff --git a/cpython_2/environment/repo/Doc/library/shlex.rst b/cpython_2/environment/repo/Doc/library/shlex.rst new file mode 100644 index 0000000000000000000000000000000000000000..7f7f0c7f124ac5a4278354d668caca5e662c0775 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/shlex.rst @@ -0,0 +1,449 @@ +:mod:`shlex` --- Simple lexical analysis +======================================== + +.. module:: shlex + :synopsis: Simple lexical analysis for Unix shell-like languages. + +.. moduleauthor:: Eric S. Raymond +.. moduleauthor:: Gustavo Niemeyer +.. sectionauthor:: Eric S. Raymond +.. sectionauthor:: Gustavo Niemeyer + +**Source code:** :source:`Lib/shlex.py` + +-------------- + +The :class:`~shlex.shlex` class makes it easy to write lexical analyzers for +simple syntaxes resembling that of the Unix shell. This will often be useful +for writing minilanguages, (for example, in run control files for Python +applications) or for parsing quoted strings. + +The :mod:`shlex` module defines the following functions: + + +.. function:: split(s, comments=False, posix=True) + + Split the string *s* using shell-like syntax. If *comments* is :const:`False` + (the default), the parsing of comments in the given string will be disabled + (setting the :attr:`~shlex.commenters` attribute of the + :class:`~shlex.shlex` instance to the empty string). This function operates + in POSIX mode by default, but uses non-POSIX mode if the *posix* argument is + false. + + .. note:: + + Since the :func:`split` function instantiates a :class:`~shlex.shlex` + instance, passing ``None`` for *s* will read the string to split from + standard input. + + .. deprecated:: 3.9 + Passing ``None`` for *s* will raise an exception in future Python + versions. + +.. function:: join(split_command) + + Concatenate the tokens of the list *split_command* and return a string. + This function is the inverse of :func:`split`. + + >>> from shlex import join + >>> print(join(['echo', '-n', 'Multiple words'])) + echo -n 'Multiple words' + + The returned value is shell-escaped to protect against injection + vulnerabilities (see :func:`quote`). + + .. versionadded:: 3.8 + + +.. function:: quote(s) + + Return a shell-escaped version of the string *s*. The returned value is a + string that can safely be used as one token in a shell command line, for + cases where you cannot use a list. + + This idiom would be unsafe: + + >>> filename = 'somefile; rm -rf ~' + >>> command = 'ls -l {}'.format(filename) + >>> print(command) # executed by a shell: boom! + ls -l somefile; rm -rf ~ + + :func:`quote` lets you plug the security hole: + + >>> from shlex import quote + >>> command = 'ls -l {}'.format(quote(filename)) + >>> print(command) + ls -l 'somefile; rm -rf ~' + >>> remote_command = 'ssh home {}'.format(quote(command)) + >>> print(remote_command) + ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"'' + + The quoting is compatible with UNIX shells and with :func:`split`: + + >>> from shlex import split + >>> remote_command = split(remote_command) + >>> remote_command + ['ssh', 'home', "ls -l 'somefile; rm -rf ~'"] + >>> command = split(remote_command[-1]) + >>> command + ['ls', '-l', 'somefile; rm -rf ~'] + + .. versionadded:: 3.3 + +The :mod:`shlex` module defines the following class: + + +.. class:: shlex(instream=None, infile=None, posix=False, punctuation_chars=False) + + A :class:`~shlex.shlex` instance or subclass instance is a lexical analyzer + object. The initialization argument, if present, specifies where to read + characters from. It must be a file-/stream-like object with + :meth:`~io.TextIOBase.read` and :meth:`~io.TextIOBase.readline` methods, or + a string. If no argument is given, input will be taken from ``sys.stdin``. + The second optional argument is a filename string, which sets the initial + value of the :attr:`~shlex.infile` attribute. If the *instream* + argument is omitted or equal to ``sys.stdin``, this second argument + defaults to "stdin". The *posix* argument defines the operational mode: + when *posix* is not true (default), the :class:`~shlex.shlex` instance will + operate in compatibility mode. When operating in POSIX mode, + :class:`~shlex.shlex` will try to be as close as possible to the POSIX shell + parsing rules. The *punctuation_chars* argument provides a way to make the + behaviour even closer to how real shells parse. This can take a number of + values: the default value, ``False``, preserves the behaviour seen under + Python 3.5 and earlier. If set to ``True``, then parsing of the characters + ``();<>|&`` is changed: any run of these characters (considered punctuation + characters) is returned as a single token. If set to a non-empty string of + characters, those characters will be used as the punctuation characters. Any + characters in the :attr:`wordchars` attribute that appear in + *punctuation_chars* will be removed from :attr:`wordchars`. See + :ref:`improved-shell-compatibility` for more information. *punctuation_chars* + can be set only upon :class:`~shlex.shlex` instance creation and can't be + modified later. + + .. versionchanged:: 3.6 + The *punctuation_chars* parameter was added. + +.. seealso:: + + Module :mod:`configparser` + Parser for configuration files similar to the Windows :file:`.ini` files. + + +.. _shlex-objects: + +shlex Objects +------------- + +A :class:`~shlex.shlex` instance has the following methods: + + +.. method:: shlex.get_token() + + Return a token. If tokens have been stacked using :meth:`push_token`, pop a + token off the stack. Otherwise, read one from the input stream. If reading + encounters an immediate end-of-file, :attr:`eof` is returned (the empty + string (``''``) in non-POSIX mode, and ``None`` in POSIX mode). + + +.. method:: shlex.push_token(str) + + Push the argument onto the token stack. + + +.. method:: shlex.read_token() + + Read a raw token. Ignore the pushback stack, and do not interpret source + requests. (This is not ordinarily a useful entry point, and is documented here + only for the sake of completeness.) + + +.. method:: shlex.sourcehook(filename) + + When :class:`~shlex.shlex` detects a source request (see :attr:`source` + below) this method is given the following token as argument, and expected + to return a tuple consisting of a filename and an open file-like object. + + Normally, this method first strips any quotes off the argument. If the result + is an absolute pathname, or there was no previous source request in effect, or + the previous source was a stream (such as ``sys.stdin``), the result is left + alone. Otherwise, if the result is a relative pathname, the directory part of + the name of the file immediately before it on the source inclusion stack is + prepended (this behavior is like the way the C preprocessor handles ``#include + "file.h"``). + + The result of the manipulations is treated as a filename, and returned as the + first component of the tuple, with :func:`open` called on it to yield the second + component. (Note: this is the reverse of the order of arguments in instance + initialization!) + + This hook is exposed so that you can use it to implement directory search paths, + addition of file extensions, and other namespace hacks. There is no + corresponding 'close' hook, but a shlex instance will call the + :meth:`~io.IOBase.close` method of the sourced input stream when it returns + EOF. + + For more explicit control of source stacking, use the :meth:`push_source` and + :meth:`pop_source` methods. + + +.. method:: shlex.push_source(newstream, newfile=None) + + Push an input source stream onto the input stack. If the filename argument is + specified it will later be available for use in error messages. This is the + same method used internally by the :meth:`sourcehook` method. + + +.. method:: shlex.pop_source() + + Pop the last-pushed input source from the input stack. This is the same method + used internally when the lexer reaches EOF on a stacked input stream. + + +.. method:: shlex.error_leader(infile=None, lineno=None) + + This method generates an error message leader in the format of a Unix C compiler + error label; the format is ``'"%s", line %d: '``, where the ``%s`` is replaced + with the name of the current source file and the ``%d`` with the current input + line number (the optional arguments can be used to override these). + + This convenience is provided to encourage :mod:`shlex` users to generate error + messages in the standard, parseable format understood by Emacs and other Unix + tools. + +Instances of :class:`~shlex.shlex` subclasses have some public instance +variables which either control lexical analysis or can be used for debugging: + + +.. attribute:: shlex.commenters + + The string of characters that are recognized as comment beginners. All + characters from the comment beginner to end of line are ignored. Includes just + ``'#'`` by default. + + +.. attribute:: shlex.wordchars + + The string of characters that will accumulate into multi-character tokens. By + default, includes all ASCII alphanumerics and underscore. In POSIX mode, the + accented characters in the Latin-1 set are also included. If + :attr:`punctuation_chars` is not empty, the characters ``~-./*?=``, which can + appear in filename specifications and command line parameters, will also be + included in this attribute, and any characters which appear in + ``punctuation_chars`` will be removed from ``wordchars`` if they are present + there. If :attr:`whitespace_split` is set to ``True``, this will have no + effect. + + +.. attribute:: shlex.whitespace + + Characters that will be considered whitespace and skipped. Whitespace bounds + tokens. By default, includes space, tab, linefeed and carriage-return. + + +.. attribute:: shlex.escape + + Characters that will be considered as escape. This will be only used in POSIX + mode, and includes just ``'\'`` by default. + + +.. attribute:: shlex.quotes + + Characters that will be considered string quotes. The token accumulates until + the same quote is encountered again (thus, different quote types protect each + other as in the shell.) By default, includes ASCII single and double quotes. + + +.. attribute:: shlex.escapedquotes + + Characters in :attr:`quotes` that will interpret escape characters defined in + :attr:`escape`. This is only used in POSIX mode, and includes just ``'"'`` by + default. + + +.. attribute:: shlex.whitespace_split + + If ``True``, tokens will only be split in whitespaces. This is useful, for + example, for parsing command lines with :class:`~shlex.shlex`, getting + tokens in a similar way to shell arguments. When used in combination with + :attr:`punctuation_chars`, tokens will be split on whitespace in addition to + those characters. + + .. versionchanged:: 3.8 + The :attr:`punctuation_chars` attribute was made compatible with the + :attr:`whitespace_split` attribute. + + +.. attribute:: shlex.infile + + The name of the current input file, as initially set at class instantiation time + or stacked by later source requests. It may be useful to examine this when + constructing error messages. + + +.. attribute:: shlex.instream + + The input stream from which this :class:`~shlex.shlex` instance is reading + characters. + + +.. attribute:: shlex.source + + This attribute is ``None`` by default. If you assign a string to it, that + string will be recognized as a lexical-level inclusion request similar to the + ``source`` keyword in various shells. That is, the immediately following token + will be opened as a filename and input will be taken from that stream until + EOF, at which point the :meth:`~io.IOBase.close` method of that stream will be + called and the input source will again become the original input stream. Source + requests may be stacked any number of levels deep. + + +.. attribute:: shlex.debug + + If this attribute is numeric and ``1`` or more, a :class:`~shlex.shlex` + instance will print verbose progress output on its behavior. If you need + to use this, you can read the module source code to learn the details. + + +.. attribute:: shlex.lineno + + Source line number (count of newlines seen so far plus one). + + +.. attribute:: shlex.token + + The token buffer. It may be useful to examine this when catching exceptions. + + +.. attribute:: shlex.eof + + Token used to determine end of file. This will be set to the empty string + (``''``), in non-POSIX mode, and to ``None`` in POSIX mode. + + +.. attribute:: shlex.punctuation_chars + + A read-only property. Characters that will be considered punctuation. Runs of + punctuation characters will be returned as a single token. However, note that no + semantic validity checking will be performed: for example, '>>>' could be + returned as a token, even though it may not be recognised as such by shells. + + .. versionadded:: 3.6 + + +.. _shlex-parsing-rules: + +Parsing Rules +------------- + +When operating in non-POSIX mode, :class:`~shlex.shlex` will try to obey to the +following rules. + +* Quote characters are not recognized within words (``Do"Not"Separate`` is + parsed as the single word ``Do"Not"Separate``); + +* Escape characters are not recognized; + +* Enclosing characters in quotes preserve the literal value of all characters + within the quotes; + +* Closing quotes separate words (``"Do"Separate`` is parsed as ``"Do"`` and + ``Separate``); + +* If :attr:`~shlex.whitespace_split` is ``False``, any character not + declared to be a word character, whitespace, or a quote will be returned as + a single-character token. If it is ``True``, :class:`~shlex.shlex` will only + split words in whitespaces; + +* EOF is signaled with an empty string (``''``); + +* It's not possible to parse empty strings, even if quoted. + +When operating in POSIX mode, :class:`~shlex.shlex` will try to obey to the +following parsing rules. + +* Quotes are stripped out, and do not separate words (``"Do"Not"Separate"`` is + parsed as the single word ``DoNotSeparate``); + +* Non-quoted escape characters (e.g. ``'\'``) preserve the literal value of the + next character that follows; + +* Enclosing characters in quotes which are not part of + :attr:`~shlex.escapedquotes` (e.g. ``"'"``) preserve the literal value + of all characters within the quotes; + +* Enclosing characters in quotes which are part of + :attr:`~shlex.escapedquotes` (e.g. ``'"'``) preserves the literal value + of all characters within the quotes, with the exception of the characters + mentioned in :attr:`~shlex.escape`. The escape characters retain its + special meaning only when followed by the quote in use, or the escape + character itself. Otherwise the escape character will be considered a + normal character. + +* EOF is signaled with a :const:`None` value; + +* Quoted empty strings (``''``) are allowed. + +.. _improved-shell-compatibility: + +Improved Compatibility with Shells +---------------------------------- + +.. versionadded:: 3.6 + +The :class:`shlex` class provides compatibility with the parsing performed by +common Unix shells like ``bash``, ``dash``, and ``sh``. To take advantage of +this compatibility, specify the ``punctuation_chars`` argument in the +constructor. This defaults to ``False``, which preserves pre-3.6 behaviour. +However, if it is set to ``True``, then parsing of the characters ``();<>|&`` +is changed: any run of these characters is returned as a single token. While +this is short of a full parser for shells (which would be out of scope for the +standard library, given the multiplicity of shells out there), it does allow +you to perform processing of command lines more easily than you could +otherwise. To illustrate, you can see the difference in the following snippet: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> import shlex + >>> text = "a && b; c && d || e; f >'abc'; (def \"ghi\")" + >>> s = shlex.shlex(text, posix=True) + >>> s.whitespace_split = True + >>> list(s) + ['a', '&&', 'b;', 'c', '&&', 'd', '||', 'e;', 'f', '>abc;', '(def', 'ghi)'] + >>> s = shlex.shlex(text, posix=True, punctuation_chars=True) + >>> s.whitespace_split = True + >>> list(s) + ['a', '&&', 'b', ';', 'c', '&&', 'd', '||', 'e', ';', 'f', '>', 'abc', ';', + '(', 'def', 'ghi', ')'] + +Of course, tokens will be returned which are not valid for shells, and you'll +need to implement your own error checks on the returned tokens. + +Instead of passing ``True`` as the value for the punctuation_chars parameter, +you can pass a string with specific characters, which will be used to determine +which characters constitute punctuation. For example:: + + >>> import shlex + >>> s = shlex.shlex("a && b || c", punctuation_chars="|") + >>> list(s) + ['a', '&', '&', 'b', '||', 'c'] + +.. note:: When ``punctuation_chars`` is specified, the :attr:`~shlex.wordchars` + attribute is augmented with the characters ``~-./*?=``. That is because these + characters can appear in file names (including wildcards) and command-line + arguments (e.g. ``--color=auto``). Hence:: + + >>> import shlex + >>> s = shlex.shlex('~/a && b-c --color=auto || d *.py?', + ... punctuation_chars=True) + >>> list(s) + ['~/a', '&&', 'b-c', '--color=auto', '||', 'd', '*.py?'] + + However, to match the shell as closely as possible, it is recommended to + always use ``posix`` and :attr:`~shlex.whitespace_split` when using + :attr:`~shlex.punctuation_chars`, which will negate + :attr:`~shlex.wordchars` entirely. + +For best effect, ``punctuation_chars`` should be set in conjunction with +``posix=True``. (Note that ``posix=False`` is the default for +:class:`~shlex.shlex`.) diff --git a/cpython_2/environment/repo/Doc/library/shutil.rst b/cpython_2/environment/repo/Doc/library/shutil.rst new file mode 100644 index 0000000000000000000000000000000000000000..c7c63e6f80844aa42cf7aa99fd8d55cd051f619f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/shutil.rst @@ -0,0 +1,762 @@ +:mod:`shutil` --- High-level file operations +============================================ + +.. module:: shutil + :synopsis: High-level file operations, including copying. + +.. sectionauthor:: Fred L. Drake, Jr. +.. partly based on the docstrings + +**Source code:** :source:`Lib/shutil.py` + +.. index:: + single: file; copying + single: copying files + +-------------- + +The :mod:`shutil` module offers a number of high-level operations on files and +collections of files. In particular, functions are provided which support file +copying and removal. For operations on individual files, see also the +:mod:`os` module. + +.. warning:: + + Even the higher-level file copying functions (:func:`shutil.copy`, + :func:`shutil.copy2`) cannot 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 + not be correct. On Windows, file owners, ACLs and alternate data streams + are not copied. + + +.. _file-operations: + +Directory and files operations +------------------------------ + +.. function:: copyfileobj(fsrc, fdst[, length]) + + Copy the contents of the file-like object *fsrc* to the file-like object *fdst*. + The integer *length*, if given, is the buffer size. In particular, a negative + *length* value means to copy the data without looping over the source data in + chunks; by default the data is read in chunks to avoid uncontrolled memory + consumption. Note that if the current file position of the *fsrc* object is not + 0, only the contents from the current file position to the end of the file will + be copied. + + +.. function:: copyfile(src, dst, *, follow_symlinks=True) + + Copy the contents (no metadata) of the file named *src* to a file named + *dst* and return *dst* in the most efficient way possible. + *src* and *dst* are path-like objects or path names given as strings. + + *dst* must be the complete target file name; look at :func:`~shutil.copy` + for a copy that accepts a target directory path. If *src* and *dst* + specify the same file, :exc:`SameFileError` is raised. + + The destination location must be writable; otherwise, an :exc:`OSError` + exception will be raised. If *dst* already exists, it will be replaced. + Special files such as character or block devices and pipes cannot be + copied with this function. + + If *follow_symlinks* is false and *src* is a symbolic link, + a new symbolic link will be created instead of copying the + file *src* points to. + + .. audit-event:: shutil.copyfile src,dst shutil.copyfile + + .. versionchanged:: 3.3 + :exc:`IOError` used to be raised instead of :exc:`OSError`. + Added *follow_symlinks* argument. + Now returns *dst*. + + .. versionchanged:: 3.4 + Raise :exc:`SameFileError` instead of :exc:`Error`. Since the former is + a subclass of the latter, this change is backward compatible. + + .. versionchanged:: 3.8 + Platform-specific fast-copy syscalls may be used internally in order to + copy the file more efficiently. See + :ref:`shutil-platform-dependent-efficient-copy-operations` section. + +.. exception:: SameFileError + + This exception is raised if source and destination in :func:`copyfile` + are the same file. + + .. versionadded:: 3.4 + + +.. function:: copymode(src, dst, *, follow_symlinks=True) + + Copy the permission bits from *src* to *dst*. The file contents, owner, and + group are unaffected. *src* and *dst* are path-like objects or path names + given as strings. + If *follow_symlinks* is false, and both *src* and *dst* are symbolic links, + :func:`copymode` will attempt to modify the mode of *dst* itself (rather + than the file it points to). This functionality is not available on every + platform; please see :func:`copystat` for more information. If + :func:`copymode` cannot modify symbolic links on the local platform, and it + is asked to do so, it will do nothing and return. + + .. audit-event:: shutil.copymode src,dst shutil.copymode + + .. versionchanged:: 3.3 + Added *follow_symlinks* argument. + +.. function:: copystat(src, dst, *, follow_symlinks=True) + + Copy the permission bits, last access time, last modification time, and + flags from *src* to *dst*. On Linux, :func:`copystat` also copies the + "extended attributes" where possible. The file contents, owner, and + group are unaffected. *src* and *dst* are path-like objects or path + names given as strings. + + If *follow_symlinks* is false, and *src* and *dst* both + refer to symbolic links, :func:`copystat` will operate on + the symbolic links themselves rather than the files the + symbolic links refer to—reading the information from the + *src* symbolic link, and writing the information to the + *dst* symbolic link. + + .. note:: + + Not all platforms provide the ability to examine and + modify symbolic links. Python itself can tell you what + functionality is locally available. + + * If ``os.chmod in os.supports_follow_symlinks`` is + ``True``, :func:`copystat` can modify the permission + bits of a symbolic link. + + * If ``os.utime in os.supports_follow_symlinks`` is + ``True``, :func:`copystat` can modify the last access + and modification times of a symbolic link. + + * If ``os.chflags in os.supports_follow_symlinks`` is + ``True``, :func:`copystat` can modify the flags of + a symbolic link. (``os.chflags`` is not available on + all platforms.) + + On platforms where some or all of this functionality + is unavailable, when asked to modify a symbolic link, + :func:`copystat` will copy everything it can. + :func:`copystat` never returns failure. + + Please see :data:`os.supports_follow_symlinks` + for more information. + + .. audit-event:: shutil.copystat src,dst shutil.copystat + + .. versionchanged:: 3.3 + Added *follow_symlinks* argument and support for Linux extended attributes. + +.. function:: copy(src, dst, *, follow_symlinks=True) + + Copies the file *src* to the file or directory *dst*. *src* and *dst* + should be strings. If *dst* specifies a directory, the file will be + copied into *dst* using the base filename from *src*. Returns the + path to the newly created file. + + If *follow_symlinks* is false, and *src* is a symbolic link, + *dst* will be created as a symbolic link. If *follow_symlinks* + is true and *src* is a symbolic link, *dst* will be a copy of + the file *src* refers to. + + :func:`~shutil.copy` copies the file data and the file's permission + mode (see :func:`os.chmod`). Other metadata, like the + file's creation and modification times, is not preserved. + To preserve all file metadata from the original, use + :func:`~shutil.copy2` instead. + + .. audit-event:: shutil.copyfile src,dst shutil.copy + + .. audit-event:: shutil.copymode src,dst shutil.copy + + .. versionchanged:: 3.3 + Added *follow_symlinks* argument. + Now returns path to the newly created file. + + .. versionchanged:: 3.8 + Platform-specific fast-copy syscalls may be used internally in order to + copy the file more efficiently. See + :ref:`shutil-platform-dependent-efficient-copy-operations` section. + +.. function:: copy2(src, dst, *, follow_symlinks=True) + + Identical to :func:`~shutil.copy` except that :func:`copy2` + also attempts to preserve file metadata. + + When *follow_symlinks* is false, and *src* is a symbolic + link, :func:`copy2` attempts to copy all metadata from the + *src* symbolic link to the newly-created *dst* symbolic link. + However, this functionality is not available on all platforms. + On platforms where some or all of this functionality is + unavailable, :func:`copy2` will preserve all the metadata + it can; :func:`copy2` never raises an exception because it + cannot preserve file metadata. + + :func:`copy2` uses :func:`copystat` to copy the file metadata. + Please see :func:`copystat` for more information + about platform support for modifying symbolic link metadata. + + .. audit-event:: shutil.copyfile src,dst shutil.copy2 + + .. audit-event:: shutil.copystat src,dst shutil.copy2 + + .. versionchanged:: 3.3 + Added *follow_symlinks* argument, try to copy extended + file system attributes too (currently Linux only). + Now returns path to the newly created file. + + .. versionchanged:: 3.8 + Platform-specific fast-copy syscalls may be used internally in order to + copy the file more efficiently. See + :ref:`shutil-platform-dependent-efficient-copy-operations` section. + +.. function:: ignore_patterns(\*patterns) + + This factory function creates a function that can be used as a callable for + :func:`copytree`\'s *ignore* argument, ignoring files and directories that + match one of the glob-style *patterns* provided. See the example below. + + +.. function:: copytree(src, dst, symlinks=False, ignore=None, \ + copy_function=copy2, ignore_dangling_symlinks=False, \ + dirs_exist_ok=False) + + Recursively copy an entire directory tree rooted at *src* to a directory + named *dst* and return the destination directory. *dirs_exist_ok* dictates + whether to raise an exception in case *dst* or any missing parent directory + already exists. + + Permissions and times of directories are copied with :func:`copystat`, + individual files are copied using :func:`~shutil.copy2`. + + If *symlinks* is true, symbolic links in the source tree are represented as + symbolic links in the new tree and the metadata of the original links will + be copied as far as the platform allows; if false or omitted, the contents + and metadata of the linked files are copied to the new tree. + + When *symlinks* is false, if the file pointed by the symlink doesn't + exist, an exception will be added in the list of errors raised in + an :exc:`Error` exception at the end of the copy process. + You can set the optional *ignore_dangling_symlinks* flag to true if you + want to silence this exception. Notice that this option has no effect + on platforms that don't support :func:`os.symlink`. + + If *ignore* is given, it must be a callable that will receive as its + arguments the directory being visited by :func:`copytree`, and a list of its + contents, as returned by :func:`os.listdir`. Since :func:`copytree` is + called recursively, the *ignore* callable will be called once for each + directory that is copied. The callable must return a sequence of directory + and file names relative to the current directory (i.e. a subset of the items + in its second argument); these names will then be ignored in the copy + process. :func:`ignore_patterns` can be used to create such a callable that + ignores names based on glob-style patterns. + + If exception(s) occur, an :exc:`Error` is raised with a list of reasons. + + If *copy_function* is given, it must be a callable that will be used to copy + each file. It will be called with the source path and the destination path +   as arguments. By default, :func:`~shutil.copy2` is used, but any function +   that supports the same signature (like :func:`~shutil.copy`) can be used. + + .. audit-event:: shutil.copytree src,dst shutil.copytree + + .. versionchanged:: 3.3 + Copy metadata when *symlinks* is false. + Now returns *dst*. + + .. versionchanged:: 3.2 + Added the *copy_function* argument to be able to provide a custom copy + function. + Added the *ignore_dangling_symlinks* argument to silent dangling symlinks + errors when *symlinks* is false. + + .. versionchanged:: 3.8 + Platform-specific fast-copy syscalls may be used internally in order to + copy the file more efficiently. See + :ref:`shutil-platform-dependent-efficient-copy-operations` section. + + .. versionadded:: 3.8 + The *dirs_exist_ok* parameter. + +.. function:: rmtree(path, ignore_errors=False, onerror=None) + + .. index:: single: directory; deleting + + Delete an entire directory tree; *path* must point to a directory (but not a + symbolic link to a directory). If *ignore_errors* is true, errors resulting + from failed removals will be ignored; if false or omitted, such errors are + handled by calling a handler specified by *onerror* or, if that is omitted, + they raise an exception. + + .. note:: + + On platforms that support the necessary fd-based functions a symlink + attack resistant version of :func:`rmtree` is used by default. On other + platforms, the :func:`rmtree` implementation is susceptible to a symlink + attack: given proper timing and circumstances, attackers can manipulate + symlinks on the filesystem to delete files they wouldn't be able to access + otherwise. Applications can use the :data:`rmtree.avoids_symlink_attacks` + function attribute to determine which case applies. + + If *onerror* is provided, it must be a callable that accepts three + parameters: *function*, *path*, and *excinfo*. + + The first parameter, *function*, is the function which raised the exception; + it depends on the platform and implementation. The second parameter, + *path*, will be the path name passed to *function*. The third parameter, + *excinfo*, will be the exception information returned by + :func:`sys.exc_info`. Exceptions raised by *onerror* will not be caught. + + .. audit-event:: shutil.rmtree path shutil.rmtree + + .. versionchanged:: 3.3 + Added a symlink attack resistant version that is used automatically + if platform supports fd-based functions. + + .. versionchanged:: 3.8 + On Windows, will no longer delete the contents of a directory junction + before removing the junction. + + .. attribute:: rmtree.avoids_symlink_attacks + + Indicates whether the current platform and implementation provides a + symlink attack resistant version of :func:`rmtree`. Currently this is + only true for platforms supporting fd-based directory access functions. + + .. versionadded:: 3.3 + + +.. function:: move(src, dst, copy_function=copy2) + + Recursively move a file or directory (*src*) to another location (*dst*) + and return the destination. + + If the destination is an existing directory, then *src* is moved inside that + directory. If the destination already exists but is not a directory, it may + be overwritten depending on :func:`os.rename` semantics. + + If the destination is on the current filesystem, then :func:`os.rename` is + used. Otherwise, *src* is copied to *dst* using *copy_function* and then + removed. In case of symlinks, a new symlink pointing to the target of *src* + will be created in or as *dst* and *src* will be removed. + + If *copy_function* is given, it must be a callable that takes two arguments + *src* and *dst*, and will be used to copy *src* to *dest* if + :func:`os.rename` cannot be used. If the source is a directory, + :func:`copytree` is called, passing it the :func:`copy_function`. The + default *copy_function* is :func:`copy2`. Using :func:`~shutil.copy` as the + *copy_function* allows the move to succeed when it is not possible to also + copy the metadata, at the expense of not copying any of the metadata. + + .. audit-event:: shutil.move src,dst shutil.move + + .. versionchanged:: 3.3 + Added explicit symlink handling for foreign filesystems, thus adapting + it to the behavior of GNU's :program:`mv`. + Now returns *dst*. + + .. versionchanged:: 3.5 + Added the *copy_function* keyword argument. + + .. versionchanged:: 3.8 + Platform-specific fast-copy syscalls may be used internally in order to + copy the file more efficiently. See + :ref:`shutil-platform-dependent-efficient-copy-operations` section. + + .. versionchanged:: 3.9 + Accepts a :term:`path-like object` for both *src* and *dst*. + +.. function:: disk_usage(path) + + Return disk usage statistics about the given path as a :term:`named tuple` + with the attributes *total*, *used* and *free*, which are the amount of + total, used and free space, in bytes. *path* may be a file or a + directory. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.8 + On Windows, *path* can now be a file or directory. + + .. availability:: Unix, Windows. + +.. function:: chown(path, user=None, group=None) + + Change owner *user* and/or *group* of the given *path*. + + *user* can be a system user name or a uid; the same applies to *group*. At + least one argument is required. + + See also :func:`os.chown`, the underlying function. + + .. audit-event:: shutil.chown path,user,group shutil.chown + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: which(cmd, mode=os.F_OK | os.X_OK, path=None) + + Return the path to an executable which would be run if the given *cmd* was + called. If no *cmd* would be called, return ``None``. + + *mode* is a permission mask passed to :func:`os.access`, by default + determining if the file exists and executable. + + When no *path* is specified, the results of :func:`os.environ` are used, + returning either the "PATH" value or a fallback of :attr:`os.defpath`. + + On Windows, the current directory is always prepended to the *path* whether + or not you use the default or provide your own, which is the behavior the + command shell uses when finding executables. Additionally, when finding the + *cmd* in the *path*, the ``PATHEXT`` environment variable is checked. For + example, if you call ``shutil.which("python")``, :func:`which` will search + ``PATHEXT`` to know that it should look for ``python.exe`` within the *path* + directories. For example, on Windows:: + + >>> shutil.which("python") + 'C:\\Python33\\python.EXE' + + .. versionadded:: 3.3 + + .. versionchanged:: 3.8 + The :class:`bytes` type is now accepted. If *cmd* type is + :class:`bytes`, the result type is also :class:`bytes`. + +.. exception:: Error + + This exception collects exceptions that are raised during a multi-file + operation. For :func:`copytree`, the exception argument is a list of 3-tuples + (*srcname*, *dstname*, *exception*). + +.. _shutil-platform-dependent-efficient-copy-operations: + +Platform-dependent efficient copy operations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Starting from Python 3.8 all functions involving a file copy (:func:`copyfile`, +:func:`copy`, :func:`copy2`, :func:`copytree`, and :func:`move`) may use +platform-specific "fast-copy" syscalls in order to copy the file more +efficiently (see :issue:`33671`). +"fast-copy" means that the copying operation occurs within the kernel, avoiding +the use of userspace buffers in Python as in "``outfd.write(infd.read())``". + +On macOS `fcopyfile`_ is used to copy the file content (not metadata). + +On Linux :func:`os.sendfile` is used. + +On Windows :func:`shutil.copyfile` uses a bigger default buffer size (1 MiB +instead of 64 KiB) and a :func:`memoryview`-based variant of +:func:`shutil.copyfileobj` is used. + +If the fast-copy operation fails and no data was written in the destination +file then shutil will silently fallback on using less efficient +:func:`copyfileobj` function internally. + +.. versionchanged:: 3.8 + +.. _shutil-copytree-example: + +copytree example +~~~~~~~~~~~~~~~~ + +This example is the implementation of the :func:`copytree` function, described +above, with the docstring omitted. It demonstrates many of the other functions +provided by this module. :: + + def copytree(src, dst, symlinks=False): + names = os.listdir(src) + os.makedirs(dst) + errors = [] + for name in names: + srcname = os.path.join(src, name) + dstname = os.path.join(dst, name) + try: + if symlinks and os.path.islink(srcname): + linkto = os.readlink(srcname) + os.symlink(linkto, dstname) + elif os.path.isdir(srcname): + copytree(srcname, dstname, symlinks) + else: + copy2(srcname, dstname) + # XXX What about devices, sockets etc.? + except OSError as why: + errors.append((srcname, dstname, str(why))) + # catch the Error from the recursive copytree so that we can + # continue with other files + except Error as err: + errors.extend(err.args[0]) + try: + copystat(src, dst) + except OSError as why: + # can't copy file access times on Windows + if why.winerror is None: + errors.extend((src, dst, str(why))) + if errors: + raise Error(errors) + +Another example that uses the :func:`ignore_patterns` helper:: + + from shutil import copytree, ignore_patterns + + copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*')) + +This will copy everything except ``.pyc`` files and files or directories whose +name starts with ``tmp``. + +Another example that uses the *ignore* argument to add a logging call:: + + from shutil import copytree + import logging + + def _logpath(path, names): + logging.info('Working in %s', path) + return [] # nothing will be ignored + + copytree(source, destination, ignore=_logpath) + + +.. _shutil-rmtree-example: + +rmtree example +~~~~~~~~~~~~~~ + +This example shows how to remove a directory tree on Windows where some +of the files have their read-only bit set. It uses the onerror callback +to clear the readonly bit and reattempt the remove. Any subsequent failure +will propagate. :: + + import os, stat + import shutil + + def remove_readonly(func, path, _): + "Clear the readonly bit and reattempt the removal" + os.chmod(path, stat.S_IWRITE) + func(path) + + shutil.rmtree(directory, onerror=remove_readonly) + +.. _archiving-operations: + +Archiving operations +-------------------- + +.. versionadded:: 3.2 + +.. versionchanged:: 3.5 + Added support for the *xztar* format. + + +High-level utilities to create and read compressed and archived files are also +provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules. + +.. function:: make_archive(base_name, format, [root_dir, [base_dir, [verbose, [dry_run, [owner, [group, [logger]]]]]]]) + + Create an archive file (such as zip or tar) and return its name. + + *base_name* is the name of the file to create, including the path, minus + any format-specific extension. *format* is the archive format: one of + "zip" (if the :mod:`zlib` module is available), "tar", "gztar" (if the + :mod:`zlib` module is available), "bztar" (if the :mod:`bz2` module is + available), or "xztar" (if the :mod:`lzma` module is available). + + *root_dir* is a directory that will be the root directory of the + archive; for example, we typically chdir into *root_dir* before creating the + archive. + + *base_dir* is the directory where we start archiving from; + i.e. *base_dir* will be the common prefix of all files and + directories in the archive. + + *root_dir* and *base_dir* both default to the current directory. + + If *dry_run* is true, no archive is created, but the operations that would be + executed are logged to *logger*. + + *owner* and *group* are used when creating a tar archive. By default, + uses the current owner and group. + + *logger* must be an object compatible with :pep:`282`, usually an instance of + :class:`logging.Logger`. + + The *verbose* argument is unused and deprecated. + + .. audit-event:: shutil.make_archive base_name,format,root_dir,base_dir shutil.make_archive + + .. versionchanged:: 3.8 + The modern pax (POSIX.1-2001) format is now used instead of + the legacy GNU format for archives created with ``format="tar"``. + + +.. function:: get_archive_formats() + + Return a list of supported formats for archiving. + Each element of the returned sequence is a tuple ``(name, description)``. + + By default :mod:`shutil` provides these formats: + + - *zip*: ZIP file (if the :mod:`zlib` module is available). + - *tar*: Uncompressed tar file. Uses POSIX.1-2001 pax format for new archives. + - *gztar*: gzip'ed tar-file (if the :mod:`zlib` module is available). + - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available). + - *xztar*: xz'ed tar-file (if the :mod:`lzma` module is available). + + You can register new formats or provide your own archiver for any existing + formats, by using :func:`register_archive_format`. + + +.. function:: register_archive_format(name, function, [extra_args, [description]]) + + Register an archiver for the format *name*. + + *function* is the callable that will be used to unpack archives. The callable + will receive the *base_name* of the file to create, followed by the + *base_dir* (which defaults to :data:`os.curdir`) to start archiving from. + Further arguments are passed as keyword arguments: *owner*, *group*, + *dry_run* and *logger* (as passed in :func:`make_archive`). + + If given, *extra_args* is a sequence of ``(name, value)`` pairs that will be + used as extra keywords arguments when the archiver callable is used. + + *description* is used by :func:`get_archive_formats` which returns the + list of archivers. Defaults to an empty string. + + +.. function:: unregister_archive_format(name) + + Remove the archive format *name* from the list of supported formats. + + +.. function:: unpack_archive(filename[, extract_dir[, format]]) + + Unpack an archive. *filename* is the full path of the archive. + + *extract_dir* is the name of the target directory where the archive is + unpacked. If not provided, the current working directory is used. + + *format* is the archive format: one of "zip", "tar", "gztar", "bztar", or + "xztar". Or any other format registered with + :func:`register_unpack_format`. If not provided, :func:`unpack_archive` + will use the archive file name extension and see if an unpacker was + registered for that extension. In case none is found, + a :exc:`ValueError` is raised. + + .. audit-event:: shutil.unpack_archive filename,extract_dir,format shutil.unpack_archive + + .. versionchanged:: 3.7 + Accepts a :term:`path-like object` for *filename* and *extract_dir*. + + +.. function:: register_unpack_format(name, extensions, function[, extra_args[, description]]) + + Registers an unpack format. *name* is the name of the format and + *extensions* is a list of extensions corresponding to the format, like + ``.zip`` for Zip files. + + *function* is the callable that will be used to unpack archives. The + callable will receive the path of the archive, followed by the directory + the archive must be extracted to. + + When provided, *extra_args* is a sequence of ``(name, value)`` tuples that + will be passed as keywords arguments to the callable. + + *description* can be provided to describe the format, and will be returned + by the :func:`get_unpack_formats` function. + + +.. function:: unregister_unpack_format(name) + + Unregister an unpack format. *name* is the name of the format. + + +.. function:: get_unpack_formats() + + Return a list of all registered formats for unpacking. + Each element of the returned sequence is a tuple + ``(name, extensions, description)``. + + By default :mod:`shutil` provides these formats: + + - *zip*: ZIP file (unpacking compressed files works only if the corresponding + module is available). + - *tar*: uncompressed tar file. + - *gztar*: gzip'ed tar-file (if the :mod:`zlib` module is available). + - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available). + - *xztar*: xz'ed tar-file (if the :mod:`lzma` module is available). + + You can register new formats or provide your own unpacker for any existing + formats, by using :func:`register_unpack_format`. + + +.. _shutil-archiving-example: + +Archiving example +~~~~~~~~~~~~~~~~~ + +In this example, we create a gzip'ed tar-file archive containing all files +found in the :file:`.ssh` directory of the user:: + + >>> from shutil import make_archive + >>> import os + >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive')) + >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh')) + >>> make_archive(archive_name, 'gztar', root_dir) + '/Users/tarek/myarchive.tar.gz' + +The resulting archive contains: + +.. code-block:: shell-session + + $ tar -tzvf /Users/tarek/myarchive.tar.gz + drwx------ tarek/staff 0 2010-02-01 16:23:40 ./ + -rw-r--r-- tarek/staff 609 2008-06-09 13:26:54 ./authorized_keys + -rwxr-xr-x tarek/staff 65 2008-06-09 13:26:54 ./config + -rwx------ tarek/staff 668 2008-06-09 13:26:54 ./id_dsa + -rwxr-xr-x tarek/staff 609 2008-06-09 13:26:54 ./id_dsa.pub + -rw------- tarek/staff 1675 2008-06-09 13:26:54 ./id_rsa + -rw-r--r-- tarek/staff 397 2008-06-09 13:26:54 ./id_rsa.pub + -rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts + + +Querying the size of the output terminal +---------------------------------------- + +.. function:: get_terminal_size(fallback=(columns, lines)) + + Get the size of the terminal window. + + For each of the two dimensions, the environment variable, ``COLUMNS`` + and ``LINES`` respectively, is checked. If the variable is defined and + the value is a positive integer, it is used. + + When ``COLUMNS`` or ``LINES`` is not defined, which is the common case, + the terminal connected to :data:`sys.__stdout__` is queried + by invoking :func:`os.get_terminal_size`. + + If the terminal size cannot be successfully queried, either because + the system doesn't support querying, or because we are not + connected to a terminal, the value given in ``fallback`` parameter + is used. ``fallback`` defaults to ``(80, 24)`` which is the default + size used by many terminal emulators. + + The value returned is a named tuple of type :class:`os.terminal_size`. + + See also: The Single UNIX Specification, Version 2, + `Other Environment Variables`_. + + .. versionadded:: 3.3 + +.. _`fcopyfile`: + http://www.manpagez.com/man/3/copyfile/ + +.. _`Other Environment Variables`: + http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003 diff --git a/cpython_2/environment/repo/Doc/library/signal.rst b/cpython_2/environment/repo/Doc/library/signal.rst new file mode 100644 index 0000000000000000000000000000000000000000..05b285ed110ec4ce94e72d9386719ff18abbaf28 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/signal.rst @@ -0,0 +1,679 @@ +:mod:`signal` --- Set handlers for asynchronous events +====================================================== + +.. module:: signal + :synopsis: Set handlers for asynchronous events. + +-------------- + +This module provides mechanisms to use signal handlers in Python. + + +General rules +------------- + +The :func:`signal.signal` function allows defining custom handlers to be +executed when a signal is received. A small number of default handlers are +installed: :const:`SIGPIPE` is ignored (so write errors on pipes and sockets +can be reported as ordinary Python exceptions) and :const:`SIGINT` is +translated into a :exc:`KeyboardInterrupt` exception if the parent process +has not changed it. + +A handler for a particular signal, once set, remains installed until it is +explicitly reset (Python emulates the BSD style interface regardless of the +underlying implementation), with the exception of the handler for +:const:`SIGCHLD`, which follows the underlying implementation. + + +Execution of Python signal handlers +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A Python signal handler does not get executed inside the low-level (C) signal +handler. Instead, the low-level signal handler sets a flag which tells the +:term:`virtual machine` to execute the corresponding Python signal handler +at a later point(for example at the next :term:`bytecode` instruction). +This has consequences: + +* It makes little sense to catch synchronous errors like :const:`SIGFPE` or + :const:`SIGSEGV` that are caused by an invalid operation in C code. Python + will return from the signal handler to the C code, which is likely to raise + the same signal again, causing Python to apparently hang. From Python 3.3 + onwards, you can use the :mod:`faulthandler` module to report on synchronous + errors. + +* A long-running calculation implemented purely in C (such as regular + expression matching on a large body of text) may run uninterrupted for an + arbitrary amount of time, regardless of any signals received. The Python + signal handlers will be called when the calculation finishes. + + +.. _signals-and-threads: + + +Signals and threads +^^^^^^^^^^^^^^^^^^^ + +Python signal handlers are always executed in the main Python thread of the main interpreter, +even if the signal was received in another thread. This means that signals +can't be used as a means of inter-thread communication. You can use +the synchronization primitives from the :mod:`threading` module instead. + +Besides, only the main thread of the main interpreter is allowed to set a new signal handler. + + +Module contents +--------------- + +.. versionchanged:: 3.5 + signal (SIG*), handler (:const:`SIG_DFL`, :const:`SIG_IGN`) and sigmask + (:const:`SIG_BLOCK`, :const:`SIG_UNBLOCK`, :const:`SIG_SETMASK`) + related constants listed below were turned into + :class:`enums `. + :func:`getsignal`, :func:`pthread_sigmask`, :func:`sigpending` and + :func:`sigwait` functions return human-readable + :class:`enums `. + + +The variables defined in the :mod:`signal` module are: + + +.. data:: SIG_DFL + + This is one of two standard signal handling options; it will simply perform + the default function for the signal. For example, on most systems the + default action for :const:`SIGQUIT` is to dump core and exit, while the + default action for :const:`SIGCHLD` is to simply ignore it. + + +.. data:: SIG_IGN + + This is another standard signal handler, which will simply ignore the given + signal. + + +.. data:: SIGABRT + + Abort signal from :manpage:`abort(3)`. + +.. data:: SIGALRM + + Timer signal from :manpage:`alarm(2)`. + + .. availability:: Unix. + +.. data:: SIGBREAK + + Interrupt from keyboard (CTRL + BREAK). + + .. availability:: Windows. + +.. data:: SIGBUS + + Bus error (bad memory access). + + .. availability:: Unix. + +.. data:: SIGCHLD + + Child process stopped or terminated. + + .. availability:: Windows. + +.. data:: SIGCLD + + Alias to :data:`SIGCHLD`. + +.. data:: SIGCONT + + Continue the process if it is currently stopped + + .. availability:: Unix. + +.. data:: SIGFPE + + Floating-point exception. For example, division by zero. + + .. seealso:: + :exc:`ZeroDivisionError` is raised when the second argument of a division + or modulo operation is zero. + +.. data:: SIGHUP + + Hangup detected on controlling terminal or death of controlling process. + + .. availability:: Unix. + +.. data:: SIGILL + + Illegal instruction. + +.. data:: SIGINT + + Interrupt from keyboard (CTRL + C). + + Default action is to raise :exc:`KeyboardInterrupt`. + +.. data:: SIGKILL + + Kill signal. + + It cannot be caught, blocked, or ignored. + + .. availability:: Unix. + +.. data:: SIGPIPE + + Broken pipe: write to pipe with no readers. + + Default action is to ignore the signal. + + .. availability:: Unix. + +.. data:: SIGSEGV + + Segmentation fault: invalid memory reference. + +.. data:: SIGTERM + + Termination signal. + +.. data:: SIGUSR1 + + User-defined signal 1. + + .. availability:: Unix. + +.. data:: SIGUSR2 + + User-defined signal 2. + + .. availability:: Unix. + +.. data:: SIGWINCH + + Window resize signal. + + .. availability:: Unix. + +.. data:: SIG* + + All the signal numbers are defined symbolically. For example, the hangup signal + is defined as :const:`signal.SIGHUP`; the variable names are identical to the + names used in C programs, as found in ````. The Unix man page for + ':c:func:`signal`' lists the existing signals (on some systems this is + :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that + not all systems define the same set of signal names; only those names defined by + the system are defined by this module. + + +.. data:: CTRL_C_EVENT + + The signal corresponding to the :kbd:`Ctrl+C` keystroke event. This signal can + only be used with :func:`os.kill`. + + .. availability:: Windows. + + .. versionadded:: 3.2 + + +.. data:: CTRL_BREAK_EVENT + + The signal corresponding to the :kbd:`Ctrl+Break` keystroke event. This signal can + only be used with :func:`os.kill`. + + .. availability:: Windows. + + .. versionadded:: 3.2 + + +.. data:: NSIG + + One more than the number of the highest signal number. + + +.. data:: ITIMER_REAL + + Decrements interval timer in real time, and delivers :const:`SIGALRM` upon + expiration. + + +.. data:: ITIMER_VIRTUAL + + 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 + in user and kernel space. SIGPROF is delivered upon expiration. + + +.. data:: SIG_BLOCK + + A possible value for the *how* parameter to :func:`pthread_sigmask` + indicating that signals are to be blocked. + + .. versionadded:: 3.3 + +.. data:: SIG_UNBLOCK + + A possible value for the *how* parameter to :func:`pthread_sigmask` + indicating that signals are to be unblocked. + + .. versionadded:: 3.3 + +.. data:: SIG_SETMASK + + A possible value for the *how* parameter to :func:`pthread_sigmask` + indicating that the signal mask is to be replaced. + + .. versionadded:: 3.3 + + +The :mod:`signal` module defines one exception: + +.. exception:: ItimerError + + 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`. + This error is a subtype of :exc:`OSError`. + + .. versionadded:: 3.3 + This error used to be a subtype of :exc:`IOError`, which is now an + alias of :exc:`OSError`. + + +The :mod:`signal` module defines the following functions: + + +.. function:: alarm(time) + + If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be + sent to the process in *time* seconds. Any previously scheduled alarm is + canceled (only one alarm can be scheduled at any time). The returned value is + then the number of seconds before any previously set alarm was to have been + delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is + canceled. If the return value is zero, no alarm is currently scheduled. + + .. availability:: Unix. See the man page :manpage:`alarm(2)` for further + information. + + +.. function:: getsignal(signalnum) + + Return the current signal handler for the signal *signalnum*. The returned value + may be a callable Python object, or one of the special values + :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`. Here, + :const:`signal.SIG_IGN` means that the signal was previously ignored, + :const:`signal.SIG_DFL` means that the default way of handling the signal was + previously in use, and ``None`` means that the previous signal handler was not + installed from Python. + + +.. function:: strsignal(signalnum) + + Return the system description of the signal *signalnum*, such as + "Interrupt", "Segmentation fault", etc. Returns :const:`None` if the signal + is not recognized. + + .. versionadded:: 3.8 + + +.. function:: valid_signals() + + Return the set of valid signal numbers on this platform. This can be + less than ``range(1, NSIG)`` if some signals are reserved by the system + for internal use. + + .. versionadded:: 3.8 + + +.. function:: pause() + + Cause the process to sleep until a signal is received; the appropriate handler + will then be called. Returns nothing. + + .. availability:: Unix. See the man page :manpage:`signal(2)` for further + information. + + See also :func:`sigwait`, :func:`sigwaitinfo`, :func:`sigtimedwait` and + :func:`sigpending`. + + +.. function:: raise_signal(signum) + + Sends a signal to the calling process. Returns nothing. + + .. versionadded:: 3.8 + + +.. function:: pidfd_send_signal(pidfd, sig, siginfo=None, flags=0) + + Send signal *sig* to the process referred to by file descriptor *pidfd*. + Python does not currently support the *siginfo* parameter; it must be + ``None``. The *flags* argument is provided for future extensions; no flag + values are currently defined. + + See the :manpage:`pidfd_send_signal(2)` man page for more information. + + .. availability:: Linux 5.1+ + .. versionadded:: 3.9 + + +.. function:: pthread_kill(thread_id, signalnum) + + Send the signal *signalnum* to the thread *thread_id*, another thread in the + same process as the caller. The target thread can be executing any code + (Python or not). However, if the target thread is executing the Python + interpreter, the Python signal handlers will be :ref:`executed by the main + thread of the main interpreter `. Therefore, the only point of sending a + signal to a particular Python thread would be to force a running system call + to fail with :exc:`InterruptedError`. + + Use :func:`threading.get_ident()` or the :attr:`~threading.Thread.ident` + attribute of :class:`threading.Thread` objects to get a suitable value + for *thread_id*. + + If *signalnum* is 0, then no signal is sent, but error checking is still + performed; this can be used to check if the target thread is still running. + + .. audit-event:: signal.pthread_kill thread_id,signalnum signal.pthread_kill + + .. availability:: Unix. See the man page :manpage:`pthread_kill(3)` for further + information. + + See also :func:`os.kill`. + + .. versionadded:: 3.3 + + +.. function:: pthread_sigmask(how, mask) + + Fetch and/or change the signal mask of the calling thread. The signal mask + is the set of signals whose delivery is currently blocked for the caller. + Return the old signal mask as a set of signals. + + The behavior of the call is dependent on the value of *how*, as follows. + + * :data:`SIG_BLOCK`: The set of blocked signals is the union of the current + set and the *mask* argument. + * :data:`SIG_UNBLOCK`: The signals in *mask* are removed from the current + set of blocked signals. It is permissible to attempt to unblock a + signal which is not blocked. + * :data:`SIG_SETMASK`: The set of blocked signals is set to the *mask* + argument. + + *mask* is a set of signal numbers (e.g. {:const:`signal.SIGINT`, + :const:`signal.SIGTERM`}). Use :func:`~signal.valid_signals` for a full + mask including all signals. + + For example, ``signal.pthread_sigmask(signal.SIG_BLOCK, [])`` reads the + signal mask of the calling thread. + + :data:`SIGKILL` and :data:`SIGSTOP` cannot be blocked. + + .. availability:: Unix. See the man page :manpage:`sigprocmask(3)` and + :manpage:`pthread_sigmask(3)` for further information. + + See also :func:`pause`, :func:`sigpending` and :func:`sigwait`. + + .. versionadded:: 3.3 + + +.. function:: setitimer(which, seconds, interval=0.0) + + 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 + :func:`alarm`) and after that every *interval* seconds (if *interval* + is non-zero). 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`, + :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 an + :exc:`ItimerError`. + + .. availability:: Unix. + + +.. function:: getitimer(which) + + Returns current value of a given interval timer specified by *which*. + + .. availability:: Unix. + + +.. function:: set_wakeup_fd(fd, *, warn_on_full_buffer=True) + + Set the wakeup file descriptor to *fd*. When a signal is received, the + signal number is written as a single byte into the fd. This can be used by + a library to wakeup a poll or select call, allowing the signal to be fully + processed. + + The old wakeup fd is returned (or -1 if file descriptor wakeup was not + enabled). If *fd* is -1, file descriptor wakeup is disabled. + If not -1, *fd* must be non-blocking. It is up to the library to remove + any bytes from *fd* before calling poll or select again. + + When threads are enabled, this function can only be called + from :ref:`the main thread of the main interpreter `; + attempting to call it from other threads will cause a :exc:`ValueError` + exception to be raised. + + There are two common ways to use this function. In both approaches, + you use the fd to wake up when a signal arrives, but then they + differ in how they determine *which* signal or signals have + arrived. + + In the first approach, we read the data out of the fd's buffer, and + the byte values give you the signal numbers. This is simple, but in + rare cases it can run into a problem: generally the fd will have a + limited amount of buffer space, and if too many signals arrive too + quickly, then the buffer may become full, and some signals may be + lost. If you use this approach, then you should set + ``warn_on_full_buffer=True``, which will at least cause a warning + to be printed to stderr when signals are lost. + + In the second approach, we use the wakeup fd *only* for wakeups, + and ignore the actual byte values. In this case, all we care about + is whether the fd's buffer is empty or non-empty; a full buffer + doesn't indicate a problem at all. If you use this approach, then + you should set ``warn_on_full_buffer=False``, so that your users + are not confused by spurious warning messages. + + .. versionchanged:: 3.5 + On Windows, the function now also supports socket handles. + + .. versionchanged:: 3.7 + Added ``warn_on_full_buffer`` parameter. + +.. function:: siginterrupt(signalnum, flag) + + Change system call restart behaviour: if *flag* is :const:`False`, system + calls 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 + :c:func:`siginterrupt` with a true *flag* value for the given signal. + + +.. function:: signal(signalnum, handler) + + Set the handler for signal *signalnum* to the function *handler*. *handler* can + be a callable Python object taking two arguments (see below), or one of the + special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`. The previous + signal handler will be returned (see the description of :func:`getsignal` + above). (See the Unix man page :manpage:`signal(2)` for further information.) + + When threads are enabled, this function can only be called + from :ref:`the main thread of the main interpreter `; + attempting to call it from other threads will cause a :exc:`ValueError` + exception to be raised. + + The *handler* is called with two arguments: the signal number and the current + stack frame (``None`` or a frame object; for a description of frame objects, + see the :ref:`description in the type hierarchy ` or see the + attribute descriptions in the :mod:`inspect` module). + + On Windows, :func:`signal` can only be called with :const:`SIGABRT`, + :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, + :const:`SIGTERM`, or :const:`SIGBREAK`. + A :exc:`ValueError` will be raised in any other case. + Note that not all systems define the same set of signal names; an + :exc:`AttributeError` will be raised if a signal name is not defined as + ``SIG*`` module level constant. + + +.. function:: sigpending() + + Examine the set of signals that are pending for delivery to the calling + thread (i.e., the signals which have been raised while blocked). Return the + set of the pending signals. + + .. availability:: Unix. See the man page :manpage:`sigpending(2)` for further + information. + + See also :func:`pause`, :func:`pthread_sigmask` and :func:`sigwait`. + + .. versionadded:: 3.3 + + +.. function:: sigwait(sigset) + + Suspend execution of the calling thread until the delivery of one of the + signals specified in the signal set *sigset*. The function accepts the signal + (removes it from the pending list of signals), and returns the signal number. + + .. availability:: Unix. See the man page :manpage:`sigwait(3)` for further + information. + + See also :func:`pause`, :func:`pthread_sigmask`, :func:`sigpending`, + :func:`sigwaitinfo` and :func:`sigtimedwait`. + + .. versionadded:: 3.3 + + +.. function:: sigwaitinfo(sigset) + + Suspend execution of the calling thread until the delivery of one of the + signals specified in the signal set *sigset*. The function accepts the + signal and removes it from the pending list of signals. If one of the + signals in *sigset* is already pending for the calling thread, the function + will return immediately with information about that signal. The signal + handler is not called for the delivered signal. The function raises an + :exc:`InterruptedError` if it is interrupted by a signal that is not in + *sigset*. + + The return value is an object representing the data contained in the + :c:type:`siginfo_t` structure, namely: :attr:`si_signo`, :attr:`si_code`, + :attr:`si_errno`, :attr:`si_pid`, :attr:`si_uid`, :attr:`si_status`, + :attr:`si_band`. + + .. availability:: Unix. See the man page :manpage:`sigwaitinfo(2)` for further + information. + + See also :func:`pause`, :func:`sigwait` and :func:`sigtimedwait`. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.5 + The function is now retried if interrupted by a signal not in *sigset* + and the signal handler does not raise an exception (see :pep:`475` for + the rationale). + + +.. function:: sigtimedwait(sigset, timeout) + + Like :func:`sigwaitinfo`, but takes an additional *timeout* argument + specifying a timeout. If *timeout* is specified as :const:`0`, a poll is + performed. Returns :const:`None` if a timeout occurs. + + .. availability:: Unix. See the man page :manpage:`sigtimedwait(2)` for further + information. + + See also :func:`pause`, :func:`sigwait` and :func:`sigwaitinfo`. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.5 + The function is now retried with the recomputed *timeout* if interrupted + by a signal not in *sigset* and the signal handler does not raise an + exception (see :pep:`475` for the rationale). + + +.. _signal-example: + +Example +------- + +Here is a minimal example program. It uses the :func:`alarm` function to limit +the time spent waiting to open a file; this is useful if the file is for a +serial device that may not be turned on, which would normally cause the +:func:`os.open` to hang indefinitely. The solution is to set a 5-second alarm +before opening the file; if the operation takes too long, the alarm signal will +be sent, and the handler raises an exception. :: + + import signal, os + + def handler(signum, frame): + print('Signal handler called with signal', signum) + raise OSError("Couldn't open device!") + + # Set the signal handler and a 5-second alarm + signal.signal(signal.SIGALRM, handler) + signal.alarm(5) + + # This open() may hang indefinitely + fd = os.open('/dev/ttyS0', os.O_RDWR) + + signal.alarm(0) # Disable the alarm + +Note on SIGPIPE +--------------- + +Piping output of your program to tools like :manpage:`head(1)` will +cause a :const:`SIGPIPE` signal to be sent to your process when the receiver +of its standard output closes early. This results in an exception +like :code:`BrokenPipeError: [Errno 32] Broken pipe`. To handle this +case, wrap your entry point to catch this exception as follows:: + + import os + import sys + + def main(): + try: + # simulate large output (your code replaces this loop) + for x in range(10000): + print("y") + # flush output here to force SIGPIPE to be triggered + # while inside this try block. + sys.stdout.flush() + except BrokenPipeError: + # Python flushes standard streams on exit; redirect remaining output + # to devnull to avoid another BrokenPipeError at shutdown + devnull = os.open(os.devnull, os.O_WRONLY) + os.dup2(devnull, sys.stdout.fileno()) + sys.exit(1) # Python exits with error code 1 on EPIPE + + if __name__ == '__main__': + main() + +Do not set :const:`SIGPIPE`'s disposition to :const:`SIG_DFL` +in order to avoid :exc:`BrokenPipeError`. Doing that would cause +your program to exit unexpectedly also whenever any socket connection +is interrupted while your program is still writing to it. diff --git a/cpython_2/environment/repo/Doc/library/site.rst b/cpython_2/environment/repo/Doc/library/site.rst new file mode 100644 index 0000000000000000000000000000000000000000..b424e1ba348d870a7534d54cec06a29fcb9cec88 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/site.rst @@ -0,0 +1,277 @@ +:mod:`site` --- Site-specific configuration hook +================================================ + +.. module:: site + :synopsis: Module responsible for site-specific configuration. + +**Source code:** :source:`Lib/site.py` + +-------------- + +.. highlight:: none + +**This module is automatically imported during initialization.** The automatic +import can be suppressed using the interpreter's :option:`-S` option. + +.. index:: triple: module; search; path + +Importing this module will append site-specific paths to the module search path +and add a few builtins, unless :option:`-S` was used. In that case, this module +can be safely imported with no automatic modifications to the module search path +or additions to the builtins. To explicitly trigger the usual site-specific +additions, call the :func:`site.main` function. + +.. versionchanged:: 3.3 + Importing the module used to trigger paths manipulation even when using + :option:`-S`. + +.. index:: + pair: site-packages; directory + +It starts by constructing up to four directories from a head and a tail part. +For the head part, it uses ``sys.prefix`` and ``sys.exec_prefix``; empty heads +are skipped. For the tail part, it uses the empty string and then +:file:`lib/site-packages` (on Windows) or +:file:`lib/python{X.Y}/site-packages` (on Unix and Macintosh). For each +of the distinct head-tail combinations, it sees if it refers to an existing +directory, and if so, adds it to ``sys.path`` and also inspects the newly +added path for configuration files. + +.. versionchanged:: 3.5 + Support for the "site-python" directory has been removed. + +If a file named "pyvenv.cfg" exists one directory above sys.executable, +sys.prefix and sys.exec_prefix are set to that directory and +it is also checked for site-packages (sys.base_prefix and +sys.base_exec_prefix will always be the "real" prefixes of the Python +installation). If "pyvenv.cfg" (a bootstrap configuration file) contains +the key "include-system-site-packages" set to anything other than "true" +(case-insensitive), the system-level prefixes will not be +searched for site-packages; otherwise they will. + +.. index:: + single: # (hash); comment + statement: import + +A path configuration file is a file whose name has the form :file:`{name}.pth` +and exists in one of the four directories mentioned above; its contents are +additional items (one per line) to be added to ``sys.path``. Non-existing items +are never added to ``sys.path``, and no check is made that the item refers to a +directory rather than a file. No item is added to ``sys.path`` more than +once. Blank lines and lines beginning with ``#`` are skipped. Lines starting +with ``import`` (followed by space or tab) are executed. + +.. note:: + + An executable line in a :file:`.pth` file is run at every Python startup, + regardless of whether a particular module is actually going to be used. + Its impact should thus be kept to a minimum. + The primary intended purpose of executable lines is to make the + corresponding module(s) importable + (load 3rd-party import hooks, adjust :envvar:`PATH` etc). + Any other initialization is supposed to be done upon a module's + actual import, if and when it happens. + Limiting a code chunk to a single line is a deliberate measure + to discourage putting anything more complex here. + +.. index:: + single: package + triple: path; configuration; file + +For example, suppose ``sys.prefix`` and ``sys.exec_prefix`` are set to +:file:`/usr/local`. The Python X.Y library is then installed in +:file:`/usr/local/lib/python{X.Y}`. Suppose this has +a subdirectory :file:`/usr/local/lib/python{X.Y}/site-packages` with three +subsubdirectories, :file:`foo`, :file:`bar` and :file:`spam`, and two path +configuration files, :file:`foo.pth` and :file:`bar.pth`. Assume +:file:`foo.pth` contains the following:: + + # foo package configuration + + foo + bar + bletch + +and :file:`bar.pth` contains:: + + # bar package configuration + + bar + +Then the following version-specific directories are added to +``sys.path``, in this order:: + + /usr/local/lib/pythonX.Y/site-packages/bar + /usr/local/lib/pythonX.Y/site-packages/foo + +Note that :file:`bletch` is omitted because it doesn't exist; the :file:`bar` +directory precedes the :file:`foo` directory because :file:`bar.pth` comes +alphabetically before :file:`foo.pth`; and :file:`spam` is omitted because it is +not mentioned in either path configuration file. + +.. index:: module: sitecustomize + +After these path manipulations, an attempt is made to import a module named +:mod:`sitecustomize`, which can perform arbitrary site-specific customizations. +It is typically created by a system administrator in the site-packages +directory. If this import fails with an :exc:`ImportError` or its subclass +exception, and the exception's :attr:`name` attribute equals to ``'sitecustomize'``, +it is silently ignored. If Python is started without output streams available, as +with :file:`pythonw.exe` on Windows (which is used by default to start IDLE), +attempted output from :mod:`sitecustomize` is ignored. Any other exception +causes a silent and perhaps mysterious failure of the process. + +.. index:: module: usercustomize + +After this, an attempt is made to import a module named :mod:`usercustomize`, +which can perform arbitrary user-specific customizations, if +:data:`ENABLE_USER_SITE` is true. This file is intended to be created in the +user site-packages directory (see below), which is part of ``sys.path`` unless +disabled by :option:`-s`. If this import fails with an :exc:`ImportError` or +its subclass exception, and the exception's :attr:`name` attribute equals to +``'usercustomize'``, it is silently ignored. + +Note that for some non-Unix systems, ``sys.prefix`` and ``sys.exec_prefix`` are +empty, and the path manipulations are skipped; however the import of +:mod:`sitecustomize` and :mod:`usercustomize` is still attempted. + + +.. _rlcompleter-config: + +Readline configuration +---------------------- + +On systems that support :mod:`readline`, this module will also import and +configure the :mod:`rlcompleter` module, if Python is started in +:ref:`interactive mode ` and without the :option:`-S` option. +The default behavior is enable tab-completion and to use +:file:`~/.python_history` as the history save file. To disable it, delete (or +override) the :data:`sys.__interactivehook__` attribute in your +:mod:`sitecustomize` or :mod:`usercustomize` module or your +:envvar:`PYTHONSTARTUP` file. + +.. versionchanged:: 3.4 + Activation of rlcompleter and history was made automatic. + + +Module contents +--------------- + +.. data:: PREFIXES + + A list of prefixes for site-packages directories. + + +.. data:: ENABLE_USER_SITE + + Flag showing the status of the user site-packages directory. ``True`` means + that it is enabled and was added to ``sys.path``. ``False`` means that it + was disabled by user request (with :option:`-s` or + :envvar:`PYTHONNOUSERSITE`). ``None`` means it was disabled for security + reasons (mismatch between user or group id and effective id) or by an + administrator. + + +.. data:: USER_SITE + + Path to the user site-packages for the running Python. Can be ``None`` if + :func:`getusersitepackages` hasn't been called yet. Default value is + :file:`~/.local/lib/python{X.Y}/site-packages` for UNIX and non-framework Mac + OS X builds, :file:`~/Library/Python/{X.Y}/lib/python/site-packages` for Mac + framework builds, and :file:`{%APPDATA%}\\Python\\Python{XY}\\site-packages` + on Windows. This directory is a site directory, which means that + :file:`.pth` files in it will be processed. + + +.. data:: USER_BASE + + Path to the base directory for the user site-packages. Can be ``None`` if + :func:`getuserbase` hasn't been called yet. Default value is + :file:`~/.local` for UNIX and Mac OS X non-framework builds, + :file:`~/Library/Python/{X.Y}` for Mac framework builds, and + :file:`{%APPDATA%}\\Python` for Windows. This value is used by Distutils to + compute the installation directories for scripts, data files, Python modules, + etc. for the :ref:`user installation scheme `. + See also :envvar:`PYTHONUSERBASE`. + + +.. function:: main() + + Adds all the standard site-specific directories to the module search + path. This function is called automatically when this module is imported, + unless the Python interpreter was started with the :option:`-S` flag. + + .. versionchanged:: 3.3 + This function used to be called unconditionally. + + +.. function:: addsitedir(sitedir, known_paths=None) + + Add a directory to sys.path and process its :file:`.pth` files. Typically + used in :mod:`sitecustomize` or :mod:`usercustomize` (see above). + + +.. function:: getsitepackages() + + Return a list containing all global site-packages directories. + + .. versionadded:: 3.2 + + +.. function:: getuserbase() + + Return the path of the user base directory, :data:`USER_BASE`. If it is not + initialized yet, this function will also set it, respecting + :envvar:`PYTHONUSERBASE`. + + .. versionadded:: 3.2 + + +.. function:: getusersitepackages() + + Return the path of the user-specific site-packages directory, + :data:`USER_SITE`. If it is not initialized yet, this function will also set + it, respecting :envvar:`PYTHONNOUSERSITE` and :data:`USER_BASE`. + + .. versionadded:: 3.2 + + +.. _site-commandline: + +Command Line Interface +---------------------- + +.. program:: site + +The :mod:`site` module also provides a way to get the user directories from the +command line: + +.. code-block:: shell-session + + $ python3 -m site --user-site + /home/user/.local/lib/python3.3/site-packages + +If it is called without arguments, it will print the contents of +:data:`sys.path` on the standard output, followed by the value of +:data:`USER_BASE` and whether the directory exists, then the same thing for +:data:`USER_SITE`, and finally the value of :data:`ENABLE_USER_SITE`. + +.. cmdoption:: --user-base + + Print the path to the user base directory. + +.. cmdoption:: --user-site + + Print the path to the user site-packages directory. + +If both options are given, user base and user site will be printed (always in +this order), separated by :data:`os.pathsep`. + +If any option is given, the script will exit with one of these values: ``0`` if +the user site-packages directory is enabled, ``1`` if it was disabled by the +user, ``2`` if it is disabled for security reasons or by an administrator, and a +value greater than 2 if there is an error. + +.. seealso:: + + :pep:`370` -- Per user site-packages directory diff --git a/cpython_2/environment/repo/Doc/library/smtpd.rst b/cpython_2/environment/repo/Doc/library/smtpd.rst new file mode 100644 index 0000000000000000000000000000000000000000..d84e74a8ceaaff506cfcfcc62f6985be3cf80915 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/smtpd.rst @@ -0,0 +1,283 @@ +:mod:`smtpd` --- SMTP Server +============================ + +.. module:: smtpd + :synopsis: A SMTP server implementation in Python. + +.. moduleauthor:: Barry Warsaw +.. sectionauthor:: Moshe Zadka + +**Source code:** :source:`Lib/smtpd.py` + +-------------- + +This module offers several classes to implement SMTP (email) servers. + +.. seealso:: + + The `aiosmtpd `_ package is a recommended + replacement for this module. It is based on :mod:`asyncio` and provides a + more straightforward API. :mod:`smtpd` should be considered deprecated. + +Several server implementations are present; one is a generic +do-nothing implementation, which can be overridden, while the other two offer +specific mail-sending strategies. + +Additionally the SMTPChannel may be extended to implement very specific +interaction behaviour with SMTP clients. + +The code supports :RFC:`5321`, plus the :rfc:`1870` SIZE and :rfc:`6531` +SMTPUTF8 extensions. + + +SMTPServer Objects +------------------ + + +.. class:: SMTPServer(localaddr, remoteaddr, data_size_limit=33554432,\ + map=None, enable_SMTPUTF8=False, decode_data=False) + + Create a new :class:`SMTPServer` object, which binds to local address + *localaddr*. It will treat *remoteaddr* as an upstream SMTP relayer. Both + *localaddr* and *remoteaddr* should be a :ref:`(host, port) ` + tuple. The object inherits from :class:`asyncore.dispatcher`, and so will + insert itself into :mod:`asyncore`'s event loop on instantiation. + + *data_size_limit* specifies the maximum number of bytes that will be + accepted in a ``DATA`` command. A value of ``None`` or ``0`` means no + limit. + + *map* is the socket map to use for connections (an initially empty + dictionary is a suitable value). If not specified the :mod:`asyncore` + global socket map is used. + + *enable_SMTPUTF8* determines whether the ``SMTPUTF8`` extension (as defined + in :RFC:`6531`) should be enabled. The default is ``False``. + When ``True``, ``SMTPUTF8`` is accepted as a parameter to the ``MAIL`` + command and when present is passed to :meth:`process_message` in the + ``kwargs['mail_options']`` list. *decode_data* and *enable_SMTPUTF8* + cannot be set to ``True`` at the same time. + + *decode_data* specifies whether the data portion of the SMTP transaction + should be decoded using UTF-8. When *decode_data* is ``False`` (the + default), the server advertises the ``8BITMIME`` + extension (:rfc:`6152`), accepts the ``BODY=8BITMIME`` parameter to + the ``MAIL`` command, and when present passes it to :meth:`process_message` + in the ``kwargs['mail_options']`` list. *decode_data* and *enable_SMTPUTF8* + cannot be set to ``True`` at the same time. + + .. method:: process_message(peer, mailfrom, rcpttos, data, **kwargs) + + Raise a :exc:`NotImplementedError` exception. Override this in subclasses to + do something useful with this message. Whatever was passed in the + constructor as *remoteaddr* will be available as the :attr:`_remoteaddr` + attribute. *peer* is the remote host's address, *mailfrom* is the envelope + originator, *rcpttos* are the envelope recipients and *data* is a string + containing the contents of the e-mail (which should be in :rfc:`5321` + format). + + If the *decode_data* constructor keyword is set to ``True``, the *data* + argument will be a unicode string. If it is set to ``False``, it + will be a bytes object. + + *kwargs* is a dictionary containing additional information. It is empty + if ``decode_data=True`` was given as an init argument, otherwise + it contains the following keys: + + *mail_options*: + a list of all received parameters to the ``MAIL`` + command (the elements are uppercase strings; example: + ``['BODY=8BITMIME', 'SMTPUTF8']``). + + *rcpt_options*: + same as *mail_options* but for the ``RCPT`` command. + Currently no ``RCPT TO`` options are supported, so for now + this will always be an empty list. + + Implementations of ``process_message`` should use the ``**kwargs`` + signature to accept arbitrary keyword arguments, since future feature + enhancements may add keys to the kwargs dictionary. + + Return ``None`` to request a normal ``250 Ok`` response; otherwise + return the desired response string in :RFC:`5321` format. + + .. attribute:: channel_class + + Override this in subclasses to use a custom :class:`SMTPChannel` for + managing SMTP clients. + + .. versionadded:: 3.4 + The *map* constructor argument. + + .. versionchanged:: 3.5 + *localaddr* and *remoteaddr* may now contain IPv6 addresses. + + .. versionadded:: 3.5 + The *decode_data* and *enable_SMTPUTF8* constructor parameters, and the + *kwargs* parameter to :meth:`process_message` when *decode_data* is + ``False``. + + .. versionchanged:: 3.6 + *decode_data* is now ``False`` by default. + + +DebuggingServer Objects +----------------------- + + +.. class:: DebuggingServer(localaddr, remoteaddr) + + Create a new debugging server. Arguments are as per :class:`SMTPServer`. + Messages will be discarded, and printed on stdout. + + +PureProxy Objects +----------------- + + +.. class:: PureProxy(localaddr, remoteaddr) + + Create a new pure proxy server. Arguments are as per :class:`SMTPServer`. + Everything will be relayed to *remoteaddr*. Note that running this has a good + chance to make you into an open relay, so please be careful. + + +MailmanProxy Objects +-------------------- + + +.. class:: MailmanProxy(localaddr, remoteaddr) + + .. deprecated-removed:: 3.9 3.11 + + :class:`MailmanProxy` is deprecated, it depends on a ``Mailman`` + module which no longer exists and therefore is already broken. + + + Create a new pure proxy server. Arguments are as per :class:`SMTPServer`. + Everything will be relayed to *remoteaddr*, unless local mailman configurations + knows about an address, in which case it will be handled via mailman. Note that + running this has a good chance to make you into an open relay, so please be + careful. + +SMTPChannel Objects +------------------- + +.. class:: SMTPChannel(server, conn, addr, data_size_limit=33554432,\ + map=None, enable_SMTPUTF8=False, decode_data=False) + + Create a new :class:`SMTPChannel` object which manages the communication + between the server and a single SMTP client. + + *conn* and *addr* are as per the instance variables described below. + + *data_size_limit* specifies the maximum number of bytes that will be + accepted in a ``DATA`` command. A value of ``None`` or ``0`` means no + limit. + + *enable_SMTPUTF8* determines whether the ``SMTPUTF8`` extension (as defined + in :RFC:`6531`) should be enabled. The default is ``False``. + *decode_data* and *enable_SMTPUTF8* cannot be set to ``True`` at the same + time. + + A dictionary can be specified in *map* to avoid using a global socket map. + + *decode_data* specifies whether the data portion of the SMTP transaction + should be decoded using UTF-8. The default is ``False``. + *decode_data* and *enable_SMTPUTF8* cannot be set to ``True`` at the same + time. + + To use a custom SMTPChannel implementation you need to override the + :attr:`SMTPServer.channel_class` of your :class:`SMTPServer`. + + .. versionchanged:: 3.5 + The *decode_data* and *enable_SMTPUTF8* parameters were added. + + .. versionchanged:: 3.6 + *decode_data* is now ``False`` by default. + + The :class:`SMTPChannel` has the following instance variables: + + .. attribute:: smtp_server + + Holds the :class:`SMTPServer` that spawned this channel. + + .. attribute:: conn + + Holds the socket object connecting to the client. + + .. attribute:: addr + + Holds the address of the client, the second value returned by + :func:`socket.accept ` + + .. attribute:: received_lines + + Holds a list of the line strings (decoded using UTF-8) received from + the client. The lines have their ``"\r\n"`` line ending translated to + ``"\n"``. + + .. attribute:: smtp_state + + Holds the current state of the channel. This will be either + :attr:`COMMAND` initially and then :attr:`DATA` after the client sends + a "DATA" line. + + .. attribute:: seen_greeting + + Holds a string containing the greeting sent by the client in its "HELO". + + .. attribute:: mailfrom + + Holds a string containing the address identified in the "MAIL FROM:" line + from the client. + + .. attribute:: rcpttos + + Holds a list of strings containing the addresses identified in the + "RCPT TO:" lines from the client. + + .. attribute:: received_data + + Holds a string containing all of the data sent by the client during the + DATA state, up to but not including the terminating ``"\r\n.\r\n"``. + + .. attribute:: fqdn + + Holds the fully-qualified domain name of the server as returned by + :func:`socket.getfqdn`. + + .. attribute:: peer + + Holds the name of the client peer as returned by ``conn.getpeername()`` + where ``conn`` is :attr:`conn`. + + The :class:`SMTPChannel` operates by invoking methods named ``smtp_`` + upon reception of a command line from the client. Built into the base + :class:`SMTPChannel` class are methods for handling the following commands + (and responding to them appropriately): + + ======== =================================================================== + Command Action taken + ======== =================================================================== + HELO Accepts the greeting from the client and stores it in + :attr:`seen_greeting`. Sets server to base command mode. + EHLO Accepts the greeting from the client and stores it in + :attr:`seen_greeting`. Sets server to extended command mode. + NOOP Takes no action. + QUIT Closes the connection cleanly. + MAIL Accepts the "MAIL FROM:" syntax and stores the supplied address as + :attr:`mailfrom`. In extended command mode, accepts the + :rfc:`1870` SIZE attribute and responds appropriately based on the + value of *data_size_limit*. + RCPT Accepts the "RCPT TO:" syntax and stores the supplied addresses in + the :attr:`rcpttos` list. + RSET Resets the :attr:`mailfrom`, :attr:`rcpttos`, and + :attr:`received_data`, but not the greeting. + DATA Sets the internal state to :attr:`DATA` and stores remaining lines + from the client in :attr:`received_data` until the terminator + ``"\r\n.\r\n"`` is received. + HELP Returns minimal information on command syntax + VRFY Returns code 252 (the server doesn't know if the address is valid) + EXPN Reports that the command is not implemented. + ======== =================================================================== diff --git a/cpython_2/environment/repo/Doc/library/smtplib.rst b/cpython_2/environment/repo/Doc/library/smtplib.rst new file mode 100644 index 0000000000000000000000000000000000000000..a88e358eae5fdece69f68c5da6bc5289f158128c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/smtplib.rst @@ -0,0 +1,604 @@ +:mod:`smtplib` --- SMTP protocol client +======================================= + +.. module:: smtplib + :synopsis: SMTP protocol client (requires sockets). + +.. sectionauthor:: Eric S. Raymond + +**Source code:** :source:`Lib/smtplib.py` + +.. index:: + pair: SMTP; protocol + single: Simple Mail Transfer Protocol + +-------------- + +The :mod:`smtplib` module defines an SMTP client session object that can be used +to send mail to any Internet machine with an SMTP or ESMTP listener daemon. For +details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer +Protocol) and :rfc:`1869` (SMTP Service Extensions). + + +.. class:: SMTP(host='', port=0, local_hostname=None[, timeout], source_address=None) + + An :class:`SMTP` instance encapsulates an SMTP connection. It has methods + that support a full repertoire of SMTP and ESMTP operations. If the optional + host and port parameters are given, the SMTP :meth:`connect` method is + called with those parameters during initialization. If specified, + *local_hostname* is used as the FQDN of the local host in the HELO/EHLO + command. Otherwise, the local hostname is found using + :func:`socket.getfqdn`. If the :meth:`connect` call returns anything other + than a success code, an :exc:`SMTPConnectError` is raised. The optional + *timeout* parameter specifies a timeout in seconds for blocking operations + like the connection attempt (if not specified, the global default timeout + setting will be used). If the timeout expires, :exc:`socket.timeout` is + raised. The optional source_address parameter allows binding + to some specific source address in a machine with multiple network + interfaces, and/or to some specific source TCP port. It takes a 2-tuple + (host, port), for the socket to bind to as its source address before + connecting. If omitted (or if host or port are ``''`` and/or 0 respectively) + the OS default behavior will be used. + + For normal use, you should only require the initialization/connect, + :meth:`sendmail`, and :meth:`SMTP.quit` methods. + An example is included below. + + The :class:`SMTP` class supports the :keyword:`with` statement. When used + like this, the SMTP ``QUIT`` command is issued automatically when the + :keyword:`!with` statement exits. E.g.:: + + >>> from smtplib import SMTP + >>> with SMTP("domain.org") as smtp: + ... smtp.noop() + ... + (250, b'Ok') + >>> + + .. audit-event:: smtplib.send self,data smtplib.SMTP + + All commands will raise an :ref:`auditing event ` + ``smtplib.SMTP.send`` with arguments ``self`` and ``data``, + where ``data`` is the bytes about to be sent to the remote host. + + .. versionchanged:: 3.3 + Support for the :keyword:`with` statement was added. + + .. versionchanged:: 3.3 + source_address argument was added. + + .. versionadded:: 3.5 + The SMTPUTF8 extension (:rfc:`6531`) is now supported. + + .. versionchanged:: 3.9 + If the *timeout* parameter is set to be zero, it will raise a + :class:`ValueError` to prevent the creation of a non-blocking socket + +.. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, \ + certfile=None [, timeout], context=None, \ + source_address=None) + + An :class:`SMTP_SSL` instance behaves exactly the same as instances of + :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is + required from the beginning of the connection and using :meth:`starttls` is + not appropriate. If *host* is not specified, the local host is used. If + *port* is zero, the standard SMTP-over-SSL port (465) is used. The optional + arguments *local_hostname*, *timeout* and *source_address* have the same + meaning as they do in the :class:`SMTP` class. *context*, also optional, + can contain a :class:`~ssl.SSLContext` and allows configuring various + aspects of the secure connection. Please read :ref:`ssl-security` for + best practices. + + *keyfile* and *certfile* are a legacy alternative to *context*, and can + point to a PEM formatted private key and certificate chain file for the + SSL connection. + + .. versionchanged:: 3.3 + *context* was added. + + .. versionchanged:: 3.3 + source_address argument was added. + + .. versionchanged:: 3.4 + The class now supports hostname check with + :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see + :data:`ssl.HAS_SNI`). + + .. deprecated:: 3.6 + + *keyfile* and *certfile* are deprecated in favor of *context*. + Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let + :func:`ssl.create_default_context` select the system's trusted CA + certificates for you. + + .. versionchanged:: 3.9 + If the *timeout* parameter is set to be zero, it will raise a + :class:`ValueError` to prevent the creation of a non-blocking socket + +.. class:: LMTP(host='', port=LMTP_PORT, local_hostname=None, + source_address=None[, timeout]) + + The LMTP protocol, which is very similar to ESMTP, is heavily based on the + standard SMTP client. It's common to use Unix sockets for LMTP, so our + :meth:`connect` method must support that as well as a regular host:port + server. The optional arguments local_hostname and source_address have the + same meaning as they do in the :class:`SMTP` class. To specify a Unix + socket, you must use an absolute path for *host*, starting with a '/'. + + Authentication is supported, using the regular SMTP mechanism. When using a + Unix socket, LMTP generally don't support or require any authentication, but + your mileage might vary. + + .. versionchanged:: 3.9 + The optional *timeout* parameter was added. + + +A nice selection of exceptions is defined as well: + + +.. exception:: SMTPException + + Subclass of :exc:`OSError` that is the base exception class for all + the other exceptions provided by this module. + + .. versionchanged:: 3.4 + SMTPException became subclass of :exc:`OSError` + + +.. exception:: SMTPServerDisconnected + + This exception is raised when the server unexpectedly disconnects, or when an + attempt is made to use the :class:`SMTP` instance before connecting it to a + server. + + +.. exception:: SMTPResponseException + + Base class for all exceptions that include an SMTP error code. These exceptions + are generated in some instances when the SMTP server returns an error code. The + error code is stored in the :attr:`smtp_code` attribute of the error, and the + :attr:`smtp_error` attribute is set to the error message. + + +.. exception:: SMTPSenderRefused + + Sender address refused. In addition to the attributes set by on all + :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that + the SMTP server refused. + + +.. exception:: SMTPRecipientsRefused + + All recipient addresses refused. The errors for each recipient are accessible + through the attribute :attr:`recipients`, which is a dictionary of exactly the + same sort as :meth:`SMTP.sendmail` returns. + + +.. exception:: SMTPDataError + + The SMTP server refused to accept the message data. + + +.. exception:: SMTPConnectError + + Error occurred during establishment of a connection with the server. + + +.. exception:: SMTPHeloError + + The server refused our ``HELO`` message. + + +.. exception:: SMTPNotSupportedError + + The command or option attempted is not supported by the server. + + .. versionadded:: 3.5 + + +.. exception:: SMTPAuthenticationError + + SMTP authentication went wrong. Most probably the server didn't accept the + username/password combination provided. + + +.. seealso:: + + :rfc:`821` - Simple Mail Transfer Protocol + Protocol definition for SMTP. This document covers the model, operating + procedure, and protocol details for SMTP. + + :rfc:`1869` - SMTP Service Extensions + Definition of the ESMTP extensions for SMTP. This describes a framework for + extending SMTP with new commands, supporting dynamic discovery of the commands + provided by the server, and defines a few additional commands. + + +.. _smtp-objects: + +SMTP Objects +------------ + +An :class:`SMTP` instance has the following methods: + + +.. method:: SMTP.set_debuglevel(level) + + Set the debug output level. A value of 1 or ``True`` for *level* results in + debug messages for connection and for all messages sent to and received from + the server. A value of 2 for *level* results in these messages being + timestamped. + + .. versionchanged:: 3.5 Added debuglevel 2. + + +.. method:: SMTP.docmd(cmd, args='') + + Send a command *cmd* to the server. The optional argument *args* is simply + concatenated to the command, separated by a space. + + This returns a 2-tuple composed of a numeric response code and the actual + response line (multiline responses are joined into one long line.) + + In normal operation it should not be necessary to call this method explicitly. + It is used to implement other methods and may be useful for testing private + extensions. + + If the connection to the server is lost while waiting for the reply, + :exc:`SMTPServerDisconnected` will be raised. + + +.. method:: SMTP.connect(host='localhost', port=0) + + Connect to a host on a given port. The defaults are to connect to the local + host at the standard SMTP port (25). If the hostname ends with a colon (``':'``) + followed by a number, that suffix will be stripped off and the number + interpreted as the port number to use. This method is automatically invoked by + the constructor if a host is specified during instantiation. Returns a + 2-tuple of the response code and message sent by the server in its + connection response. + + .. audit-event:: smtplib.connect self,host,port smtplib.SMTP.connect + + +.. method:: SMTP.helo(name='') + + Identify yourself to the SMTP server using ``HELO``. The hostname argument + defaults to the fully qualified domain name of the local host. + The message returned by the server is stored as the :attr:`helo_resp` attribute + of the object. + + In normal operation it should not be necessary to call this method explicitly. + It will be implicitly called by the :meth:`sendmail` when necessary. + + +.. method:: SMTP.ehlo(name='') + + 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` + 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 parameters (if any). + + Unless you wish to use :meth:`has_extn` before sending mail, it should not be + necessary to call this method explicitly. It will be implicitly called by + :meth:`sendmail` when necessary. + +.. method:: SMTP.ehlo_or_helo_if_needed() + + This method calls :meth:`ehlo` and/or :meth:`helo` if there has been no + previous ``EHLO`` or ``HELO`` command this session. It tries ESMTP ``EHLO`` + first. + + :exc:`SMTPHeloError` + The server didn't reply properly to the ``HELO`` greeting. + +.. method:: SMTP.has_extn(name) + + Return :const:`True` if *name* is in the set of SMTP service extensions returned + by the server, :const:`False` otherwise. Case is ignored. + + +.. method:: SMTP.verify(address) + + Check the validity of an address on this server using SMTP ``VRFY``. Returns a + tuple consisting of code 250 and a full :rfc:`822` address (including human + name) if the user address is valid. Otherwise returns an SMTP error code of 400 + or greater and an error string. + + .. note:: + + Many sites disable SMTP ``VRFY`` in order to foil spammers. + + +.. method:: SMTP.login(user, password, *, initial_response_ok=True) + + Log in on an SMTP server that requires authentication. The arguments are the + username and the password to authenticate with. If there has been no previous + ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO`` + first. This method will return normally if the authentication was successful, or + may raise the following exceptions: + + :exc:`SMTPHeloError` + The server didn't reply properly to the ``HELO`` greeting. + + :exc:`SMTPAuthenticationError` + The server didn't accept the username/password combination. + + :exc:`SMTPNotSupportedError` + The ``AUTH`` command is not supported by the server. + + :exc:`SMTPException` + No suitable authentication method was found. + + Each of the authentication methods supported by :mod:`smtplib` are tried in + turn if they are advertised as supported by the server. See :meth:`auth` + for a list of supported authentication methods. *initial_response_ok* is + passed through to :meth:`auth`. + + Optional keyword argument *initial_response_ok* specifies whether, for + authentication methods that support it, an "initial response" as specified + in :rfc:`4954` can be sent along with the ``AUTH`` command, rather than + requiring a challenge/response. + + .. versionchanged:: 3.5 + :exc:`SMTPNotSupportedError` may be raised, and the + *initial_response_ok* parameter was added. + + +.. method:: SMTP.auth(mechanism, authobject, *, initial_response_ok=True) + + Issue an ``SMTP`` ``AUTH`` command for the specified authentication + *mechanism*, and handle the challenge response via *authobject*. + + *mechanism* specifies which authentication mechanism is to + be used as argument to the ``AUTH`` command; the valid values are + those listed in the ``auth`` element of :attr:`esmtp_features`. + + *authobject* must be a callable object taking an optional single argument: + + data = authobject(challenge=None) + + If optional keyword argument *initial_response_ok* is true, + ``authobject()`` will be called first with no argument. It can return the + :rfc:`4954` "initial response" ASCII ``str`` which will be encoded and sent with + the ``AUTH`` command as below. If the ``authobject()`` does not support an + initial response (e.g. because it requires a challenge), it should return + ``None`` when called with ``challenge=None``. If *initial_response_ok* is + false, then ``authobject()`` will not be called first with ``None``. + + If the initial response check returns ``None``, or if *initial_response_ok* is + false, ``authobject()`` will be called to process the server's challenge + response; the *challenge* argument it is passed will be a ``bytes``. It + should return ASCII ``str`` *data* that will be base64 encoded and sent to the + server. + + The ``SMTP`` class provides ``authobjects`` for the ``CRAM-MD5``, ``PLAIN``, + and ``LOGIN`` mechanisms; they are named ``SMTP.auth_cram_md5``, + ``SMTP.auth_plain``, and ``SMTP.auth_login`` respectively. They all require + that the ``user`` and ``password`` properties of the ``SMTP`` instance are + set to appropriate values. + + User code does not normally need to call ``auth`` directly, but can instead + call the :meth:`login` method, which will try each of the above mechanisms + in turn, in the order listed. ``auth`` is exposed to facilitate the + implementation of authentication methods not (or not yet) supported + directly by :mod:`smtplib`. + + .. versionadded:: 3.5 + + +.. method:: SMTP.starttls(keyfile=None, certfile=None, context=None) + + Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP + commands that follow will be encrypted. You should then call :meth:`ehlo` + again. + + If *keyfile* and *certfile* are provided, they are used to create an + :class:`ssl.SSLContext`. + + Optional *context* parameter is an :class:`ssl.SSLContext` object; This is + an alternative to using a keyfile and a certfile and if specified both + *keyfile* and *certfile* should be ``None``. + + If there has been no previous ``EHLO`` or ``HELO`` command this session, + this method tries ESMTP ``EHLO`` first. + + .. deprecated:: 3.6 + + *keyfile* and *certfile* are deprecated in favor of *context*. + Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let + :func:`ssl.create_default_context` select the system's trusted CA + certificates for you. + + :exc:`SMTPHeloError` + The server didn't reply properly to the ``HELO`` greeting. + + :exc:`SMTPNotSupportedError` + The server does not support the STARTTLS extension. + + :exc:`RuntimeError` + SSL/TLS support is not available to your Python interpreter. + + .. versionchanged:: 3.3 + *context* was added. + + .. versionchanged:: 3.4 + The method now supports hostname check with + :attr:`SSLContext.check_hostname` and *Server Name Indicator* (see + :data:`~ssl.HAS_SNI`). + + .. versionchanged:: 3.5 + The error raised for lack of STARTTLS support is now the + :exc:`SMTPNotSupportedError` subclass instead of the base + :exc:`SMTPException`. + + +.. method:: SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=()) + + Send mail. The required arguments are an :rfc:`822` from-address string, a list + of :rfc:`822` to-address strings (a bare string will be treated as a list with 1 + address), and a message string. The caller may pass a list of ESMTP options + (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*. + ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT`` + commands can be passed as *rcpt_options*. (If you need to use different ESMTP + options to different recipients you have to use the low-level methods such as + :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.) + + .. note:: + + The *from_addr* and *to_addrs* parameters are used to construct the message + envelope used by the transport agents. ``sendmail`` does not modify the + message headers in any way. + + *msg* may be a string containing characters in the ASCII range, or a byte + string. A string is encoded to bytes using the ascii codec, and lone ``\r`` + and ``\n`` characters are converted to ``\r\n`` characters. A byte string is + not modified. + + If there has been no previous ``EHLO`` or ``HELO`` command this session, this + method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and + each of the specified options will be passed to it (if the option is in the + feature set the server advertises). If ``EHLO`` fails, ``HELO`` will be tried + and ESMTP options suppressed. + + This method will return normally if the mail is accepted for at least one + recipient. Otherwise it will raise an exception. That is, if this method does + not raise an exception, then someone should get your mail. If this method does + not raise an exception, it returns a dictionary, with one entry for each + recipient that was refused. Each entry contains a tuple of the SMTP error code + and the accompanying error message sent by the server. + + If ``SMTPUTF8`` is included in *mail_options*, and the server supports it, + *from_addr* and *to_addrs* may contain non-ASCII characters. + + This method may raise the following exceptions: + + :exc:`SMTPRecipientsRefused` + All recipients were refused. Nobody got the mail. The :attr:`recipients` + attribute of the exception object is a dictionary with information about the + refused recipients (like the one returned when at least one recipient was + accepted). + + :exc:`SMTPHeloError` + The server didn't reply properly to the ``HELO`` greeting. + + :exc:`SMTPSenderRefused` + The server didn't accept the *from_addr*. + + :exc:`SMTPDataError` + The server replied with an unexpected error code (other than a refusal of a + recipient). + + :exc:`SMTPNotSupportedError` + ``SMTPUTF8`` was given in the *mail_options* but is not supported by the + server. + + Unless otherwise noted, the connection will be open even after an exception is + raised. + + .. versionchanged:: 3.2 + *msg* may be a byte string. + + .. versionchanged:: 3.5 + ``SMTPUTF8`` support added, and :exc:`SMTPNotSupportedError` may be + raised if ``SMTPUTF8`` is specified but the server does not support it. + + +.. method:: SMTP.send_message(msg, from_addr=None, to_addrs=None, \ + mail_options=(), rcpt_options=()) + + This is a convenience method for calling :meth:`sendmail` with the message + represented by an :class:`email.message.Message` object. The arguments have + the same meaning as for :meth:`sendmail`, except that *msg* is a ``Message`` + object. + + If *from_addr* is ``None`` or *to_addrs* is ``None``, ``send_message`` fills + those arguments with addresses extracted from the headers of *msg* as + specified in :rfc:`5322`\: *from_addr* is set to the :mailheader:`Sender` + field if it is present, and otherwise to the :mailheader:`From` field. + *to_addrs* combines the values (if any) of the :mailheader:`To`, + :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*. If exactly one + set of :mailheader:`Resent-*` headers appear in the message, the regular + headers are ignored and the :mailheader:`Resent-*` headers are used instead. + If the message contains more than one set of :mailheader:`Resent-*` headers, + a :exc:`ValueError` is raised, since there is no way to unambiguously detect + the most recent set of :mailheader:`Resent-` headers. + + ``send_message`` serializes *msg* using + :class:`~email.generator.BytesGenerator` with ``\r\n`` as the *linesep*, and + calls :meth:`sendmail` to transmit the resulting message. Regardless of the + values of *from_addr* and *to_addrs*, ``send_message`` does not transmit any + :mailheader:`Bcc` or :mailheader:`Resent-Bcc` headers that may appear + in *msg*. If any of the addresses in *from_addr* and *to_addrs* contain + non-ASCII characters and the server does not advertise ``SMTPUTF8`` support, + an :exc:`SMTPNotSupported` error is raised. Otherwise the ``Message`` is + serialized with a clone of its :mod:`~email.policy` with the + :attr:`~email.policy.EmailPolicy.utf8` attribute set to ``True``, and + ``SMTPUTF8`` and ``BODY=8BITMIME`` are added to *mail_options*. + + .. versionadded:: 3.2 + + .. versionadded:: 3.5 + Support for internationalized addresses (``SMTPUTF8``). + + +.. method:: SMTP.quit() + + Terminate the SMTP session and close the connection. Return the result of + the SMTP ``QUIT`` command. + + +Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``, +``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported. +Normally these do not need to be called directly, so they are not documented +here. For details, consult the module code. + + +.. _smtp-example: + +SMTP Example +------------ + +This example prompts the user for addresses needed in the message envelope ('To' +and 'From' addresses), and the message to be delivered. Note that the headers +to be included with the message must be included in the message as entered; this +example doesn't do any processing of the :rfc:`822` headers. In particular, the +'To' and 'From' addresses must be included in the message headers explicitly. :: + + import smtplib + + def prompt(prompt): + return input(prompt).strip() + + fromaddr = prompt("From: ") + toaddrs = prompt("To: ").split() + print("Enter message, end with ^D (Unix) or ^Z (Windows):") + + # Add the From: and To: headers at the start! + msg = ("From: %s\r\nTo: %s\r\n\r\n" + % (fromaddr, ", ".join(toaddrs))) + while True: + try: + line = input() + except EOFError: + break + if not line: + break + msg = msg + line + + print("Message length is", len(msg)) + + server = smtplib.SMTP('localhost') + server.set_debuglevel(1) + server.sendmail(fromaddr, toaddrs, msg) + server.quit() + +.. note:: + + In general, you will want to use the :mod:`email` package's features to + construct an email message, which you can then send + via :meth:`~smtplib.SMTP.send_message`; see :ref:`email-examples`. diff --git a/cpython_2/environment/repo/Doc/library/sndhdr.rst b/cpython_2/environment/repo/Doc/library/sndhdr.rst new file mode 100644 index 0000000000000000000000000000000000000000..6bfa9a9fd210bef3fee5aaffa7c2054853d7175c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/sndhdr.rst @@ -0,0 +1,51 @@ +:mod:`sndhdr` --- Determine type of sound file +============================================== + +.. module:: sndhdr + :synopsis: Determine type of a sound file. + +.. sectionauthor:: Fred L. Drake, Jr. +.. Based on comments in the module source file. + +**Source code:** :source:`Lib/sndhdr.py` + +.. index:: + single: A-LAW + single: u-LAW + +-------------- + +The :mod:`sndhdr` provides utility functions which attempt to determine the type +of sound data which is in a file. When these functions are able to determine +what type of sound data is stored in a file, they return a +:func:`~collections.namedtuple`, containing five attributes: (``filetype``, +``framerate``, ``nchannels``, ``nframes``, ``sampwidth``). The value for *type* +indicates the data type and will be one of the strings ``'aifc'``, ``'aiff'``, +``'au'``, ``'hcom'``, ``'sndr'``, ``'sndt'``, ``'voc'``, ``'wav'``, ``'8svx'``, +``'sb'``, ``'ub'``, or ``'ul'``. The *sampling_rate* will be either the actual +value or ``0`` if unknown or difficult to decode. Similarly, *channels* will be +either the number of channels or ``0`` if it cannot be determined or if the +value is difficult to decode. The value for *frames* will be either the number +of frames or ``-1``. The last item in the tuple, *bits_per_sample*, will either +be the sample size in bits or ``'A'`` for A-LAW or ``'U'`` for u-LAW. + + +.. function:: what(filename) + + Determines the type of sound data stored in the file *filename* using + :func:`whathdr`. If it succeeds, returns a namedtuple as described above, otherwise + ``None`` is returned. + + .. versionchanged:: 3.5 + Result changed from a tuple to a namedtuple. + + +.. function:: whathdr(filename) + + Determines the type of sound data stored in a file based on the file header. + The name of the file is given by *filename*. This function returns a namedtuple as + described above on success, or ``None``. + + .. versionchanged:: 3.5 + Result changed from a tuple to a namedtuple. + diff --git a/cpython_2/environment/repo/Doc/library/socket.rst b/cpython_2/environment/repo/Doc/library/socket.rst new file mode 100644 index 0000000000000000000000000000000000000000..d798c1a9d10a059c096fd0b3e5efc9a10e70638f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/socket.rst @@ -0,0 +1,2045 @@ +:mod:`socket` --- Low-level networking interface +================================================ + +.. module:: socket + :synopsis: Low-level networking interface. + +**Source code:** :source:`Lib/socket.py` + +-------------- + +This module provides access to the BSD *socket* interface. It is available on +all modern Unix systems, Windows, MacOS, and probably additional platforms. + +.. note:: + + Some behavior may be platform dependent, since calls are made to the operating + system socket APIs. + +.. index:: object: socket + +The Python interface is a straightforward transliteration of the Unix system +call and library interface for sockets to Python's object-oriented style: the +:func:`.socket` function returns a :dfn:`socket object` whose methods implement +the various socket system calls. Parameter types are somewhat higher-level than +in the C interface: as with :meth:`read` and :meth:`write` operations on Python +files, buffer allocation on receive operations is automatic, and buffer length +is implicit on send operations. + + +.. seealso:: + + Module :mod:`socketserver` + Classes that simplify writing network servers. + + Module :mod:`ssl` + A TLS/SSL wrapper for socket objects. + + +Socket families +--------------- + +Depending on the system and the build options, various socket families +are supported by this module. + +The address format required by a particular socket object is automatically +selected based on the address family specified when the socket object was +created. Socket addresses are represented as follows: + +- The address of an :const:`AF_UNIX` socket bound to a file system node + is represented as a string, using the file system encoding and the + ``'surrogateescape'`` error handler (see :pep:`383`). An address in + Linux's abstract namespace is returned as a :term:`bytes-like object` with + an initial null byte; note that sockets in this namespace can + communicate with normal file system sockets, so programs intended to + run on Linux may need to deal with both types of address. A string or + bytes-like object can be used for either type of address when + passing it as an argument. + + .. versionchanged:: 3.3 + Previously, :const:`AF_UNIX` socket paths were assumed to use UTF-8 + encoding. + + .. versionchanged:: 3.5 + Writable :term:`bytes-like object` is now accepted. + +.. _host_port: + +- A pair ``(host, port)`` is used for the :const:`AF_INET` address family, + where *host* is a string representing either a hostname in Internet domain + notation like ``'daring.cwi.nl'`` or an IPv4 address like ``'100.50.200.5'``, + and *port* is an integer. + + - For IPv4 addresses, two special forms are accepted instead of a host + address: ``''`` represents :const:`INADDR_ANY`, which is used to bind to all + interfaces, and the string ``''`` represents + :const:`INADDR_BROADCAST`. This behavior is not compatible with IPv6, + therefore, you may want to avoid these if you intend to support IPv6 with your + Python programs. + +- For :const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo, + scope_id)`` is used, where *flowinfo* and *scope_id* represent the ``sin6_flowinfo`` + and ``sin6_scope_id`` members in :const:`struct sockaddr_in6` in C. For + :mod:`socket` module methods, *flowinfo* and *scope_id* can be omitted just for + backward compatibility. Note, however, omission of *scope_id* can cause problems + in manipulating scoped IPv6 addresses. + + .. versionchanged:: 3.7 + For multicast addresses (with *scope_id* meaningful) *address* may not contain + ``%scope_id`` (or ``zone id``) part. This information is superfluous and may + be safely omitted (recommended). + +- :const:`AF_NETLINK` sockets are represented as pairs ``(pid, groups)``. + +- Linux-only support for TIPC is available using the :const:`AF_TIPC` + address family. TIPC is an open, non-IP based networked protocol designed + for use in clustered computer environments. Addresses are represented by a + tuple, and the fields depend on the address type. The general tuple form is + ``(addr_type, v1, v2, v3 [, scope])``, where: + + - *addr_type* is one of :const:`TIPC_ADDR_NAMESEQ`, :const:`TIPC_ADDR_NAME`, + or :const:`TIPC_ADDR_ID`. + - *scope* is one of :const:`TIPC_ZONE_SCOPE`, :const:`TIPC_CLUSTER_SCOPE`, and + :const:`TIPC_NODE_SCOPE`. + - If *addr_type* is :const:`TIPC_ADDR_NAME`, then *v1* is the server type, *v2* is + the port identifier, and *v3* should be 0. + + If *addr_type* is :const:`TIPC_ADDR_NAMESEQ`, then *v1* is the server type, *v2* + is the lower port number, and *v3* is the upper port number. + + If *addr_type* is :const:`TIPC_ADDR_ID`, then *v1* is the node, *v2* is the + reference, and *v3* should be set to 0. + +- A tuple ``(interface, )`` is used for the :const:`AF_CAN` address family, + where *interface* is a string representing a network interface name like + ``'can0'``. The network interface name ``''`` can be used to receive packets + from all network interfaces of this family. + + - :const:`CAN_ISOTP` protocol require a tuple ``(interface, rx_addr, tx_addr)`` + where both additional parameters are unsigned long integer that represent a + CAN identifier (standard or extended). + - :const:`CAN_J1939` protocol require a tuple ``(interface, name, pgn, addr)`` + where additional parameters are 64-bit unsigned integer representing the + ECU name, a 32-bit unsigned integer representing the Parameter Group Number + (PGN), and an 8-bit integer representing the address. + +- A string or a tuple ``(id, unit)`` is used for the :const:`SYSPROTO_CONTROL` + protocol of the :const:`PF_SYSTEM` family. The string is the name of a + kernel control using a dynamically-assigned ID. The tuple can be used if ID + and unit number of the kernel control are known or if a registered ID is + used. + + .. versionadded:: 3.3 + +- :const:`AF_BLUETOOTH` supports the following protocols and address + formats: + + - :const:`BTPROTO_L2CAP` accepts ``(bdaddr, psm)`` where ``bdaddr`` is + the Bluetooth address as a string and ``psm`` is an integer. + + - :const:`BTPROTO_RFCOMM` accepts ``(bdaddr, channel)`` where ``bdaddr`` + is the Bluetooth address as a string and ``channel`` is an integer. + + - :const:`BTPROTO_HCI` accepts ``(device_id,)`` where ``device_id`` is + either an integer or a string with the Bluetooth address of the + interface. (This depends on your OS; NetBSD and DragonFlyBSD expect + a Bluetooth address while everything else expects an integer.) + + .. versionchanged:: 3.2 + NetBSD and DragonFlyBSD support added. + + - :const:`BTPROTO_SCO` accepts ``bdaddr`` where ``bdaddr`` is a + :class:`bytes` object containing the Bluetooth address in a + string format. (ex. ``b'12:23:34:45:56:67'``) This protocol is not + supported under FreeBSD. + +- :const:`AF_ALG` is a Linux-only socket based interface to Kernel + cryptography. An algorithm socket is configured with a tuple of two to four + elements ``(type, name [, feat [, mask]])``, where: + + - *type* is the algorithm type as string, e.g. ``aead``, ``hash``, + ``skcipher`` or ``rng``. + + - *name* is the algorithm name and operation mode as string, e.g. + ``sha256``, ``hmac(sha256)``, ``cbc(aes)`` or ``drbg_nopr_ctr_aes256``. + + - *feat* and *mask* are unsigned 32bit integers. + + .. availability:: Linux 2.6.38, some algorithm types require more recent Kernels. + + .. versionadded:: 3.6 + +- :const:`AF_VSOCK` allows communication between virtual machines and + their hosts. The sockets are represented as a ``(CID, port)`` tuple + where the context ID or CID and port are integers. + + .. availability:: Linux >= 4.8 QEMU >= 2.8 ESX >= 4.0 ESX Workstation >= 6.5. + + .. versionadded:: 3.7 + +- :const:`AF_PACKET` is a low-level interface directly to network devices. + The packets are represented by the tuple + ``(ifname, proto[, pkttype[, hatype[, addr]]])`` where: + + - *ifname* - String specifying the device name. + - *proto* - An in network-byte-order integer specifying the Ethernet + protocol number. + - *pkttype* - Optional integer specifying the packet type: + + - ``PACKET_HOST`` (the default) - Packet addressed to the local host. + - ``PACKET_BROADCAST`` - Physical-layer broadcast packet. + - ``PACKET_MULTIHOST`` - Packet sent to a physical-layer multicast address. + - ``PACKET_OTHERHOST`` - Packet to some other host that has been caught by + a device driver in promiscuous mode. + - ``PACKET_OUTGOING`` - Packet originating from the local host that is + looped back to a packet socket. + - *hatype* - Optional integer specifying the ARP hardware address type. + - *addr* - Optional bytes-like object specifying the hardware physical + address, whose interpretation depends on the device. + +- :const:`AF_QIPCRTR` is a Linux-only socket based interface for communicating + with services running on co-processors in Qualcomm platforms. The address + family is represented as a ``(node, port)`` tuple where the *node* and *port* + are non-negative integers. + + .. versionadded:: 3.8 + +- :const:`IPPROTO_UDPLITE` is a variant of UDP which allows you to specify + what portion of a packet is covered with the checksum. It adds two socket + options that you can change. + ``self.setsockopt(IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, length)`` will + change what portion of outgoing packets are covered by the checksum and + ``self.setsockopt(IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, length)`` will + filter out packets which cover too little of their data. In both cases + ``length`` should be in ``range(8, 2**16, 8)``. + + Such a socket should be constructed with + ``socket(AF_INET, SOCK_DGRAM, IPPROTO_UDPLITE)`` for IPv4 or + ``socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDPLITE)`` for IPv6. + + .. availability:: Linux >= 2.6.20, FreeBSD >= 10.1-RELEASE + + .. versionadded:: 3.9 + +If you use a hostname in the *host* portion of IPv4/v6 socket address, the +program may show a nondeterministic behavior, as Python uses the first address +returned from the DNS resolution. The socket address will be resolved +differently into an actual IPv4/v6 address, depending on the results from DNS +resolution and/or the host configuration. For deterministic behavior use a +numeric address in *host* portion. + +All errors raise exceptions. The normal exceptions for invalid argument types +and out-of-memory conditions can be raised; starting from Python 3.3, errors +related to socket or address semantics raise :exc:`OSError` or one of its +subclasses (they used to raise :exc:`socket.error`). + +Non-blocking mode is supported through :meth:`~socket.setblocking`. A +generalization of this based on timeouts is supported through +:meth:`~socket.settimeout`. + + +Module contents +--------------- + +The module :mod:`socket` exports the following elements. + + +Exceptions +^^^^^^^^^^ + +.. exception:: error + + A deprecated alias of :exc:`OSError`. + + .. versionchanged:: 3.3 + Following :pep:`3151`, this class was made an alias of :exc:`OSError`. + + +.. exception:: herror + + A subclass of :exc:`OSError`, this exception is raised for + address-related errors, i.e. for functions that use *h_errno* in the POSIX + C API, including :func:`gethostbyname_ex` and :func:`gethostbyaddr`. + The accompanying value is a pair ``(h_errno, string)`` representing an + error returned by a library call. *h_errno* is a numeric value, while + *string* represents the description of *h_errno*, as returned by the + :c:func:`hstrerror` C function. + + .. versionchanged:: 3.3 + This class was made a subclass of :exc:`OSError`. + +.. exception:: gaierror + + A subclass of :exc:`OSError`, this exception is raised for + address-related errors by :func:`getaddrinfo` and :func:`getnameinfo`. + The accompanying value is a pair ``(error, string)`` representing an error + returned by a library call. *string* represents the description of + *error*, as returned by the :c:func:`gai_strerror` C function. The + numeric *error* value will match one of the :const:`EAI_\*` constants + defined in this module. + + .. versionchanged:: 3.3 + This class was made a subclass of :exc:`OSError`. + +.. exception:: timeout + + A subclass of :exc:`OSError`, this exception is raised when a timeout + occurs on a socket which has had timeouts enabled via a prior call to + :meth:`~socket.settimeout` (or implicitly through + :func:`~socket.setdefaulttimeout`). The accompanying value is a string + whose value is currently always "timed out". + + .. versionchanged:: 3.3 + This class was made a subclass of :exc:`OSError`. + + +Constants +^^^^^^^^^ + + The AF_* and SOCK_* constants are now :class:`AddressFamily` and + :class:`SocketKind` :class:`.IntEnum` collections. + + .. versionadded:: 3.4 + +.. data:: AF_UNIX + AF_INET + AF_INET6 + + These constants represent the address (and protocol) families, used for the + first argument to :func:`.socket`. If the :const:`AF_UNIX` constant is not + defined then this protocol is unsupported. More constants may be available + depending on the system. + + +.. data:: SOCK_STREAM + SOCK_DGRAM + SOCK_RAW + SOCK_RDM + SOCK_SEQPACKET + + These constants represent the socket types, used for the second argument to + :func:`.socket`. More constants may be available depending on the system. + (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be generally + useful.) + +.. data:: SOCK_CLOEXEC + SOCK_NONBLOCK + + These two constants, if defined, can be combined with the socket types and + allow you to set some flags atomically (thus avoiding possible race + conditions and the need for separate calls). + + .. seealso:: + + `Secure File Descriptor Handling `_ + for a more thorough explanation. + + .. availability:: Linux >= 2.6.27. + + .. versionadded:: 3.2 + +.. data:: SO_* + SOMAXCONN + MSG_* + SOL_* + SCM_* + IPPROTO_* + IPPORT_* + INADDR_* + IP_* + IPV6_* + EAI_* + AI_* + NI_* + TCP_* + + Many constants of these forms, documented in the Unix documentation on sockets + and/or the IP protocol, are also defined in the socket module. They are + generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt` + methods of socket objects. In most cases, only those symbols that are defined + in the Unix header files are defined; for a few symbols, default values are + provided. + + .. versionchanged:: 3.6 + ``SO_DOMAIN``, ``SO_PROTOCOL``, ``SO_PEERSEC``, ``SO_PASSSEC``, + ``TCP_USER_TIMEOUT``, ``TCP_CONGESTION`` were added. + + .. versionchanged:: 3.6.5 + On Windows, ``TCP_FASTOPEN``, ``TCP_KEEPCNT`` appear if run-time Windows + supports. + + .. versionchanged:: 3.7 + ``TCP_NOTSENT_LOWAT`` was added. + + On Windows, ``TCP_KEEPIDLE``, ``TCP_KEEPINTVL`` appear if run-time Windows + supports. + +.. data:: AF_CAN + PF_CAN + SOL_CAN_* + CAN_* + + Many constants of these forms, documented in the Linux documentation, are + also defined in the socket module. + + .. availability:: Linux >= 2.6.25. + + .. versionadded:: 3.3 + +.. data:: CAN_BCM + CAN_BCM_* + + CAN_BCM, in the CAN protocol family, is the broadcast manager (BCM) protocol. + Broadcast manager constants, documented in the Linux documentation, are also + defined in the socket module. + + .. availability:: Linux >= 2.6.25. + + .. note:: + The :data:`CAN_BCM_CAN_FD_FRAME` flag is only available on Linux >= 4.8. + + .. versionadded:: 3.4 + +.. data:: CAN_RAW_FD_FRAMES + + Enables CAN FD support in a CAN_RAW socket. This is disabled by default. + This allows your application to send both CAN and CAN FD frames; however, + you must accept both CAN and CAN FD frames when reading from the socket. + + This constant is documented in the Linux documentation. + + .. availability:: Linux >= 3.6. + + .. versionadded:: 3.5 + +.. data:: CAN_RAW_JOIN_FILTERS + + Joins the applied CAN filters such that only CAN frames that match all + given CAN filters are passed to user space. + + This constant is documented in the Linux documentation. + + .. availability:: Linux >= 4.1. + + .. versionadded:: 3.9 + +.. data:: CAN_ISOTP + + CAN_ISOTP, in the CAN protocol family, is the ISO-TP (ISO 15765-2) protocol. + ISO-TP constants, documented in the Linux documentation. + + .. availability:: Linux >= 2.6.25. + + .. versionadded:: 3.7 + +.. data:: CAN_J1939 + + CAN_J1939, in the CAN protocol family, is the SAE J1939 protocol. + J1939 constants, documented in the Linux documentation. + + .. availability:: Linux >= 5.4. + + .. versionadded:: 3.9 + + +.. data:: AF_PACKET + PF_PACKET + PACKET_* + + Many constants of these forms, documented in the Linux documentation, are + also defined in the socket module. + + .. availability:: Linux >= 2.2. + + +.. data:: AF_RDS + PF_RDS + SOL_RDS + RDS_* + + Many constants of these forms, documented in the Linux documentation, are + also defined in the socket module. + + .. availability:: Linux >= 2.6.30. + + .. versionadded:: 3.3 + + +.. data:: SIO_RCVALL + SIO_KEEPALIVE_VALS + SIO_LOOPBACK_FAST_PATH + RCVALL_* + + Constants for Windows' WSAIoctl(). The constants are used as arguments to the + :meth:`~socket.socket.ioctl` method of socket objects. + + .. versionchanged:: 3.6 + ``SIO_LOOPBACK_FAST_PATH`` was added. + + +.. data:: TIPC_* + + TIPC related constants, matching the ones exported by the C socket API. See + the TIPC documentation for more information. + +.. data:: AF_ALG + SOL_ALG + ALG_* + + Constants for Linux Kernel cryptography. + + .. availability:: Linux >= 2.6.38. + + .. versionadded:: 3.6 + + +.. data:: AF_VSOCK + IOCTL_VM_SOCKETS_GET_LOCAL_CID + VMADDR* + SO_VM* + + Constants for Linux host/guest communication. + + .. availability:: Linux >= 4.8. + + .. versionadded:: 3.7 + +.. data:: AF_LINK + + .. availability:: BSD, OSX. + + .. versionadded:: 3.4 + +.. data:: has_ipv6 + + This constant contains a boolean value which indicates if IPv6 is supported on + this platform. + +.. data:: BDADDR_ANY + BDADDR_LOCAL + + These are string constants containing Bluetooth addresses with special + meanings. For example, :const:`BDADDR_ANY` can be used to indicate + any address when specifying the binding socket with + :const:`BTPROTO_RFCOMM`. + +.. data:: HCI_FILTER + HCI_TIME_STAMP + HCI_DATA_DIR + + For use with :const:`BTPROTO_HCI`. :const:`HCI_FILTER` is not + available for NetBSD or DragonFlyBSD. :const:`HCI_TIME_STAMP` and + :const:`HCI_DATA_DIR` are not available for FreeBSD, NetBSD, or + DragonFlyBSD. + +.. data:: AF_QIPCRTR + + Constant for Qualcomm's IPC router protocol, used to communicate with + service providing remote processors. + + .. availability:: Linux >= 4.7. + +Functions +^^^^^^^^^ + +Creating sockets +'''''''''''''''' + +The following functions all create :ref:`socket objects `. + + +.. function:: socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None) + + Create a new socket using the given address family, socket type and protocol + number. The address family should be :const:`AF_INET` (the default), + :const:`AF_INET6`, :const:`AF_UNIX`, :const:`AF_CAN`, :const:`AF_PACKET`, + or :const:`AF_RDS`. The socket type should be :const:`SOCK_STREAM` (the + default), :const:`SOCK_DGRAM`, :const:`SOCK_RAW` or perhaps one of the other + ``SOCK_`` constants. The protocol number is usually zero and may be omitted + or in the case where the address family is :const:`AF_CAN` the protocol + should be one of :const:`CAN_RAW`, :const:`CAN_BCM`, :const:`CAN_ISOTP` or + :const:`CAN_J1939`. + + If *fileno* is specified, the values for *family*, *type*, and *proto* are + auto-detected from the specified file descriptor. Auto-detection can be + overruled by calling the function with explicit *family*, *type*, or *proto* + arguments. This only affects how Python represents e.g. the return value + of :meth:`socket.getpeername` but not the actual OS resource. Unlike + :func:`socket.fromfd`, *fileno* will return the same socket and not a + duplicate. This may help close a detached socket using + :meth:`socket.close()`. + + The newly created socket is :ref:`non-inheritable `. + + .. audit-event:: socket.__new__ self,family,type,protocol socket.socket + + .. versionchanged:: 3.3 + The AF_CAN family was added. + The AF_RDS family was added. + + .. versionchanged:: 3.4 + The CAN_BCM protocol was added. + + .. versionchanged:: 3.4 + The returned socket is now non-inheritable. + + .. versionchanged:: 3.7 + The CAN_ISOTP protocol was added. + + .. versionchanged:: 3.7 + When :const:`SOCK_NONBLOCK` or :const:`SOCK_CLOEXEC` + bit flags are applied to *type* they are cleared, and + :attr:`socket.type` will not reflect them. They are still passed + to the underlying system `socket()` call. Therefore, + + :: + + sock = socket.socket( + socket.AF_INET, + socket.SOCK_STREAM | socket.SOCK_NONBLOCK) + + will still create a non-blocking socket on OSes that support + ``SOCK_NONBLOCK``, but ``sock.type`` will be set to + ``socket.SOCK_STREAM``. + + .. versionchanged:: 3.9 + The CAN_J1939 protocol was added. + +.. function:: socketpair([family[, type[, proto]]]) + + Build a pair of connected socket objects using the given address family, socket + type, and protocol number. Address family, socket type, and protocol number are + as for the :func:`.socket` function above. The default family is :const:`AF_UNIX` + if defined on the platform; otherwise, the default is :const:`AF_INET`. + + The newly created sockets are :ref:`non-inheritable `. + + .. versionchanged:: 3.2 + The returned socket objects now support the whole socket API, rather + than a subset. + + .. versionchanged:: 3.4 + The returned sockets are now non-inheritable. + + .. versionchanged:: 3.5 + Windows support added. + + +.. function:: create_connection(address[, timeout[, source_address]]) + + Connect to a TCP service listening on the Internet *address* (a 2-tuple + ``(host, port)``), and return the socket object. This is a higher-level + function than :meth:`socket.connect`: if *host* is a non-numeric hostname, + it will try to resolve it for both :data:`AF_INET` and :data:`AF_INET6`, + and then try to connect to all possible addresses in turn until a + connection succeeds. This makes it easy to write clients that are + compatible to both IPv4 and IPv6. + + Passing the optional *timeout* parameter will set the timeout on the + socket instance before attempting to connect. If no *timeout* is + supplied, the global default timeout setting returned by + :func:`getdefaulttimeout` is used. + + If supplied, *source_address* must be a 2-tuple ``(host, port)`` for the + socket to bind to as its source address before connecting. If host or port + are '' or 0 respectively the OS default behavior will be used. + + .. versionchanged:: 3.2 + *source_address* was added. + +.. function:: create_server(address, *, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False) + + Convenience function which creates a TCP socket bound to *address* (a 2-tuple + ``(host, port)``) and return the socket object. + + *family* should be either :data:`AF_INET` or :data:`AF_INET6`. + *backlog* is the queue size passed to :meth:`socket.listen`; when ``0`` + a default reasonable value is chosen. + *reuse_port* dictates whether to set the :data:`SO_REUSEPORT` socket option. + + If *dualstack_ipv6* is true and the platform supports it the socket will + be able to accept both IPv4 and IPv6 connections, else it will raise + :exc:`ValueError`. Most POSIX platforms and Windows are supposed to support + this functionality. + When this functionality is enabled the address returned by + :meth:`socket.getpeername` when an IPv4 connection occurs will be an IPv6 + address represented as an IPv4-mapped IPv6 address. + If *dualstack_ipv6* is false it will explicitly disable this functionality + on platforms that enable it by default (e.g. Linux). + This parameter can be used in conjunction with :func:`has_dualstack_ipv6`: + + :: + + import socket + + addr = ("", 8080) # all interfaces, port 8080 + if socket.has_dualstack_ipv6(): + s = socket.create_server(addr, family=socket.AF_INET6, dualstack_ipv6=True) + else: + s = socket.create_server(addr) + + .. note:: + On POSIX platforms the :data:`SO_REUSEADDR` socket option is set in order to + immediately reuse previous sockets which were bound on the same *address* + and remained in TIME_WAIT state. + + .. versionadded:: 3.8 + +.. function:: has_dualstack_ipv6() + + Return ``True`` if the platform supports creating a TCP socket which can + handle both IPv4 and IPv6 connections. + + .. versionadded:: 3.8 + +.. function:: fromfd(fd, family, type, proto=0) + + Duplicate the file descriptor *fd* (an integer as returned by a file object's + :meth:`fileno` method) and build a socket object from the result. Address + family, socket type and protocol number are as for the :func:`.socket` function + above. The file descriptor should refer to a socket, but this is not checked --- + subsequent operations on the object may fail if the file descriptor is invalid. + This function is rarely needed, but can be used to get or set socket options on + a socket passed to a program as standard input or output (such as a server + started by the Unix inet daemon). The socket is assumed to be in blocking mode. + + The newly created socket is :ref:`non-inheritable `. + + .. versionchanged:: 3.4 + The returned socket is now non-inheritable. + + +.. function:: fromshare(data) + + Instantiate a socket from data obtained from the :meth:`socket.share` + method. The socket is assumed to be in blocking mode. + + .. availability:: Windows. + + .. versionadded:: 3.3 + + +.. data:: SocketType + + This is a Python type object that represents the socket object type. It is the + same as ``type(socket(...))``. + + +Other functions +''''''''''''''' + +The :mod:`socket` module also offers various network-related services: + + +.. function:: close(fd) + + Close a socket file descriptor. This is like :func:`os.close`, but for + sockets. On some platforms (most noticeable Windows) :func:`os.close` + does not work for socket file descriptors. + + .. versionadded:: 3.7 + +.. function:: getaddrinfo(host, port, family=0, type=0, proto=0, flags=0) + + Translate the *host*/*port* argument into a sequence of 5-tuples that contain + all the necessary arguments for creating a socket connected to that service. + *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``. By passing ``None`` as the value of *host* + and *port*, you can pass ``NULL`` to the underlying C API. + + The *family*, *type* and *proto* arguments can be optionally specified + in order to narrow the list of addresses returned. Passing zero as a + value for each of these arguments selects the full range of results. + The *flags* argument can be one or several of the ``AI_*`` constants, + and will influence how results are computed and returned. + For example, :const:`AI_NUMERICHOST` will disable domain name resolution + and will raise an error if *host* is a domain name. + + The function returns a list of 5-tuples with the following structure: + + ``(family, type, proto, canonname, sockaddr)`` + + In these tuples, *family*, *type*, *proto* are all integers and are + meant to be passed to the :func:`.socket` function. *canonname* will be + a string representing the canonical name of the *host* if + :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname* + will be empty. *sockaddr* is a tuple describing a socket address, whose + format depends on the returned *family* (a ``(address, port)`` 2-tuple for + :const:`AF_INET`, a ``(address, port, flowinfo, scope_id)`` 4-tuple for + :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect` + method. + + .. audit-event:: socket.getaddrinfo host,port,family,type,protocol socket.getaddrinfo + + The following example fetches address information for a hypothetical TCP + connection to ``example.org`` on port 80 (results may differ on your + system if IPv6 isn't enabled):: + + >>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP) + [(, , + 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)), + (, , + 6, '', ('93.184.216.34', 80))] + + .. versionchanged:: 3.2 + parameters can now be passed using keyword arguments. + + .. versionchanged:: 3.7 + for IPv6 multicast addresses, string representing an address will not + contain ``%scope_id`` part. + +.. function:: getfqdn([name]) + + Return a fully qualified domain name for *name*. If *name* is omitted or empty, + it is interpreted as the local host. To find the fully qualified name, the + hostname returned by :func:`gethostbyaddr` is checked, followed by aliases for the + host, if available. The first name which includes a period is selected. In + case no fully qualified domain name is available, the hostname as returned by + :func:`gethostname` is returned. + + +.. function:: gethostbyname(hostname) + + Translate a host name to IPv4 address format. The IPv4 address is returned as a + string, such as ``'100.50.200.5'``. If the host name is an IPv4 address itself + it is returned unchanged. See :func:`gethostbyname_ex` for a more complete + interface. :func:`gethostbyname` does not support IPv6 name resolution, and + :func:`getaddrinfo` should be used instead for IPv4/v6 dual stack support. + + .. audit-event:: socket.gethostbyname hostname socket.gethostbyname + + +.. function:: gethostbyname_ex(hostname) + + Translate a host name to IPv4 address format, extended interface. Return a + triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the primary + host name responding to the given *ip_address*, *aliaslist* is a (possibly + empty) list of alternative host names for the same address, and *ipaddrlist* is + a list of IPv4 addresses for the same interface on the same host (often but not + always a single address). :func:`gethostbyname_ex` does not support IPv6 name + resolution, and :func:`getaddrinfo` should be used instead for IPv4/v6 dual + stack support. + + .. audit-event:: socket.gethostbyname hostname socket.gethostbyname_ex + + +.. function:: gethostname() + + Return a string containing the hostname of the machine where the Python + interpreter is currently executing. + + .. audit-event:: socket.gethostname "" socket.gethostname + + Note: :func:`gethostname` doesn't always return the fully qualified domain + name; use :func:`getfqdn` for that. + + +.. function:: gethostbyaddr(ip_address) + + Return a triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the + primary host name responding to the given *ip_address*, *aliaslist* is a + (possibly empty) list of alternative host names for the same address, and + *ipaddrlist* is a list of IPv4/v6 addresses for the same interface on the same + host (most likely containing only a single address). To find the fully qualified + domain name, use the function :func:`getfqdn`. :func:`gethostbyaddr` supports + both IPv4 and IPv6. + + .. audit-event:: socket.gethostbyaddr ip_address socket.gethostbyaddr + + +.. function:: getnameinfo(sockaddr, flags) + + Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending + on the settings of *flags*, the result can contain a fully-qualified domain name + or numeric address representation in *host*. Similarly, *port* can contain a + string port name or a numeric port number. + + For IPv6 addresses, ``%scope_id`` is appended to the host part if *sockaddr* + contains meaningful *scope_id*. Usually this happens for multicast addresses. + + For more information about *flags* you can consult :manpage:`getnameinfo(3)`. + + .. audit-event:: socket.getnameinfo sockaddr socket.getnameinfo + +.. function:: getprotobyname(protocolname) + + Translate an Internet protocol name (for example, ``'icmp'``) to a constant + suitable for passing as the (optional) third argument to the :func:`.socket` + function. This is usually only needed for sockets opened in "raw" mode + (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen + automatically if the protocol is omitted or zero. + + +.. function:: getservbyname(servicename[, protocolname]) + + Translate an Internet service name and protocol name to a port number for that + service. The optional protocol name, if given, should be ``'tcp'`` or + ``'udp'``, otherwise any protocol will match. + + .. audit-event:: socket.getservbyname servicename,protocolname socket.getservbyname + + +.. function:: getservbyport(port[, protocolname]) + + Translate an Internet port number and protocol name to a service name for that + service. The optional protocol name, if given, should be ``'tcp'`` or + ``'udp'``, otherwise any protocol will match. + + .. audit-event:: socket.getservbyport port,protocolname socket.getservbyport + + +.. function:: ntohl(x) + + Convert 32-bit positive integers from network to host byte order. On machines + where the host byte order is the same as network byte order, this is a no-op; + otherwise, it performs a 4-byte swap operation. + + +.. function:: ntohs(x) + + Convert 16-bit positive integers from network to host byte order. On machines + where the host byte order is the same as network byte order, this is a no-op; + otherwise, it performs a 2-byte swap operation. + + .. deprecated:: 3.7 + In case *x* does not fit in 16-bit unsigned integer, but does fit in a + positive C int, it is silently truncated to 16-bit unsigned integer. + This silent truncation feature is deprecated, and will raise an + exception in future versions of Python. + + +.. function:: htonl(x) + + Convert 32-bit positive integers from host to network byte order. On machines + where the host byte order is the same as network byte order, this is a no-op; + otherwise, it performs a 4-byte swap operation. + + +.. function:: htons(x) + + Convert 16-bit positive integers from host to network byte order. On machines + where the host byte order is the same as network byte order, this is a no-op; + otherwise, it performs a 2-byte swap operation. + + .. deprecated:: 3.7 + In case *x* does not fit in 16-bit unsigned integer, but does fit in a + positive C int, it is silently truncated to 16-bit unsigned integer. + This silent truncation feature is deprecated, and will raise an + exception in future versions of Python. + + +.. function:: inet_aton(ip_string) + + Convert an IPv4 address from dotted-quad string format (for example, + '123.45.67.89') to 32-bit packed binary format, as a bytes object four characters in + length. This is useful when conversing with a program that uses the standard C + library and needs objects of type :c:type:`struct in_addr`, which is the C type + for the 32-bit packed binary this function returns. + + :func:`inet_aton` also accepts strings with less than three dots; see the + Unix manual page :manpage:`inet(3)` for details. + + If the IPv4 address string passed to this function is invalid, + :exc:`OSError` will be raised. Note that exactly what is valid depends on + the underlying C implementation of :c:func:`inet_aton`. + + :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used + instead for IPv4/v6 dual stack support. + + +.. function:: inet_ntoa(packed_ip) + + Convert a 32-bit packed IPv4 address (a :term:`bytes-like object` four + bytes in length) to its standard dotted-quad string representation (for example, + '123.45.67.89'). This is useful when conversing with a program that uses the + standard C library and needs objects of type :c:type:`struct in_addr`, which + is the C type for the 32-bit packed binary data this function takes as an + argument. + + If the byte sequence passed to this function is not exactly 4 bytes in + length, :exc:`OSError` will be raised. :func:`inet_ntoa` does not + support IPv6, and :func:`inet_ntop` should be used instead for IPv4/v6 dual + stack support. + + .. versionchanged:: 3.5 + Writable :term:`bytes-like object` is now accepted. + + +.. function:: inet_pton(address_family, ip_string) + + Convert an IP address from its family-specific string format to a packed, + binary format. :func:`inet_pton` is useful when a library or network protocol + calls for an object of type :c:type:`struct in_addr` (similar to + :func:`inet_aton`) or :c:type:`struct in6_addr`. + + Supported values for *address_family* are currently :const:`AF_INET` and + :const:`AF_INET6`. If the IP address string *ip_string* is invalid, + :exc:`OSError` will be raised. Note that exactly what is valid depends on + both the value of *address_family* and the underlying implementation of + :c:func:`inet_pton`. + + .. availability:: Unix (maybe not all platforms), Windows. + + .. versionchanged:: 3.4 + Windows support added + + +.. function:: inet_ntop(address_family, packed_ip) + + Convert a packed IP address (a :term:`bytes-like object` of some number of + bytes) to its standard, family-specific string representation (for + example, ``'7.10.0.5'`` or ``'5aef:2b::8'``). + :func:`inet_ntop` is useful when a library or network protocol returns an + object of type :c:type:`struct in_addr` (similar to :func:`inet_ntoa`) or + :c:type:`struct in6_addr`. + + Supported values for *address_family* are currently :const:`AF_INET` and + :const:`AF_INET6`. If the bytes object *packed_ip* is not the correct + length for the specified address family, :exc:`ValueError` will be raised. + :exc:`OSError` is raised for errors from the call to :func:`inet_ntop`. + + .. availability:: Unix (maybe not all platforms), Windows. + + .. versionchanged:: 3.4 + Windows support added + + .. versionchanged:: 3.5 + Writable :term:`bytes-like object` is now accepted. + + +.. + XXX: Are sendmsg(), recvmsg() and CMSG_*() available on any + non-Unix platforms? The old (obsolete?) 4.2BSD form of the + interface, in which struct msghdr has no msg_control or + msg_controllen members, is not currently supported. + +.. function:: CMSG_LEN(length) + + Return the total length, without trailing padding, of an ancillary + data item with associated data of the given *length*. This value + can often be used as the buffer size for :meth:`~socket.recvmsg` to + receive a single item of ancillary data, but :rfc:`3542` requires + portable applications to use :func:`CMSG_SPACE` and thus include + space for padding, even when the item will be the last in the + buffer. Raises :exc:`OverflowError` if *length* is outside the + permissible range of values. + + .. availability:: most Unix platforms, possibly others. + + .. versionadded:: 3.3 + + +.. function:: CMSG_SPACE(length) + + Return the buffer size needed for :meth:`~socket.recvmsg` to + receive an ancillary data item with associated data of the given + *length*, along with any trailing padding. The buffer space needed + to receive multiple items is the sum of the :func:`CMSG_SPACE` + values for their associated data lengths. Raises + :exc:`OverflowError` if *length* is outside the permissible range + of values. + + Note that some systems might support ancillary data without + providing this function. Also note that setting the buffer size + using the results of this function may not precisely limit the + amount of ancillary data that can be received, since additional + data may be able to fit into the padding area. + + .. availability:: most Unix platforms, possibly others. + + .. versionadded:: 3.3 + + +.. function:: getdefaulttimeout() + + Return the default timeout in seconds (float) for new socket objects. A value + of ``None`` indicates that new socket objects have no timeout. When the socket + module is first imported, the default is ``None``. + + +.. function:: setdefaulttimeout(timeout) + + Set the default timeout in seconds (float) for new socket objects. When + the socket module is first imported, the default is ``None``. See + :meth:`~socket.settimeout` for possible values and their respective + meanings. + + +.. function:: sethostname(name) + + Set the machine's hostname to *name*. This will raise an + :exc:`OSError` if you don't have enough rights. + + .. audit-event:: socket.sethostname name socket.sethostname + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: if_nameindex() + + Return a list of network interface information + (index int, name string) tuples. + :exc:`OSError` if the system call fails. + + .. availability:: Unix, Windows. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.8 + Windows support was added. + + +.. function:: if_nametoindex(if_name) + + Return a network interface index number corresponding to an + interface name. + :exc:`OSError` if no interface with the given name exists. + + .. availability:: Unix, Windows. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.8 + Windows support was added. + + +.. function:: if_indextoname(if_index) + + Return a network interface name corresponding to an + interface index number. + :exc:`OSError` if no interface with the given index exists. + + .. availability:: Unix, Windows. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.8 + Windows support was added. + + +.. _socket-objects: + +Socket Objects +-------------- + +Socket objects have the following methods. Except for +:meth:`~socket.makefile`, these correspond to Unix system calls applicable +to sockets. + +.. versionchanged:: 3.2 + Support for the :term:`context manager` protocol was added. Exiting the + context manager is equivalent to calling :meth:`~socket.close`. + + +.. method:: socket.accept() + + Accept a connection. The socket must be bound to an address and listening for + connections. The return value is a pair ``(conn, address)`` where *conn* is a + *new* socket object usable to send and receive data on the connection, and + *address* is the address bound to the socket on the other end of the connection. + + The newly created socket is :ref:`non-inheritable `. + + .. versionchanged:: 3.4 + The socket is now non-inheritable. + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise + an exception, the method now retries the system call instead of raising + an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + +.. method:: socket.bind(address) + + Bind the socket to *address*. The socket must not already be bound. (The format + of *address* depends on the address family --- see above.) + + .. audit-event:: socket.bind self,address socket.socket.bind + +.. method:: socket.close() + + Mark the socket closed. The underlying system resource (e.g. a file + descriptor) is also closed when all file objects from :meth:`makefile()` + are closed. Once that happens, all future operations on the socket + object will fail. The remote end will receive no more data (after + queued data is flushed). + + Sockets are automatically closed when they are garbage-collected, but + it is recommended to :meth:`close` them explicitly, or to use a + :keyword:`with` statement around them. + + .. versionchanged:: 3.6 + :exc:`OSError` is now raised if an error occurs when the underlying + :c:func:`close` call is made. + + .. note:: + + :meth:`close()` releases the resource associated with a connection but + does not necessarily close the connection immediately. If you want + to close the connection in a timely fashion, call :meth:`shutdown()` + before :meth:`close()`. + + +.. method:: socket.connect(address) + + Connect to a remote socket at *address*. (The format of *address* depends on the + address family --- see above.) + + If the connection is interrupted by a signal, the method waits until the + connection completes, or raise a :exc:`socket.timeout` on timeout, if the + signal handler doesn't raise an exception and the socket is blocking or has + a timeout. For non-blocking sockets, the method raises an + :exc:`InterruptedError` exception if the connection is interrupted by a + signal (or the exception raised by the signal handler). + + .. audit-event:: socket.connect self,address socket.socket.connect + + .. versionchanged:: 3.5 + The method now waits until the connection completes instead of raising an + :exc:`InterruptedError` exception if the connection is interrupted by a + signal, the signal handler doesn't raise an exception and the socket is + blocking or has a timeout (see the :pep:`475` for the rationale). + + +.. method:: socket.connect_ex(address) + + Like ``connect(address)``, but return an error indicator instead of raising an + exception for errors returned by the C-level :c:func:`connect` call (other + problems, such as "host not found," can still raise exceptions). The error + indicator is ``0`` if the operation succeeded, otherwise the value of the + :c:data:`errno` variable. This is useful to support, for example, asynchronous + connects. + + .. audit-event:: socket.connect self,address socket.socket.connect_ex + +.. method:: socket.detach() + + Put the socket object into closed state without actually closing the + underlying file descriptor. The file descriptor is returned, and can + be reused for other purposes. + + .. versionadded:: 3.2 + + +.. method:: socket.dup() + + Duplicate the socket. + + The newly created socket is :ref:`non-inheritable `. + + .. versionchanged:: 3.4 + The socket is now non-inheritable. + + +.. method:: socket.fileno() + + Return the socket's file descriptor (a small integer), or -1 on failure. This + is useful with :func:`select.select`. + + Under Windows the small integer returned by this method cannot be used where a + file descriptor can be used (such as :func:`os.fdopen`). Unix does not have + this limitation. + +.. method:: socket.get_inheritable() + + Get the :ref:`inheritable flag ` of the socket's file + descriptor or socket's handle: ``True`` if the socket can be inherited in + child processes, ``False`` if it cannot. + + .. versionadded:: 3.4 + + +.. method:: socket.getpeername() + + Return the remote address to which the socket is connected. This is useful to + find out the port number of a remote IPv4/v6 socket, for instance. (The format + of the address returned depends on the address family --- see above.) On some + systems this function is not supported. + + +.. method:: socket.getsockname() + + Return the socket's own address. This is useful to find out the port number of + an IPv4/v6 socket, for instance. (The format of the address returned depends on + the address family --- see above.) + + +.. method:: socket.getsockopt(level, optname[, buflen]) + + Return the value of the given socket option (see the Unix man page + :manpage:`getsockopt(2)`). The needed symbolic constants (:const:`SO_\*` etc.) + are defined in this module. If *buflen* is absent, an integer option is assumed + and its integer value is returned by the function. If *buflen* is present, it + specifies the maximum length of the buffer used to receive the option in, and + this buffer is returned as a bytes object. It is up to the caller to decode the + 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.getblocking() + + Return ``True`` if socket is in blocking mode, ``False`` if in + non-blocking. + + This is equivalent to checking ``socket.gettimeout() == 0``. + + .. versionadded:: 3.7 + + +.. method:: socket.gettimeout() + + Return the timeout in seconds (float) associated with socket operations, + or ``None`` if no timeout is set. This reflects the last call to + :meth:`setblocking` or :meth:`settimeout`. + + +.. method:: socket.ioctl(control, option) + + :platform: Windows + + The :meth:`ioctl` method is a limited interface to the WSAIoctl system + interface. Please refer to the `Win32 documentation + `_ for more + information. + + On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl` + functions may be used; they accept a socket object as their first argument. + + Currently only the following control codes are supported: + ``SIO_RCVALL``, ``SIO_KEEPALIVE_VALS``, and ``SIO_LOOPBACK_FAST_PATH``. + + .. versionchanged:: 3.6 + ``SIO_LOOPBACK_FAST_PATH`` was added. + +.. method:: socket.listen([backlog]) + + Enable a server to accept connections. If *backlog* is specified, it must + be at least 0 (if it is lower, it is set to 0); it specifies the number of + unaccepted connections that the system will allow before refusing new + connections. If not specified, a default reasonable value is chosen. + + .. versionchanged:: 3.5 + The *backlog* parameter is now optional. + +.. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, \ + errors=None, newline=None) + + .. index:: single: I/O control; buffering + + Return a :term:`file object` associated with the socket. The exact returned + type depends on the arguments given to :meth:`makefile`. These arguments are + interpreted the same way as by the built-in :func:`open` function, except + the only supported *mode* values are ``'r'`` (default), ``'w'`` and ``'b'``. + + The socket must be in blocking mode; it can have a timeout, but the file + object's internal buffer may end up in an inconsistent state if a timeout + occurs. + + Closing the file object returned by :meth:`makefile` won't close the + original socket unless all other file objects have been closed and + :meth:`socket.close` has been called on the socket object. + + .. note:: + + On Windows, the file-like object created by :meth:`makefile` cannot be + used where a file object with a file descriptor is expected, such as the + stream arguments of :meth:`subprocess.Popen`. + + +.. method:: socket.recv(bufsize[, flags]) + + Receive data from the socket. The return value is a bytes object representing the + data received. The maximum amount of data to be received at once is specified + by *bufsize*. See the Unix manual page :manpage:`recv(2)` for the meaning of + the optional argument *flags*; it defaults to zero. + + .. note:: + + For best match with hardware and network realities, the value of *bufsize* + should be a relatively small power of 2, for example, 4096. + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise + an exception, the method now retries the system call instead of raising + an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + +.. method:: socket.recvfrom(bufsize[, flags]) + + Receive data from the socket. The return value is a pair ``(bytes, address)`` + where *bytes* is a bytes object representing the data received and *address* is the + address of the socket sending the data. See the Unix manual page + :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults + to zero. (The format of *address* depends on the address family --- see above.) + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise + an exception, the method now retries the system call instead of raising + an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + .. versionchanged:: 3.7 + For multicast IPv6 address, first item of *address* does not contain + ``%scope_id`` part anymore. In order to get full IPv6 address use + :func:`getnameinfo`. + +.. method:: socket.recvmsg(bufsize[, ancbufsize[, flags]]) + + Receive normal data (up to *bufsize* bytes) and ancillary data from + the socket. The *ancbufsize* argument sets the size in bytes of + the internal buffer used to receive the ancillary data; it defaults + to 0, meaning that no ancillary data will be received. Appropriate + buffer sizes for ancillary data can be calculated using + :func:`CMSG_SPACE` or :func:`CMSG_LEN`, and items which do not fit + into the buffer might be truncated or discarded. The *flags* + argument defaults to 0 and has the same meaning as for + :meth:`recv`. + + The return value is a 4-tuple: ``(data, ancdata, msg_flags, + address)``. The *data* item is a :class:`bytes` object holding the + non-ancillary data received. The *ancdata* item is a list of zero + or more tuples ``(cmsg_level, cmsg_type, cmsg_data)`` representing + the ancillary data (control messages) received: *cmsg_level* and + *cmsg_type* are integers specifying the protocol level and + protocol-specific type respectively, and *cmsg_data* is a + :class:`bytes` object holding the associated data. The *msg_flags* + item is the bitwise OR of various flags indicating conditions on + the received message; see your system documentation for details. + If the receiving socket is unconnected, *address* is the address of + the sending socket, if available; otherwise, its value is + unspecified. + + On some systems, :meth:`sendmsg` and :meth:`recvmsg` can be used to + pass file descriptors between processes over an :const:`AF_UNIX` + socket. When this facility is used (it is often restricted to + :const:`SOCK_STREAM` sockets), :meth:`recvmsg` will return, in its + ancillary data, items of the form ``(socket.SOL_SOCKET, + socket.SCM_RIGHTS, fds)``, where *fds* is a :class:`bytes` object + representing the new file descriptors as a binary array of the + native C :c:type:`int` type. If :meth:`recvmsg` raises an + exception after the system call returns, it will first attempt to + close any file descriptors received via this mechanism. + + Some systems do not indicate the truncated length of ancillary data + items which have been only partially received. If an item appears + to extend beyond the end of the buffer, :meth:`recvmsg` will issue + a :exc:`RuntimeWarning`, and will return the part of it which is + inside the buffer provided it has not been truncated before the + start of its associated data. + + On systems which support the :const:`SCM_RIGHTS` mechanism, the + following function will receive up to *maxfds* file descriptors, + returning the message data and a list containing the descriptors + (while ignoring unexpected conditions such as unrelated control + messages being received). See also :meth:`sendmsg`. :: + + import socket, array + + def recv_fds(sock, msglen, maxfds): + fds = array.array("i") # Array of ints + msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize)) + for cmsg_level, cmsg_type, cmsg_data in ancdata: + if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS: + # Append data, ignoring any truncated integers at the end. + fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) + return msg, list(fds) + + .. availability:: most Unix platforms, possibly others. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise + an exception, the method now retries the system call instead of raising + an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + +.. method:: socket.recvmsg_into(buffers[, ancbufsize[, flags]]) + + Receive normal data and ancillary data from the socket, behaving as + :meth:`recvmsg` would, but scatter the non-ancillary data into a + series of buffers instead of returning a new bytes object. The + *buffers* argument must be an iterable of objects that export + writable buffers (e.g. :class:`bytearray` objects); these will be + filled with successive chunks of the non-ancillary data until it + has all been written or there are no more buffers. The operating + system may set a limit (:func:`~os.sysconf` value ``SC_IOV_MAX``) + on the number of buffers that can be used. The *ancbufsize* and + *flags* arguments have the same meaning as for :meth:`recvmsg`. + + The return value is a 4-tuple: ``(nbytes, ancdata, msg_flags, + address)``, where *nbytes* is the total number of bytes of + non-ancillary data written into the buffers, and *ancdata*, + *msg_flags* and *address* are the same as for :meth:`recvmsg`. + + Example:: + + >>> import socket + >>> s1, s2 = socket.socketpair() + >>> b1 = bytearray(b'----') + >>> b2 = bytearray(b'0123456789') + >>> b3 = bytearray(b'--------------') + >>> s1.send(b'Mary had a little lamb') + 22 + >>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3]) + (22, [], 0, None) + >>> [b1, b2, b3] + [bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')] + + .. availability:: most Unix platforms, possibly others. + + .. versionadded:: 3.3 + + +.. method:: socket.recvfrom_into(buffer[, nbytes[, flags]]) + + Receive data from the socket, writing it into *buffer* instead of creating a + new bytestring. The return value is a pair ``(nbytes, address)`` where *nbytes* is + the number of bytes received and *address* is the address of the socket sending + the data. See the Unix manual page :manpage:`recv(2)` for the meaning of the + optional argument *flags*; it defaults to zero. (The format of *address* + depends on the address family --- see above.) + + +.. method:: socket.recv_into(buffer[, nbytes[, flags]]) + + Receive up to *nbytes* bytes from the socket, storing the data into a buffer + rather than creating a new bytestring. If *nbytes* is not specified (or 0), + receive up to the size available in the given buffer. Returns the number of + bytes received. See the Unix manual page :manpage:`recv(2)` for the meaning + of the optional argument *flags*; it defaults to zero. + + +.. method:: socket.send(bytes[, flags]) + + Send data to the socket. The socket must be connected to a remote socket. The + optional *flags* argument has the same meaning as for :meth:`recv` above. + Returns the number of bytes sent. Applications are responsible for checking that + all data has been sent; if only some of the data was transmitted, the + application needs to attempt delivery of the remaining data. For further + information on this topic, consult the :ref:`socket-howto`. + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise + an exception, the method now retries the system call instead of raising + an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + +.. method:: socket.sendall(bytes[, flags]) + + Send data to the socket. The socket must be connected to a remote socket. The + optional *flags* argument has the same meaning as for :meth:`recv` above. + Unlike :meth:`send`, this method continues to send data from *bytes* until + either all data has been sent or an error occurs. ``None`` is returned on + success. On error, an exception is raised, and there is no way to determine how + much data, if any, was successfully sent. + + .. versionchanged:: 3.5 + The socket timeout is no more reset each time data is sent successfully. + The socket timeout is now the maximum total duration to send all data. + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise + an exception, the method now retries the system call instead of raising + an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + +.. method:: socket.sendto(bytes, address) + socket.sendto(bytes, flags, address) + + Send data to the socket. The socket should not be connected to a remote socket, + since the destination socket is specified by *address*. The optional *flags* + argument has the same meaning as for :meth:`recv` above. Return the number of + bytes sent. (The format of *address* depends on the address family --- see + above.) + + .. audit-event:: socket.sendto self,address socket.socket.sendto + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise + an exception, the method now retries the system call instead of raising + an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + + +.. method:: socket.sendmsg(buffers[, ancdata[, flags[, address]]]) + + Send normal and ancillary data to the socket, gathering the + non-ancillary data from a series of buffers and concatenating it + into a single message. The *buffers* argument specifies the + non-ancillary data as an iterable of + :term:`bytes-like objects ` + (e.g. :class:`bytes` objects); the operating system may set a limit + (:func:`~os.sysconf` value ``SC_IOV_MAX``) on the number of buffers + that can be used. The *ancdata* argument specifies the ancillary + data (control messages) as an iterable of zero or more tuples + ``(cmsg_level, cmsg_type, cmsg_data)``, where *cmsg_level* and + *cmsg_type* are integers specifying the protocol level and + protocol-specific type respectively, and *cmsg_data* is a + bytes-like object holding the associated data. Note that + some systems (in particular, systems without :func:`CMSG_SPACE`) + might support sending only one control message per call. The + *flags* argument defaults to 0 and has the same meaning as for + :meth:`send`. If *address* is supplied and not ``None``, it sets a + destination address for the message. The return value is the + number of bytes of non-ancillary data sent. + + The following function sends the list of file descriptors *fds* + over an :const:`AF_UNIX` socket, on systems which support the + :const:`SCM_RIGHTS` mechanism. See also :meth:`recvmsg`. :: + + import socket, array + + def send_fds(sock, msg, fds): + return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))]) + + .. availability:: most Unix platforms, possibly others. + + .. audit-event:: socket.sendmsg self,address socket.socket.sendmsg + + .. versionadded:: 3.3 + + .. versionchanged:: 3.5 + If the system call is interrupted and the signal handler does not raise + an exception, the method now retries the system call instead of raising + an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). + +.. method:: socket.sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags]]]) + + Specialized version of :meth:`~socket.sendmsg` for :const:`AF_ALG` socket. + Set mode, IV, AEAD associated data length and flags for :const:`AF_ALG` socket. + + .. availability:: Linux >= 2.6.38. + + .. versionadded:: 3.6 + +.. method:: socket.send_fds(sock, buffers, fds[, flags[, address]]) + + Send the list of file descriptors *fds* over an :const:`AF_UNIX` socket. + The *fds* parameter is a sequence of file descriptors. + Consult :meth:`sendmsg` for the documentation of these parameters. + + .. availability:: Unix supporting :meth:`~socket.sendmsg` and :const:`SCM_RIGHTS` mechanism. + + .. versionadded:: 3.9 + +.. method:: socket.recv_fds(sock, bufsize, maxfds[, flags]) + + Receive up to *maxfds* file descriptors. Return ``(msg, list(fds), flags, addr)``. Consult + :meth:`recvmsg` for the documentation of these parameters. + + .. availability:: Unix supporting :meth:`~socket.recvmsg` and :const:`SCM_RIGHTS` mechanism. + + .. versionadded:: 3.9 + + .. note:: + + Any truncated integers at the end of the list of file descriptors. + +.. method:: socket.sendfile(file, offset=0, count=None) + + Send a file until EOF is reached by using high-performance + :mod:`os.sendfile` and return the total number of bytes which were sent. + *file* must be a regular file object opened in binary mode. If + :mod:`os.sendfile` is not available (e.g. Windows) or *file* is not a + regular file :meth:`send` will be used instead. *offset* tells from where to + start reading the file. If specified, *count* is the total number of bytes + to transmit as opposed to sending the file until EOF is reached. File + position is updated on return or also in case of error in which case + :meth:`file.tell() ` can be used to figure out the number of + bytes which were sent. The socket must be of :const:`SOCK_STREAM` type. + Non-blocking sockets are not supported. + + .. versionadded:: 3.5 + +.. method:: socket.set_inheritable(inheritable) + + Set the :ref:`inheritable flag ` of the socket's file + descriptor or socket's handle. + + .. versionadded:: 3.4 + + +.. method:: socket.setblocking(flag) + + Set blocking or non-blocking mode of the socket: if *flag* is false, the + socket is set to non-blocking, else to blocking mode. + + This method is a shorthand for certain :meth:`~socket.settimeout` calls: + + * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)`` + + * ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0.0)`` + + .. versionchanged:: 3.7 + The method no longer applies :const:`SOCK_NONBLOCK` flag on + :attr:`socket.type`. + + +.. method:: socket.settimeout(value) + + Set a timeout on blocking socket operations. The *value* argument can be a + nonnegative floating point number expressing seconds, or ``None``. + If a non-zero value is given, subsequent socket operations will raise a + :exc:`timeout` exception if the timeout period *value* has elapsed before + the operation has completed. If zero is given, the socket is put in + non-blocking mode. If ``None`` is given, the socket is put in blocking mode. + + For further information, please consult the :ref:`notes on socket timeouts `. + + .. versionchanged:: 3.7 + The method no longer toggles :const:`SOCK_NONBLOCK` flag on + :attr:`socket.type`. + + +.. method:: socket.setsockopt(level, optname, value: int) +.. method:: socket.setsockopt(level, optname, value: buffer) +.. method:: socket.setsockopt(level, optname, None, optlen: int) + + .. index:: module: struct + + Set the value of the given socket option (see the Unix manual page + :manpage:`setsockopt(2)`). The needed symbolic constants are defined in the + :mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer, + ``None`` or a :term:`bytes-like object` representing a buffer. In the later + case it is up to the caller to ensure that the bytestring contains the + proper bits (see the optional built-in module :mod:`struct` for a way to + encode C structures as bytestrings). When *value* is set to ``None``, + *optlen* argument is required. It's equivalent to call :c:func:`setsockopt` C + function with ``optval=NULL`` and ``optlen=optlen``. + + + .. versionchanged:: 3.5 + Writable :term:`bytes-like object` is now accepted. + + .. versionchanged:: 3.6 + setsockopt(level, optname, None, optlen: int) form added. + + +.. method:: socket.shutdown(how) + + Shut down one or both halves of the connection. If *how* is :const:`SHUT_RD`, + further receives are disallowed. If *how* is :const:`SHUT_WR`, further sends + are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives are + disallowed. + + +.. method:: socket.share(process_id) + + Duplicate a socket and prepare it for sharing with a target process. The + target process must be provided with *process_id*. The resulting bytes object + can then be passed to the target process using some form of interprocess + communication and the socket can be recreated there using :func:`fromshare`. + Once this method has been called, it is safe to close the socket since + the operating system has already duplicated it for the target process. + + .. availability:: Windows. + + .. versionadded:: 3.3 + + +Note that there are no methods :meth:`read` or :meth:`write`; use +:meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead. + +Socket objects also have these (read-only) attributes that correspond to the +values given to the :class:`~socket.socket` constructor. + + +.. attribute:: socket.family + + The socket family. + + +.. attribute:: socket.type + + The socket type. + + +.. attribute:: socket.proto + + The socket protocol. + + + +.. _socket-timeouts: + +Notes on socket timeouts +------------------------ + +A socket object can be in one of three modes: blocking, non-blocking, or +timeout. Sockets are by default always created in blocking mode, but this +can be changed by calling :func:`setdefaulttimeout`. + +* In *blocking mode*, operations block until complete or the system returns + an error (such as connection timed out). + +* In *non-blocking mode*, operations fail (with an error that is unfortunately + system-dependent) if they cannot be completed immediately: functions from the + :mod:`select` can be used to know when and whether a socket is available for + reading or writing. + +* In *timeout mode*, operations fail if they cannot be completed within the + timeout specified for the socket (they raise a :exc:`timeout` exception) + or if the system returns an error. + +.. note:: + At the operating system level, sockets in *timeout mode* are internally set + in non-blocking mode. Also, the blocking and timeout modes are shared between + file descriptors and socket objects that refer to the same network endpoint. + This implementation detail can have visible consequences if e.g. you decide + to use the :meth:`~socket.fileno()` of a socket. + +Timeouts and the ``connect`` method +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The :meth:`~socket.connect` operation is also subject to the timeout +setting, and in general it is recommended to call :meth:`~socket.settimeout` +before calling :meth:`~socket.connect` or pass a timeout parameter to +:meth:`create_connection`. However, the system network stack may also +return a connection timeout error of its own regardless of any Python socket +timeout setting. + +Timeouts and the ``accept`` method +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If :func:`getdefaulttimeout` is not :const:`None`, sockets returned by +the :meth:`~socket.accept` method inherit that timeout. Otherwise, the +behaviour depends on settings of the listening socket: + +* if the listening socket is in *blocking mode* or in *timeout mode*, + the socket returned by :meth:`~socket.accept` is in *blocking mode*; + +* if the listening socket is in *non-blocking mode*, whether the socket + returned by :meth:`~socket.accept` is in blocking or non-blocking mode + is operating system-dependent. If you want to ensure cross-platform + behaviour, it is recommended you manually override this setting. + + +.. _socket-example: + +Example +------- + +Here are four minimal example programs using the TCP/IP protocol: a server that +echoes all data that it receives back (servicing only one client), and a client +using it. Note that a server must perform the sequence :func:`.socket`, +:meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly +repeating the :meth:`~socket.accept` to service more than one client), while a +client only needs the sequence :func:`.socket`, :meth:`~socket.connect`. Also +note that the server does not :meth:`~socket.sendall`/:meth:`~socket.recv` on +the socket it is listening on but on the new socket returned by +:meth:`~socket.accept`. + +The first two examples support IPv4 only. :: + + # Echo server program + import socket + + HOST = '' # Symbolic name meaning all available interfaces + PORT = 50007 # Arbitrary non-privileged port + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind((HOST, PORT)) + s.listen(1) + conn, addr = s.accept() + with conn: + print('Connected by', addr) + while True: + data = conn.recv(1024) + if not data: break + conn.sendall(data) + +:: + + # Echo client program + import socket + + HOST = 'daring.cwi.nl' # The remote host + PORT = 50007 # The same port as used by the server + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.connect((HOST, PORT)) + s.sendall(b'Hello, world') + data = s.recv(1024) + print('Received', repr(data)) + +The next two examples are identical to the above two, but support both IPv4 and +IPv6. The server side will listen to the first address family available (it +should listen to both instead). On most of IPv6-ready systems, IPv6 will take +precedence and the server may not accept IPv4 traffic. The client side will try +to connect to the all addresses returned as a result of the name resolution, and +sends traffic to the first one connected successfully. :: + + # Echo server program + import socket + import sys + + HOST = None # Symbolic name meaning all available interfaces + PORT = 50007 # Arbitrary non-privileged port + s = None + for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, + socket.SOCK_STREAM, 0, socket.AI_PASSIVE): + af, socktype, proto, canonname, sa = res + try: + s = socket.socket(af, socktype, proto) + except OSError as msg: + s = None + continue + try: + s.bind(sa) + s.listen(1) + except OSError as msg: + s.close() + s = None + continue + break + if s is None: + print('could not open socket') + sys.exit(1) + conn, addr = s.accept() + with conn: + print('Connected by', addr) + while True: + data = conn.recv(1024) + if not data: break + conn.send(data) + +:: + + # Echo client program + import socket + import sys + + HOST = 'daring.cwi.nl' # The remote host + PORT = 50007 # The same port as used by the server + s = None + for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): + af, socktype, proto, canonname, sa = res + try: + s = socket.socket(af, socktype, proto) + except OSError as msg: + s = None + continue + try: + s.connect(sa) + except OSError as msg: + s.close() + s = None + continue + break + if s is None: + print('could not open socket') + sys.exit(1) + with s: + s.sendall(b'Hello, world') + data = s.recv(1024) + print('Received', repr(data)) + +The next example shows how to write a very simple network sniffer with raw +sockets on Windows. The example requires administrator privileges to modify +the interface:: + + import socket + + # 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) + +The next example shows how to use the socket interface to communicate to a CAN +network using the raw socket protocol. To use CAN with the broadcast +manager protocol instead, open a socket with:: + + socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) + +After binding (:const:`CAN_RAW`) or connecting (:const:`CAN_BCM`) the socket, you +can use the :meth:`socket.send`, and the :meth:`socket.recv` operations (and +their counterparts) on the socket object as usual. + +This last example might require special privileges:: + + import socket + import struct + + + # CAN frame packing/unpacking (see 'struct can_frame' in ) + + can_frame_fmt = "=IB3x8s" + can_frame_size = struct.calcsize(can_frame_fmt) + + def build_can_frame(can_id, data): + can_dlc = len(data) + data = data.ljust(8, b'\x00') + return struct.pack(can_frame_fmt, can_id, can_dlc, data) + + def dissect_can_frame(frame): + can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame) + return (can_id, can_dlc, data[:can_dlc]) + + + # create a raw socket and bind it to the 'vcan0' interface + s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW) + s.bind(('vcan0',)) + + while True: + cf, addr = s.recvfrom(can_frame_size) + + print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf)) + + try: + s.send(cf) + except OSError: + print('Error sending CAN frame') + + try: + s.send(build_can_frame(0x01, b'\x01\x02\x03')) + except OSError: + print('Error sending CAN frame') + +Running an example several times with too small delay between executions, could +lead to this error:: + + OSError: [Errno 98] Address already in use + +This is because the previous execution has left the socket in a ``TIME_WAIT`` +state, and can't be immediately reused. + +There is a :mod:`socket` flag to set, in order to prevent this, +:data:`socket.SO_REUSEADDR`:: + + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind((HOST, PORT)) + +the :data:`SO_REUSEADDR` flag tells the kernel to reuse a local socket in +``TIME_WAIT`` state, without waiting for its natural timeout to expire. + + +.. seealso:: + + For an introduction to socket programming (in C), see the following papers: + + - *An Introductory 4.3BSD Interprocess Communication Tutorial*, by Stuart Sechrest + + - *An Advanced 4.3BSD Interprocess Communication Tutorial*, by Samuel J. Leffler et + al, + + both in the UNIX Programmer's Manual, Supplementary Documents 1 (sections + PS1:7 and PS1:8). The platform-specific reference material for the various + socket-related system calls are also a valuable source of information on the + details of socket semantics. For Unix, refer to the manual pages; for Windows, + see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may + want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv6. diff --git a/cpython_2/environment/repo/Doc/library/socketserver.rst b/cpython_2/environment/repo/Doc/library/socketserver.rst new file mode 100644 index 0000000000000000000000000000000000000000..232c0616d925dc00a6632a847b024a1127e0c8f7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/socketserver.rst @@ -0,0 +1,662 @@ +:mod:`socketserver` --- A framework for network servers +======================================================= + +.. module:: socketserver + :synopsis: A framework for network servers. + +**Source code:** :source:`Lib/socketserver.py` + +-------------- + +The :mod:`socketserver` module simplifies the task of writing network servers. + +There are four basic concrete server classes: + + +.. class:: TCPServer(server_address, RequestHandlerClass, bind_and_activate=True) + + This uses the Internet TCP protocol, which provides for + continuous streams of data between the client and server. + If *bind_and_activate* is true, the constructor automatically attempts to + invoke :meth:`~BaseServer.server_bind` and + :meth:`~BaseServer.server_activate`. The other parameters are passed to + the :class:`BaseServer` base class. + + +.. class:: UDPServer(server_address, RequestHandlerClass, bind_and_activate=True) + + This uses datagrams, which are discrete packets of information that may + arrive out of order or be lost while in transit. The parameters are + the same as for :class:`TCPServer`. + + +.. class:: UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True) + UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True) + + These more infrequently used classes are similar to the TCP and + UDP classes, but use Unix domain sockets; they're not available on + non-Unix platforms. The parameters are the same as for + :class:`TCPServer`. + + +These four classes process requests :dfn:`synchronously`; each request must be +completed before the next request can be started. This isn't suitable if each +request takes a long time to complete, because it requires a lot of computation, +or because it returns a lot of data which the client is slow to process. The +solution is to create a separate process or thread to handle each request; the +:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes can be used to +support asynchronous behaviour. + +Creating a server requires several steps. First, you must create a request +handler class by subclassing the :class:`BaseRequestHandler` class and +overriding its :meth:`~BaseRequestHandler.handle` method; +this method will process incoming +requests. Second, you must instantiate one of the server classes, passing it +the server's address and the request handler class. It is recommended to use +the server in a :keyword:`with` statement. Then call the +:meth:`~BaseServer.handle_request` or +:meth:`~BaseServer.serve_forever` method of the server object to +process one or many requests. Finally, call :meth:`~BaseServer.server_close` +to close the socket (unless you used a :keyword:`!with` statement). + +When inheriting from :class:`ThreadingMixIn` for threaded connection behavior, +you should explicitly declare how you want your threads to behave on an abrupt +shutdown. The :class:`ThreadingMixIn` class defines an attribute +*daemon_threads*, which indicates whether or not the server should wait for +thread termination. You should set the flag explicitly if you would like +threads to behave autonomously; the default is :const:`False`, meaning that +Python will not exit until all threads created by :class:`ThreadingMixIn` have +exited. + +Server classes have the same external methods and attributes, no matter what +network protocol they use. + + +Server Creation Notes +--------------------- + +There are five classes in an inheritance diagram, four of which represent +synchronous servers of four types:: + + +------------+ + | BaseServer | + +------------+ + | + v + +-----------+ +------------------+ + | TCPServer |------->| UnixStreamServer | + +-----------+ +------------------+ + | + v + +-----------+ +--------------------+ + | UDPServer |------->| UnixDatagramServer | + +-----------+ +--------------------+ + +Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from +:class:`UnixStreamServer` --- the only difference between an IP and a Unix +stream server is the address family, which is simply repeated in both Unix +server classes. + + +.. class:: ForkingMixIn + ThreadingMixIn + + Forking and threading versions of each type of server can be created + using these mix-in classes. For instance, :class:`ThreadingUDPServer` + is created as follows:: + + class ThreadingUDPServer(ThreadingMixIn, UDPServer): + pass + + The mix-in class comes first, since it overrides a method defined in + :class:`UDPServer`. Setting the various attributes also changes the + behavior of the underlying server mechanism. + + :class:`ForkingMixIn` and the Forking classes mentioned below are + only available on POSIX platforms that support :func:`~os.fork`. + + :meth:`socketserver.ForkingMixIn.server_close` waits until all child + processes complete, except if + :attr:`socketserver.ForkingMixIn.block_on_close` attribute is false. + + :meth:`socketserver.ThreadingMixIn.server_close` waits until all non-daemon + threads complete, except if + :attr:`socketserver.ThreadingMixIn.block_on_close` attribute is false. Use + daemonic threads by setting + :data:`ThreadingMixIn.daemon_threads` to ``True`` to not wait until threads + complete. + + .. versionchanged:: 3.7 + + :meth:`socketserver.ForkingMixIn.server_close` and + :meth:`socketserver.ThreadingMixIn.server_close` now waits until all + child processes and non-daemonic threads complete. + Add a new :attr:`socketserver.ForkingMixIn.block_on_close` class + attribute to opt-in for the pre-3.7 behaviour. + + +.. class:: ForkingTCPServer + ForkingUDPServer + ThreadingTCPServer + ThreadingUDPServer + + These classes are pre-defined using the mix-in classes. + + +To implement a service, you must derive a class from :class:`BaseRequestHandler` +and redefine its :meth:`~BaseRequestHandler.handle` method. +You can then run various versions of +the service by combining one of the server classes with your request handler +class. The request handler class must be different for datagram or stream +services. This can be hidden by using the handler subclasses +:class:`StreamRequestHandler` or :class:`DatagramRequestHandler`. + +Of course, you still have to use your head! For instance, it makes no sense to +use a forking server if the service contains state in memory that can be +modified by different requests, since the modifications in the child process +would never reach the initial state kept in the parent process and passed to +each child. In this case, you can use a threading server, but you will probably +have to use locks to protect the integrity of the shared data. + +On the other hand, if you are building an HTTP server where all data is stored +externally (for instance, in the file system), a synchronous class will +essentially render the service "deaf" while one request is being handled -- +which may be for a very long time if a client is slow to receive all the data it +has requested. Here a threading or forking server is appropriate. + +In some cases, it may be appropriate to process part of a request synchronously, +but to finish processing in a forked child depending on the request data. This +can be implemented by using a synchronous server and doing an explicit fork in +the request handler class :meth:`~BaseRequestHandler.handle` method. + +Another approach to handling multiple simultaneous requests in an environment +that supports neither threads nor :func:`~os.fork` (or where these are too +expensive or inappropriate for the service) is to maintain an explicit table of +partially finished requests and to use :mod:`selectors` to decide which +request to work on next (or whether to handle a new incoming request). This is +particularly important for stream services where each client can potentially be +connected for a long time (if threads or subprocesses cannot be used). See +:mod:`asyncore` for another way to manage this. + +.. XXX should data and methods be intermingled, or separate? + how should the distinction between class and instance variables be drawn? + + +Server Objects +-------------- + +.. class:: BaseServer(server_address, RequestHandlerClass) + + This is the superclass of all Server objects in the module. It defines the + interface, given below, but does not implement most of the methods, which is + done in subclasses. The two parameters are stored in the respective + :attr:`server_address` and :attr:`RequestHandlerClass` attributes. + + + .. method:: fileno() + + Return an integer file descriptor for the socket on which the server is + listening. This function is most commonly passed to :mod:`selectors`, to + allow monitoring multiple servers in the same process. + + + .. method:: handle_request() + + Process a single request. This function calls the following methods in + order: :meth:`get_request`, :meth:`verify_request`, and + :meth:`process_request`. If the user-provided + :meth:`~BaseRequestHandler.handle` method of the + handler class raises an exception, the server's :meth:`handle_error` method + will be called. If no request is received within :attr:`timeout` + seconds, :meth:`handle_timeout` will be called and :meth:`handle_request` + will return. + + + .. method:: serve_forever(poll_interval=0.5) + + Handle requests until an explicit :meth:`shutdown` request. Poll for + shutdown every *poll_interval* seconds. + Ignores the :attr:`timeout` attribute. It + also calls :meth:`service_actions`, which may be used by a subclass or mixin + to provide actions specific to a given service. For example, the + :class:`ForkingMixIn` class uses :meth:`service_actions` to clean up zombie + child processes. + + .. versionchanged:: 3.3 + Added ``service_actions`` call to the ``serve_forever`` method. + + + .. method:: service_actions() + + This is called in the :meth:`serve_forever` loop. This method can be + overridden by subclasses or mixin classes to perform actions specific to + a given service, such as cleanup actions. + + .. versionadded:: 3.3 + + .. method:: shutdown() + + Tell the :meth:`serve_forever` loop to stop and wait until it does. + :meth:`shutdown` must be called while :meth:`serve_forever` is running in a + different thread otherwise it will deadlock. + + + .. method:: server_close() + + Clean up the server. May be overridden. + + + .. attribute:: address_family + + The family of protocols to which the server's socket belongs. + Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`. + + + .. attribute:: RequestHandlerClass + + The user-provided request handler class; an instance of this class is created + for each request. + + + .. attribute:: server_address + + The address on which the server is listening. The format of addresses varies + depending on the protocol family; + see the documentation for the :mod:`socket` module + for details. For Internet protocols, this is a tuple containing a string giving + the address, and an integer port number: ``('127.0.0.1', 80)``, for example. + + + .. attribute:: socket + + The socket object on which the server will listen for incoming requests. + + + The server classes support the following class variables: + + .. XXX should class variables be covered before instance variables, or vice versa? + + .. attribute:: allow_reuse_address + + Whether the server will allow the reuse of an address. This defaults to + :const:`False`, and can be set in subclasses to change the policy. + + + .. attribute:: request_queue_size + + The size of the request queue. If it takes a long time to process a single + request, any requests that arrive while the server is busy are placed into a + queue, up to :attr:`request_queue_size` requests. Once the queue is full, + further requests from clients will get a "Connection denied" error. The default + value is usually 5, but this can be overridden by subclasses. + + + .. attribute:: socket_type + + The type of socket used by the server; :const:`socket.SOCK_STREAM` and + :const:`socket.SOCK_DGRAM` are two common values. + + + .. attribute:: timeout + + Timeout duration, measured in seconds, or :const:`None` if no timeout is + desired. If :meth:`handle_request` receives no incoming requests within the + timeout period, the :meth:`handle_timeout` method is called. + + + There are various server methods that can be overridden by subclasses of base + server classes like :class:`TCPServer`; these methods aren't useful to external + users of the server object. + + .. XXX should the default implementations of these be documented, or should + it be assumed that the user will look at socketserver.py? + + .. method:: finish_request(request, client_address) + + Actually processes the request by instantiating :attr:`RequestHandlerClass` and + calling its :meth:`~BaseRequestHandler.handle` method. + + + .. method:: get_request() + + Must accept a request from the socket, and return a 2-tuple containing the *new* + socket object to be used to communicate with the client, and the client's + address. + + + .. method:: handle_error(request, client_address) + + This function is called if the :meth:`~BaseRequestHandler.handle` + method of a :attr:`RequestHandlerClass` instance raises + an exception. The default action is to print the traceback to + standard error and continue handling further requests. + + .. versionchanged:: 3.6 + Now only called for exceptions derived from the :exc:`Exception` + class. + + + .. method:: handle_timeout() + + This function is called when the :attr:`timeout` attribute has been set to a + value other than :const:`None` and the timeout period has passed with no + requests being received. The default action for forking servers is + to collect the status of any child processes that have exited, while + in threading servers this method does nothing. + + + .. method:: process_request(request, client_address) + + Calls :meth:`finish_request` to create an instance of the + :attr:`RequestHandlerClass`. If desired, this function can create a new process + or thread to handle the request; the :class:`ForkingMixIn` and + :class:`ThreadingMixIn` classes do this. + + + .. Is there any point in documenting the following two functions? + What would the purpose of overriding them be: initializing server + instance variables, adding new network families? + + .. method:: server_activate() + + Called by the server's constructor to activate the server. The default behavior + for a TCP server just invokes :meth:`~socket.socket.listen` + on the server's socket. May be overridden. + + + .. method:: server_bind() + + Called by the server's constructor to bind the socket to the desired address. + May be overridden. + + + .. method:: verify_request(request, client_address) + + Must return a Boolean value; if the value is :const:`True`, the request will + be processed, and if it's :const:`False`, the request will be denied. This + function can be overridden to implement access controls for a server. The + default implementation always returns :const:`True`. + + + .. versionchanged:: 3.6 + Support for the :term:`context manager` protocol was added. Exiting the + context manager is equivalent to calling :meth:`server_close`. + + +Request Handler Objects +----------------------- + +.. class:: BaseRequestHandler + + This is the superclass of all request handler objects. It defines + the interface, given below. A concrete request handler subclass must + define a new :meth:`handle` method, and can override any of + the other methods. A new instance of the subclass is created for each + request. + + + .. method:: setup() + + Called before the :meth:`handle` method to perform any initialization actions + required. The default implementation does nothing. + + + .. method:: handle() + + This function must do all the work required to service a request. The + default implementation does nothing. Several instance attributes are + available to it; the request is available as :attr:`self.request`; the client + address as :attr:`self.client_address`; and the server instance as + :attr:`self.server`, in case it needs access to per-server information. + + The type of :attr:`self.request` is different for datagram or stream + services. For stream services, :attr:`self.request` is a socket object; for + datagram services, :attr:`self.request` is a pair of string and socket. + + + .. method:: finish() + + Called after the :meth:`handle` method to perform any clean-up actions + required. The default implementation does nothing. If :meth:`setup` + raises an exception, this function will not be called. + + +.. class:: StreamRequestHandler + DatagramRequestHandler + + These :class:`BaseRequestHandler` subclasses override the + :meth:`~BaseRequestHandler.setup` and :meth:`~BaseRequestHandler.finish` + methods, and provide :attr:`self.rfile` and :attr:`self.wfile` attributes. + The :attr:`self.rfile` and :attr:`self.wfile` attributes can be + read or written, respectively, to get the request data or return data + to the client. + + The :attr:`rfile` attributes of both classes support the + :class:`io.BufferedIOBase` readable interface, and + :attr:`DatagramRequestHandler.wfile` supports the + :class:`io.BufferedIOBase` writable interface. + + .. versionchanged:: 3.6 + :attr:`StreamRequestHandler.wfile` also supports the + :class:`io.BufferedIOBase` writable interface. + + +Examples +-------- + +:class:`socketserver.TCPServer` Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This is the server side:: + + import socketserver + + class MyTCPHandler(socketserver.BaseRequestHandler): + """ + The request handler class for our server. + + It is instantiated once per connection to the server, and must + override the handle() method to implement communication to the + client. + """ + + def handle(self): + # self.request is the TCP socket connected to the client + self.data = self.request.recv(1024).strip() + print("{} wrote:".format(self.client_address[0])) + print(self.data) + # just send back the same data, but upper-cased + self.request.sendall(self.data.upper()) + + if __name__ == "__main__": + HOST, PORT = "localhost", 9999 + + # Create the server, binding to localhost on port 9999 + with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server: + # Activate the server; this will keep running until you + # interrupt the program with Ctrl-C + server.serve_forever() + +An alternative request handler class that makes use of streams (file-like +objects that simplify communication by providing the standard file interface):: + + class MyTCPHandler(socketserver.StreamRequestHandler): + + def handle(self): + # self.rfile is a file-like object created by the handler; + # we can now use e.g. readline() instead of raw recv() calls + self.data = self.rfile.readline().strip() + print("{} wrote:".format(self.client_address[0])) + print(self.data) + # Likewise, self.wfile is a file-like object used to write back + # to the client + self.wfile.write(self.data.upper()) + +The difference is that the ``readline()`` call in the second handler will call +``recv()`` multiple times until it encounters a newline character, while the +single ``recv()`` call in the first handler will just return what has been sent +from the client in one ``sendall()`` call. + + +This is the client side:: + + import socket + import sys + + HOST, PORT = "localhost", 9999 + data = " ".join(sys.argv[1:]) + + # Create a socket (SOCK_STREAM means a TCP socket) + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + # Connect to server and send data + sock.connect((HOST, PORT)) + sock.sendall(bytes(data + "\n", "utf-8")) + + # Receive data from the server and shut down + received = str(sock.recv(1024), "utf-8") + + print("Sent: {}".format(data)) + print("Received: {}".format(received)) + + +The output of the example should look something like this: + +Server: + +.. code-block:: shell-session + + $ python TCPServer.py + 127.0.0.1 wrote: + b'hello world with TCP' + 127.0.0.1 wrote: + b'python is nice' + +Client: + +.. code-block:: shell-session + + $ python TCPClient.py hello world with TCP + Sent: hello world with TCP + Received: HELLO WORLD WITH TCP + $ python TCPClient.py python is nice + Sent: python is nice + Received: PYTHON IS NICE + + +:class:`socketserver.UDPServer` Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This is the server side:: + + import socketserver + + class MyUDPHandler(socketserver.BaseRequestHandler): + """ + This class works similar to the TCP handler class, except that + self.request consists of a pair of data and client socket, and since + there is no connection the client address must be given explicitly + when sending data back via sendto(). + """ + + def handle(self): + data = self.request[0].strip() + socket = self.request[1] + print("{} wrote:".format(self.client_address[0])) + print(data) + socket.sendto(data.upper(), self.client_address) + + if __name__ == "__main__": + HOST, PORT = "localhost", 9999 + with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server: + server.serve_forever() + +This is the client side:: + + import socket + import sys + + HOST, PORT = "localhost", 9999 + data = " ".join(sys.argv[1:]) + + # SOCK_DGRAM is the socket type to use for UDP sockets + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + + # As you can see, there is no connect() call; UDP has no connections. + # Instead, data is directly sent to the recipient via sendto(). + sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT)) + received = str(sock.recv(1024), "utf-8") + + print("Sent: {}".format(data)) + print("Received: {}".format(received)) + +The output of the example should look exactly like for the TCP server example. + + +Asynchronous Mixins +~~~~~~~~~~~~~~~~~~~ + +To build asynchronous handlers, use the :class:`ThreadingMixIn` and +:class:`ForkingMixIn` classes. + +An example for the :class:`ThreadingMixIn` class:: + + import socket + import threading + import socketserver + + class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): + + def handle(self): + data = str(self.request.recv(1024), 'ascii') + cur_thread = threading.current_thread() + response = bytes("{}: {}".format(cur_thread.name, data), 'ascii') + self.request.sendall(response) + + class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): + pass + + def client(ip, port, message): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.connect((ip, port)) + sock.sendall(bytes(message, 'ascii')) + response = str(sock.recv(1024), 'ascii') + print("Received: {}".format(response)) + + if __name__ == "__main__": + # Port 0 means to select an arbitrary unused port + HOST, PORT = "localhost", 0 + + server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) + with server: + ip, port = server.server_address + + # Start a thread with the server -- that thread will then start one + # more thread for each request + server_thread = threading.Thread(target=server.serve_forever) + # Exit the server thread when the main thread terminates + server_thread.daemon = True + server_thread.start() + print("Server loop running in thread:", server_thread.name) + + client(ip, port, "Hello World 1") + client(ip, port, "Hello World 2") + client(ip, port, "Hello World 3") + + server.shutdown() + + +The output of the example should look something like this: + +.. code-block:: shell-session + + $ python ThreadedTCPServer.py + Server loop running in thread: Thread-1 + Received: Thread-2: Hello World 1 + Received: Thread-3: Hello World 2 + Received: Thread-4: Hello World 3 + + +The :class:`ForkingMixIn` class is used in the same way, except that the server +will spawn a new process for each request. +Available only on POSIX platforms that support :func:`~os.fork`. + diff --git a/cpython_2/environment/repo/Doc/library/spwd.rst b/cpython_2/environment/repo/Doc/library/spwd.rst new file mode 100644 index 0000000000000000000000000000000000000000..c6cad2a3c32849fba0aef2c63d0c242809e06ae7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/spwd.rst @@ -0,0 +1,75 @@ +:mod:`spwd` --- The shadow password database +============================================ + +.. module:: spwd + :platform: Unix + :synopsis: The shadow password database (getspnam() and friends). + +-------------- + +This module provides access to the Unix shadow password database. It is +available on various Unix versions. + +You must have enough privileges to access the shadow password database (this +usually means you have to be root). + +Shadow password database entries are reported as a tuple-like object, whose +attributes correspond to the members of the ``spwd`` structure (Attribute field +below, see ````): + ++-------+---------------+---------------------------------+ +| Index | Attribute | Meaning | ++=======+===============+=================================+ +| 0 | ``sp_namp`` | Login name | ++-------+---------------+---------------------------------+ +| 1 | ``sp_pwdp`` | Encrypted password | ++-------+---------------+---------------------------------+ +| 2 | ``sp_lstchg`` | Date of last change | ++-------+---------------+---------------------------------+ +| 3 | ``sp_min`` | Minimal number of days between | +| | | changes | ++-------+---------------+---------------------------------+ +| 4 | ``sp_max`` | Maximum number of days between | +| | | changes | ++-------+---------------+---------------------------------+ +| 5 | ``sp_warn`` | Number of days before password | +| | | expires to warn user about it | ++-------+---------------+---------------------------------+ +| 6 | ``sp_inact`` | Number of days after password | +| | | expires until account is | +| | | disabled | ++-------+---------------+---------------------------------+ +| 7 | ``sp_expire`` | Number of days since 1970-01-01 | +| | | when account expires | ++-------+---------------+---------------------------------+ +| 8 | ``sp_flag`` | Reserved | ++-------+---------------+---------------------------------+ + +The sp_namp and sp_pwdp items are strings, all others are integers. +:exc:`KeyError` is raised if the entry asked for cannot be found. + +The following functions are defined: + + +.. function:: getspnam(name) + + Return the shadow password database entry for the given user name. + + .. versionchanged:: 3.6 + Raises a :exc:`PermissionError` instead of :exc:`KeyError` if the user + doesn't have privileges. + +.. function:: getspall() + + Return a list of all available shadow password database entries, in arbitrary + order. + + +.. seealso:: + + Module :mod:`grp` + An interface to the group database, similar to this. + + Module :mod:`pwd` + An interface to the normal password database, similar to this. + diff --git a/cpython_2/environment/repo/Doc/library/sqlite3.rst b/cpython_2/environment/repo/Doc/library/sqlite3.rst new file mode 100644 index 0000000000000000000000000000000000000000..ccb82278bdaa13368f30bc78ed6fce5efd483cc6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/sqlite3.rst @@ -0,0 +1,1113 @@ +:mod:`sqlite3` --- DB-API 2.0 interface for SQLite databases +============================================================ + +.. module:: sqlite3 + :synopsis: A DB-API 2.0 implementation using SQLite 3.x. + +.. sectionauthor:: Gerhard Häring + +**Source code:** :source:`Lib/sqlite3/` + +-------------- + +SQLite is a C library that provides a lightweight disk-based database that +doesn't require a separate server process and allows accessing the database +using a nonstandard variant of the SQL query language. Some applications can use +SQLite for internal data storage. It's also possible to prototype an +application using SQLite and then port the code to a larger database such as +PostgreSQL or Oracle. + +The sqlite3 module was written by Gerhard Häring. It provides a SQL interface +compliant with the DB-API 2.0 specification described by :pep:`249`. + +To use the module, you must first create a :class:`Connection` object that +represents the database. Here the data will be stored in the +:file:`example.db` file:: + + import sqlite3 + conn = sqlite3.connect('example.db') + +You can also supply the special name ``:memory:`` to create a database in RAM. + +Once you have a :class:`Connection`, you can create a :class:`Cursor` object +and call its :meth:`~Cursor.execute` method to perform SQL commands:: + + c = conn.cursor() + + # Create table + c.execute('''CREATE TABLE stocks + (date text, trans text, symbol text, qty real, price real)''') + + # Insert a row of data + c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)") + + # Save (commit) the changes + conn.commit() + + # We can also close the connection if we are done with it. + # Just be sure any changes have been committed or they will be lost. + conn.close() + +The data you've saved is persistent and is available in subsequent sessions:: + + import sqlite3 + conn = sqlite3.connect('example.db') + c = conn.cursor() + +Usually your SQL operations will need to use values from Python variables. You +shouldn't assemble your query using Python's string operations because doing so +is insecure; it makes your program vulnerable to an SQL injection attack +(see https://xkcd.com/327/ for humorous example of what can go wrong). + +Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder +wherever you want to use a value, and then provide a tuple of values as the +second argument to the cursor's :meth:`~Cursor.execute` method. (Other database +modules may use a different placeholder, such as ``%s`` or ``:1``.) For +example:: + + # Never do this -- insecure! + symbol = 'RHAT' + c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol) + + # Do this instead + t = ('RHAT',) + c.execute('SELECT * FROM stocks WHERE symbol=?', t) + print(c.fetchone()) + + # Larger example that inserts many records at a time + purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), + ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), + ('2006-04-06', 'SELL', 'IBM', 500, 53.00), + ] + c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases) + +To retrieve data after executing a SELECT statement, you can either treat the +cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to +retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the +matching rows. + +This example uses the iterator form:: + + >>> for row in c.execute('SELECT * FROM stocks ORDER BY price'): + print(row) + + ('2006-01-05', 'BUY', 'RHAT', 100, 35.14) + ('2006-03-28', 'BUY', 'IBM', 1000, 45.0) + ('2006-04-06', 'SELL', 'IBM', 500, 53.0) + ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0) + + +.. seealso:: + + https://github.com/ghaering/pysqlite + The pysqlite web page -- sqlite3 is developed externally under the name + "pysqlite". + + https://www.sqlite.org + The SQLite web page; the documentation describes the syntax and the + available data types for the supported SQL dialect. + + https://www.w3schools.com/sql/ + Tutorial, reference and examples for learning SQL syntax. + + :pep:`249` - Database API Specification 2.0 + PEP written by Marc-André Lemburg. + + +.. _sqlite3-module-contents: + +Module functions and constants +------------------------------ + + +.. data:: version + + The version number of this module, as a string. This is not the version of + the SQLite library. + + +.. data:: version_info + + The version number of this module, as a tuple of integers. This is not the + version of the SQLite library. + + +.. data:: sqlite_version + + The version number of the run-time SQLite library, as a string. + + +.. data:: sqlite_version_info + + The version number of the run-time SQLite library, as a tuple of integers. + + +.. data:: PARSE_DECLTYPES + + This constant is meant to be used with the *detect_types* parameter of the + :func:`connect` function. + + Setting it makes the :mod:`sqlite3` module parse the declared type for each + column it returns. It will parse out the first word of the declared type, + i. e. for "integer primary key", it will parse out "integer", or for + "number(10)" it will parse out "number". Then for that column, it will look + into the converters dictionary and use the converter function registered for + that type there. + + +.. data:: PARSE_COLNAMES + + This constant is meant to be used with the *detect_types* parameter of the + :func:`connect` function. + + Setting this makes the SQLite interface parse the column name for each column it + returns. It will look for a string formed [mytype] in there, and then decide + that 'mytype' is the type of the column. It will try to find an entry of + 'mytype' in the converters dictionary and then use the converter function found + there to return the value. The column name found in :attr:`Cursor.description` + does not include the type, i. e. if you use something like + ``'as "Expiration date [datetime]"'`` in your SQL, then we will parse out + everything until the first ``'['`` for the column name and strip + the preceeding space: the column name would simply be "Expiration date". + + +.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri]) + + Opens a connection to the SQLite database file *database*. By default returns a + :class:`Connection` object, unless a custom *factory* is given. + + *database* is a :term:`path-like object` giving the pathname (absolute or + relative to the current working directory) of the database file to be opened. + You can use ``":memory:"`` to open a database connection to a database that + resides in RAM instead of on disk. + + When a database is accessed by multiple connections, and one of the processes + modifies the database, the SQLite database is locked until that transaction is + committed. The *timeout* parameter specifies how long the connection should wait + for the lock to go away until raising an exception. The default for the timeout + parameter is 5.0 (five seconds). + + For the *isolation_level* parameter, please see the + :attr:`~Connection.isolation_level` property of :class:`Connection` objects. + + SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If + you want to use other types you must add support for them yourself. The + *detect_types* parameter and the using custom **converters** registered with the + module-level :func:`register_converter` function allow you to easily do that. + + *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to + any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn + type detection on. + + By default, *check_same_thread* is :const:`True` and only the creating thread may + use the connection. If set :const:`False`, the returned connection may be shared + across multiple threads. When using multiple threads with the same connection + writing operations should be serialized by the user to avoid data corruption. + + By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the + connect call. You can, however, subclass the :class:`Connection` class and make + :func:`connect` use your class instead by providing your class for the *factory* + parameter. + + Consult the section :ref:`sqlite3-types` of this manual for details. + + The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing + overhead. If you want to explicitly set the number of statements that are cached + for the connection, you can set the *cached_statements* parameter. The currently + implemented default is to cache 100 statements. + + If *uri* is true, *database* is interpreted as a URI. This allows you + to specify options. For example, to open a database in read-only mode + you can use:: + + db = sqlite3.connect('file:path/to/database?mode=ro', uri=True) + + More information about this feature, including a list of recognized options, can + be found in the `SQLite URI documentation `_. + + .. audit-event:: sqlite3.connect database sqlite3.connect + + .. versionchanged:: 3.4 + Added the *uri* parameter. + + .. versionchanged:: 3.7 + *database* can now also be a :term:`path-like object`, not only a string. + + +.. function:: register_converter(typename, callable) + + Registers a callable to convert a bytestring from the database into a custom + Python type. The callable will be invoked for all database values that are of + the type *typename*. Confer the parameter *detect_types* of the :func:`connect` + function for how the type detection works. Note that *typename* and the name of + the type in your query are matched in case-insensitive manner. + + +.. function:: register_adapter(type, callable) + + Registers a callable to convert the custom Python type *type* into one of + SQLite's supported types. The callable *callable* accepts as single parameter + the Python value, and must return a value of the following types: int, + float, str or bytes. + + +.. function:: complete_statement(sql) + + Returns :const:`True` if the string *sql* contains one or more complete SQL + statements terminated by semicolons. It does not verify that the SQL is + syntactically correct, only that there are no unclosed string literals and the + statement is terminated by a semicolon. + + This can be used to build a shell for SQLite, as in the following example: + + + .. literalinclude:: ../includes/sqlite3/complete_statement.py + + +.. function:: enable_callback_tracebacks(flag) + + By default you will not get any tracebacks in user-defined functions, + aggregates, converters, authorizer callbacks etc. If you want to debug them, + you can call this function with *flag* set to ``True``. Afterwards, you will + get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to + disable the feature again. + + +.. _sqlite3-connection-objects: + +Connection Objects +------------------ + +.. class:: Connection + + A SQLite database connection has the following attributes and methods: + + .. attribute:: isolation_level + + Get or set the current default isolation level. :const:`None` for autocommit mode or + one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section + :ref:`sqlite3-controlling-transactions` for a more detailed explanation. + + .. attribute:: in_transaction + + :const:`True` if a transaction is active (there are uncommitted changes), + :const:`False` otherwise. Read-only attribute. + + .. versionadded:: 3.2 + + .. method:: cursor(factory=Cursor) + + The cursor method accepts a single optional parameter *factory*. If + supplied, this must be a callable returning an instance of :class:`Cursor` + or its subclasses. + + .. method:: commit() + + This method commits the current transaction. If you don't call this method, + anything you did since the last call to ``commit()`` is not visible from + other database connections. If you wonder why you don't see the data you've + written to the database, please check you didn't forget to call this method. + + .. method:: rollback() + + This method rolls back any changes to the database since the last call to + :meth:`commit`. + + .. method:: close() + + This closes the database connection. Note that this does not automatically + call :meth:`commit`. If you just close your database connection without + calling :meth:`commit` first, your changes will be lost! + + .. method:: execute(sql[, parameters]) + + This is a nonstandard shortcut that creates a cursor object by calling + the :meth:`~Connection.cursor` method, calls the cursor's + :meth:`~Cursor.execute` method with the *parameters* given, and returns + the cursor. + + .. method:: executemany(sql[, parameters]) + + This is a nonstandard shortcut that creates a cursor object by + calling the :meth:`~Connection.cursor` method, calls the cursor's + :meth:`~Cursor.executemany` method with the *parameters* given, and + returns the cursor. + + .. method:: executescript(sql_script) + + This is a nonstandard shortcut that creates a cursor object by + calling the :meth:`~Connection.cursor` method, calls the cursor's + :meth:`~Cursor.executescript` method with the given *sql_script*, and + returns the cursor. + + .. method:: create_function(name, num_params, func, *, deterministic=False) + + Creates a user-defined function that you can later use from within SQL + statements under the function name *name*. *num_params* is the number of + parameters the function accepts (if *num_params* is -1, the function may + take any number of arguments), and *func* is a Python callable that is + called as the SQL function. If *deterministic* is true, the created function + is marked as `deterministic `_, which + allows SQLite to perform additional optimizations. This flag is supported by + SQLite 3.8.3 or higher, :exc:`NotSupportedError` will be raised if used + with older versions. + + The function can return any of the types supported by SQLite: bytes, str, int, + float and ``None``. + + .. versionchanged:: 3.8 + The *deterministic* parameter was added. + + Example: + + .. literalinclude:: ../includes/sqlite3/md5func.py + + + .. method:: create_aggregate(name, num_params, aggregate_class) + + Creates a user-defined aggregate function. + + The aggregate class must implement a ``step`` method, which accepts the number + of parameters *num_params* (if *num_params* is -1, the function may take + any number of arguments), and a ``finalize`` method which will return the + final result of the aggregate. + + The ``finalize`` method can return any of the types supported by SQLite: + bytes, str, int, float and ``None``. + + Example: + + .. literalinclude:: ../includes/sqlite3/mysumaggr.py + + + .. method:: create_collation(name, callable) + + Creates a collation with the specified *name* and *callable*. The callable will + be passed two string arguments. It should return -1 if the first is ordered + lower than the second, 0 if they are ordered equal and 1 if the first is ordered + higher than the second. Note that this controls sorting (ORDER BY in SQL) so + your comparisons don't affect other SQL operations. + + Note that the callable will get its parameters as Python bytestrings, which will + normally be encoded in UTF-8. + + The following example shows a custom collation that sorts "the wrong way": + + .. literalinclude:: ../includes/sqlite3/collation_reverse.py + + To remove a collation, call ``create_collation`` with ``None`` as callable:: + + con.create_collation("reverse", None) + + + .. method:: interrupt() + + You can call this method from a different thread to abort any queries that might + be executing on the connection. The query will then abort and the caller will + get an exception. + + + .. method:: set_authorizer(authorizer_callback) + + This routine registers a callback. The callback is invoked for each attempt to + access a column of a table in the database. The callback should return + :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL + statement should be aborted with an error and :const:`SQLITE_IGNORE` if the + column should be treated as a NULL value. These constants are available in the + :mod:`sqlite3` module. + + The first argument to the callback signifies what kind of operation is to be + authorized. The second and third argument will be arguments or :const:`None` + depending on the first argument. The 4th argument is the name of the database + ("main", "temp", etc.) if applicable. The 5th argument is the name of the + inner-most trigger or view that is responsible for the access attempt or + :const:`None` if this access attempt is directly from input SQL code. + + Please consult the SQLite documentation about the possible values for the first + argument and the meaning of the second and third argument depending on the first + one. All necessary constants are available in the :mod:`sqlite3` module. + + + .. method:: set_progress_handler(handler, n) + + This routine registers a callback. The callback is invoked for every *n* + instructions of the SQLite virtual machine. This is useful if you want to + get called from SQLite during long-running operations, for example to update + a GUI. + + If you want to clear any previously installed progress handler, call the + method with :const:`None` for *handler*. + + Returning a non-zero value from the handler function will terminate the + currently executing query and cause it to raise an :exc:`OperationalError` + exception. + + + .. method:: set_trace_callback(trace_callback) + + Registers *trace_callback* to be called for each SQL statement that is + actually executed by the SQLite backend. + + The only argument passed to the callback is the statement (as string) that + is being executed. The return value of the callback is ignored. Note that + the backend does not only run statements passed to the :meth:`Cursor.execute` + methods. Other sources include the transaction management of the Python + module and the execution of triggers defined in the current database. + + Passing :const:`None` as *trace_callback* will disable the trace callback. + + .. versionadded:: 3.3 + + + .. method:: enable_load_extension(enabled) + + This routine allows/disallows the SQLite engine to load SQLite extensions + from shared libraries. SQLite extensions can define new functions, + aggregates or whole new virtual table implementations. One well-known + extension is the fulltext-search extension distributed with SQLite. + + Loadable extensions are disabled by default. See [#f1]_. + + .. versionadded:: 3.2 + + .. literalinclude:: ../includes/sqlite3/load_extension.py + + .. method:: load_extension(path) + + This routine loads a SQLite extension from a shared library. You have to + enable extension loading with :meth:`enable_load_extension` before you can + use this routine. + + Loadable extensions are disabled by default. See [#f1]_. + + .. versionadded:: 3.2 + + .. attribute:: row_factory + + You can change this attribute to a callable that accepts the cursor and the + original row as a tuple and will return the real result row. This way, you can + implement more advanced ways of returning results, such as returning an object + that can also access columns by name. + + Example: + + .. literalinclude:: ../includes/sqlite3/row_factory.py + + If returning a tuple doesn't suffice and you want name-based access to + columns, you should consider setting :attr:`row_factory` to the + highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both + index-based and case-insensitive name-based access to columns with almost no + memory overhead. It will probably be better than your own custom + dictionary-based approach or even a db_row based solution. + + .. XXX what's a db_row-based solution? + + + .. attribute:: text_factory + + Using this attribute you can control what objects are returned for the ``TEXT`` + data type. By default, this attribute is set to :class:`str` and the + :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to + return bytestrings instead, you can set it to :class:`bytes`. + + You can also set it to any other callable that accepts a single bytestring + parameter and returns the resulting object. + + See the following example code for illustration: + + .. literalinclude:: ../includes/sqlite3/text_factory.py + + + .. attribute:: total_changes + + Returns the total number of database rows that have been modified, inserted, or + deleted since the database connection was opened. + + + .. method:: iterdump + + Returns an iterator to dump the database in an SQL text format. Useful when + saving an in-memory database for later restoration. This function provides + the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3` + shell. + + Example:: + + # Convert file existing_db.db to SQL dump file dump.sql + import sqlite3 + + con = sqlite3.connect('existing_db.db') + with open('dump.sql', 'w') as f: + for line in con.iterdump(): + f.write('%s\n' % line) + con.close() + + + .. method:: backup(target, *, pages=0, progress=None, name="main", sleep=0.250) + + This method makes a backup of a SQLite database even while it's being accessed + by other clients, or concurrently by the same connection. The copy will be + written into the mandatory argument *target*, that must be another + :class:`Connection` instance. + + By default, or when *pages* is either ``0`` or a negative integer, the entire + database is copied in a single step; otherwise the method performs a loop + copying up to *pages* pages at a time. + + If *progress* is specified, it must either be ``None`` or a callable object that + will be executed at each iteration with three integer arguments, respectively + the *status* of the last iteration, the *remaining* number of pages still to be + copied and the *total* number of pages. + + The *name* argument specifies the database name that will be copied: it must be + a string containing either ``"main"``, the default, to indicate the main + database, ``"temp"`` to indicate the temporary database or the name specified + after the ``AS`` keyword in an ``ATTACH DATABASE`` statement for an attached + database. + + The *sleep* argument specifies the number of seconds to sleep by between + successive attempts to backup remaining pages, can be specified either as an + integer or a floating point value. + + Example 1, copy an existing database into another:: + + import sqlite3 + + def progress(status, remaining, total): + print(f'Copied {total-remaining} of {total} pages...') + + con = sqlite3.connect('existing_db.db') + bck = sqlite3.connect('backup.db') + with bck: + con.backup(bck, pages=1, progress=progress) + bck.close() + con.close() + + Example 2, copy an existing database into a transient copy:: + + import sqlite3 + + source = sqlite3.connect('existing_db.db') + dest = sqlite3.connect(':memory:') + source.backup(dest) + + Availability: SQLite 3.6.11 or higher + + .. versionadded:: 3.7 + + +.. _sqlite3-cursor-objects: + +Cursor Objects +-------------- + +.. class:: Cursor + + A :class:`Cursor` instance has the following attributes and methods. + + .. index:: single: ? (question mark); in SQL statements + .. index:: single: : (colon); in SQL statements + + .. method:: execute(sql[, parameters]) + + Executes an SQL statement. The SQL statement may be parameterized (i. e. + placeholders instead of SQL literals). The :mod:`sqlite3` module supports two + kinds of placeholders: question marks (qmark style) and named placeholders + (named style). + + Here's an example of both styles: + + .. literalinclude:: ../includes/sqlite3/execute_1.py + + :meth:`execute` will only execute a single SQL statement. If you try to execute + more than one statement with it, it will raise a :exc:`.Warning`. Use + :meth:`executescript` if you want to execute multiple SQL statements with one + call. + + + .. method:: executemany(sql, seq_of_parameters) + + Executes an SQL command against all parameter sequences or mappings found in + the sequence *seq_of_parameters*. The :mod:`sqlite3` module also allows + using an :term:`iterator` yielding parameters instead of a sequence. + + .. literalinclude:: ../includes/sqlite3/executemany_1.py + + Here's a shorter example using a :term:`generator`: + + .. literalinclude:: ../includes/sqlite3/executemany_2.py + + + .. method:: executescript(sql_script) + + This is a nonstandard convenience method for executing multiple SQL statements + at once. It issues a ``COMMIT`` statement first, then executes the SQL script it + gets as a parameter. + + *sql_script* can be an instance of :class:`str`. + + Example: + + .. literalinclude:: ../includes/sqlite3/executescript.py + + + .. method:: fetchone() + + Fetches the next row of a query result set, returning a single sequence, + or :const:`None` when no more data is available. + + + .. method:: fetchmany(size=cursor.arraysize) + + Fetches the next set of rows of a query result, returning a list. An empty + list is returned when no more rows are available. + + The number of rows to fetch per call is specified by the *size* parameter. + If it is not given, the cursor's arraysize determines the number of rows + to be fetched. The method should try to fetch as many rows as indicated by + the size parameter. If this is not possible due to the specified number of + rows not being available, fewer rows may be returned. + + Note there are performance considerations involved with the *size* parameter. + For optimal performance, it is usually best to use the arraysize attribute. + If the *size* parameter is used, then it is best for it to retain the same + value from one :meth:`fetchmany` call to the next. + + .. method:: fetchall() + + Fetches all (remaining) rows of a query result, returning a list. Note that + the cursor's arraysize attribute can affect the performance of this operation. + An empty list is returned when no rows are available. + + .. method:: close() + + Close the cursor now (rather than whenever ``__del__`` is called). + + The cursor will be unusable from this point forward; a :exc:`ProgrammingError` + exception will be raised if any operation is attempted with the cursor. + + .. attribute:: rowcount + + Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this + attribute, the database engine's own support for the determination of "rows + affected"/"rows selected" is quirky. + + For :meth:`executemany` statements, the number of modifications are summed up + into :attr:`rowcount`. + + As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in + case no ``executeXX()`` has been performed on the cursor or the rowcount of the + last operation is not determinable by the interface". This includes ``SELECT`` + statements because we cannot determine the number of rows a query produced + until all rows were fetched. + + With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if + you make a ``DELETE FROM table`` without any condition. + + .. attribute:: lastrowid + + This read-only attribute provides the rowid of the last modified row. It is + only set if you issued an ``INSERT`` or a ``REPLACE`` statement using the + :meth:`execute` method. For operations other than ``INSERT`` or + ``REPLACE`` or when :meth:`executemany` is called, :attr:`lastrowid` is + set to :const:`None`. + + If the ``INSERT`` or ``REPLACE`` statement failed to insert the previous + successful rowid is returned. + + .. versionchanged:: 3.6 + Added support for the ``REPLACE`` statement. + + .. attribute:: arraysize + + Read/write attribute that controls the number of rows returned by :meth:`fetchmany`. + The default value is 1 which means a single row would be fetched per call. + + .. attribute:: description + + 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`. + + It is set for ``SELECT`` statements without any matching rows as well. + + .. attribute:: connection + + This read-only attribute provides the SQLite database :class:`Connection` + used by the :class:`Cursor` object. A :class:`Cursor` object created by + calling :meth:`con.cursor() ` will have a + :attr:`connection` attribute that refers to *con*:: + + >>> con = sqlite3.connect(":memory:") + >>> cur = con.cursor() + >>> cur.connection == con + True + +.. _sqlite3-row-objects: + +Row Objects +----------- + +.. class:: Row + + A :class:`Row` instance serves as a highly optimized + :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, + representation, equality testing and :func:`len`. + + If two :class:`Row` objects have exactly the same columns and their + members are equal, they compare equal. + + .. method:: keys + + This method returns a list of column names. Immediately after a query, + it is the first member of each tuple in :attr:`Cursor.description`. + + .. versionchanged:: 3.5 + Added support of slicing. + +Let's assume we initialize a table as in the example given above:: + + conn = sqlite3.connect(":memory:") + c = conn.cursor() + c.execute('''create table stocks + (date text, trans text, symbol text, + qty real, price real)''') + c.execute("""insert into stocks + values ('2006-01-05','BUY','RHAT',100,35.14)""") + conn.commit() + c.close() + +Now we plug :class:`Row` in:: + + >>> conn.row_factory = sqlite3.Row + >>> c = conn.cursor() + >>> c.execute('select * from stocks') + + >>> r = c.fetchone() + >>> type(r) + + >>> tuple(r) + ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14) + >>> len(r) + 5 + >>> r[2] + 'RHAT' + >>> r.keys() + ['date', 'trans', 'symbol', 'qty', 'price'] + >>> r['qty'] + 100.0 + >>> for member in r: + ... print(member) + ... + 2006-01-05 + BUY + RHAT + 100.0 + 35.14 + + +.. _sqlite3-exceptions: + +Exceptions +---------- + +.. exception:: Warning + + A subclass of :exc:`Exception`. + +.. exception:: Error + + The base class of the other exceptions in this module. It is a subclass + of :exc:`Exception`. + +.. exception:: DatabaseError + + Exception raised for errors that are related to the database. + +.. exception:: IntegrityError + + Exception raised when the relational integrity of the database is affected, + e.g. a foreign key check fails. It is a subclass of :exc:`DatabaseError`. + +.. exception:: ProgrammingError + + Exception raised for programming errors, e.g. table not found or already + exists, syntax error in the SQL statement, wrong number of parameters + specified, etc. It is a subclass of :exc:`DatabaseError`. + +.. exception:: OperationalError + + Exception raised for errors that are related to the database's operation + and not necessarily under the control of the programmer, e.g. an unexpected + disconnect occurs, the data source name is not found, a transaction could + not be processed, etc. It is a subclass of :exc:`DatabaseError`. + +.. exception:: NotSupportedError + + Exception raised in case a method or database API was used which is not + supported by the database, e.g. calling the :meth:`~Connection.rollback` + method on a connection that does not support transaction or has + transactions turned off. It is a subclass of :exc:`DatabaseError`. + + +.. _sqlite3-types: + +SQLite and Python types +----------------------- + + +Introduction +^^^^^^^^^^^^ + +SQLite natively supports the following types: ``NULL``, ``INTEGER``, +``REAL``, ``TEXT``, ``BLOB``. + +The following Python types can thus be sent to SQLite without any problem: + ++-------------------------------+-------------+ +| Python type | SQLite type | ++===============================+=============+ +| :const:`None` | ``NULL`` | ++-------------------------------+-------------+ +| :class:`int` | ``INTEGER`` | ++-------------------------------+-------------+ +| :class:`float` | ``REAL`` | ++-------------------------------+-------------+ +| :class:`str` | ``TEXT`` | ++-------------------------------+-------------+ +| :class:`bytes` | ``BLOB`` | ++-------------------------------+-------------+ + + +This is how SQLite types are converted to Python types by default: + ++-------------+----------------------------------------------+ +| SQLite type | Python type | ++=============+==============================================+ +| ``NULL`` | :const:`None` | ++-------------+----------------------------------------------+ +| ``INTEGER`` | :class:`int` | ++-------------+----------------------------------------------+ +| ``REAL`` | :class:`float` | ++-------------+----------------------------------------------+ +| ``TEXT`` | depends on :attr:`~Connection.text_factory`, | +| | :class:`str` by default | ++-------------+----------------------------------------------+ +| ``BLOB`` | :class:`bytes` | ++-------------+----------------------------------------------+ + +The type system of the :mod:`sqlite3` module is extensible in two ways: you can +store additional Python types in a SQLite database via object adaptation, and +you can let the :mod:`sqlite3` module convert SQLite types to different Python +types via converters. + + +Using adapters to store additional Python types in SQLite databases +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +As described before, SQLite supports only a limited set of types natively. To +use other Python types with SQLite, you must **adapt** them to one of the +sqlite3 module's supported types for SQLite: one of NoneType, int, float, +str, bytes. + +There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python +type to one of the supported ones. + + +Letting your object adapt itself +"""""""""""""""""""""""""""""""" + +This is a good approach if you write the class yourself. Let's suppose you have +a class like this:: + + class Point: + def __init__(self, x, y): + self.x, self.y = x, y + +Now you want to store the point in a single SQLite column. First you'll have to +choose one of the supported types to be used for representing the point. +Let's just use str and separate the coordinates using a semicolon. Then you need +to give your class a method ``__conform__(self, protocol)`` which must return +the converted value. The parameter *protocol* will be :class:`PrepareProtocol`. + +.. literalinclude:: ../includes/sqlite3/adapter_point_1.py + + +Registering an adapter callable +""""""""""""""""""""""""""""""" + +The other possibility is to create a function that converts the type to the +string representation and register the function with :meth:`register_adapter`. + +.. literalinclude:: ../includes/sqlite3/adapter_point_2.py + +The :mod:`sqlite3` module has two default adapters for Python's built-in +:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose +we want to store :class:`datetime.datetime` objects not in ISO representation, +but as a Unix timestamp. + +.. literalinclude:: ../includes/sqlite3/adapter_datetime.py + + +Converting SQLite values to custom Python types +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Writing an adapter lets you send custom Python types to SQLite. But to make it +really useful we need to make the Python to SQLite to Python roundtrip work. + +Enter converters. + +Let's go back to the :class:`Point` class. We stored the x and y coordinates +separated via semicolons as strings in SQLite. + +First, we'll define a converter function that accepts the string as a parameter +and constructs a :class:`Point` object from it. + +.. note:: + + Converter functions **always** get called with a :class:`bytes` object, no + matter under which data type you sent the value to SQLite. + +:: + + def convert_point(s): + x, y = map(float, s.split(b";")) + return Point(x, y) + +Now you need to make the :mod:`sqlite3` module know that what you select from +the database is actually a point. There are two ways of doing this: + +* Implicitly via the declared type + +* Explicitly via the column name + +Both ways are described in section :ref:`sqlite3-module-contents`, in the entries +for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`. + +The following example illustrates both approaches. + +.. literalinclude:: ../includes/sqlite3/converter_point.py + + +Default adapters and converters +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +There are default adapters for the date and datetime types in the datetime +module. They will be sent as ISO dates/ISO timestamps to SQLite. + +The default converters are registered under the name "date" for +:class:`datetime.date` and under the name "timestamp" for +:class:`datetime.datetime`. + +This way, you can use date/timestamps from Python without any additional +fiddling in most cases. The format of the adapters is also compatible with the +experimental SQLite date/time functions. + +The following example demonstrates this. + +.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py + +If a timestamp stored in SQLite has a fractional part longer than 6 +numbers, its value will be truncated to microsecond precision by the +timestamp converter. + + +.. _sqlite3-controlling-transactions: + +Controlling Transactions +------------------------ + +The underlying ``sqlite3`` library operates in ``autocommit`` mode by default, +but the Python :mod:`sqlite3` module by default does not. + +``autocommit`` mode means that statements that modify the database take effect +immediately. A ``BEGIN`` or ``SAVEPOINT`` statement disables ``autocommit`` +mode, and a ``COMMIT``, a ``ROLLBACK``, or a ``RELEASE`` that ends the +outermost transaction, turns ``autocommit`` mode back on. + +The Python :mod:`sqlite3` module by default issues a ``BEGIN`` statement +implicitly before a Data Modification Language (DML) statement (i.e. +``INSERT``/``UPDATE``/``DELETE``/``REPLACE``). + +You can control which kind of ``BEGIN`` statements :mod:`sqlite3` implicitly +executes via the *isolation_level* parameter to the :func:`connect` +call, or via the :attr:`isolation_level` property of connections. +If you specify no *isolation_level*, a plain ``BEGIN`` is used, which is +equivalent to specifying ``DEFERRED``. Other possible values are ``IMMEDIATE`` +and ``EXCLUSIVE``. + +You can disable the :mod:`sqlite3` module's implicit transaction management by +setting :attr:`isolation_level` to ``None``. This will leave the underlying +``sqlite3`` library operating in ``autocommit`` mode. You can then completely +control the transaction state by explicitly issuing ``BEGIN``, ``ROLLBACK``, +``SAVEPOINT``, and ``RELEASE`` statements in your code. + +.. versionchanged:: 3.6 + :mod:`sqlite3` used to implicitly commit an open transaction before DDL + statements. This is no longer the case. + + +Using :mod:`sqlite3` efficiently +-------------------------------- + + +Using shortcut methods +^^^^^^^^^^^^^^^^^^^^^^ + +Using the nonstandard :meth:`execute`, :meth:`executemany` and +:meth:`executescript` methods of the :class:`Connection` object, your code can +be written more concisely because you don't have to create the (often +superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor` +objects are created implicitly and these shortcut methods return the cursor +objects. This way, you can execute a ``SELECT`` statement and iterate over it +directly using only a single call on the :class:`Connection` object. + +.. literalinclude:: ../includes/sqlite3/shortcut_methods.py + + +Accessing columns by name instead of by index +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +One useful feature of the :mod:`sqlite3` module is the built-in +:class:`sqlite3.Row` class designed to be used as a row factory. + +Rows wrapped with this class can be accessed both by index (like tuples) and +case-insensitively by name: + +.. literalinclude:: ../includes/sqlite3/rowclass.py + + +Using the connection as a context manager +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Connection objects can be used as context managers +that automatically commit or rollback transactions. In the event of an +exception, the transaction is rolled back; otherwise, the transaction is +committed: + +.. literalinclude:: ../includes/sqlite3/ctx_manager.py + + +Common issues +------------- + +Multithreading +^^^^^^^^^^^^^^ + +Older SQLite versions had issues with sharing connections between threads. +That's why the Python module disallows sharing connections and cursors between +threads. If you still try to do so, you will get an exception at runtime. + +The only exception is calling the :meth:`~Connection.interrupt` method, which +only makes sense to call from a different thread. + +.. rubric:: Footnotes + +.. [#f1] The sqlite3 module is not built with loadable extension support by + default, because some platforms (notably Mac OS X) have SQLite + libraries which are compiled without this feature. To get loadable + extension support, you must pass --enable-loadable-sqlite-extensions to + configure. diff --git a/cpython_2/environment/repo/Doc/library/ssl.rst b/cpython_2/environment/repo/Doc/library/ssl.rst new file mode 100644 index 0000000000000000000000000000000000000000..952ee1653b9248e2f1f175e8c0325c942ad6bc52 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/ssl.rst @@ -0,0 +1,2772 @@ +:mod:`ssl` --- TLS/SSL wrapper for socket objects +================================================= + +.. module:: ssl + :synopsis: TLS/SSL wrapper for socket objects + +.. moduleauthor:: Bill Janssen +.. sectionauthor:: Bill Janssen + +**Source code:** :source:`Lib/ssl.py` + +.. index:: single: OpenSSL; (use in module ssl) + +.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer + +-------------- + +This module provides access to Transport Layer Security (often known as "Secure +Sockets Layer") encryption and peer authentication facilities for network +sockets, both client-side and server-side. This module uses the OpenSSL +library. It is available on all modern Unix systems, Windows, Mac OS X, and +probably additional platforms, as long as OpenSSL is installed on that platform. + +.. note:: + + Some behavior may be platform dependent, since calls are made to the + operating system socket APIs. The installed version of OpenSSL may also + cause variations in behavior. For example, TLSv1.1 and TLSv1.2 come with + openssl version 1.0.1. + +.. warning:: + Don't use this module without reading the :ref:`ssl-security`. Doing so + may lead to a false sense of security, as the default settings of the + ssl module are not necessarily appropriate for your application. + + +This section documents the objects and functions in the ``ssl`` module; for more +general information about TLS, SSL, and certificates, the reader is referred to +the documents in the "See Also" section at the bottom. + +This module provides a class, :class:`ssl.SSLSocket`, which is derived from the +:class:`socket.socket` type, and provides a socket-like wrapper that also +encrypts and decrypts the data going over the socket with SSL. It supports +additional methods such as :meth:`getpeercert`, which retrieves the +certificate of the other side of the connection, and :meth:`cipher`, which +retrieves the cipher being used for the secure connection. + +For more sophisticated applications, the :class:`ssl.SSLContext` class +helps manage settings and certificates, which can then be inherited +by SSL sockets created through the :meth:`SSLContext.wrap_socket` method. + +.. versionchanged:: 3.5.3 + Updated to support linking with OpenSSL 1.1.0 + +.. versionchanged:: 3.6 + + OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. + In the future the ssl module will require at least OpenSSL 1.0.2 or + 1.1.0. + + +Functions, Constants, and Exceptions +------------------------------------ + + +Socket creation +^^^^^^^^^^^^^^^ + +Since Python 3.2 and 2.7.9, it is recommended to use the +:meth:`SSLContext.wrap_socket` of an :class:`SSLContext` instance to wrap +sockets as :class:`SSLSocket` objects. The helper functions +:func:`create_default_context` returns a new context with secure default +settings. The old :func:`wrap_socket` function is deprecated since it is +both inefficient and has no support for server name indication (SNI) and +hostname matching. + +Client socket example with default context and IPv4/IPv6 dual stack:: + + import socket + import ssl + + hostname = 'www.python.org' + context = ssl.create_default_context() + + with socket.create_connection((hostname, 443)) as sock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: + print(ssock.version()) + + +Client socket example with custom context and IPv4:: + + hostname = 'www.python.org' + # PROTOCOL_TLS_CLIENT requires valid cert chain and hostname + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.load_verify_locations('path/to/cabundle.pem') + + with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: + with context.wrap_socket(sock, server_hostname=hostname) as ssock: + print(ssock.version()) + + +Server socket example listening on localhost IPv4:: + + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key') + + with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: + sock.bind(('127.0.0.1', 8443)) + sock.listen(5) + with context.wrap_socket(sock, server_side=True) as ssock: + conn, addr = ssock.accept() + ... + + +Context creation +^^^^^^^^^^^^^^^^ + +A convenience function helps create :class:`SSLContext` objects for common +purposes. + +.. function:: create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None) + + Return a new :class:`SSLContext` object with default settings for + the given *purpose*. The settings are chosen by the :mod:`ssl` module, + and usually represent a higher security level than when calling the + :class:`SSLContext` constructor directly. + + *cafile*, *capath*, *cadata* represent optional CA certificates to + trust for certificate verification, as in + :meth:`SSLContext.load_verify_locations`. If all three are + :const:`None`, this function can choose to trust the system's default + CA certificates instead. + + The settings are: :data:`PROTOCOL_TLS`, :data:`OP_NO_SSLv2`, and + :data:`OP_NO_SSLv3` with high encryption cipher suites without RC4 and + without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH` + as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED` + and either loads CA certificates (when at least one of *cafile*, *capath* or + *cadata* is given) or uses :meth:`SSLContext.load_default_certs` to load + default CA certificates. + + When :attr:`~SSLContext.keylog_filename` is supported and the environment + variable :envvar:`SSLKEYLOGFILE` is set, :func:`create_default_context` + enables key logging. + + .. note:: + The protocol, options, cipher and other settings may change to more + restrictive values anytime without prior deprecation. The values + represent a fair balance between compatibility and security. + + If your application needs specific settings, you should create a + :class:`SSLContext` and apply the settings yourself. + + .. note:: + If you find that when certain older clients or servers attempt to connect + with a :class:`SSLContext` created by this function that they get an error + stating "Protocol or cipher suite mismatch", it may be that they only + support SSL3.0 which this function excludes using the + :data:`OP_NO_SSLv3`. SSL3.0 is widely considered to be `completely broken + `_. If you still wish to continue to + use this function but still allow SSL 3.0 connections you can re-enable + them using:: + + ctx = ssl.create_default_context(Purpose.CLIENT_AUTH) + ctx.options &= ~ssl.OP_NO_SSLv3 + + .. versionadded:: 3.4 + + .. versionchanged:: 3.4.4 + + RC4 was dropped from the default cipher string. + + .. versionchanged:: 3.6 + + ChaCha20/Poly1305 was added to the default cipher string. + + 3DES was dropped from the default cipher string. + + .. versionchanged:: 3.8 + + Support for key logging to :envvar:`SSLKEYLOGFILE` was added. + + +Exceptions +^^^^^^^^^^ + +.. exception:: SSLError + + Raised to signal an error from the underlying SSL implementation + (currently provided by the OpenSSL library). 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:`OSError`. The error code and message of + :exc:`SSLError` instances are provided by the OpenSSL library. + + .. versionchanged:: 3.3 + :exc:`SSLError` used to be a subtype of :exc:`socket.error`. + + .. attribute:: library + + A string mnemonic designating the OpenSSL submodule in which the error + occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible + values depends on the OpenSSL version. + + .. versionadded:: 3.3 + + .. attribute:: reason + + A string mnemonic designating the reason this error occurred, for + example ``CERTIFICATE_VERIFY_FAILED``. The range of possible + values depends on the OpenSSL version. + + .. versionadded:: 3.3 + +.. exception:: SSLZeroReturnError + + A subclass of :exc:`SSLError` raised when trying to read or write and + the SSL connection has been closed cleanly. Note that this doesn't + mean that the underlying transport (read TCP) has been closed. + + .. versionadded:: 3.3 + +.. exception:: SSLWantReadError + + A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket + ` when trying to read or write data, but more data needs + to be received on the underlying TCP transport before the request can be + fulfilled. + + .. versionadded:: 3.3 + +.. exception:: SSLWantWriteError + + A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket + ` when trying to read or write data, but more data needs + to be sent on the underlying TCP transport before the request can be + fulfilled. + + .. versionadded:: 3.3 + +.. exception:: SSLSyscallError + + A subclass of :exc:`SSLError` raised when a system error was encountered + while trying to fulfill an operation on a SSL socket. Unfortunately, + there is no easy way to inspect the original errno number. + + .. versionadded:: 3.3 + +.. exception:: SSLEOFError + + A subclass of :exc:`SSLError` raised when the SSL connection has been + terminated abruptly. Generally, you shouldn't try to reuse the underlying + transport when this error is encountered. + + .. versionadded:: 3.3 + +.. exception:: SSLCertVerificationError + + A subclass of :exc:`SSLError` raised when certificate validation has + failed. + + .. versionadded:: 3.7 + + .. attribute:: verify_code + + A numeric error number that denotes the verification error. + + .. attribute:: verify_message + + A human readable string of the verification error. + +.. exception:: CertificateError + + An alias for :exc:`SSLCertVerificationError`. + + .. versionchanged:: 3.7 + The exception is now an alias for :exc:`SSLCertVerificationError`. + + +Random generation +^^^^^^^^^^^^^^^^^ + +.. function:: RAND_bytes(num) + + Return *num* cryptographically strong pseudo-random bytes. Raises an + :class:`SSLError` if the PRNG has not been seeded with enough data or if the + operation is not supported by the current RAND method. :func:`RAND_status` + can be used to check the status of the PRNG and :func:`RAND_add` can be used + to seed the PRNG. + + For almost all applications :func:`os.urandom` is preferable. + + Read the Wikipedia article, `Cryptographically secure pseudorandom number + generator (CSPRNG) + `_, + to get the requirements of a cryptographically strong generator. + + .. versionadded:: 3.3 + +.. function:: RAND_pseudo_bytes(num) + + Return (bytes, is_cryptographic): bytes are *num* pseudo-random bytes, + is_cryptographic is ``True`` if the bytes generated are cryptographically + strong. Raises an :class:`SSLError` if the operation is not supported by the + current RAND method. + + Generated pseudo-random byte sequences will be unique if they are of + sufficient length, but are not necessarily unpredictable. They can be used + for non-cryptographic purposes and for certain purposes in cryptographic + protocols, but usually not for key generation etc. + + For almost all applications :func:`os.urandom` is preferable. + + .. versionadded:: 3.3 + + .. deprecated:: 3.6 + + OpenSSL has deprecated :func:`ssl.RAND_pseudo_bytes`, use + :func:`ssl.RAND_bytes` instead. + +.. function:: RAND_status() + + Return ``True`` if the SSL pseudo-random number generator has been seeded + with 'enough' randomness, and ``False`` otherwise. You can use + :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness of + the pseudo-random number generator. + +.. function:: RAND_egd(path) + + If you are running an entropy-gathering daemon (EGD) somewhere, and *path* + is the pathname of a socket connection open to it, this will read 256 bytes + of randomness from the socket, and add it to the SSL pseudo-random number + generator to increase the security of generated secret keys. This is + typically only necessary on systems without better sources of randomness. + + See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources + of entropy-gathering daemons. + + .. availability:: not available with LibreSSL and OpenSSL > 1.1.0. + +.. function:: RAND_add(bytes, entropy) + + Mix the given *bytes* into the SSL pseudo-random number generator. The + parameter *entropy* (a float) is a lower bound on the entropy contained in + string (so you can always use :const:`0.0`). See :rfc:`1750` for more + information on sources of entropy. + + .. versionchanged:: 3.5 + Writable :term:`bytes-like object` is now accepted. + +Certificate handling +^^^^^^^^^^^^^^^^^^^^ + +.. testsetup:: + + import ssl + +.. function:: match_hostname(cert, hostname) + + Verify that *cert* (in decoded format as returned by + :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules + applied are those for checking the identity of HTTPS servers as outlined + in :rfc:`2818`, :rfc:`5280` and :rfc:`6125`. In addition to HTTPS, this + function should be suitable for checking the identity of servers in + various SSL-based protocols such as FTPS, IMAPS, POPS and others. + + :exc:`CertificateError` is raised on failure. On success, the function + returns nothing:: + + >>> cert = {'subject': ((('commonName', 'example.com'),),)} + >>> ssl.match_hostname(cert, "example.com") + >>> ssl.match_hostname(cert, "example.org") + Traceback (most recent call last): + File "", line 1, in + File "/home/py3k/Lib/ssl.py", line 130, in match_hostname + ssl.CertificateError: hostname 'example.org' doesn't match 'example.com' + + .. versionadded:: 3.2 + + .. versionchanged:: 3.3.3 + The function now follows :rfc:`6125`, section 6.4.3 and does neither + match multiple wildcards (e.g. ``*.*.com`` or ``*a*.example.org``) nor + a wildcard inside an internationalized domain names (IDN) fragment. + IDN A-labels such as ``www*.xn--pthon-kva.org`` are still supported, + but ``x*.python.org`` no longer matches ``xn--tda.python.org``. + + .. versionchanged:: 3.5 + Matching of IP addresses, when present in the subjectAltName field + of the certificate, is now supported. + + .. versionchanged:: 3.7 + The function is no longer used to TLS connections. Hostname matching + is now performed by OpenSSL. + + Allow wildcard when it is the leftmost and the only character + in that segment. Partial wildcards like ``www*.example.com`` are no + longer supported. + + .. deprecated:: 3.7 + +.. function:: cert_time_to_seconds(cert_time) + + Return the time in seconds since the Epoch, given the ``cert_time`` + string representing the "notBefore" or "notAfter" date from a + certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C + locale). + + Here's an example: + + .. doctest:: newcontext + + >>> import ssl + >>> timestamp = ssl.cert_time_to_seconds("Jan 5 09:34:43 2018 GMT") + >>> timestamp # doctest: +SKIP + 1515144883 + >>> from datetime import datetime + >>> print(datetime.utcfromtimestamp(timestamp)) # doctest: +SKIP + 2018-01-05 09:34:43 + + "notBefore" or "notAfter" dates must use GMT (:rfc:`5280`). + + .. versionchanged:: 3.5 + Interpret the input time as a time in UTC as specified by 'GMT' + timezone in the input string. Local timezone was used + previously. Return an integer (no fractions of a second in the + input format) + +.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None) + + Given the address ``addr`` of an SSL-protected server, as a (*hostname*, + *port-number*) pair, fetches the server's certificate, and returns it as a + PEM-encoded string. If ``ssl_version`` is specified, uses that version of + the SSL protocol to attempt to connect to the server. If ``ca_certs`` is + specified, it should be a file containing a list of root certificates, the + same format as used for the same parameter in + :meth:`SSLContext.wrap_socket`. The call will attempt to validate the + server certificate against that set of root certificates, and will fail + if the validation attempt fails. + + .. versionchanged:: 3.3 + This function is now IPv6-compatible. + + .. versionchanged:: 3.5 + The default *ssl_version* is changed from :data:`PROTOCOL_SSLv3` to + :data:`PROTOCOL_TLS` for maximum compatibility with modern servers. + +.. function:: DER_cert_to_PEM_cert(DER_cert_bytes) + + Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded + string version of the same certificate. + +.. function:: PEM_cert_to_DER_cert(PEM_cert_string) + + Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of + bytes for that same certificate. + +.. function:: get_default_verify_paths() + + Returns a named tuple with paths to OpenSSL's default cafile and capath. + The paths are the same as used by + :meth:`SSLContext.set_default_verify_paths`. The return value is a + :term:`named tuple` ``DefaultVerifyPaths``: + + * :attr:`cafile` - resolved path to cafile or ``None`` if the file doesn't exist, + * :attr:`capath` - resolved path to capath or ``None`` if the directory doesn't exist, + * :attr:`openssl_cafile_env` - OpenSSL's environment key that points to a cafile, + * :attr:`openssl_cafile` - hard coded path to a cafile, + * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath, + * :attr:`openssl_capath` - hard coded path to a capath directory + + .. availability:: LibreSSL ignores the environment vars + :attr:`openssl_cafile_env` and :attr:`openssl_capath_env`. + + .. versionadded:: 3.4 + +.. function:: enum_certificates(store_name) + + Retrieve certificates from Windows' system cert store. *store_name* may be + one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert + stores, too. + + The function returns a list of (cert_bytes, encoding_type, trust) tuples. + The encoding_type specifies the encoding of cert_bytes. It is either + :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for + PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set + of OIDS or exactly ``True`` if the certificate is trustworthy for all + purposes. + + Example:: + + >>> ssl.enum_certificates("CA") + [(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}), + (b'data...', 'x509_asn', True)] + + .. availability:: Windows. + + .. versionadded:: 3.4 + +.. function:: enum_crls(store_name) + + Retrieve CRLs from Windows' system cert store. *store_name* may be + one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert + stores, too. + + The function returns a list of (cert_bytes, encoding_type, trust) tuples. + The encoding_type specifies the encoding of cert_bytes. It is either + :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for + PKCS#7 ASN.1 data. + + .. availability:: Windows. + + .. versionadded:: 3.4 + +.. function:: wrap_socket(sock, keyfile=None, certfile=None, \ + server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_TLS, \ + ca_certs=None, do_handshake_on_connect=True, \ + suppress_ragged_eofs=True, ciphers=None) + + Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance + of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps + the underlying socket in an SSL context. ``sock`` must be a + :data:`~socket.SOCK_STREAM` socket; other socket types are unsupported. + + Internally, function creates a :class:`SSLContext` with protocol + *ssl_version* and :attr:`SSLContext.options` set to *cert_reqs*. If + parameters *keyfile*, *certfile*, *ca_certs* or *ciphers* are set, then + the values are passed to :meth:`SSLContext.load_cert_chain`, + :meth:`SSLContext.load_verify_locations`, and + :meth:`SSLContext.set_ciphers`. + + The arguments *server_side*, *do_handshake_on_connect*, and + *suppress_ragged_eofs* have the same meaning as + :meth:`SSLContext.wrap_socket`. + + .. deprecated:: 3.7 + + Since Python 3.2 and 2.7.9, it is recommended to use the + :meth:`SSLContext.wrap_socket` instead of :func:`wrap_socket`. The + top-level function is limited and creates an insecure client socket + without server name indication or hostname matching. + +Constants +^^^^^^^^^ + + All constants are now :class:`enum.IntEnum` or :class:`enum.IntFlag` collections. + + .. versionadded:: 3.6 + +.. data:: CERT_NONE + + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. Except for :const:`PROTOCOL_TLS_CLIENT`, + it is the default mode. With client-side sockets, just about any + cert is accepted. Validation errors, such as untrusted or expired cert, + are ignored and do not abort the TLS/SSL handshake. + + In server mode, no certificate is requested from the client, so the client + does not send any for client cert authentication. + + See the discussion of :ref:`ssl-security` below. + +.. data:: CERT_OPTIONAL + + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In client mode, :const:`CERT_OPTIONAL` + has the same meaning as :const:`CERT_REQUIRED`. It is recommended to + use :const:`CERT_REQUIRED` for client-side sockets instead. + + In server mode, a client certificate request is sent to the client. The + client may either ignore the request or send a certificate in order + perform TLS client cert authentication. If the client chooses to send + a certificate, it is verified. Any verification error immediately aborts + the TLS handshake. + + Use of this setting requires a valid set of CA certificates to + be passed, either to :meth:`SSLContext.load_verify_locations` or as a + value of the ``ca_certs`` parameter to :func:`wrap_socket`. + +.. data:: CERT_REQUIRED + + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In this mode, certificates are + required from the other side of the socket connection; an :class:`SSLError` + will be raised if no certificate is provided, or if its validation fails. + This mode is **not** sufficient to verify a certificate in client mode as + it does not match hostnames. :attr:`~SSLContext.check_hostname` must be + enabled as well to verify the authenticity of a cert. + :const:`PROTOCOL_TLS_CLIENT` uses :const:`CERT_REQUIRED` and + enables :attr:`~SSLContext.check_hostname` by default. + + With server socket, this mode provides mandatory TLS client cert + authentication. A client certificate request is sent to the client and + the client must provide a valid and trusted certificate. + + Use of this setting requires a valid set of CA certificates to + be passed, either to :meth:`SSLContext.load_verify_locations` or as a + value of the ``ca_certs`` parameter to :func:`wrap_socket`. + +.. class:: VerifyMode + + :class:`enum.IntEnum` collection of CERT_* constants. + + .. versionadded:: 3.6 + +.. data:: VERIFY_DEFAULT + + Possible value for :attr:`SSLContext.verify_flags`. In this mode, certificate + revocation lists (CRLs) are not checked. By default OpenSSL does neither + require nor verify CRLs. + + .. versionadded:: 3.4 + +.. data:: VERIFY_CRL_CHECK_LEAF + + Possible value for :attr:`SSLContext.verify_flags`. In this mode, only the + peer cert is checked but none of the intermediate CA certificates. The mode + requires a valid CRL that is signed by the peer cert's issuer (its direct + ancestor CA). If no proper CRL has has been loaded with + :attr:`SSLContext.load_verify_locations`, validation will fail. + + .. versionadded:: 3.4 + +.. data:: VERIFY_CRL_CHECK_CHAIN + + Possible value for :attr:`SSLContext.verify_flags`. In this mode, CRLs of + all certificates in the peer cert chain are checked. + + .. versionadded:: 3.4 + +.. data:: VERIFY_X509_STRICT + + Possible value for :attr:`SSLContext.verify_flags` to disable workarounds + for broken X.509 certificates. + + .. versionadded:: 3.4 + +.. data:: VERIFY_X509_TRUSTED_FIRST + + Possible value for :attr:`SSLContext.verify_flags`. It instructs OpenSSL to + prefer trusted certificates when building the trust chain to validate a + certificate. This flag is enabled by default. + + .. versionadded:: 3.4.4 + +.. class:: VerifyFlags + + :class:`enum.IntFlag` collection of VERIFY_* constants. + + .. versionadded:: 3.6 + +.. data:: PROTOCOL_TLS + + Selects the highest protocol version that both the client and server support. + Despite the name, this option can select both "SSL" and "TLS" protocols. + + .. versionadded:: 3.6 + +.. data:: PROTOCOL_TLS_CLIENT + + Auto-negotiate the highest protocol version like :data:`PROTOCOL_TLS`, + but only support client-side :class:`SSLSocket` connections. The protocol + enables :data:`CERT_REQUIRED` and :attr:`~SSLContext.check_hostname` by + default. + + .. versionadded:: 3.6 + +.. data:: PROTOCOL_TLS_SERVER + + Auto-negotiate the highest protocol version like :data:`PROTOCOL_TLS`, + but only support server-side :class:`SSLSocket` connections. + + .. versionadded:: 3.6 + +.. data:: PROTOCOL_SSLv23 + + Alias for :data:`PROTOCOL_TLS`. + + .. deprecated:: 3.6 + + Use :data:`PROTOCOL_TLS` instead. + +.. data:: PROTOCOL_SSLv2 + + Selects SSL version 2 as the channel encryption protocol. + + This protocol is not available if OpenSSL is compiled with the + ``OPENSSL_NO_SSL2`` flag. + + .. warning:: + + SSL version 2 is insecure. Its use is highly discouraged. + + .. deprecated:: 3.6 + + OpenSSL has removed support for SSLv2. + +.. data:: PROTOCOL_SSLv3 + + Selects SSL version 3 as the channel encryption protocol. + + This protocol is not be available if OpenSSL is compiled with the + ``OPENSSL_NO_SSLv3`` flag. + + .. warning:: + + SSL version 3 is insecure. Its use is highly discouraged. + + .. deprecated:: 3.6 + + OpenSSL has deprecated all version specific protocols. Use the default + protocol :data:`PROTOCOL_TLS` with flags like :data:`OP_NO_SSLv3` instead. + +.. data:: PROTOCOL_TLSv1 + + Selects TLS version 1.0 as the channel encryption protocol. + + .. deprecated:: 3.6 + + OpenSSL has deprecated all version specific protocols. Use the default + protocol :data:`PROTOCOL_TLS` with flags like :data:`OP_NO_SSLv3` instead. + +.. data:: PROTOCOL_TLSv1_1 + + Selects TLS version 1.1 as the channel encryption protocol. + Available only with openssl version 1.0.1+. + + .. versionadded:: 3.4 + + .. deprecated:: 3.6 + + OpenSSL has deprecated all version specific protocols. Use the default + protocol :data:`PROTOCOL_TLS` with flags like :data:`OP_NO_SSLv3` instead. + +.. data:: PROTOCOL_TLSv1_2 + + Selects TLS version 1.2 as the channel encryption protocol. This is the + most modern version, and probably the best choice for maximum protection, + if both sides can speak it. Available only with openssl version 1.0.1+. + + .. versionadded:: 3.4 + + .. deprecated:: 3.6 + + OpenSSL has deprecated all version specific protocols. Use the default + protocol :data:`PROTOCOL_TLS` with flags like :data:`OP_NO_SSLv3` instead. + +.. data:: OP_ALL + + Enables workarounds for various bugs present in other SSL implementations. + This option is set by default. It does not necessarily set the same + flags as OpenSSL's ``SSL_OP_ALL`` constant. + + .. versionadded:: 3.2 + +.. data:: OP_NO_SSLv2 + + Prevents an SSLv2 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_TLS`. It prevents the peers from + choosing SSLv2 as the protocol version. + + .. versionadded:: 3.2 + + .. deprecated:: 3.6 + + SSLv2 is deprecated + + +.. data:: OP_NO_SSLv3 + + Prevents an SSLv3 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_TLS`. It prevents the peers from + choosing SSLv3 as the protocol version. + + .. versionadded:: 3.2 + + .. deprecated:: 3.6 + + SSLv3 is deprecated + +.. data:: OP_NO_TLSv1 + + Prevents a TLSv1 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_TLS`. It prevents the peers from + choosing TLSv1 as the protocol version. + + .. versionadded:: 3.2 + + .. deprecated:: 3.7 + The option is deprecated since OpenSSL 1.1.0, use the new + :attr:`SSLContext.minimum_version` and + :attr:`SSLContext.maximum_version` instead. + +.. data:: OP_NO_TLSv1_1 + + Prevents a TLSv1.1 connection. This option is only applicable in conjunction + with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.1 as + the protocol version. Available only with openssl version 1.0.1+. + + .. versionadded:: 3.4 + + .. deprecated:: 3.7 + The option is deprecated since OpenSSL 1.1.0. + +.. data:: OP_NO_TLSv1_2 + + Prevents a TLSv1.2 connection. This option is only applicable in conjunction + with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.2 as + the protocol version. Available only with openssl version 1.0.1+. + + .. versionadded:: 3.4 + + .. deprecated:: 3.7 + The option is deprecated since OpenSSL 1.1.0. + +.. data:: OP_NO_TLSv1_3 + + Prevents a TLSv1.3 connection. This option is only applicable in conjunction + with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.3 as + the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later. + When Python has been compiled against an older version of OpenSSL, the + flag defaults to *0*. + + .. versionadded:: 3.7 + + .. deprecated:: 3.7 + The option is deprecated since OpenSSL 1.1.0. It was added to 2.7.15, + 3.6.3 and 3.7.0 for backwards compatibility with OpenSSL 1.0.2. + +.. data:: OP_NO_RENEGOTIATION + + Disable all renegotiation in TLSv1.2 and earlier. Do not send + HelloRequest messages, and ignore renegotiation requests via ClientHello. + + This option is only available with OpenSSL 1.1.0h and later. + + .. versionadded:: 3.7 + +.. data:: OP_CIPHER_SERVER_PREFERENCE + + Use the server's cipher ordering preference, rather than the client's. + This option has no effect on client sockets and SSLv2 server sockets. + + .. versionadded:: 3.3 + +.. data:: OP_SINGLE_DH_USE + + Prevents re-use of the same DH key for distinct SSL sessions. This + improves forward secrecy but requires more computational resources. + This option only applies to server sockets. + + .. versionadded:: 3.3 + +.. data:: OP_SINGLE_ECDH_USE + + Prevents re-use of the same ECDH key for distinct SSL sessions. This + improves forward secrecy but requires more computational resources. + This option only applies to server sockets. + + .. versionadded:: 3.3 + +.. data:: OP_ENABLE_MIDDLEBOX_COMPAT + + Send dummy Change Cipher Spec (CCS) messages in TLS 1.3 handshake to make + a TLS 1.3 connection look more like a TLS 1.2 connection. + + This option is only available with OpenSSL 1.1.1 and later. + + .. versionadded:: 3.8 + +.. data:: OP_NO_COMPRESSION + + Disable compression on the SSL channel. This is useful if the application + protocol supports its own compression scheme. + + This option is only available with OpenSSL 1.0.0 and later. + + .. versionadded:: 3.3 + +.. class:: Options + + :class:`enum.IntFlag` collection of OP_* constants. + +.. data:: OP_NO_TICKET + + Prevent client side from requesting a session ticket. + + .. versionadded:: 3.6 + +.. data:: HAS_ALPN + + Whether the OpenSSL library has built-in support for the *Application-Layer + Protocol Negotiation* TLS extension as described in :rfc:`7301`. + + .. versionadded:: 3.5 + +.. data:: HAS_NEVER_CHECK_COMMON_NAME + + Whether the OpenSSL library has built-in support not checking subject + common name and :attr:`SSLContext.hostname_checks_common_name` is + writeable. + + .. versionadded:: 3.7 + +.. data:: HAS_ECDH + + Whether the OpenSSL library has built-in support for the Elliptic Curve-based + Diffie-Hellman key exchange. This should be true unless the feature was + explicitly disabled by the distributor. + + .. versionadded:: 3.3 + +.. data:: HAS_SNI + + Whether the OpenSSL library has built-in support for the *Server Name + Indication* extension (as defined in :rfc:`6066`). + + .. versionadded:: 3.2 + +.. data:: HAS_NPN + + Whether the OpenSSL library has built-in support for the *Next Protocol + Negotiation* as described in the `Application Layer Protocol + Negotiation `_. + When true, you can use the :meth:`SSLContext.set_npn_protocols` method to advertise + which protocols you want to support. + + .. versionadded:: 3.3 + +.. data:: HAS_SSLv2 + + Whether the OpenSSL library has built-in support for the SSL 2.0 protocol. + + .. versionadded:: 3.7 + +.. data:: HAS_SSLv3 + + Whether the OpenSSL library has built-in support for the SSL 3.0 protocol. + + .. versionadded:: 3.7 + +.. data:: HAS_TLSv1 + + Whether the OpenSSL library has built-in support for the TLS 1.0 protocol. + + .. versionadded:: 3.7 + +.. data:: HAS_TLSv1_1 + + Whether the OpenSSL library has built-in support for the TLS 1.1 protocol. + + .. versionadded:: 3.7 + +.. data:: HAS_TLSv1_2 + + Whether the OpenSSL library has built-in support for the TLS 1.2 protocol. + + .. versionadded:: 3.7 + +.. data:: HAS_TLSv1_3 + + Whether the OpenSSL library has built-in support for the TLS 1.3 protocol. + + .. versionadded:: 3.7 + +.. data:: CHANNEL_BINDING_TYPES + + List of supported TLS channel binding types. Strings in this list + can be used as arguments to :meth:`SSLSocket.get_channel_binding`. + + .. versionadded:: 3.3 + +.. data:: OPENSSL_VERSION + + The version string of the OpenSSL library loaded by the interpreter:: + + >>> ssl.OPENSSL_VERSION + 'OpenSSL 1.0.2k 26 Jan 2017' + + .. versionadded:: 3.2 + +.. data:: OPENSSL_VERSION_INFO + + A tuple of five integers representing version information about the + OpenSSL library:: + + >>> ssl.OPENSSL_VERSION_INFO + (1, 0, 2, 11, 15) + + .. versionadded:: 3.2 + +.. data:: OPENSSL_VERSION_NUMBER + + The raw version number of the OpenSSL library, as a single integer:: + + >>> ssl.OPENSSL_VERSION_NUMBER + 268443839 + >>> hex(ssl.OPENSSL_VERSION_NUMBER) + '0x100020bf' + + .. versionadded:: 3.2 + +.. data:: ALERT_DESCRIPTION_HANDSHAKE_FAILURE + ALERT_DESCRIPTION_INTERNAL_ERROR + ALERT_DESCRIPTION_* + + Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry + `_ + contains this list and references to the RFCs where their meaning is defined. + + Used as the return value of the callback function in + :meth:`SSLContext.set_servername_callback`. + + .. versionadded:: 3.4 + +.. class:: AlertDescription + + :class:`enum.IntEnum` collection of ALERT_DESCRIPTION_* constants. + + .. versionadded:: 3.6 + +.. data:: Purpose.SERVER_AUTH + + Option for :func:`create_default_context` and + :meth:`SSLContext.load_default_certs`. This value indicates that the + context may be used to authenticate Web servers (therefore, it will + be used to create client-side sockets). + + .. versionadded:: 3.4 + +.. data:: Purpose.CLIENT_AUTH + + Option for :func:`create_default_context` and + :meth:`SSLContext.load_default_certs`. This value indicates that the + context may be used to authenticate Web clients (therefore, it will + be used to create server-side sockets). + + .. versionadded:: 3.4 + +.. class:: SSLErrorNumber + + :class:`enum.IntEnum` collection of SSL_ERROR_* constants. + + .. versionadded:: 3.6 + +.. class:: TLSVersion + + :class:`enum.IntEnum` collection of SSL and TLS versions for + :attr:`SSLContext.maximum_version` and :attr:`SSLContext.minimum_version`. + + .. versionadded:: 3.7 + +.. attribute:: TLSVersion.MINIMUM_SUPPORTED +.. attribute:: TLSVersion.MAXIMUM_SUPPORTED + + The minimum or maximum supported SSL or TLS version. These are magic + constants. Their values don't reflect the lowest and highest available + TLS/SSL versions. + +.. attribute:: TLSVersion.SSLv3 +.. attribute:: TLSVersion.TLSv1 +.. attribute:: TLSVersion.TLSv1_1 +.. attribute:: TLSVersion.TLSv1_2 +.. attribute:: TLSVersion.TLSv1_3 + + SSL 3.0 to TLS 1.3. + + +SSL Sockets +----------- + +.. class:: SSLSocket(socket.socket) + + SSL sockets provide the following methods of :ref:`socket-objects`: + + - :meth:`~socket.socket.accept()` + - :meth:`~socket.socket.bind()` + - :meth:`~socket.socket.close()` + - :meth:`~socket.socket.connect()` + - :meth:`~socket.socket.detach()` + - :meth:`~socket.socket.fileno()` + - :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()` + - :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()` + - :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`, + :meth:`~socket.socket.setblocking()` + - :meth:`~socket.socket.listen()` + - :meth:`~socket.socket.makefile()` + - :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()` + (but passing a non-zero ``flags`` argument is not allowed) + - :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with + the same limitation) + - :meth:`~socket.socket.sendfile()` (but :mod:`os.sendfile` will be used + for plain-text sockets only, else :meth:`~socket.socket.send()` will be used) + - :meth:`~socket.socket.shutdown()` + + However, since the SSL (and TLS) protocol has its own framing atop + of TCP, the SSL sockets abstraction can, in certain respects, diverge from + the specification of normal, OS-level sockets. See especially the + :ref:`notes on non-blocking sockets `. + + Instances of :class:`SSLSocket` must be created using the + :meth:`SSLContext.wrap_socket` method. + + .. versionchanged:: 3.5 + The :meth:`sendfile` method was added. + + .. versionchanged:: 3.5 + The :meth:`shutdown` does not reset the socket timeout each time bytes + are received or sent. The socket timeout is now to maximum total duration + of the shutdown. + + .. deprecated:: 3.6 + It is deprecated to create a :class:`SSLSocket` instance directly, use + :meth:`SSLContext.wrap_socket` to wrap a socket. + + .. versionchanged:: 3.7 + :class:`SSLSocket` instances must to created with + :meth:`~SSLContext.wrap_socket`. In earlier versions, it was possible + to create instances directly. This was never documented or officially + supported. + +SSL sockets also have the following additional methods and attributes: + +.. method:: SSLSocket.read(len=1024, buffer=None) + + Read up to *len* bytes of data from the SSL socket and return the result as + a ``bytes`` instance. If *buffer* is specified, then read into the buffer + instead, and return the number of bytes read. + + Raise :exc:`SSLWantReadError` or :exc:`SSLWantWriteError` if the socket is + :ref:`non-blocking ` and the read would block. + + As at any time a re-negotiation is possible, a call to :meth:`read` can also + cause write operations. + + .. versionchanged:: 3.5 + The socket timeout is no more reset each time bytes are received or sent. + The socket timeout is now to maximum total duration to read up to *len* + bytes. + + .. deprecated:: 3.6 + Use :meth:`~SSLSocket.recv` instead of :meth:`~SSLSocket.read`. + +.. method:: SSLSocket.write(buf) + + Write *buf* to the SSL socket and return the number of bytes written. The + *buf* argument must be an object supporting the buffer interface. + + Raise :exc:`SSLWantReadError` or :exc:`SSLWantWriteError` if the socket is + :ref:`non-blocking ` and the write would block. + + As at any time a re-negotiation is possible, a call to :meth:`write` can + also cause read operations. + + .. versionchanged:: 3.5 + The socket timeout is no more reset each time bytes are received or sent. + The socket timeout is now to maximum total duration to write *buf*. + + .. deprecated:: 3.6 + Use :meth:`~SSLSocket.send` instead of :meth:`~SSLSocket.write`. + +.. note:: + + The :meth:`~SSLSocket.read` and :meth:`~SSLSocket.write` methods are the + low-level methods that read and write unencrypted, application-level data + and decrypt/encrypt it to encrypted, wire-level data. These methods + require an active SSL connection, i.e. the handshake was completed and + :meth:`SSLSocket.unwrap` was not called. + + Normally you should use the socket API methods like + :meth:`~socket.socket.recv` and :meth:`~socket.socket.send` instead of these + methods. + +.. method:: SSLSocket.do_handshake() + + Perform the SSL setup handshake. + + .. versionchanged:: 3.4 + The handshake method also performs :func:`match_hostname` when the + :attr:`~SSLContext.check_hostname` attribute of the socket's + :attr:`~SSLSocket.context` is true. + + .. versionchanged:: 3.5 + The socket timeout is no more reset each time bytes are received or sent. + The socket timeout is now to maximum total duration of the handshake. + + .. versionchanged:: 3.7 + Hostname or IP address is matched by OpenSSL during handshake. The + function :func:`match_hostname` is no longer used. In case OpenSSL + refuses a hostname or IP address, the handshake is aborted early and + a TLS alert message is send to the peer. + +.. method:: SSLSocket.getpeercert(binary_form=False) + + If there is no certificate for the peer on the other end of the connection, + return ``None``. If the SSL handshake hasn't been done yet, raise + :exc:`ValueError`. + + If the ``binary_form`` parameter is :const:`False`, and a certificate was + received from the peer, this method returns a :class:`dict` instance. If the + certificate was not validated, the dict is empty. If the certificate was + validated, it returns a dict with several keys, amongst them ``subject`` + (the principal for which the certificate was issued) and ``issuer`` + (the principal issuing the certificate). If a certificate contains an + instance of the *Subject Alternative Name* extension (see :rfc:`3280`), + there will also be a ``subjectAltName`` key in the dictionary. + + The ``subject`` and ``issuer`` fields are tuples containing the sequence + of relative distinguished names (RDNs) given in the certificate's data + structure for the respective fields, and each RDN is a sequence of + name-value pairs. Here is a real-world example:: + + {'issuer': ((('countryName', 'IL'),), + (('organizationName', 'StartCom Ltd.'),), + (('organizationalUnitName', + 'Secure Digital Certificate Signing'),), + (('commonName', + 'StartCom Class 2 Primary Intermediate Server CA'),)), + 'notAfter': 'Nov 22 08:15:19 2013 GMT', + 'notBefore': 'Nov 21 03:09:52 2011 GMT', + 'serialNumber': '95F0', + 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),), + (('countryName', 'US'),), + (('stateOrProvinceName', 'California'),), + (('localityName', 'San Francisco'),), + (('organizationName', 'Electronic Frontier Foundation, Inc.'),), + (('commonName', '*.eff.org'),), + (('emailAddress', 'hostmaster@eff.org'),)), + 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')), + 'version': 3} + + .. note:: + + To validate a certificate for a particular service, you can use the + :func:`match_hostname` function. + + If the ``binary_form`` parameter is :const:`True`, and a certificate was + provided, this method returns the DER-encoded form of the entire certificate + as a sequence of bytes, or :const:`None` if the peer did not provide a + certificate. Whether the peer provides a certificate depends on the SSL + socket's role: + + * for a client SSL socket, the server will always provide a certificate, + regardless of whether validation was required; + + * for a server SSL socket, the client will only provide a certificate + when requested by the server; therefore :meth:`getpeercert` will return + :const:`None` if you used :const:`CERT_NONE` (rather than + :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`). + + .. versionchanged:: 3.2 + The returned dictionary includes additional items such as ``issuer`` + and ``notBefore``. + + .. versionchanged:: 3.4 + :exc:`ValueError` is raised when the handshake isn't done. + The returned dictionary includes additional X509v3 extension items + such as ``crlDistributionPoints``, ``caIssuers`` and ``OCSP`` URIs. + + .. versionchanged:: 3.9 + IPv6 address strings no longer have a trailing new line. + +.. method:: SSLSocket.cipher() + + Returns a three-value tuple containing the name of the cipher being used, the + version of the SSL protocol that defines its use, and the number of secret + bits being used. If no connection has been established, returns ``None``. + +.. method:: SSLSocket.shared_ciphers() + + Return the list of ciphers shared by the client during the handshake. Each + entry of the returned list is a three-value tuple containing the name of the + cipher, the version of the SSL protocol that defines its use, and the number + of secret bits the cipher uses. :meth:`~SSLSocket.shared_ciphers` returns + ``None`` if no connection has been established or the socket is a client + socket. + + .. versionadded:: 3.5 + +.. method:: SSLSocket.compression() + + Return the compression algorithm being used as a string, or ``None`` + if the connection isn't compressed. + + If the higher-level protocol supports its own compression mechanism, + you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression. + + .. versionadded:: 3.3 + +.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique") + + Get channel binding data for current connection, as a bytes object. Returns + ``None`` if not connected or the handshake has not been completed. + + The *cb_type* parameter allow selection of the desired channel binding + type. Valid channel binding types are listed in the + :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel + binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be + raised if an unsupported channel binding type is requested. + + .. versionadded:: 3.3 + +.. method:: SSLSocket.selected_alpn_protocol() + + Return the protocol that was selected during the TLS handshake. If + :meth:`SSLContext.set_alpn_protocols` was not called, if the other party does + not support ALPN, if this socket does not support any of the client's + proposed protocols, or if the handshake has not happened yet, ``None`` is + returned. + + .. versionadded:: 3.5 + +.. method:: SSLSocket.selected_npn_protocol() + + Return the higher-level protocol that was selected during the TLS/SSL + handshake. If :meth:`SSLContext.set_npn_protocols` was not called, or + if the other party does not support NPN, or if the handshake has not yet + happened, this will return ``None``. + + .. versionadded:: 3.3 + +.. method:: SSLSocket.unwrap() + + Performs the SSL shutdown handshake, which removes the TLS layer from the + underlying socket, and returns the underlying socket object. This can be + used to go from encrypted operation over a connection to unencrypted. The + returned socket should always be used for further communication with the + other side of the connection, rather than the original socket. + +.. method:: SSLSocket.verify_client_post_handshake() + + Requests post-handshake authentication (PHA) from a TLS 1.3 client. PHA + can only be initiated for a TLS 1.3 connection from a server-side socket, + after the initial TLS handshake and with PHA enabled on both sides, see + :attr:`SSLContext.post_handshake_auth`. + + The method does not perform a cert exchange immediately. The server-side + sends a CertificateRequest during the next write event and expects the + client to respond with a certificate on the next read event. + + If any precondition isn't met (e.g. not TLS 1.3, PHA not enabled), an + :exc:`SSLError` is raised. + + .. note:: + Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 + support, the method raises :exc:`NotImplementedError`. + + .. versionadded:: 3.8 + +.. method:: SSLSocket.version() + + Return the actual SSL protocol version negotiated by the connection + as a string, or ``None`` is no secure connection is established. + As of this writing, possible return values include ``"SSLv2"``, + ``"SSLv3"``, ``"TLSv1"``, ``"TLSv1.1"`` and ``"TLSv1.2"``. + Recent OpenSSL versions may define more return values. + + .. versionadded:: 3.5 + +.. method:: SSLSocket.pending() + + Returns the number of already decrypted bytes available for read, pending on + the connection. + +.. attribute:: SSLSocket.context + + The :class:`SSLContext` object this SSL socket is tied to. If the SSL + socket was created using the deprecated :func:`wrap_socket` function + (rather than :meth:`SSLContext.wrap_socket`), this is a custom context + object created for this SSL socket. + + .. versionadded:: 3.2 + +.. attribute:: SSLSocket.server_side + + A boolean which is ``True`` for server-side sockets and ``False`` for + client-side sockets. + + .. versionadded:: 3.2 + +.. attribute:: SSLSocket.server_hostname + + Hostname of the server: :class:`str` type, or ``None`` for server-side + socket or if the hostname was not specified in the constructor. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.7 + The attribute is now always ASCII text. When ``server_hostname`` is + an internationalized domain name (IDN), this attribute now stores the + A-label form (``"xn--pythn-mua.org"``), rather than the U-label form + (``"pythön.org"``). + +.. attribute:: SSLSocket.session + + The :class:`SSLSession` for this SSL connection. The session is available + for client and server side sockets after the TLS handshake has been + performed. For client sockets the session can be set before + :meth:`~SSLSocket.do_handshake` has been called to reuse a session. + + .. versionadded:: 3.6 + +.. attribute:: SSLSocket.session_reused + + .. versionadded:: 3.6 + + +SSL Contexts +------------ + +.. versionadded:: 3.2 + +An SSL context holds various data longer-lived than single SSL connections, +such as SSL configuration options, certificate(s) and private key(s). +It also manages a cache of SSL sessions for server-side sockets, in order +to speed up repeated connections from the same clients. + +.. class:: SSLContext(protocol=PROTOCOL_TLS) + + Create a new SSL context. You may pass *protocol* which must be one + of the ``PROTOCOL_*`` constants defined in this module. The parameter + specifies which version of the SSL protocol to use. Typically, the + server chooses a particular protocol version, and the client must adapt + to the server's choice. Most of the versions are not interoperable + with the other versions. If not specified, the default is + :data:`PROTOCOL_TLS`; it provides the most compatibility with other + versions. + + Here's a table showing which versions in a client (down the side) can connect + to which versions in a server (along the top): + + .. table:: + + ======================== ============ ============ ============= ========= =========== =========== + *client* / **server** **SSLv2** **SSLv3** **TLS** [3]_ **TLSv1** **TLSv1.1** **TLSv1.2** + ------------------------ ------------ ------------ ------------- --------- ----------- ----------- + *SSLv2* yes no no [1]_ no no no + *SSLv3* no yes no [2]_ no no no + *TLS* (*SSLv23*) [3]_ no [1]_ no [2]_ yes yes yes yes + *TLSv1* no no yes yes no no + *TLSv1.1* no no yes no yes no + *TLSv1.2* no no yes no no yes + ======================== ============ ============ ============= ========= =========== =========== + + .. rubric:: Footnotes + .. [1] :class:`SSLContext` disables SSLv2 with :data:`OP_NO_SSLv2` by default. + .. [2] :class:`SSLContext` disables SSLv3 with :data:`OP_NO_SSLv3` by default. + .. [3] TLS 1.3 protocol will be available with :data:`PROTOCOL_TLS` in + OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just + TLS 1.3. + + .. seealso:: + :func:`create_default_context` lets the :mod:`ssl` module choose + security settings for a given purpose. + + .. versionchanged:: 3.6 + + The context is created with secure default values. The options + :data:`OP_NO_COMPRESSION`, :data:`OP_CIPHER_SERVER_PREFERENCE`, + :data:`OP_SINGLE_DH_USE`, :data:`OP_SINGLE_ECDH_USE`, + :data:`OP_NO_SSLv2` (except for :data:`PROTOCOL_SSLv2`), + and :data:`OP_NO_SSLv3` (except for :data:`PROTOCOL_SSLv3`) are + set by default. The initial cipher suite list contains only ``HIGH`` + ciphers, no ``NULL`` ciphers and no ``MD5`` ciphers (except for + :data:`PROTOCOL_SSLv2`). + + +:class:`SSLContext` objects have the following methods and attributes: + +.. method:: SSLContext.cert_store_stats() + + Get statistics about quantities of loaded X.509 certificates, count of + X.509 certificates flagged as CA certificates and certificate revocation + lists as dictionary. + + Example for a context with one CA cert and one other cert:: + + >>> context.cert_store_stats() + {'crl': 0, 'x509_ca': 1, 'x509': 2} + + .. versionadded:: 3.4 + + +.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None) + + Load a private key and the corresponding certificate. The *certfile* + string must be the path to a single file in PEM format containing the + certificate as well as any number of CA certificates needed to establish + the certificate's authenticity. The *keyfile* string, if present, must + point to a file containing the private key in. Otherwise the private + key will be taken from *certfile* as well. See the discussion of + :ref:`ssl-certificates` for more information on how the certificate + is stored in the *certfile*. + + The *password* argument may be a function to call to get the password for + decrypting the private key. It will only be called if the private key is + encrypted and a password is necessary. It will be called with no arguments, + and it should return a string, bytes, or bytearray. If the return value is + a string it will be encoded as UTF-8 before using it to decrypt the key. + Alternatively a string, bytes, or bytearray value may be supplied directly + as the *password* argument. It will be ignored if the private key is not + encrypted and no password is needed. + + If the *password* argument is not specified and a password is required, + OpenSSL's built-in password prompting mechanism will be used to + interactively prompt the user for a password. + + An :class:`SSLError` is raised if the private key doesn't + match with the certificate. + + .. versionchanged:: 3.3 + New optional argument *password*. + +.. method:: SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH) + + Load a set of default "certification authority" (CA) certificates from + default locations. On Windows it loads CA certs from the ``CA`` and + ``ROOT`` system stores. On other systems it calls + :meth:`SSLContext.set_default_verify_paths`. In the future the method may + load CA certificates from other locations, too. + + The *purpose* flag specifies what kind of CA certificates are loaded. The + default settings :data:`Purpose.SERVER_AUTH` loads certificates, that are + flagged and trusted for TLS web server authentication (client side + sockets). :data:`Purpose.CLIENT_AUTH` loads CA certificates for client + certificate verification on the server side. + + .. versionadded:: 3.4 + +.. method:: SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None) + + Load a set of "certification authority" (CA) certificates used to validate + other peers' certificates when :data:`verify_mode` is other than + :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified. + + This method can also load certification revocation lists (CRLs) in PEM or + DER format. In order to make use of CRLs, :attr:`SSLContext.verify_flags` + must be configured properly. + + The *cafile* string, if present, is the path to a file of concatenated + CA certificates in PEM format. See the discussion of + :ref:`ssl-certificates` for more information about how to arrange the + certificates in this file. + + The *capath* string, if present, is + the path to a directory containing several CA certificates in PEM format, + following an `OpenSSL specific layout + `_. + + The *cadata* object, if present, is either an ASCII string of one or more + PEM-encoded certificates or a :term:`bytes-like object` of DER-encoded + certificates. Like with *capath* extra lines around PEM-encoded + certificates are ignored but at least one certificate must be present. + + .. versionchanged:: 3.4 + New optional argument *cadata* + +.. method:: SSLContext.get_ca_certs(binary_form=False) + + Get a list of loaded "certification authority" (CA) certificates. If the + ``binary_form`` parameter is :const:`False` each list + entry is a dict like the output of :meth:`SSLSocket.getpeercert`. Otherwise + the method returns a list of DER-encoded certificates. The returned list + does not contain certificates from *capath* unless a certificate was + requested and loaded by a SSL connection. + + .. note:: + Certificates in a capath directory aren't loaded unless they have + been used at least once. + + .. versionadded:: 3.4 + +.. method:: SSLContext.get_ciphers() + + Get a list of enabled ciphers. The list is in order of cipher priority. + See :meth:`SSLContext.set_ciphers`. + + Example:: + + >>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + >>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA') + >>> ctx.get_ciphers() # OpenSSL 1.0.x + [{'alg_bits': 256, + 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' + 'Enc=AESGCM(256) Mac=AEAD', + 'id': 50380848, + 'name': 'ECDHE-RSA-AES256-GCM-SHA384', + 'protocol': 'TLSv1/SSLv3', + 'strength_bits': 256}, + {'alg_bits': 128, + 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' + 'Enc=AESGCM(128) Mac=AEAD', + 'id': 50380847, + 'name': 'ECDHE-RSA-AES128-GCM-SHA256', + 'protocol': 'TLSv1/SSLv3', + 'strength_bits': 128}] + + On OpenSSL 1.1 and newer the cipher dict contains additional fields:: + + >>> ctx.get_ciphers() # OpenSSL 1.1+ + [{'aead': True, + 'alg_bits': 256, + 'auth': 'auth-rsa', + 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' + 'Enc=AESGCM(256) Mac=AEAD', + 'digest': None, + 'id': 50380848, + 'kea': 'kx-ecdhe', + 'name': 'ECDHE-RSA-AES256-GCM-SHA384', + 'protocol': 'TLSv1.2', + 'strength_bits': 256, + 'symmetric': 'aes-256-gcm'}, + {'aead': True, + 'alg_bits': 128, + 'auth': 'auth-rsa', + 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' + 'Enc=AESGCM(128) Mac=AEAD', + 'digest': None, + 'id': 50380847, + 'kea': 'kx-ecdhe', + 'name': 'ECDHE-RSA-AES128-GCM-SHA256', + 'protocol': 'TLSv1.2', + 'strength_bits': 128, + 'symmetric': 'aes-128-gcm'}] + + .. availability:: OpenSSL 1.0.2+. + + .. versionadded:: 3.6 + +.. method:: SSLContext.set_default_verify_paths() + + Load a set of default "certification authority" (CA) certificates from + a filesystem path defined when building the OpenSSL library. Unfortunately, + there's no easy way to know whether this method succeeds: no error is + returned if no certificates are to be found. When the OpenSSL library is + provided as part of the operating system, though, it is likely to be + configured properly. + +.. method:: SSLContext.set_ciphers(ciphers) + + Set the available ciphers for sockets created with this context. + It should be a string in the `OpenSSL cipher list format + `_. + If no cipher can be selected (because compile-time options or other + configuration forbids use of all the specified ciphers), an + :class:`SSLError` will be raised. + + .. note:: + when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will + give the currently selected cipher. + + OpenSSL 1.1.1 has TLS 1.3 cipher suites enabled by default. The suites + cannot be disabled with :meth:`~SSLContext.set_ciphers`. + +.. method:: SSLContext.set_alpn_protocols(protocols) + + Specify which protocols the socket should advertise during the SSL/TLS + handshake. It should be a list of ASCII strings, like ``['http/1.1', + 'spdy/2']``, ordered by preference. The selection of a protocol will happen + during the handshake, and will play out according to :rfc:`7301`. After a + successful handshake, the :meth:`SSLSocket.selected_alpn_protocol` method will + return the agreed-upon protocol. + + This method will raise :exc:`NotImplementedError` if :data:`HAS_ALPN` is + ``False``. + + OpenSSL 1.1.0 to 1.1.0e will abort the handshake and raise :exc:`SSLError` + when both sides support ALPN but cannot agree on a protocol. 1.1.0f+ + behaves like 1.0.2, :meth:`SSLSocket.selected_alpn_protocol` returns None. + + .. versionadded:: 3.5 + +.. method:: SSLContext.set_npn_protocols(protocols) + + Specify which protocols the socket should advertise during the SSL/TLS + handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``, + ordered by preference. The selection of a protocol will happen during the + handshake, and will play out according to the `Application Layer Protocol Negotiation + `_. After a + successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will + return the agreed-upon protocol. + + This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is + ``False``. + + .. versionadded:: 3.3 + +.. attribute:: SSLContext.sni_callback + + Register a callback function that will be called after the TLS Client Hello + handshake message has been received by the SSL/TLS server when the TLS client + specifies a server name indication. The server name indication mechanism + is specified in :rfc:`6066` section 3 - Server Name Indication. + + Only one callback can be set per ``SSLContext``. If *sni_callback* + is set to ``None`` then the callback is disabled. Calling this function a + subsequent time will disable the previously registered callback. + + The callback function will be called with three + arguments; the first being the :class:`ssl.SSLSocket`, the second is a string + that represents the server name that the client is intending to communicate + (or :const:`None` if the TLS Client Hello does not contain a server name) + and the third argument is the original :class:`SSLContext`. The server name + argument is text. For internationalized domain name, the server + name is an IDN A-label (``"xn--pythn-mua.org"``). + + A typical use of this callback is to change the :class:`ssl.SSLSocket`'s + :attr:`SSLSocket.context` attribute to a new object of type + :class:`SSLContext` representing a certificate chain that matches the server + name. + + Due to the early negotiation phase of the TLS connection, only limited + methods and attributes are usable like + :meth:`SSLSocket.selected_alpn_protocol` and :attr:`SSLSocket.context`. + :meth:`SSLSocket.getpeercert`, :meth:`SSLSocket.getpeercert`, + :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compress` methods require that + the TLS connection has progressed beyond the TLS Client Hello and therefore + will not contain return meaningful values nor can they be called safely. + + The *sni_callback* function must return ``None`` to allow the + TLS negotiation to continue. If a TLS failure is required, a constant + :const:`ALERT_DESCRIPTION_* ` can be + returned. Other return values will result in a TLS fatal error with + :const:`ALERT_DESCRIPTION_INTERNAL_ERROR`. + + If an exception is raised from the *sni_callback* function the TLS + connection will terminate with a fatal TLS alert message + :const:`ALERT_DESCRIPTION_HANDSHAKE_FAILURE`. + + This method will raise :exc:`NotImplementedError` if the OpenSSL library + had OPENSSL_NO_TLSEXT defined when it was built. + + .. versionadded:: 3.7 + +.. attribute:: SSLContext.set_servername_callback(server_name_callback) + + This is a legacy API retained for backwards compatibility. When possible, + you should use :attr:`sni_callback` instead. The given *server_name_callback* + is similar to *sni_callback*, except that when the server hostname is an + IDN-encoded internationalized domain name, the *server_name_callback* + receives a decoded U-label (``"pythön.org"``). + + If there is an decoding error on the server name, the TLS connection will + terminate with an :const:`ALERT_DESCRIPTION_INTERNAL_ERROR` fatal TLS + alert message to the client. + + .. versionadded:: 3.4 + +.. method:: SSLContext.load_dh_params(dhfile) + + Load the key generation parameters for Diffie-Hellman (DH) key exchange. + Using DH key exchange improves forward secrecy at the expense of + computational resources (both on the server and on the client). + The *dhfile* parameter should be the path to a file containing DH + parameters in PEM format. + + This setting doesn't apply to client sockets. You can also use the + :data:`OP_SINGLE_DH_USE` option to further improve security. + + .. versionadded:: 3.3 + +.. method:: SSLContext.set_ecdh_curve(curve_name) + + Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key + exchange. ECDH is significantly faster than regular DH while arguably + as secure. The *curve_name* parameter should be a string describing + a well-known elliptic curve, for example ``prime256v1`` for a widely + supported curve. + + This setting doesn't apply to client sockets. You can also use the + :data:`OP_SINGLE_ECDH_USE` option to further improve security. + + This method is not available if :data:`HAS_ECDH` is ``False``. + + .. versionadded:: 3.3 + + .. seealso:: + `SSL/TLS & Perfect Forward Secrecy `_ + Vincent Bernat. + +.. method:: SSLContext.wrap_socket(sock, server_side=False, \ + do_handshake_on_connect=True, suppress_ragged_eofs=True, \ + server_hostname=None, session=None) + + Wrap an existing Python socket *sock* and return an instance of + :attr:`SSLContext.sslsocket_class` (default :class:`SSLSocket`). The + returned SSL socket is tied to the context, its settings and certificates. + *sock* must be a :data:`~socket.SOCK_STREAM` socket; other + socket types are unsupported. + + The parameter ``server_side`` is a boolean which identifies whether + server-side or client-side behavior is desired from this socket. + + For client-side sockets, the context construction is lazy; if the + underlying socket isn't connected yet, the context construction will be + performed after :meth:`connect` is called on the socket. For + server-side sockets, if the socket has no remote peer, it is assumed + to be a listening socket, and the server-side SSL wrapping is + automatically performed on client connections accepted via the + :meth:`accept` method. The method may raise :exc:`SSLError`. + + On client connections, the optional parameter *server_hostname* specifies + the hostname of the service which we are connecting to. This allows a + single server to host multiple SSL-based services with distinct certificates, + quite similarly to HTTP virtual hosts. Specifying *server_hostname* will + raise a :exc:`ValueError` if *server_side* is true. + + The parameter ``do_handshake_on_connect`` specifies whether to do the SSL + handshake automatically after doing a :meth:`socket.connect`, or whether the + application program will call it explicitly, by invoking the + :meth:`SSLSocket.do_handshake` method. Calling + :meth:`SSLSocket.do_handshake` explicitly gives the program control over the + blocking behavior of the socket I/O involved in the handshake. + + The parameter ``suppress_ragged_eofs`` specifies how the + :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end + of the connection. If specified as :const:`True` (the default), it returns a + normal EOF (an empty bytes object) in response to unexpected EOF errors + raised from the underlying socket; if :const:`False`, it will raise the + exceptions back to the caller. + + *session*, see :attr:`~SSLSocket.session`. + + .. versionchanged:: 3.5 + Always allow a server_hostname to be passed, even if OpenSSL does not + have SNI. + + .. versionchanged:: 3.6 + *session* argument was added. + + .. versionchanged:: 3.7 + The method returns on instance of :attr:`SSLContext.sslsocket_class` + instead of hard-coded :class:`SSLSocket`. + +.. attribute:: SSLContext.sslsocket_class + + The return type of :meth:`SSLContext.wrap_socket`, defaults to + :class:`SSLSocket`. The attribute can be overridden on instance of class + in order to return a custom subclass of :class:`SSLSocket`. + + .. versionadded:: 3.7 + +.. method:: SSLContext.wrap_bio(incoming, outgoing, server_side=False, \ + server_hostname=None, session=None) + + Wrap the BIO objects *incoming* and *outgoing* and return an instance of + :attr:`SSLContext.sslobject_class` (default :class:`SSLObject`). The SSL + routines will read input data from the incoming BIO and write data to the + outgoing BIO. + + The *server_side*, *server_hostname* and *session* parameters have the + same meaning as in :meth:`SSLContext.wrap_socket`. + + .. versionchanged:: 3.6 + *session* argument was added. + + .. versionchanged:: 3.7 + The method returns on instance of :attr:`SSLContext.sslobject_class` + instead of hard-coded :class:`SSLObject`. + +.. attribute:: SSLContext.sslobject_class + + The return type of :meth:`SSLContext.wrap_bio`, defaults to + :class:`SSLObject`. The attribute can be overridden on instance of class + in order to return a custom subclass of :class:`SSLObject`. + + .. versionadded:: 3.7 + +.. method:: SSLContext.session_stats() + + Get statistics about the SSL sessions created or managed by this context. + A dictionary is returned which maps the names of each `piece of information `_ to their + numeric values. For example, here is the total number of hits and misses + in the session cache since the context was created:: + + >>> stats = context.session_stats() + >>> stats['hits'], stats['misses'] + (0, 0) + +.. attribute:: SSLContext.check_hostname + + Whether to match the peer cert's hostname with :func:`match_hostname` in + :meth:`SSLSocket.do_handshake`. The context's + :attr:`~SSLContext.verify_mode` must be set to :data:`CERT_OPTIONAL` or + :data:`CERT_REQUIRED`, and you must pass *server_hostname* to + :meth:`~SSLContext.wrap_socket` in order to match the hostname. Enabling + hostname checking automatically sets :attr:`~SSLContext.verify_mode` from + :data:`CERT_NONE` to :data:`CERT_REQUIRED`. It cannot be set back to + :data:`CERT_NONE` as long as hostname checking is enabled. The + :data:`PROTOCOL_TLS_CLIENT` protocol enables hostname checking by default. + With other protocols, hostname checking must be enabled explicitly. + + Example:: + + import socket, ssl + + context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) + context.verify_mode = ssl.CERT_REQUIRED + context.check_hostname = True + context.load_default_certs() + + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com') + ssl_sock.connect(('www.verisign.com', 443)) + + .. versionadded:: 3.4 + + .. versionchanged:: 3.7 + + :attr:`~SSLContext.verify_mode` is now automatically changed + to :data:`CERT_REQUIRED` when hostname checking is enabled and + :attr:`~SSLContext.verify_mode` is :data:`CERT_NONE`. Previously + the same operation would have failed with a :exc:`ValueError`. + + .. note:: + + This features requires OpenSSL 0.9.8f or newer. + +.. attribute:: SSLContext.keylog_filename + + Write TLS keys to a keylog file, whenever key material is generated or + received. The keylog file is designed for debugging purposes only. The + file format is specified by NSS and used by many traffic analyzers such + as Wireshark. The log file is opened in append-only mode. Writes are + synchronized between threads, but not between processes. + + .. versionadded:: 3.8 + + .. note:: + + This features requires OpenSSL 1.1.1 or newer. + +.. attribute:: SSLContext.maximum_version + + A :class:`TLSVersion` enum member representing the highest supported + TLS version. The value defaults to :attr:`TLSVersion.MAXIMUM_SUPPORTED`. + The attribute is read-only for protocols other than :attr:`PROTOCOL_TLS`, + :attr:`PROTOCOL_TLS_CLIENT`, and :attr:`PROTOCOL_TLS_SERVER`. + + The attributes :attr:`~SSLContext.maximum_version`, + :attr:`~SSLContext.minimum_version` and + :attr:`SSLContext.options` all affect the supported SSL + and TLS versions of the context. The implementation does not prevent + invalid combination. For example a context with + :attr:`OP_NO_TLSv1_2` in :attr:`~SSLContext.options` and + :attr:`~SSLContext.maximum_version` set to :attr:`TLSVersion.TLSv1_2` + will not be able to establish a TLS 1.2 connection. + + .. note:: + + This attribute is not available unless the ssl module is compiled + with OpenSSL 1.1.0g or newer. + + .. versionadded:: 3.7 + +.. attribute:: SSLContext.minimum_version + + Like :attr:`SSLContext.maximum_version` except it is the lowest + supported version or :attr:`TLSVersion.MINIMUM_SUPPORTED`. + + .. note:: + + This attribute is not available unless the ssl module is compiled + with OpenSSL 1.1.0g or newer. + + .. versionadded:: 3.7 + +.. attribute:: SSLContext.num_tickets + + Control the number of TLS 1.3 session tickets of a + :attr:`TLS_PROTOCOL_SERVER` context. The setting has no impact on TLS + 1.0 to 1.2 connections. + + .. note:: + + This attribute is not available unless the ssl module is compiled + with OpenSSL 1.1.1 or newer. + + .. versionadded:: 3.8 + +.. attribute:: SSLContext.options + + An integer representing the set of SSL options enabled on this context. + The default value is :data:`OP_ALL`, but you can specify other options + such as :data:`OP_NO_SSLv2` by ORing them together. + + .. note:: + With versions of OpenSSL older than 0.9.8m, it is only possible + to set options, not to clear them. Attempting to clear an option + (by resetting the corresponding bits) will raise a :exc:`ValueError`. + + .. versionchanged:: 3.6 + :attr:`SSLContext.options` returns :class:`Options` flags: + + >>> ssl.create_default_context().options # doctest: +SKIP + + +.. attribute:: SSLContext.post_handshake_auth + + Enable TLS 1.3 post-handshake client authentication. Post-handshake auth + is disabled by default and a server can only request a TLS client + certificate during the initial handshake. When enabled, a server may + request a TLS client certificate at any time after the handshake. + + When enabled on client-side sockets, the client signals the server that + it supports post-handshake authentication. + + When enabled on server-side sockets, :attr:`SSLContext.verify_mode` must + be set to :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`, too. The + actual client cert exchange is delayed until + :meth:`SSLSocket.verify_client_post_handshake` is called and some I/O is + performed. + + .. note:: + Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 + support, the property value is None and can't be modified + + .. versionadded:: 3.8 + +.. attribute:: SSLContext.protocol + + The protocol version chosen when constructing the context. This attribute + is read-only. + +.. attribute:: SSLContext.hostname_checks_common_name + + Whether :attr:`~SSLContext.check_hostname` falls back to verify the cert's + subject common name in the absence of a subject alternative name + extension (default: true). + + .. note:: + Only writeable with OpenSSL 1.1.0 or higher. + + .. versionadded:: 3.7 + +.. attribute:: SSLContext.verify_flags + + The flags for certificate verification operations. You can set flags like + :data:`VERIFY_CRL_CHECK_LEAF` by ORing them together. By default OpenSSL + does neither require nor verify certificate revocation lists (CRLs). + Available only with openssl version 0.9.8+. + + .. versionadded:: 3.4 + + .. versionchanged:: 3.6 + :attr:`SSLContext.verify_flags` returns :class:`VerifyFlags` flags: + + >>> ssl.create_default_context().verify_flags # doctest: +SKIP + + +.. attribute:: SSLContext.verify_mode + + Whether to try to verify other peers' certificates and how to behave + if verification fails. This attribute must be one of + :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`. + + .. versionchanged:: 3.6 + :attr:`SSLContext.verify_mode` returns :class:`VerifyMode` enum: + + >>> ssl.create_default_context().verify_mode + + +.. index:: single: certificates + +.. index:: single: X509 certificate + +.. _ssl-certificates: + +Certificates +------------ + +Certificates in general are part of a public-key / private-key system. In this +system, each *principal*, (which may be a machine, or a person, or an +organization) is assigned a unique two-part encryption key. One part of the key +is public, and is called the *public key*; the other part is kept secret, and is +called the *private key*. The two parts are related, in that if you encrypt a +message with one of the parts, you can decrypt it with the other part, and +**only** with the other part. + +A certificate contains information about two principals. It contains the name +of a *subject*, and the subject's public key. It also contains a statement by a +second principal, the *issuer*, that the subject is who they claim to be, and +that this is indeed the subject's public key. The issuer's statement is signed +with the issuer's private key, which only the issuer knows. However, anyone can +verify the issuer's statement by finding the issuer's public key, decrypting the +statement with it, and comparing it to the other information in the certificate. +The certificate also contains information about the time period over which it is +valid. This is expressed as two fields, called "notBefore" and "notAfter". + +In the Python use of certificates, a client or server can use a certificate to +prove who they are. The other side of a network connection can also be required +to produce a certificate, and that certificate can be validated to the +satisfaction of the client or server that requires such validation. The +connection attempt can be set to raise an exception if the validation fails. +Validation is done automatically, by the underlying OpenSSL framework; the +application need not concern itself with its mechanics. But the application +does usually need to provide sets of certificates to allow this process to take +place. + +Python uses files to contain certificates. They should be formatted as "PEM" +(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line +and a footer line:: + + -----BEGIN CERTIFICATE----- + ... (certificate in base64 PEM encoding) ... + -----END CERTIFICATE----- + +Certificate chains +^^^^^^^^^^^^^^^^^^ + +The Python files which contain certificates can contain a sequence of +certificates, sometimes called a *certificate chain*. This chain should start +with the specific certificate for the principal who "is" the client or server, +and then the certificate for the issuer of that certificate, and then the +certificate for the issuer of *that* certificate, and so on up the chain till +you get to a certificate which is *self-signed*, that is, a certificate which +has the same subject and issuer, sometimes called a *root certificate*. The +certificates should just be concatenated together in the certificate file. For +example, suppose we had a three certificate chain, from our server certificate +to the certificate of the certification authority that signed our server +certificate, to the root certificate of the agency which issued the +certification authority's certificate:: + + -----BEGIN CERTIFICATE----- + ... (certificate for your server)... + -----END CERTIFICATE----- + -----BEGIN CERTIFICATE----- + ... (the certificate for the CA)... + -----END CERTIFICATE----- + -----BEGIN CERTIFICATE----- + ... (the root certificate for the CA's issuer)... + -----END CERTIFICATE----- + +CA certificates +^^^^^^^^^^^^^^^ + +If you are going to require validation of the other side of the connection's +certificate, you need to provide a "CA certs" file, filled with the certificate +chains for each issuer you are willing to trust. Again, this file just contains +these chains concatenated together. For validation, Python will use the first +chain it finds in the file which matches. The platform's certificates file can +be used by calling :meth:`SSLContext.load_default_certs`, this is done +automatically with :func:`.create_default_context`. + +Combined key and certificate +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Often the private key is stored in the same file as the certificate; in this +case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain` +and :func:`wrap_socket` needs to be passed. If the private key is stored +with the certificate, it should come before the first certificate in +the certificate chain:: + + -----BEGIN RSA PRIVATE KEY----- + ... (private key in base64 encoding) ... + -----END RSA PRIVATE KEY----- + -----BEGIN CERTIFICATE----- + ... (certificate in base64 PEM encoding) ... + -----END CERTIFICATE----- + +Self-signed certificates +^^^^^^^^^^^^^^^^^^^^^^^^ + +If you are going to create a server that provides SSL-encrypted connection +services, you will need to acquire a certificate for that service. There are +many ways of acquiring appropriate certificates, such as buying one from a +certification authority. Another common practice is to generate a self-signed +certificate. The simplest way to do this is with the OpenSSL package, using +something like the following:: + + % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem + Generating a 1024 bit RSA private key + .......++++++ + .............................++++++ + writing new private key to 'cert.pem' + ----- + You are about to be asked to enter information that will be incorporated + into your certificate request. + What you are about to enter is what is called a Distinguished Name or a DN. + There are quite a few fields but you can leave some blank + For some fields there will be a default value, + If you enter '.', the field will be left blank. + ----- + Country Name (2 letter code) [AU]:US + State or Province Name (full name) [Some-State]:MyState + Locality Name (eg, city) []:Some City + Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc. + Organizational Unit Name (eg, section) []:My Group + Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com + Email Address []:ops@myserver.mygroup.myorganization.com + % + +The disadvantage of a self-signed certificate is that it is its own root +certificate, and no one else will have it in their cache of known (and trusted) +root certificates. + + +Examples +-------- + +Testing for SSL support +^^^^^^^^^^^^^^^^^^^^^^^ + +To test for the presence of SSL support in a Python installation, user code +should use the following idiom:: + + try: + import ssl + except ImportError: + pass + else: + ... # do something that requires SSL support + +Client-side operation +^^^^^^^^^^^^^^^^^^^^^ + +This example creates a SSL context with the recommended security settings +for client sockets, including automatic certificate verification:: + + >>> context = ssl.create_default_context() + +If you prefer to tune security settings yourself, you might create +a context from scratch (but beware that you might not get the settings +right):: + + >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") + +(this snippet assumes your operating system places a bundle of all CA +certificates in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an +error and have to adjust the location) + +The :data:`PROTOCOL_TLS_CLIENT` protocol configures the context for cert +validation and hostname verification. :attr:`~SSLContext.verify_mode` is +set to :data:`CERT_REQUIRED` and :attr:`~SSLContext.check_hostname` is set +to ``True``. All other protocols create SSL contexts with insecure defaults. + +When you use the context to connect to a server, :const:`CERT_REQUIRED` +and :attr:`~SSLContext.check_hostname` validate the server certificate: it +ensures that the server certificate was signed with one of the CA +certificates, checks the signature for correctness, and verifies other +properties like validity and identity of the hostname:: + + >>> conn = context.wrap_socket(socket.socket(socket.AF_INET), + ... server_hostname="www.python.org") + >>> conn.connect(("www.python.org", 443)) + +You may then fetch the certificate:: + + >>> cert = conn.getpeercert() + +Visual inspection shows that the certificate does identify the desired service +(that is, the HTTPS host ``www.python.org``):: + + >>> pprint.pprint(cert) + {'OCSP': ('http://ocsp.digicert.com',), + 'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',), + 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl', + 'http://crl4.digicert.com/sha2-ev-server-g1.crl'), + 'issuer': ((('countryName', 'US'),), + (('organizationName', 'DigiCert Inc'),), + (('organizationalUnitName', 'www.digicert.com'),), + (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)), + 'notAfter': 'Sep 9 12:00:00 2016 GMT', + 'notBefore': 'Sep 5 00:00:00 2014 GMT', + 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26', + 'subject': ((('businessCategory', 'Private Organization'),), + (('1.3.6.1.4.1.311.60.2.1.3', 'US'),), + (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),), + (('serialNumber', '3359300'),), + (('streetAddress', '16 Allen Rd'),), + (('postalCode', '03894-4801'),), + (('countryName', 'US'),), + (('stateOrProvinceName', 'NH'),), + (('localityName', 'Wolfeboro'),), + (('organizationName', 'Python Software Foundation'),), + (('commonName', 'www.python.org'),)), + 'subjectAltName': (('DNS', 'www.python.org'), + ('DNS', 'python.org'), + ('DNS', 'pypi.org'), + ('DNS', 'docs.python.org'), + ('DNS', 'testpypi.org'), + ('DNS', 'bugs.python.org'), + ('DNS', 'wiki.python.org'), + ('DNS', 'hg.python.org'), + ('DNS', 'mail.python.org'), + ('DNS', 'packaging.python.org'), + ('DNS', 'pythonhosted.org'), + ('DNS', 'www.pythonhosted.org'), + ('DNS', 'test.pythonhosted.org'), + ('DNS', 'us.pycon.org'), + ('DNS', 'id.python.org')), + 'version': 3} + +Now the SSL channel is established and the certificate verified, you can +proceed to talk with the server:: + + >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n") + >>> pprint.pprint(conn.recv(1024).split(b"\r\n")) + [b'HTTP/1.1 200 OK', + b'Date: Sat, 18 Oct 2014 18:27:20 GMT', + b'Server: nginx', + b'Content-Type: text/html; charset=utf-8', + b'X-Frame-Options: SAMEORIGIN', + b'Content-Length: 45679', + b'Accept-Ranges: bytes', + b'Via: 1.1 varnish', + b'Age: 2188', + b'X-Served-By: cache-lcy1134-LCY', + b'X-Cache: HIT', + b'X-Cache-Hits: 11', + b'Vary: Cookie', + b'Strict-Transport-Security: max-age=63072000; includeSubDomains', + b'Connection: close', + b'', + b''] + +See the discussion of :ref:`ssl-security` below. + + +Server-side operation +^^^^^^^^^^^^^^^^^^^^^ + +For server operation, typically you'll need to have a server certificate, and +private key, each in a file. You'll first create a context holding the key +and the certificate, so that clients can check your authenticity. Then +you'll open a socket, bind it to a port, call :meth:`listen` on it, and start +waiting for clients to connect:: + + import socket, ssl + + context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) + context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile") + + bindsocket = socket.socket() + bindsocket.bind(('myaddr.mydomain.com', 10023)) + bindsocket.listen(5) + +When a client connects, you'll call :meth:`accept` on the socket to get the +new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket` +method to create a server-side SSL socket for the connection:: + + while True: + newsocket, fromaddr = bindsocket.accept() + connstream = context.wrap_socket(newsocket, server_side=True) + try: + deal_with_client(connstream) + finally: + connstream.shutdown(socket.SHUT_RDWR) + connstream.close() + +Then you'll read data from the ``connstream`` and do something with it till you +are finished with the client (or the client is finished with you):: + + def deal_with_client(connstream): + data = connstream.recv(1024) + # empty data means the client is finished with us + while data: + if not do_something(connstream, data): + # we'll assume do_something returns False + # when we're finished with client + break + data = connstream.recv(1024) + # finished with client + +And go back to listening for new client connections (of course, a real server +would probably handle each client connection in a separate thread, or put +the sockets in :ref:`non-blocking mode ` and use an event loop). + + +.. _ssl-nonblocking: + +Notes on non-blocking sockets +----------------------------- + +SSL sockets behave slightly different than regular sockets in +non-blocking mode. When working with non-blocking sockets, there are +thus several things you need to be aware of: + +- Most :class:`SSLSocket` methods will raise either + :exc:`SSLWantWriteError` or :exc:`SSLWantReadError` instead of + :exc:`BlockingIOError` if an I/O operation would + block. :exc:`SSLWantReadError` will be raised if a read operation on + the underlying socket is necessary, and :exc:`SSLWantWriteError` for + a write operation on the underlying socket. Note that attempts to + *write* to an SSL socket may require *reading* from the underlying + socket first, and attempts to *read* from the SSL socket may require + a prior *write* to the underlying socket. + + .. versionchanged:: 3.5 + + In earlier Python versions, the :meth:`!SSLSocket.send` method + returned zero instead of raising :exc:`SSLWantWriteError` or + :exc:`SSLWantReadError`. + +- Calling :func:`~select.select` tells you that the OS-level socket can be + read from (or written to), but it does not imply that there is sufficient + data at the upper SSL layer. For example, only part of an SSL frame might + have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv` + and :meth:`SSLSocket.send` failures, and retry after another call to + :func:`~select.select`. + +- Conversely, since the SSL layer has its own framing, a SSL socket may + still have data available for reading without :func:`~select.select` + being aware of it. Therefore, you should first call + :meth:`SSLSocket.recv` to drain any potentially available data, and then + only block on a :func:`~select.select` call if still necessary. + + (of course, similar provisions apply when using other primitives such as + :func:`~select.poll`, or those in the :mod:`selectors` module) + +- The SSL handshake itself will be non-blocking: the + :meth:`SSLSocket.do_handshake` method has to be retried until it returns + successfully. Here is a synopsis using :func:`~select.select` to wait for + the socket's readiness:: + + while True: + try: + sock.do_handshake() + break + except ssl.SSLWantReadError: + select.select([sock], [], []) + except ssl.SSLWantWriteError: + select.select([], [sock], []) + +.. seealso:: + + The :mod:`asyncio` module supports :ref:`non-blocking SSL sockets + ` and provides a + higher level API. It polls for events using the :mod:`selectors` module and + handles :exc:`SSLWantWriteError`, :exc:`SSLWantReadError` and + :exc:`BlockingIOError` exceptions. It runs the SSL handshake asynchronously + as well. + + +Memory BIO Support +------------------ + +.. versionadded:: 3.5 + +Ever since the SSL module was introduced in Python 2.6, the :class:`SSLSocket` +class has provided two related but distinct areas of functionality: + +- SSL protocol handling +- Network IO + +The network IO API is identical to that provided by :class:`socket.socket`, +from which :class:`SSLSocket` also inherits. This allows an SSL socket to be +used as a drop-in replacement for a regular socket, making it very easy to add +SSL support to an existing application. + +Combining SSL protocol handling and network IO usually works well, but there +are some cases where it doesn't. An example is async IO frameworks that want to +use a different IO multiplexing model than the "select/poll on a file +descriptor" (readiness based) model that is assumed by :class:`socket.socket` +and by the internal OpenSSL socket IO routines. This is mostly relevant for +platforms like Windows where this model is not efficient. For this purpose, a +reduced scope variant of :class:`SSLSocket` called :class:`SSLObject` is +provided. + +.. class:: SSLObject + + A reduced-scope variant of :class:`SSLSocket` representing an SSL protocol + instance that does not contain any network IO methods. This class is + typically used by framework authors that want to implement asynchronous IO + for SSL through memory buffers. + + This class implements an interface on top of a low-level SSL object as + implemented by OpenSSL. This object captures the state of an SSL connection + but does not provide any network IO itself. IO needs to be performed through + separate "BIO" objects which are OpenSSL's IO abstraction layer. + + This class has no public constructor. An :class:`SSLObject` instance + must be created using the :meth:`~SSLContext.wrap_bio` method. This + method will create the :class:`SSLObject` instance and bind it to a + pair of BIOs. The *incoming* BIO is used to pass data from Python to the + SSL protocol instance, while the *outgoing* BIO is used to pass data the + other way around. + + The following methods are available: + + - :attr:`~SSLSocket.context` + - :attr:`~SSLSocket.server_side` + - :attr:`~SSLSocket.server_hostname` + - :attr:`~SSLSocket.session` + - :attr:`~SSLSocket.session_reused` + - :meth:`~SSLSocket.read` + - :meth:`~SSLSocket.write` + - :meth:`~SSLSocket.getpeercert` + - :meth:`~SSLSocket.selected_alpn_protocol` + - :meth:`~SSLSocket.selected_npn_protocol` + - :meth:`~SSLSocket.cipher` + - :meth:`~SSLSocket.shared_ciphers` + - :meth:`~SSLSocket.compression` + - :meth:`~SSLSocket.pending` + - :meth:`~SSLSocket.do_handshake` + - :meth:`~SSLSocket.verify_client_post_handshake` + - :meth:`~SSLSocket.unwrap` + - :meth:`~SSLSocket.get_channel_binding` + - :meth:`~SSLSocket.version` + + When compared to :class:`SSLSocket`, this object lacks the following + features: + + - Any form of network IO; ``recv()`` and ``send()`` read and write only to + the underlying :class:`MemoryBIO` buffers. + + - There is no *do_handshake_on_connect* machinery. You must always manually + call :meth:`~SSLSocket.do_handshake` to start the handshake. + + - There is no handling of *suppress_ragged_eofs*. All end-of-file conditions + that are in violation of the protocol are reported via the + :exc:`SSLEOFError` exception. + + - The method :meth:`~SSLSocket.unwrap` call does not return anything, + unlike for an SSL socket where it returns the underlying socket. + + - The *server_name_callback* callback passed to + :meth:`SSLContext.set_servername_callback` will get an :class:`SSLObject` + instance instead of a :class:`SSLSocket` instance as its first parameter. + + Some notes related to the use of :class:`SSLObject`: + + - All IO on an :class:`SSLObject` is :ref:`non-blocking `. + This means that for example :meth:`~SSLSocket.read` will raise an + :exc:`SSLWantReadError` if it needs more data than the incoming BIO has + available. + + - There is no module-level ``wrap_bio()`` call like there is for + :meth:`~SSLContext.wrap_socket`. An :class:`SSLObject` is always created + via an :class:`SSLContext`. + + .. versionchanged:: 3.7 + :class:`SSLObject` instances must to created with + :meth:`~SSLContext.wrap_bio`. In earlier versions, it was possible to + create instances directly. This was never documented or officially + supported. + +An SSLObject communicates with the outside world using memory buffers. The +class :class:`MemoryBIO` provides a memory buffer that can be used for this +purpose. It wraps an OpenSSL memory BIO (Basic IO) object: + +.. class:: MemoryBIO + + A memory buffer that can be used to pass data between Python and an SSL + protocol instance. + + .. attribute:: MemoryBIO.pending + + Return the number of bytes currently in the memory buffer. + + .. attribute:: MemoryBIO.eof + + A boolean indicating whether the memory BIO is current at the end-of-file + position. + + .. method:: MemoryBIO.read(n=-1) + + Read up to *n* bytes from the memory buffer. If *n* is not specified or + negative, all bytes are returned. + + .. method:: MemoryBIO.write(buf) + + Write the bytes from *buf* to the memory BIO. The *buf* argument must be an + object supporting the buffer protocol. + + The return value is the number of bytes written, which is always equal to + the length of *buf*. + + .. method:: MemoryBIO.write_eof() + + Write an EOF marker to the memory BIO. After this method has been called, it + is illegal to call :meth:`~MemoryBIO.write`. The attribute :attr:`eof` will + become true after all data currently in the buffer has been read. + + +SSL session +----------- + +.. versionadded:: 3.6 + +.. class:: SSLSession + + Session object used by :attr:`~SSLSocket.session`. + + .. attribute:: id + .. attribute:: time + .. attribute:: timeout + .. attribute:: ticket_lifetime_hint + .. attribute:: has_ticket + + +.. _ssl-security: + +Security considerations +----------------------- + +Best defaults +^^^^^^^^^^^^^ + +For **client use**, if you don't have any special requirements for your +security policy, it is highly recommended that you use the +:func:`create_default_context` function to create your SSL context. +It will load the system's trusted CA certificates, enable certificate +validation and hostname checking, and try to choose reasonably secure +protocol and cipher settings. + +For example, here is how you would use the :class:`smtplib.SMTP` class to +create a trusted, secure connection to a SMTP server:: + + >>> import ssl, smtplib + >>> smtp = smtplib.SMTP("mail.python.org", port=587) + >>> context = ssl.create_default_context() + >>> smtp.starttls(context=context) + (220, b'2.0.0 Ready to start TLS') + +If a client certificate is needed for the connection, it can be added with +:meth:`SSLContext.load_cert_chain`. + +By contrast, if you create the SSL context by calling the :class:`SSLContext` +constructor yourself, it will not have certificate validation nor hostname +checking enabled by default. If you do so, please read the paragraphs below +to achieve a good security level. + +Manual settings +^^^^^^^^^^^^^^^ + +Verifying certificates +'''''''''''''''''''''' + +When calling the :class:`SSLContext` constructor directly, +:const:`CERT_NONE` is the default. Since it does not authenticate the other +peer, it can be insecure, especially in client mode where most of time you +would like to ensure the authenticity of the server you're talking to. +Therefore, when in client mode, it is highly recommended to use +:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also +have to check that the server certificate, which can be obtained by calling +:meth:`SSLSocket.getpeercert`, matches the desired service. For many +protocols and applications, the service can be identified by the hostname; +in this case, the :func:`match_hostname` function can be used. This common +check is automatically performed when :attr:`SSLContext.check_hostname` is +enabled. + +.. versionchanged:: 3.7 + Hostname matchings is now performed by OpenSSL. Python no longer uses + :func:`match_hostname`. + +In server mode, if you want to authenticate your clients using the SSL layer +(rather than using a higher-level authentication mechanism), you'll also have +to specify :const:`CERT_REQUIRED` and similarly check the client certificate. + + +Protocol versions +''''''''''''''''' + +SSL versions 2 and 3 are considered insecure and are therefore dangerous to +use. If you want maximum compatibility between clients and servers, it is +recommended to use :const:`PROTOCOL_TLS_CLIENT` or +:const:`PROTOCOL_TLS_SERVER` as the protocol version. SSLv2 and SSLv3 are +disabled by default. + +:: + + >>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + >>> client_context.options |= ssl.OP_NO_TLSv1 + >>> client_context.options |= ssl.OP_NO_TLSv1_1 + + +The SSL context created above will only allow TLSv1.2 and later (if +supported by your system) connections to a server. :const:`PROTOCOL_TLS_CLIENT` +implies certificate validation and hostname checks by default. You have to +load certificates into the context. + + +Cipher selection +'''''''''''''''' + +If you have advanced security requirements, fine-tuning of the ciphers +enabled when negotiating a SSL session is possible through the +:meth:`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the +ssl module disables certain weak ciphers by default, but you may want +to further restrict the cipher choice. Be sure to read OpenSSL's documentation +about the `cipher list format `_. +If you want to check which ciphers are enabled by a given cipher list, use +:meth:`SSLContext.get_ciphers` or the ``openssl ciphers`` command on your +system. + +Multi-processing +^^^^^^^^^^^^^^^^ + +If using this module as part of a multi-processed application (using, +for example the :mod:`multiprocessing` or :mod:`concurrent.futures` modules), +be aware that OpenSSL's internal random number generator does not properly +handle forked processes. Applications must change the PRNG state of the +parent process if they use any SSL feature with :func:`os.fork`. Any +successful call of :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or +:func:`~ssl.RAND_pseudo_bytes` is sufficient. + + +.. _ssl-tlsv1_3: + +TLS 1.3 +------- + +.. versionadded:: 3.7 + +Python has provisional and experimental support for TLS 1.3 with OpenSSL +1.1.1. The new protocol behaves slightly differently than previous version +of TLS/SSL. Some new TLS 1.3 features are not yet available. + +- TLS 1.3 uses a disjunct set of cipher suites. All AES-GCM and + ChaCha20 cipher suites are enabled by default. The method + :meth:`SSLContext.set_ciphers` cannot enable or disable any TLS 1.3 + ciphers yet, but :meth:`SSLContext.get_ciphers` returns them. +- Session tickets are no longer sent as part of the initial handshake and + are handled differently. :attr:`SSLSocket.session` and :class:`SSLSession` + are not compatible with TLS 1.3. +- Client-side certificates are also no longer verified during the initial + handshake. A server can request a certificate at any time. Clients + process certificate requests while they send or receive application data + from the server. +- TLS 1.3 features like early data, deferred TLS client cert request, + signature algorithm configuration, and rekeying are not supported yet. + + +.. _ssl-libressl: + +LibreSSL support +---------------- + +LibreSSL is a fork of OpenSSL 1.0.1. The ssl module has limited support for +LibreSSL. Some features are not available when the ssl module is compiled +with LibreSSL. + +* LibreSSL >= 2.6.1 no longer supports NPN. The methods + :meth:`SSLContext.set_npn_protocols` and + :meth:`SSLSocket.selected_npn_protocol` are not available. +* :meth:`SSLContext.set_default_verify_paths` ignores the env vars + :envvar:`SSL_CERT_FILE` and :envvar:`SSL_CERT_PATH` although + :func:`get_default_verify_paths` still reports them. + + +.. seealso:: + + Class :class:`socket.socket` + Documentation of underlying :mod:`socket` class + + `SSL/TLS Strong Encryption: An Introduction `_ + Intro from the Apache HTTP Server documentation + + :rfc:`RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <1422>` + Steve Kent + + :rfc:`RFC 4086: Randomness Requirements for Security <4086>` + Donald E., Jeffrey I. Schiller + + :rfc:`RFC 5280: Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile <5280>` + D. Cooper + + :rfc:`RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <5246>` + T. Dierks et. al. + + :rfc:`RFC 6066: Transport Layer Security (TLS) Extensions <6066>` + D. Eastlake + + `IANA TLS: Transport Layer Security (TLS) Parameters `_ + IANA + + :rfc:`RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) <7525>` + IETF + + `Mozilla's Server Side TLS recommendations `_ + Mozilla diff --git a/cpython_2/environment/repo/Doc/library/stat.rst b/cpython_2/environment/repo/Doc/library/stat.rst new file mode 100644 index 0000000000000000000000000000000000000000..f48a0a9faa6b0c189e7fe8b9193772e599e3f870 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/stat.rst @@ -0,0 +1,437 @@ +:mod:`stat` --- Interpreting :func:`~os.stat` results +===================================================== + +.. module:: stat + :synopsis: Utilities for interpreting the results of os.stat(), + os.lstat() and os.fstat(). + +.. sectionauthor:: Skip Montanaro + +**Source code:** :source:`Lib/stat.py` + +-------------- + +The :mod:`stat` module defines constants and functions for interpreting the +results of :func:`os.stat`, :func:`os.fstat` and :func:`os.lstat` (if they +exist). For complete details about the :c:func:`stat`, :c:func:`fstat` and +:c:func:`lstat` calls, consult the documentation for your system. + +.. versionchanged:: 3.4 + The stat module is backed by a C implementation. + +The :mod:`stat` module defines the following functions to test for specific file +types: + + +.. function:: S_ISDIR(mode) + + Return non-zero if the mode is from a directory. + + +.. function:: S_ISCHR(mode) + + Return non-zero if the mode is from a character special device file. + + +.. function:: S_ISBLK(mode) + + Return non-zero if the mode is from a block special device file. + + +.. function:: S_ISREG(mode) + + Return non-zero if the mode is from a regular file. + + +.. function:: S_ISFIFO(mode) + + Return non-zero if the mode is from a FIFO (named pipe). + + +.. function:: S_ISLNK(mode) + + Return non-zero if the mode is from a symbolic link. + + +.. function:: S_ISSOCK(mode) + + Return non-zero if the mode is from a socket. + +.. function:: S_ISDOOR(mode) + + Return non-zero if the mode is from a door. + + .. versionadded:: 3.4 + +.. function:: S_ISPORT(mode) + + Return non-zero if the mode is from an event port. + + .. versionadded:: 3.4 + +.. function:: S_ISWHT(mode) + + Return non-zero if the mode is from a whiteout. + + .. versionadded:: 3.4 + +Two additional functions are defined for more general manipulation of the file's +mode: + + +.. function:: S_IMODE(mode) + + Return the portion of the file's mode that can be set by + :func:`os.chmod`\ ---that is, the file's permission bits, plus the sticky + bit, set-group-id, and set-user-id bits (on systems that support them). + + +.. function:: S_IFMT(mode) + + Return the portion of the file's mode that describes the file type (used by the + :func:`S_IS\*` functions above). + +Normally, you would use the :func:`os.path.is\*` functions for testing the type +of a file; the functions here are useful when you are doing multiple tests of +the same file and wish to avoid the overhead of the :c:func:`stat` system call +for each test. These are also useful when checking for information about a file +that isn't handled by :mod:`os.path`, like the tests for block and character +devices. + +Example:: + + import os, sys + from stat import * + + def walktree(top, callback): + '''recursively descend the directory tree rooted at top, + calling the callback function for each regular file''' + + for f in os.listdir(top): + pathname = os.path.join(top, f) + mode = os.stat(pathname).st_mode + if S_ISDIR(mode): + # It's a directory, recurse into it + walktree(pathname, callback) + elif S_ISREG(mode): + # It's a file, call the callback function + callback(pathname) + else: + # Unknown file type, print a message + print('Skipping %s' % pathname) + + def visitfile(file): + print('visiting', file) + + if __name__ == '__main__': + walktree(sys.argv[1], visitfile) + +An additional utility function is provided to convert a file's mode in a human +readable string: + +.. function:: filemode(mode) + + Convert a file's mode to a string of the form '-rwxrwxrwx'. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.4 + The function supports :data:`S_IFDOOR`, :data:`S_IFPORT` and + :data:`S_IFWHT`. + + +All the variables below are simply symbolic indexes into the 10-tuple returned +by :func:`os.stat`, :func:`os.fstat` or :func:`os.lstat`. + + +.. data:: ST_MODE + + Inode protection mode. + + +.. data:: ST_INO + + Inode number. + + +.. data:: ST_DEV + + Device inode resides on. + + +.. data:: ST_NLINK + + Number of links to the inode. + + +.. data:: ST_UID + + User id of the owner. + + +.. data:: ST_GID + + Group id of the owner. + + +.. data:: ST_SIZE + + Size in bytes of a plain file; amount of data waiting on some special files. + + +.. data:: ST_ATIME + + Time of last access. + + +.. data:: ST_MTIME + + Time of last modification. + + +.. data:: ST_CTIME + + The "ctime" as reported by the operating system. On some systems (like Unix) is + the time of the last metadata change, and, on others (like Windows), is the + creation time (see platform documentation for details). + +The interpretation of "file size" changes according to the file type. For plain +files this is the size of the file in bytes. For FIFOs and sockets under most +flavors of Unix (including Linux in particular), the "size" is the number of +bytes waiting to be read at the time of the call to :func:`os.stat`, +:func:`os.fstat`, or :func:`os.lstat`; this can sometimes be useful, especially +for polling one of these special files after a non-blocking open. The meaning +of the size field for other character and block devices varies more, depending +on the implementation of the underlying system call. + +The variables below define the flags used in the :data:`ST_MODE` field. + +Use of the functions above is more portable than use of the first set of flags: + +.. data:: S_IFSOCK + + Socket. + +.. data:: S_IFLNK + + Symbolic link. + +.. data:: S_IFREG + + Regular file. + +.. data:: S_IFBLK + + Block device. + +.. data:: S_IFDIR + + Directory. + +.. data:: S_IFCHR + + Character device. + +.. data:: S_IFIFO + + FIFO. + +.. data:: S_IFDOOR + + Door. + + .. versionadded:: 3.4 + +.. data:: S_IFPORT + + Event port. + + .. versionadded:: 3.4 + +.. data:: S_IFWHT + + Whiteout. + + .. versionadded:: 3.4 + +.. note:: + + :data:`S_IFDOOR`, :data:`S_IFPORT` or :data:`S_IFWHT` are defined as + 0 when the platform does not have support for the file types. + +The following flags can also be used in the *mode* argument of :func:`os.chmod`: + +.. data:: S_ISUID + + Set UID bit. + +.. data:: S_ISGID + + Set-group-ID bit. This bit has several special uses. For a directory + it indicates that BSD semantics is to be used for that directory: + files created there inherit their group ID from the directory, not + from the effective group ID of the creating process, and directories + created there will also get the :data:`S_ISGID` bit set. For a + file that does not have the group execution bit (:data:`S_IXGRP`) + set, the set-group-ID bit indicates mandatory file/record locking + (see also :data:`S_ENFMT`). + +.. data:: S_ISVTX + + Sticky bit. When this bit is set on a directory it means that a file + in that directory can be renamed or deleted only by the owner of the + file, by the owner of the directory, or by a privileged process. + +.. data:: S_IRWXU + + Mask for file owner permissions. + +.. data:: S_IRUSR + + Owner has read permission. + +.. data:: S_IWUSR + + Owner has write permission. + +.. data:: S_IXUSR + + Owner has execute permission. + +.. data:: S_IRWXG + + Mask for group permissions. + +.. data:: S_IRGRP + + Group has read permission. + +.. data:: S_IWGRP + + Group has write permission. + +.. data:: S_IXGRP + + Group has execute permission. + +.. data:: S_IRWXO + + Mask for permissions for others (not in group). + +.. data:: S_IROTH + + Others have read permission. + +.. data:: S_IWOTH + + Others have write permission. + +.. data:: S_IXOTH + + Others have execute permission. + +.. data:: S_ENFMT + + System V file locking enforcement. This flag is shared with :data:`S_ISGID`: + file/record locking is enforced on files that do not have the group + execution bit (:data:`S_IXGRP`) set. + +.. data:: S_IREAD + + Unix V7 synonym for :data:`S_IRUSR`. + +.. data:: S_IWRITE + + Unix V7 synonym for :data:`S_IWUSR`. + +.. data:: S_IEXEC + + Unix V7 synonym for :data:`S_IXUSR`. + +The following flags can be used in the *flags* argument of :func:`os.chflags`: + +.. data:: UF_NODUMP + + Do not dump the file. + +.. data:: UF_IMMUTABLE + + The file may not be changed. + +.. data:: UF_APPEND + + The file may only be appended to. + +.. data:: UF_OPAQUE + + The directory is opaque when viewed through a union stack. + +.. data:: UF_NOUNLINK + + The file may not be renamed or deleted. + +.. data:: UF_COMPRESSED + + The file is stored compressed (Mac OS X 10.6+). + +.. data:: UF_HIDDEN + + The file should not be displayed in a GUI (Mac OS X 10.5+). + +.. data:: SF_ARCHIVED + + The file may be archived. + +.. data:: SF_IMMUTABLE + + The file may not be changed. + +.. data:: SF_APPEND + + The file may only be appended to. + +.. data:: SF_NOUNLINK + + The file may not be renamed or deleted. + +.. data:: SF_SNAPSHOT + + The file is a snapshot file. + +See the \*BSD or Mac OS systems man page :manpage:`chflags(2)` for more information. + +On Windows, the following file attribute constants are available for use when +testing bits in the ``st_file_attributes`` member returned by :func:`os.stat`. +See the `Windows API documentation +`_ +for more detail on the meaning of these constants. + +.. data:: FILE_ATTRIBUTE_ARCHIVE + FILE_ATTRIBUTE_COMPRESSED + FILE_ATTRIBUTE_DEVICE + FILE_ATTRIBUTE_DIRECTORY + FILE_ATTRIBUTE_ENCRYPTED + FILE_ATTRIBUTE_HIDDEN + FILE_ATTRIBUTE_INTEGRITY_STREAM + FILE_ATTRIBUTE_NORMAL + FILE_ATTRIBUTE_NOT_CONTENT_INDEXED + FILE_ATTRIBUTE_NO_SCRUB_DATA + FILE_ATTRIBUTE_OFFLINE + FILE_ATTRIBUTE_READONLY + FILE_ATTRIBUTE_REPARSE_POINT + FILE_ATTRIBUTE_SPARSE_FILE + FILE_ATTRIBUTE_SYSTEM + FILE_ATTRIBUTE_TEMPORARY + FILE_ATTRIBUTE_VIRTUAL + + .. versionadded:: 3.5 + +On Windows, the following constants are available for comparing against the +``st_reparse_tag`` member returned by :func:`os.lstat`. These are well-known +constants, but are not an exhaustive list. + +.. data:: IO_REPARSE_TAG_SYMLINK + IO_REPARSE_TAG_MOUNT_POINT + IO_REPARSE_TAG_APPEXECLINK + + .. versionadded:: 3.8 diff --git a/cpython_2/environment/repo/Doc/library/statistics.rst b/cpython_2/environment/repo/Doc/library/statistics.rst new file mode 100644 index 0000000000000000000000000000000000000000..38a499ab37e890d377ae9f1a29da9470356ba524 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/statistics.rst @@ -0,0 +1,877 @@ +:mod:`statistics` --- Mathematical statistics functions +======================================================= + +.. module:: statistics + :synopsis: Mathematical statistics functions + +.. moduleauthor:: Steven D'Aprano +.. sectionauthor:: Steven D'Aprano + +.. versionadded:: 3.4 + +**Source code:** :source:`Lib/statistics.py` + +.. testsetup:: * + + from statistics import * + __name__ = '' + +-------------- + +This module provides functions for calculating mathematical statistics of +numeric (:class:`~numbers.Real`-valued) data. + +The module is not intended to be a competitor to third-party libraries such +as `NumPy `_, `SciPy `_, or +proprietary full-featured statistics packages aimed at professional +statisticians such as Minitab, SAS and Matlab. It is aimed at the level of +graphing and scientific calculators. + +Unless explicitly noted, these functions support :class:`int`, +:class:`float`, :class:`~decimal.Decimal` and :class:`~fractions.Fraction`. +Behaviour with other types (whether in the numeric tower or not) is +currently unsupported. Collections with a mix of types are also undefined +and implementation-dependent. If your input data consists of mixed types, +you may be able to use :func:`map` to ensure a consistent result, for +example: ``map(float, input_data)``. + +Averages and measures of central location +----------------------------------------- + +These functions calculate an average or typical value from a population +or sample. + +======================= =============================================================== +:func:`mean` Arithmetic mean ("average") of data. +:func:`fmean` Fast, floating point arithmetic mean. +:func:`geometric_mean` Geometric mean of data. +:func:`harmonic_mean` Harmonic mean of data. +:func:`median` Median (middle value) of data. +:func:`median_low` Low median of data. +:func:`median_high` High median of data. +:func:`median_grouped` Median, or 50th percentile, of grouped data. +:func:`mode` Single mode (most common value) of discrete or nominal data. +:func:`multimode` List of modes (most common values) of discrete or nomimal data. +:func:`quantiles` Divide data into intervals with equal probability. +======================= =============================================================== + +Measures of spread +------------------ + +These functions calculate a measure of how much the population or sample +tends to deviate from the typical or average values. + +======================= ============================================= +:func:`pstdev` Population standard deviation of data. +:func:`pvariance` Population variance of data. +:func:`stdev` Sample standard deviation of data. +:func:`variance` Sample variance of data. +======================= ============================================= + + +Function details +---------------- + +Note: The functions do not require the data given to them to be sorted. +However, for reading convenience, most of the examples show sorted sequences. + +.. function:: mean(data) + + Return the sample arithmetic mean of *data* which can be a sequence or iterable. + + The arithmetic mean is the sum of the data divided by the number of data + points. It is commonly called "the average", although it is only one of many + different mathematical averages. It is a measure of the central location of + the data. + + If *data* is empty, :exc:`StatisticsError` will be raised. + + Some examples of use: + + .. doctest:: + + >>> mean([1, 2, 3, 4, 4]) + 2.8 + >>> mean([-1.0, 2.5, 3.25, 5.75]) + 2.625 + + >>> from fractions import Fraction as F + >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]) + Fraction(13, 21) + + >>> from decimal import Decimal as D + >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")]) + Decimal('0.5625') + + .. note:: + + The mean is strongly affected by outliers and is not a robust estimator + for central location: the mean is not necessarily a typical example of + the data points. For more robust measures of central location, see + :func:`median` and :func:`mode`. + + The sample mean gives an unbiased estimate of the true population mean, + so that when taken on average over all the possible samples, + ``mean(sample)`` converges on the true mean of the entire population. If + *data* represents the entire population rather than a sample, then + ``mean(data)`` is equivalent to calculating the true population mean μ. + + +.. function:: fmean(data) + + Convert *data* to floats and compute the arithmetic mean. + + This runs faster than the :func:`mean` function and it always returns a + :class:`float`. The *data* may be a sequence or iterable. If the input + dataset is empty, raises a :exc:`StatisticsError`. + + .. doctest:: + + >>> fmean([3.5, 4.0, 5.25]) + 4.25 + + .. versionadded:: 3.8 + + +.. function:: geometric_mean(data) + + Convert *data* to floats and compute the geometric mean. + + The geometric mean indicates the central tendency or typical value of the + *data* using the product of the values (as opposed to the arithmetic mean + which uses their sum). + + Raises a :exc:`StatisticsError` if the input dataset is empty, + if it contains a zero, or if it contains a negative value. + The *data* may be a sequence or iterable. + + No special efforts are made to achieve exact results. + (However, this may change in the future.) + + .. doctest:: + + >>> round(geometric_mean([54, 24, 36]), 1) + 36.0 + + .. versionadded:: 3.8 + + +.. function:: harmonic_mean(data) + + Return the harmonic mean of *data*, a sequence or iterable of + real-valued numbers. + + The harmonic mean, sometimes called the subcontrary mean, is the + reciprocal of the arithmetic :func:`mean` of the reciprocals of the + data. For example, the harmonic mean of three values *a*, *b* and *c* + will be equivalent to ``3/(1/a + 1/b + 1/c)``. If one of the values + is zero, the result will be zero. + + The harmonic mean is a type of average, a measure of the central + location of the data. It is often appropriate when averaging + rates or ratios, for example speeds. + + Suppose a car travels 10 km at 40 km/hr, then another 10 km at 60 km/hr. + What is the average speed? + + .. doctest:: + + >>> harmonic_mean([40, 60]) + 48.0 + + Suppose an investor purchases an equal value of shares in each of + three companies, with P/E (price/earning) ratios of 2.5, 3 and 10. + What is the average P/E ratio for the investor's portfolio? + + .. doctest:: + + >>> harmonic_mean([2.5, 3, 10]) # For an equal investment portfolio. + 3.6 + + :exc:`StatisticsError` is raised if *data* is empty, or any element + is less than zero. + + The current algorithm has an early-out when it encounters a zero + in the input. This means that the subsequent inputs are not tested + for validity. (This behavior may change in the future.) + + .. versionadded:: 3.6 + + +.. function:: median(data) + + Return the median (middle value) of numeric data, using the common "mean of + middle two" method. If *data* is empty, :exc:`StatisticsError` is raised. + *data* can be a sequence or iterable. + + The median is a robust measure of central location and is less affected by + the presence of outliers. When the number of data points is odd, the + middle data point is returned: + + .. doctest:: + + >>> median([1, 3, 5]) + 3 + + When the number of data points is even, the median is interpolated by taking + the average of the two middle values: + + .. doctest:: + + >>> median([1, 3, 5, 7]) + 4.0 + + This is suited for when your data is discrete, and you don't mind that the + median may not be an actual data point. + + If the data is ordinal (supports order operations) but not numeric (doesn't + support addition), consider using :func:`median_low` or :func:`median_high` + instead. + +.. function:: median_low(data) + + Return the low median of numeric data. If *data* is empty, + :exc:`StatisticsError` is raised. *data* can be a sequence or iterable. + + The low median is always a member of the data set. When the number of data + points is odd, the middle value is returned. When it is even, the smaller of + the two middle values is returned. + + .. doctest:: + + >>> median_low([1, 3, 5]) + 3 + >>> median_low([1, 3, 5, 7]) + 3 + + Use the low median when your data are discrete and you prefer the median to + be an actual data point rather than interpolated. + + +.. function:: median_high(data) + + Return the high median of data. If *data* is empty, :exc:`StatisticsError` + is raised. *data* can be a sequence or iterable. + + The high median is always a member of the data set. When the number of data + points is odd, the middle value is returned. When it is even, the larger of + the two middle values is returned. + + .. doctest:: + + >>> median_high([1, 3, 5]) + 3 + >>> median_high([1, 3, 5, 7]) + 5 + + Use the high median when your data are discrete and you prefer the median to + be an actual data point rather than interpolated. + + +.. function:: median_grouped(data, interval=1) + + Return the median of grouped continuous data, calculated as the 50th + percentile, using interpolation. If *data* is empty, :exc:`StatisticsError` + is raised. *data* can be a sequence or iterable. + + .. doctest:: + + >>> median_grouped([52, 52, 53, 54]) + 52.5 + + In the following example, the data are rounded, so that each value represents + the midpoint of data classes, e.g. 1 is the midpoint of the class 0.5--1.5, 2 + is the midpoint of 1.5--2.5, 3 is the midpoint of 2.5--3.5, etc. With the data + given, the middle value falls somewhere in the class 3.5--4.5, and + interpolation is used to estimate it: + + .. doctest:: + + >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) + 3.7 + + Optional argument *interval* represents the class interval, and defaults + to 1. Changing the class interval naturally will change the interpolation: + + .. doctest:: + + >>> median_grouped([1, 3, 3, 5, 7], interval=1) + 3.25 + >>> median_grouped([1, 3, 3, 5, 7], interval=2) + 3.5 + + This function does not check whether the data points are at least + *interval* apart. + + .. impl-detail:: + + Under some circumstances, :func:`median_grouped` may coerce data points to + floats. This behaviour is likely to change in the future. + + .. seealso:: + + * "Statistics for the Behavioral Sciences", Frederick J Gravetter and + Larry B Wallnau (8th Edition). + + * The `SSMEDIAN + `_ + function in the Gnome Gnumeric spreadsheet, including `this discussion + `_. + + +.. function:: mode(data) + + Return the single most common data point from discrete or nominal *data*. + The mode (when it exists) is the most typical value and serves as a + measure of central location. + + If there are multiple modes with the same frequency, returns the first one + encountered in the *data*. If the smallest or largest of those is + desired instead, use ``min(multimode(data))`` or ``max(multimode(data))``. + If the input *data* is empty, :exc:`StatisticsError` is raised. + + ``mode`` assumes discrete data and returns a single value. This is the + standard treatment of the mode as commonly taught in schools: + + .. doctest:: + + >>> mode([1, 1, 2, 3, 3, 3, 3, 4]) + 3 + + The mode is unique in that it is the only statistic in this package that + also applies to nominal (non-numeric) data: + + .. doctest:: + + >>> mode(["red", "blue", "blue", "red", "green", "red", "red"]) + 'red' + + .. versionchanged:: 3.8 + Now handles multimodal datasets by returning the first mode encountered. + Formerly, it raised :exc:`StatisticsError` when more than one mode was + found. + + +.. function:: multimode(data) + + Return a list of the most frequently occurring values in the order they + were first encountered in the *data*. Will return more than one result if + there are multiple modes or an empty list if the *data* is empty: + + .. doctest:: + + >>> multimode('aabbbbccddddeeffffgg') + ['b', 'd', 'f'] + >>> multimode('') + [] + + .. versionadded:: 3.8 + + +.. function:: pstdev(data, mu=None) + + Return the population standard deviation (the square root of the population + variance). See :func:`pvariance` for arguments and other details. + + .. doctest:: + + >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]) + 0.986893273527251 + + +.. function:: pvariance(data, mu=None) + + Return the population variance of *data*, a non-empty sequence or iterable + of real-valued numbers. Variance, or second moment about the mean, is a + measure of the variability (spread or dispersion) of data. A large + variance indicates that the data is spread out; a small variance indicates + it is clustered closely around the mean. + + If the optional second argument *mu* is given, it is typically the mean of + the *data*. It can also be used to compute the second moment around a + point that is not the mean. If it is missing or ``None`` (the default), + the arithmetic mean is automatically calculated. + + Use this function to calculate the variance from the entire population. To + estimate the variance from a sample, the :func:`variance` function is usually + a better choice. + + Raises :exc:`StatisticsError` if *data* is empty. + + Examples: + + .. doctest:: + + >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25] + >>> pvariance(data) + 1.25 + + If you have already calculated the mean of your data, you can pass it as the + optional second argument *mu* to avoid recalculation: + + .. doctest:: + + >>> mu = mean(data) + >>> pvariance(data, mu) + 1.25 + + Decimals and Fractions are supported: + + .. doctest:: + + >>> from decimal import Decimal as D + >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")]) + Decimal('24.815') + + >>> from fractions import Fraction as F + >>> pvariance([F(1, 4), F(5, 4), F(1, 2)]) + Fraction(13, 72) + + .. note:: + + When called with the entire population, this gives the population variance + σ². When called on a sample instead, this is the biased sample variance + s², also known as variance with N degrees of freedom. + + If you somehow know the true population mean μ, you may use this + function to calculate the variance of a sample, giving the known + population mean as the second argument. Provided the data points are a + random sample of the population, the result will be an unbiased estimate + of the population variance. + + +.. function:: stdev(data, xbar=None) + + Return the sample standard deviation (the square root of the sample + variance). See :func:`variance` for arguments and other details. + + .. doctest:: + + >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]) + 1.0810874155219827 + + +.. function:: variance(data, xbar=None) + + Return the sample variance of *data*, an iterable of at least two real-valued + numbers. Variance, or second moment about the mean, is a measure of the + variability (spread or dispersion) of data. A large variance indicates that + the data is spread out; a small variance indicates it is clustered closely + around the mean. + + If the optional second argument *xbar* is given, it should be the mean of + *data*. If it is missing or ``None`` (the default), the mean is + automatically calculated. + + Use this function when your data is a sample from a population. To calculate + the variance from the entire population, see :func:`pvariance`. + + Raises :exc:`StatisticsError` if *data* has fewer than two values. + + Examples: + + .. doctest:: + + >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] + >>> variance(data) + 1.3720238095238095 + + If you have already calculated the mean of your data, you can pass it as the + optional second argument *xbar* to avoid recalculation: + + .. doctest:: + + >>> m = mean(data) + >>> variance(data, m) + 1.3720238095238095 + + This function does not attempt to verify that you have passed the actual mean + as *xbar*. Using arbitrary values for *xbar* can lead to invalid or + impossible results. + + Decimal and Fraction values are supported: + + .. doctest:: + + >>> from decimal import Decimal as D + >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")]) + Decimal('31.01875') + + >>> from fractions import Fraction as F + >>> variance([F(1, 6), F(1, 2), F(5, 3)]) + Fraction(67, 108) + + .. note:: + + This is the sample variance s² with Bessel's correction, also known as + variance with N-1 degrees of freedom. Provided that the data points are + representative (e.g. independent and identically distributed), the result + should be an unbiased estimate of the true population variance. + + If you somehow know the actual population mean μ you should pass it to the + :func:`pvariance` function as the *mu* parameter to get the variance of a + sample. + +.. function:: quantiles(data, *, n=4, method='exclusive') + + Divide *data* into *n* continuous intervals with equal probability. + Returns a list of ``n - 1`` cut points separating the intervals. + + Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles. Set + *n* to 100 for percentiles which gives the 99 cuts points that separate + *data* into 100 equal sized groups. Raises :exc:`StatisticsError` if *n* + is not least 1. + + The *data* can be any iterable containing sample data. For meaningful + results, the number of data points in *data* should be larger than *n*. + Raises :exc:`StatisticsError` if there are not at least two data points. + + The cut points are linearly interpolated from the + two nearest data points. For example, if a cut point falls one-third + of the distance between two sample values, ``100`` and ``112``, the + cut-point will evaluate to ``104``. + + The *method* for computing quantiles can be varied depending on + whether the *data* includes or excludes the lowest and + highest possible values from the population. + + The default *method* is "exclusive" and is used for data sampled from + a population that can have more extreme values than found in the + samples. The portion of the population falling below the *i-th* of + *m* sorted data points is computed as ``i / (m + 1)``. Given nine + sample values, the method sorts them and assigns the following + percentiles: 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%. + + Setting the *method* to "inclusive" is used for describing population + data or for samples that are known to include the most extreme values + from the population. The minimum value in *data* is treated as the 0th + percentile and the maximum value is treated as the 100th percentile. + The portion of the population falling below the *i-th* of *m* sorted + data points is computed as ``(i - 1) / (m - 1)``. Given 11 sample + values, the method sorts them and assigns the following percentiles: + 0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%. + + .. doctest:: + + # Decile cut points for empirically sampled data + >>> data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110, + ... 100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129, + ... 106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86, + ... 111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95, + ... 103, 107, 101, 81, 109, 104] + >>> [round(q, 1) for q in quantiles(data, n=10)] + [81.0, 86.2, 89.0, 99.4, 102.5, 103.6, 106.0, 109.8, 111.0] + + .. versionadded:: 3.8 + + +Exceptions +---------- + +A single exception is defined: + +.. exception:: StatisticsError + + Subclass of :exc:`ValueError` for statistics-related exceptions. + + +:class:`NormalDist` objects +--------------------------- + +:class:`NormalDist` is a tool for creating and manipulating normal +distributions of a `random variable +`_. It is a +class that treats the mean and standard deviation of data +measurements as a single entity. + +Normal distributions arise from the `Central Limit Theorem +`_ and have a wide range +of applications in statistics. + +.. class:: NormalDist(mu=0.0, sigma=1.0) + + Returns a new *NormalDist* object where *mu* represents the `arithmetic + mean `_ and *sigma* + represents the `standard deviation + `_. + + If *sigma* is negative, raises :exc:`StatisticsError`. + + .. attribute:: mean + + A read-only property for the `arithmetic mean + `_ of a normal + distribution. + + .. attribute:: median + + A read-only property for the `median + `_ of a normal + distribution. + + .. attribute:: mode + + A read-only property for the `mode + `_ of a normal + distribution. + + .. attribute:: stdev + + A read-only property for the `standard deviation + `_ of a normal + distribution. + + .. attribute:: variance + + A read-only property for the `variance + `_ of a normal + distribution. Equal to the square of the standard deviation. + + .. classmethod:: NormalDist.from_samples(data) + + Makes a normal distribution instance with *mu* and *sigma* parameters + estimated from the *data* using :func:`fmean` and :func:`stdev`. + + The *data* can be any :term:`iterable` and should consist of values + that can be converted to type :class:`float`. If *data* does not + contain at least two elements, raises :exc:`StatisticsError` because it + takes at least one point to estimate a central value and at least two + points to estimate dispersion. + + .. method:: NormalDist.samples(n, *, seed=None) + + Generates *n* random samples for a given mean and standard deviation. + Returns a :class:`list` of :class:`float` values. + + If *seed* is given, creates a new instance of the underlying random + number generator. This is useful for creating reproducible results, + even in a multi-threading context. + + .. method:: NormalDist.pdf(x) + + Using a `probability density function (pdf) + `_, compute + the relative likelihood that a random variable *X* will be near the + given value *x*. Mathematically, it is the limit of the ratio ``P(x <= + X < x+dx) / dx`` as *dx* approaches zero. + + The relative likelihood is computed as the probability of a sample + occurring in a narrow range divided by the width of the range (hence + the word "density"). Since the likelihood is relative to other points, + its value can be greater than `1.0`. + + .. method:: NormalDist.cdf(x) + + Using a `cumulative distribution function (cdf) + `_, + compute the probability that a random variable *X* will be less than or + equal to *x*. Mathematically, it is written ``P(X <= x)``. + + .. method:: NormalDist.inv_cdf(p) + + Compute the inverse cumulative distribution function, also known as the + `quantile function `_ + or the `percent-point + `_ + function. Mathematically, it is written ``x : P(X <= x) = p``. + + Finds the value *x* of the random variable *X* such that the + probability of the variable being less than or equal to that value + equals the given probability *p*. + + .. method:: NormalDist.overlap(other) + + Measures the agreement between two normal probability distributions. + Returns a value between 0.0 and 1.0 giving `the overlapping area for + the two probability density functions + `_. + + .. method:: NormalDist.quantiles(n=4) + + Divide the normal distribution into *n* continuous intervals with + equal probability. Returns a list of (n - 1) cut points separating + the intervals. + + Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles. + Set *n* to 100 for percentiles which gives the 99 cuts points that + separate the normal distribution into 100 equal sized groups. + + .. method:: NormalDist.zscore(x) + + Compute the + `Standard Score `_ + describing *x* in terms of the number of standard deviations + above or below the mean of the normal distribution: + ``(x - mean) / stdev``. + + .. versionadded:: 3.9 + + Instances of :class:`NormalDist` support addition, subtraction, + multiplication and division by a constant. These operations + are used for translation and scaling. For example: + + .. doctest:: + + >>> temperature_february = NormalDist(5, 2.5) # Celsius + >>> temperature_february * (9/5) + 32 # Fahrenheit + NormalDist(mu=41.0, sigma=4.5) + + Dividing a constant by an instance of :class:`NormalDist` is not supported + because the result wouldn't be normally distributed. + + Since normal distributions arise from additive effects of independent + variables, it is possible to `add and subtract two independent normally + distributed random variables + `_ + represented as instances of :class:`NormalDist`. For example: + + .. doctest:: + + >>> birth_weights = NormalDist.from_samples([2.5, 3.1, 2.1, 2.4, 2.7, 3.5]) + >>> drug_effects = NormalDist(0.4, 0.15) + >>> combined = birth_weights + drug_effects + >>> round(combined.mean, 1) + 3.1 + >>> round(combined.stdev, 1) + 0.5 + + .. versionadded:: 3.8 + + +:class:`NormalDist` Examples and Recipes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:class:`NormalDist` readily solves classic probability problems. + +For example, given `historical data for SAT exams +`_ showing +that scores are normally distributed with a mean of 1060 and a standard +deviation of 195, determine the percentage of students with test scores +between 1100 and 1200, after rounding to the nearest whole number: + +.. doctest:: + + >>> sat = NormalDist(1060, 195) + >>> fraction = sat.cdf(1200 + 0.5) - sat.cdf(1100 - 0.5) + >>> round(fraction * 100.0, 1) + 18.4 + +Find the `quartiles `_ and `deciles +`_ for the SAT scores: + +.. doctest:: + + >>> list(map(round, sat.quantiles())) + [928, 1060, 1192] + >>> list(map(round, sat.quantiles(n=10))) + [810, 896, 958, 1011, 1060, 1109, 1162, 1224, 1310] + +To estimate the distribution for a model than isn't easy to solve +analytically, :class:`NormalDist` can generate input samples for a `Monte +Carlo simulation `_: + +.. doctest:: + + >>> def model(x, y, z): + ... return (3*x + 7*x*y - 5*y) / (11 * z) + ... + >>> n = 100_000 + >>> X = NormalDist(10, 2.5).samples(n, seed=3652260728) + >>> Y = NormalDist(15, 1.75).samples(n, seed=4582495471) + >>> Z = NormalDist(50, 1.25).samples(n, seed=6582483453) + >>> quantiles(map(model, X, Y, Z)) # doctest: +SKIP + [1.4591308524824727, 1.8035946855390597, 2.175091447274739] + +Normal distributions can be used to approximate `Binomial +distributions `_ +when the sample size is large and when the probability of a successful +trial is near 50%. + +For example, an open source conference has 750 attendees and two rooms with a +500 person capacity. There is a talk about Python and another about Ruby. +In previous conferences, 65% of the attendees preferred to listen to Python +talks. Assuming the population preferences haven't changed, what is the +probability that the Python room will stay within its capacity limits? + +.. doctest:: + + >>> n = 750 # Sample size + >>> p = 0.65 # Preference for Python + >>> q = 1.0 - p # Preference for Ruby + >>> k = 500 # Room capacity + + >>> # Approximation using the cumulative normal distribution + >>> from math import sqrt + >>> round(NormalDist(mu=n*p, sigma=sqrt(n*p*q)).cdf(k + 0.5), 4) + 0.8402 + + >>> # Solution using the cumulative binomial distribution + >>> from math import comb, fsum + >>> round(fsum(comb(n, r) * p**r * q**(n-r) for r in range(k+1)), 4) + 0.8402 + + >>> # Approximation using a simulation + >>> from random import seed, choices + >>> seed(8675309) + >>> def trial(): + ... return choices(('Python', 'Ruby'), (p, q), k=n).count('Python') + >>> mean(trial() <= k for i in range(10_000)) + 0.8398 + +Normal distributions commonly arise in machine learning problems. + +Wikipedia has a `nice example of a Naive Bayesian Classifier +`_. +The challenge is to predict a person's gender from measurements of normally +distributed features including height, weight, and foot size. + +We're given a training dataset with measurements for eight people. The +measurements are assumed to be normally distributed, so we summarize the data +with :class:`NormalDist`: + +.. doctest:: + + >>> height_male = NormalDist.from_samples([6, 5.92, 5.58, 5.92]) + >>> height_female = NormalDist.from_samples([5, 5.5, 5.42, 5.75]) + >>> weight_male = NormalDist.from_samples([180, 190, 170, 165]) + >>> weight_female = NormalDist.from_samples([100, 150, 130, 150]) + >>> foot_size_male = NormalDist.from_samples([12, 11, 12, 10]) + >>> foot_size_female = NormalDist.from_samples([6, 8, 7, 9]) + +Next, we encounter a new person whose feature measurements are known but whose +gender is unknown: + +.. doctest:: + + >>> ht = 6.0 # height + >>> wt = 130 # weight + >>> fs = 8 # foot size + +Starting with a 50% `prior probability +`_ of being male or female, +we compute the posterior as the prior times the product of likelihoods for the +feature measurements given the gender: + +.. doctest:: + + >>> prior_male = 0.5 + >>> prior_female = 0.5 + >>> posterior_male = (prior_male * height_male.pdf(ht) * + ... weight_male.pdf(wt) * foot_size_male.pdf(fs)) + + >>> posterior_female = (prior_female * height_female.pdf(ht) * + ... weight_female.pdf(wt) * foot_size_female.pdf(fs)) + +The final prediction goes to the largest posterior. This is known as the +`maximum a posteriori +`_ or MAP: + +.. doctest:: + + >>> 'male' if posterior_male > posterior_female else 'female' + 'female' + + +.. + # This modelines must appear within the last ten lines of the file. + kate: indent-width 3; remove-trailing-space on; replace-tabs on; encoding utf-8; diff --git a/cpython_2/environment/repo/Doc/library/stdtypes.rst b/cpython_2/environment/repo/Doc/library/stdtypes.rst new file mode 100644 index 0000000000000000000000000000000000000000..4e7729c83f49a41031769275d376ce525bd22914 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/stdtypes.rst @@ -0,0 +1,5013 @@ +.. XXX: reference/datamodel and this have quite a few overlaps! + + +.. _bltin-types: + +************** +Built-in Types +************** + +The following sections describe the standard types that are built into the +interpreter. + +.. index:: pair: built-in; types + +The principal built-in types are numerics, sequences, mappings, classes, +instances and exceptions. + +Some collection classes are mutable. The methods that add, subtract, or +rearrange their members in place, and don't return a specific item, never return +the collection instance itself but ``None``. + +Some operations are supported by several object types; in particular, +practically all objects can be compared for equality, tested for truth +value, and converted to a string (with the :func:`repr` function or the +slightly different :func:`str` function). The latter function is implicitly +used when an object is written by the :func:`print` function. + + +.. _truth: + +Truth Value Testing +=================== + +.. index:: + statement: if + statement: while + pair: truth; value + pair: Boolean; operations + single: false + +Any object can be tested for truth value, for use in an :keyword:`if` or +:keyword:`while` condition or as operand of the Boolean operations below. + +.. index:: single: true + +By default, an object is considered true unless its class defines either a +:meth:`__bool__` method that returns ``False`` or a :meth:`__len__` method that +returns zero, when called with the object. [1]_ Here are most of the built-in +objects considered false: + + .. index:: + single: None (Built-in object) + single: False (Built-in object) + +* constants defined to be false: ``None`` and ``False``. + +* zero of any numeric type: ``0``, ``0.0``, ``0j``, ``Decimal(0)``, + ``Fraction(0, 1)`` + +* empty sequences and collections: ``''``, ``()``, ``[]``, ``{}``, ``set()``, + ``range(0)`` + +.. index:: + operator: or + operator: and + single: False + single: True + +Operations and built-in functions that have a Boolean result always return ``0`` +or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated. +(Important exception: the Boolean operations ``or`` and ``and`` always return +one of their operands.) + + +.. _boolean: + +Boolean Operations --- :keyword:`!and`, :keyword:`!or`, :keyword:`!not` +======================================================================= + +.. index:: pair: Boolean; operations + +These are the Boolean operations, ordered by ascending priority: + ++-------------+---------------------------------+-------+ +| Operation | Result | Notes | ++=============+=================================+=======+ +| ``x or y`` | if *x* is false, then *y*, else | \(1) | +| | *x* | | ++-------------+---------------------------------+-------+ +| ``x and y`` | if *x* is false, then *x*, else | \(2) | +| | *y* | | ++-------------+---------------------------------+-------+ +| ``not x`` | if *x* is false, then ``True``, | \(3) | +| | else ``False`` | | ++-------------+---------------------------------+-------+ + +.. index:: + operator: and + operator: or + operator: not + +Notes: + +(1) + This is a short-circuit operator, so it only evaluates the second + argument if the first one is false. + +(2) + This is a short-circuit operator, so it only evaluates the second + argument if the first one is true. + +(3) + ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is + interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error. + + +.. _stdcomparisons: + +Comparisons +=========== + +.. index:: + pair: chaining; comparisons + pair: operator; comparison + operator: == + operator: < (less) + operator: <= + operator: > (greater) + operator: >= + operator: != + operator: is + operator: is not + +There are eight comparison operations in Python. They all have the same +priority (which is higher than that of the Boolean operations). Comparisons can +be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and +y <= z``, except that *y* is evaluated only once (but in both cases *z* is not +evaluated at all when ``x < y`` is found to be false). + +This table summarizes the comparison operations: + ++------------+-------------------------+ +| Operation | Meaning | ++============+=========================+ +| ``<`` | strictly less than | ++------------+-------------------------+ +| ``<=`` | less than or equal | ++------------+-------------------------+ +| ``>`` | strictly greater than | ++------------+-------------------------+ +| ``>=`` | greater than or equal | ++------------+-------------------------+ +| ``==`` | equal | ++------------+-------------------------+ +| ``!=`` | not equal | ++------------+-------------------------+ +| ``is`` | object identity | ++------------+-------------------------+ +| ``is not`` | negated object identity | ++------------+-------------------------+ + +.. index:: + pair: object; numeric + pair: objects; comparing + +Objects of different types, except different numeric types, never compare equal. +The ``==`` operator is always defined but for some object types (for example, +class objects) is equivalent to :keyword:`is`. The ``<``, ``<=``, ``>`` and ``>=`` +operators are only defined where they make sense; for example, they raise a +:exc:`TypeError` exception when one of the arguments is a complex number. + +.. index:: + single: __eq__() (instance method) + single: __ne__() (instance method) + single: __lt__() (instance method) + single: __le__() (instance method) + single: __gt__() (instance method) + single: __ge__() (instance method) + +Non-identical instances of a class normally compare as non-equal unless the +class defines the :meth:`__eq__` method. + +Instances of a class cannot be ordered with respect to other instances of the +same class, or other types of object, unless the class defines enough of the +methods :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` (in +general, :meth:`__lt__` and :meth:`__eq__` are sufficient, if you want the +conventional meanings of the comparison operators). + +The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be +customized; also they can be applied to any two objects and never raise an +exception. + +.. index:: + operator: in + operator: not in + +Two more operations with the same syntactic priority, :keyword:`in` and +:keyword:`not in`, are supported by types that are :term:`iterable` or +implement the :meth:`__contains__` method. + +.. _typesnumeric: + +Numeric Types --- :class:`int`, :class:`float`, :class:`complex` +================================================================ + +.. index:: + object: numeric + object: Boolean + object: integer + object: floating point + object: complex number + pair: C; language + +There are three distinct numeric types: :dfn:`integers`, :dfn:`floating +point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a +subtype of integers. Integers have unlimited precision. Floating point +numbers are usually implemented using :c:type:`double` in C; information +about the precision and internal representation of floating point +numbers for the machine on which your program is running is available +in :data:`sys.float_info`. Complex numbers have a real and imaginary +part, which are each a floating point number. To extract these parts +from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard +library includes the additional numeric types :mod:`fractions.Fraction`, for +rationals, and :mod:`decimal.Decimal`, for floating-point numbers with +user-definable precision.) + +.. index:: + pair: numeric; literals + pair: integer; literals + pair: floating point; literals + pair: complex number; literals + pair: hexadecimal; literals + pair: octal; literals + pair: binary; literals + +Numbers are created by numeric literals or as the result of built-in functions +and operators. Unadorned integer literals (including hex, octal and binary +numbers) yield integers. Numeric literals containing a decimal point or an +exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a +numeric literal yields an imaginary number (a complex number with a zero real +part) which you can add to an integer or float to get a complex number with real +and imaginary parts. + +.. index:: + single: arithmetic + builtin: int + builtin: float + builtin: complex + single: operator; + (plus) + single: + (plus); unary operator + single: + (plus); binary operator + single: operator; - (minus) + single: - (minus); unary operator + single: - (minus); binary operator + operator: * (asterisk) + operator: / (slash) + operator: // + operator: % (percent) + operator: ** + +Python fully supports mixed arithmetic: when a binary arithmetic operator has +operands of different numeric types, the operand with the "narrower" type is +widened to that of the other, where integer is narrower than floating point, +which is narrower than complex. A comparison between numbers of different types +behaves as though the exact values of those numbers were being compared. [2]_ + +The constructors :func:`int`, :func:`float`, and +:func:`complex` can be used to produce numbers of a specific type. + +All numeric types (except complex) support the following operations (for priorities of +the operations, see :ref:`operator-summary`): + ++---------------------+---------------------------------+---------+--------------------+ +| Operation | Result | Notes | Full documentation | ++=====================+=================================+=========+====================+ +| ``x + y`` | sum of *x* and *y* | | | ++---------------------+---------------------------------+---------+--------------------+ +| ``x - y`` | difference of *x* and *y* | | | ++---------------------+---------------------------------+---------+--------------------+ +| ``x * y`` | product of *x* and *y* | | | ++---------------------+---------------------------------+---------+--------------------+ +| ``x / y`` | quotient of *x* and *y* | | | ++---------------------+---------------------------------+---------+--------------------+ +| ``x // y`` | floored quotient of *x* and | \(1) | | +| | *y* | | | ++---------------------+---------------------------------+---------+--------------------+ +| ``x % y`` | remainder of ``x / y`` | \(2) | | ++---------------------+---------------------------------+---------+--------------------+ +| ``-x`` | *x* negated | | | ++---------------------+---------------------------------+---------+--------------------+ +| ``+x`` | *x* unchanged | | | ++---------------------+---------------------------------+---------+--------------------+ +| ``abs(x)`` | absolute value or magnitude of | | :func:`abs` | +| | *x* | | | ++---------------------+---------------------------------+---------+--------------------+ +| ``int(x)`` | *x* converted to integer | \(3)\(6)| :func:`int` | ++---------------------+---------------------------------+---------+--------------------+ +| ``float(x)`` | *x* converted to floating point | \(4)\(6)| :func:`float` | ++---------------------+---------------------------------+---------+--------------------+ +| ``complex(re, im)`` | a complex number with real part | \(6) | :func:`complex` | +| | *re*, imaginary part *im*. | | | +| | *im* defaults to zero. | | | ++---------------------+---------------------------------+---------+--------------------+ +| ``c.conjugate()`` | conjugate of the complex number | | | +| | *c* | | | ++---------------------+---------------------------------+---------+--------------------+ +| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` | ++---------------------+---------------------------------+---------+--------------------+ +| ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` | ++---------------------+---------------------------------+---------+--------------------+ +| ``x ** y`` | *x* to the power *y* | \(5) | | ++---------------------+---------------------------------+---------+--------------------+ + +.. index:: + triple: operations on; numeric; types + single: conjugate() (complex number method) + +Notes: + +(1) + Also referred to as integer division. The resultant value is a whole + integer, though the result's type is not necessarily int. The result is + always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is + ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``. + +(2) + Not for complex numbers. Instead convert to floats using :func:`abs` if + appropriate. + +(3) + .. index:: + module: math + single: floor() (in module math) + single: ceil() (in module math) + single: trunc() (in module math) + pair: numeric; conversions + pair: C; language + + Conversion from floating point to integer may round or truncate + as in C; see functions :func:`math.floor` and :func:`math.ceil` for + well-defined conversions. + +(4) + 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. + +(6) + The numeric literals accepted include the digits ``0`` to ``9`` or any + Unicode equivalent (code points with the ``Nd`` property). + + See https://www.unicode.org/Public/13.0.0/ucd/extracted/DerivedNumericType.txt + for a complete list of code points with the ``Nd`` property. + + +All :class:`numbers.Real` types (:class:`int` and :class:`float`) also include +the following operations: + ++--------------------+---------------------------------------------+ +| Operation | Result | ++====================+=============================================+ +| :func:`math.trunc(\| *x* truncated to :class:`~numbers.Integral` | +| x) ` | | ++--------------------+---------------------------------------------+ +| :func:`round(x[, | *x* rounded to *n* digits, | +| n]) ` | rounding half to even. If *n* is | +| | omitted, it defaults to 0. | ++--------------------+---------------------------------------------+ +| :func:`math.floor(\| the greatest :class:`~numbers.Integral` | +| x) ` | <= *x* | ++--------------------+---------------------------------------------+ +| :func:`math.ceil(x)| the least :class:`~numbers.Integral` >= *x* | +| ` | | ++--------------------+---------------------------------------------+ + +For additional numeric operations see the :mod:`math` and :mod:`cmath` +modules. + +.. XXXJH exceptions: overflow (when? what operations?) zerodivision + + +.. _bitstring-ops: + +Bitwise Operations on Integer Types +----------------------------------- + +.. index:: + triple: operations on; integer; types + pair: bitwise; operations + pair: shifting; operations + pair: masking; operations + operator: | (vertical bar) + operator: ^ (caret) + operator: & (ampersand) + operator: << + operator: >> + operator: ~ (tilde) + +Bitwise operations only make sense for integers. The result of bitwise +operations is calculated as though carried out in two's complement with an +infinite number of sign bits. + +The priorities of the binary bitwise operations are all lower than the numeric +operations and higher than the comparisons; the unary operation ``~`` has the +same priority as the other unary numeric operations (``+`` and ``-``). + +This table lists the bitwise operations sorted in ascending priority: + ++------------+--------------------------------+----------+ +| Operation | Result | Notes | ++============+================================+==========+ +| ``x | y`` | bitwise :dfn:`or` of *x* and | \(4) | +| | *y* | | ++------------+--------------------------------+----------+ +| ``x ^ y`` | bitwise :dfn:`exclusive or` of | \(4) | +| | *x* and *y* | | ++------------+--------------------------------+----------+ +| ``x & y`` | bitwise :dfn:`and` of *x* and | \(4) | +| | *y* | | ++------------+--------------------------------+----------+ +| ``x << n`` | *x* shifted left by *n* bits | (1)(2) | ++------------+--------------------------------+----------+ +| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) | ++------------+--------------------------------+----------+ +| ``~x`` | the bits of *x* inverted | | ++------------+--------------------------------+----------+ + +Notes: + +(1) + Negative shift counts are illegal and cause a :exc:`ValueError` to be raised. + +(2) + A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)`` + without overflow check. + +(3) + A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without + overflow check. + +(4) + Performing these calculations with at least one extra sign extension bit in + a finite two's complement representation (a working bit-width of + ``1 + max(x.bit_length(), y.bit_length())`` or more) is sufficient to get the + same result as if there were an infinite number of sign bits. + + +Additional Methods on Integer Types +----------------------------------- + +The int type implements the :class:`numbers.Integral` :term:`abstract base +class`. In addition, it provides a few more methods: + +.. method:: int.bit_length() + + Return the number of bits necessary to represent an integer in binary, + excluding the sign and leading zeros:: + + >>> n = -37 + >>> bin(n) + '-0b100101' + >>> n.bit_length() + 6 + + More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the + unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``. + Equivalently, when ``abs(x)`` is small enough to have a correctly + rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``. + If ``x`` is zero, then ``x.bit_length()`` returns ``0``. + + Equivalent to:: + + def bit_length(self): + s = bin(self) # binary representation: bin(-37) --> '-0b100101' + s = s.lstrip('-0b') # remove leading zeros and minus sign + return len(s) # len('100101') --> 6 + + .. versionadded:: 3.1 + +.. method:: int.to_bytes(length, byteorder, \*, signed=False) + + Return an array of bytes representing an integer. + + >>> (1024).to_bytes(2, byteorder='big') + b'\x04\x00' + >>> (1024).to_bytes(10, byteorder='big') + b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' + >>> (-1024).to_bytes(10, byteorder='big', signed=True) + b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' + >>> x = 1000 + >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') + b'\xe8\x03' + + The integer is represented using *length* bytes. An :exc:`OverflowError` + is raised if the integer is not representable with the given number of + bytes. + + The *byteorder* argument determines the byte order used to represent the + integer. If *byteorder* is ``"big"``, the most significant byte is at the + beginning of the byte array. If *byteorder* is ``"little"``, the most + significant byte is at the end of the byte array. To request the native + byte order of the host system, use :data:`sys.byteorder` as the byte order + value. + + The *signed* argument determines whether two's complement is used to + represent the integer. If *signed* is ``False`` and a negative integer is + given, an :exc:`OverflowError` is raised. The default value for *signed* + is ``False``. + + .. versionadded:: 3.2 + +.. classmethod:: int.from_bytes(bytes, byteorder, \*, signed=False) + + Return the integer represented by the given array of bytes. + + >>> int.from_bytes(b'\x00\x10', byteorder='big') + 16 + >>> int.from_bytes(b'\x00\x10', byteorder='little') + 4096 + >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) + -1024 + >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) + 64512 + >>> int.from_bytes([255, 0, 0], byteorder='big') + 16711680 + + The argument *bytes* must either be a :term:`bytes-like object` or an + iterable producing bytes. + + The *byteorder* argument determines the byte order used to represent the + integer. If *byteorder* is ``"big"``, the most significant byte is at the + beginning of the byte array. If *byteorder* is ``"little"``, the most + significant byte is at the end of the byte array. To request the native + byte order of the host system, use :data:`sys.byteorder` as the byte order + value. + + The *signed* argument indicates whether two's complement is used to + represent the integer. + + .. versionadded:: 3.2 + +.. method:: int.as_integer_ratio() + + Return a pair of integers whose ratio is exactly equal to the original + integer and with a positive denominator. The integer ratio of integers + (whole numbers) is always the integer as the numerator and ``1`` as the + denominator. + + .. versionadded:: 3.8 + +Additional Methods on Float +--------------------------- + +The float type implements the :class:`numbers.Real` :term:`abstract base +class`. float also has the following additional methods. + +.. method:: float.as_integer_ratio() + + Return a pair of integers whose ratio is exactly equal to the + original float and with a positive denominator. Raises + :exc:`OverflowError` on infinities and a :exc:`ValueError` on + NaNs. + +.. method:: float.is_integer() + + Return ``True`` if the float instance is finite with integral + value, and ``False`` otherwise:: + + >>> (-2.0).is_integer() + True + >>> (3.2).is_integer() + False + +Two methods support conversion to +and from hexadecimal strings. Since Python's floats are stored +internally as binary numbers, converting a float to or from a +*decimal* string usually involves a small rounding error. In +contrast, hexadecimal strings allow exact representation and +specification of floating-point numbers. This can be useful when +debugging, and in numerical work. + + +.. method:: float.hex() + + Return a representation of a floating-point number as a hexadecimal + string. For finite floating-point numbers, this representation + will always include a leading ``0x`` and a trailing ``p`` and + exponent. + + +.. classmethod:: float.fromhex(s) + + Class method to return the float represented by a hexadecimal + string *s*. The string *s* may have leading and trailing + whitespace. + + +Note that :meth:`float.hex` is an instance method, while +:meth:`float.fromhex` is a class method. + +A hexadecimal string takes the form:: + + [sign] ['0x'] integer ['.' fraction] ['p' exponent] + +where the optional ``sign`` may by either ``+`` or ``-``, ``integer`` +and ``fraction`` are strings of hexadecimal digits, and ``exponent`` +is a decimal integer with an optional leading sign. Case is not +significant, and there must be at least one hexadecimal digit in +either the integer or the fraction. This syntax is similar to the +syntax specified in section 6.4.4.2 of the C99 standard, and also to +the syntax used in Java 1.5 onwards. In particular, the output of +:meth:`float.hex` is usable as a hexadecimal floating-point literal in +C or Java code, and hexadecimal strings produced by C's ``%a`` format +character or Java's ``Double.toHexString`` are accepted by +:meth:`float.fromhex`. + + +Note that the exponent is written in decimal rather than hexadecimal, +and that it gives the power of 2 by which to multiply the coefficient. +For example, the hexadecimal string ``0x3.a7p10`` represents the +floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or +``3740.0``:: + + >>> float.fromhex('0x3.a7p10') + 3740.0 + + +Applying the reverse conversion to ``3740.0`` gives a different +hexadecimal string representing the same number:: + + >>> float.hex(3740.0) + '0x1.d380000000000p+11' + + +.. _numeric-hash: + +Hashing of numeric types +------------------------ + +For numbers ``x`` and ``y``, possibly of different types, it's a requirement +that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`__hash__` +method documentation for more details). For ease of implementation and +efficiency across a variety of numeric types (including :class:`int`, +:class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`) +Python's hash for numeric types is based on a single mathematical function +that's defined for any rational number, and hence applies to all instances of +:class:`int` and :class:`fractions.Fraction`, and all finite instances of +:class:`float` and :class:`decimal.Decimal`. Essentially, this function is +given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is +made available to Python as the :attr:`modulus` attribute of +:data:`sys.hash_info`. + +.. impl-detail:: + + Currently, the prime used is ``P = 2**31 - 1`` on machines with 32-bit C + longs and ``P = 2**61 - 1`` on machines with 64-bit C longs. + +Here are the rules in detail: + +- If ``x = m / n`` is a nonnegative rational number and ``n`` is not divisible + by ``P``, define ``hash(x)`` as ``m * invmod(n, P) % P``, where ``invmod(n, + P)`` gives the inverse of ``n`` modulo ``P``. + +- If ``x = m / n`` is a nonnegative rational number and ``n`` is + divisible by ``P`` (but ``m`` is not) then ``n`` has no inverse + modulo ``P`` and the rule above doesn't apply; in this case define + ``hash(x)`` to be the constant value ``sys.hash_info.inf``. + +- If ``x = m / n`` is a negative rational number define ``hash(x)`` + as ``-hash(-x)``. If the resulting hash is ``-1``, replace it with + ``-2``. + +- The particular values ``sys.hash_info.inf``, ``-sys.hash_info.inf`` + and ``sys.hash_info.nan`` are used as hash values for positive + infinity, negative infinity, or nans (respectively). (All hashable + nans have the same hash value.) + +- For a :class:`complex` number ``z``, the hash values of the real + and imaginary parts are combined by computing ``hash(z.real) + + sys.hash_info.imag * hash(z.imag)``, reduced modulo + ``2**sys.hash_info.width`` so that it lies in + ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - + 1))``. Again, if the result is ``-1``, it's replaced with ``-2``. + + +To clarify the above rules, here's some example Python code, +equivalent to the built-in hash, for computing the hash of a rational +number, :class:`float`, or :class:`complex`:: + + + import sys, math + + def hash_fraction(m, n): + """Compute the hash of a rational number m / n. + + Assumes m and n are integers, with n positive. + Equivalent to hash(fractions.Fraction(m, n)). + + """ + P = sys.hash_info.modulus + # Remove common factors of P. (Unnecessary if m and n already coprime.) + while m % P == n % P == 0: + m, n = m // P, n // P + + if n % P == 0: + hash_value = sys.hash_info.inf + else: + # Fermat's Little Theorem: pow(n, P-1, P) is 1, so + # pow(n, P-2, P) gives the inverse of n modulo P. + hash_value = (abs(m) % P) * pow(n, P - 2, P) % P + if m < 0: + hash_value = -hash_value + if hash_value == -1: + hash_value = -2 + return hash_value + + def hash_float(x): + """Compute the hash of a float x.""" + + if math.isnan(x): + return sys.hash_info.nan + elif math.isinf(x): + return sys.hash_info.inf if x > 0 else -sys.hash_info.inf + else: + return hash_fraction(*x.as_integer_ratio()) + + def hash_complex(z): + """Compute the hash of a complex number z.""" + + hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag) + # do a signed reduction modulo 2**sys.hash_info.width + M = 2**(sys.hash_info.width - 1) + hash_value = (hash_value & (M - 1)) - (hash_value & M) + if hash_value == -1: + hash_value = -2 + return hash_value + +.. _typeiter: + +Iterator Types +============== + +.. index:: + single: iterator protocol + single: protocol; iterator + single: sequence; iteration + single: container; iteration over + +Python supports a concept of iteration over containers. This is implemented +using two distinct methods; these are used to allow user-defined classes to +support iteration. Sequences, described below in more detail, always support +the iteration methods. + +One method needs to be defined for container objects to provide iteration +support: + +.. XXX duplicated in reference/datamodel! + +.. method:: container.__iter__() + + Return an iterator object. The object is required to support the iterator + protocol described below. If a container supports different types of + iteration, additional methods can be provided to specifically request + iterators for those iteration types. (An example of an object supporting + multiple forms of iteration would be a tree structure which supports both + breadth-first and depth-first traversal.) This method corresponds to the + :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python objects in the Python/C + API. + +The iterator objects themselves are required to support the following two +methods, which together form the :dfn:`iterator protocol`: + + +.. method:: iterator.__iter__() + + Return the iterator object itself. This is required to allow both containers + and iterators to be used with the :keyword:`for` and :keyword:`in` statements. + This method corresponds to the :c:member:`~PyTypeObject.tp_iter` slot of the type structure for + Python objects in the Python/C API. + + +.. method:: iterator.__next__() + + Return the next item from the container. If there are no further items, raise + the :exc:`StopIteration` exception. This method corresponds to the + :c:member:`~PyTypeObject.tp_iternext` slot of the type structure for Python objects in the + Python/C API. + +Python defines several iterator objects to support iteration over general and +specific sequence types, dictionaries, and other more specialized forms. The +specific types are not important beyond their implementation of the iterator +protocol. + +Once an iterator's :meth:`~iterator.__next__` method raises +:exc:`StopIteration`, it must continue to do so on subsequent calls. +Implementations that do not obey this property are deemed broken. + + +.. _generator-types: + +Generator Types +--------------- + +Python's :term:`generator`\s provide a convenient way to implement the iterator +protocol. If a container object's :meth:`__iter__` method is implemented as a +generator, it will automatically return an iterator object (technically, a +generator object) supplying the :meth:`__iter__` and :meth:`~generator.__next__` +methods. +More information about generators can be found in :ref:`the documentation for +the yield expression `. + + +.. _typesseq: + +Sequence Types --- :class:`list`, :class:`tuple`, :class:`range` +================================================================ + +There are three basic sequence types: lists, tuples, and range objects. +Additional sequence types tailored for processing of +:ref:`binary data ` and :ref:`text strings ` are +described in dedicated sections. + + +.. _typesseq-common: + +Common Sequence Operations +-------------------------- + +.. index:: object: sequence + +The operations in the following table are supported by most sequence types, +both mutable and immutable. The :class:`collections.abc.Sequence` ABC is +provided to make it easier to correctly implement these operations on +custom sequence types. + +This table lists the sequence operations sorted in ascending priority. In the +table, *s* and *t* are sequences of the same type, *n*, *i*, *j* and *k* are +integers and *x* is an arbitrary object that meets any type and value +restrictions imposed by *s*. + +The ``in`` and ``not in`` operations have the same priorities as the +comparison operations. The ``+`` (concatenation) and ``*`` (repetition) +operations have the same priority as the corresponding numeric operations. [3]_ + +.. index:: + triple: operations on; sequence; types + builtin: len + builtin: min + builtin: max + pair: concatenation; operation + pair: repetition; operation + pair: subscript; operation + pair: slice; operation + operator: in + operator: not in + single: count() (sequence method) + single: index() (sequence method) + ++--------------------------+--------------------------------+----------+ +| Operation | Result | Notes | ++==========================+================================+==========+ +| ``x in s`` | ``True`` if an item of *s* is | \(1) | +| | equal to *x*, else ``False`` | | ++--------------------------+--------------------------------+----------+ +| ``x not in s`` | ``False`` if an item of *s* is | \(1) | +| | equal to *x*, else ``True`` | | ++--------------------------+--------------------------------+----------+ +| ``s + t`` | the concatenation of *s* and | (6)(7) | +| | *t* | | ++--------------------------+--------------------------------+----------+ +| ``s * n`` or | equivalent to adding *s* to | (2)(7) | +| ``n * s`` | itself *n* times | | ++--------------------------+--------------------------------+----------+ +| ``s[i]`` | *i*\ th item of *s*, origin 0 | \(3) | ++--------------------------+--------------------------------+----------+ +| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) | ++--------------------------+--------------------------------+----------+ +| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) | +| | with step *k* | | ++--------------------------+--------------------------------+----------+ +| ``len(s)`` | length of *s* | | ++--------------------------+--------------------------------+----------+ +| ``min(s)`` | smallest item of *s* | | ++--------------------------+--------------------------------+----------+ +| ``max(s)`` | largest item of *s* | | ++--------------------------+--------------------------------+----------+ +| ``s.index(x[, i[, j]])`` | index of the first occurrence | \(8) | +| | of *x* in *s* (at or after | | +| | index *i* and before index *j*)| | ++--------------------------+--------------------------------+----------+ +| ``s.count(x)`` | total number of occurrences of | | +| | *x* in *s* | | ++--------------------------+--------------------------------+----------+ + +Sequences of the same type also support comparisons. In particular, tuples +and lists are compared lexicographically by comparing corresponding elements. +This means that to compare equal, every element must compare equal and the +two sequences must be of the same type and have the same length. (For full +details see :ref:`comparisons` in the language reference.) + +Notes: + +(1) + While the ``in`` and ``not in`` operations are used only for simple + containment testing in the general case, some specialised sequences + (such as :class:`str`, :class:`bytes` and :class:`bytearray`) also use + them for subsequence testing:: + + >>> "gg" in "eggs" + True + +(2) + Values of *n* less than ``0`` are treated as ``0`` (which yields an empty + sequence of the same type as *s*). Note that items in the sequence *s* + are not copied; they are referenced multiple times. This often haunts + new Python programmers; consider:: + + >>> lists = [[]] * 3 + >>> lists + [[], [], []] + >>> lists[0].append(3) + >>> lists + [[3], [3], [3]] + + What has happened is that ``[[]]`` is a one-element list containing an empty + list, so all three elements of ``[[]] * 3`` are references to this single empty + list. Modifying any of the elements of ``lists`` modifies this single list. + You can create a list of different lists this way:: + + >>> lists = [[] for i in range(3)] + >>> lists[0].append(3) + >>> lists[1].append(5) + >>> lists[2].append(7) + >>> lists + [[3], [5], [7]] + + Further explanation is available in the FAQ entry + :ref:`faq-multidimensional-list`. + +(3) + If *i* or *j* is negative, the index is relative to the end of sequence *s*: + ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is + still ``0``. + +(4) + The slice of *s* from *i* to *j* is defined as the sequence of items with index + *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use + ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or + ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is + empty. + +(5) + The slice of *s* from *i* to *j* with step *k* is defined as the sequence of + items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words, + the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when + *j* is reached (but never including *j*). When *k* is positive, + *i* and *j* are reduced to ``len(s)`` if they are greater. + When *k* is negative, *i* and *j* are reduced to ``len(s) - 1`` if + they are greater. If *i* or *j* are omitted or ``None``, they become + "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero. + If *k* is ``None``, it is treated like ``1``. + +(6) + Concatenating immutable sequences always results in a new object. This + means that building up a sequence by repeated concatenation will have a + quadratic runtime cost in the total sequence length. To get a linear + runtime cost, you must switch to one of the alternatives below: + + * if concatenating :class:`str` objects, you can build a list and use + :meth:`str.join` at the end or else write to an :class:`io.StringIO` + instance and retrieve its value when complete + + * if concatenating :class:`bytes` objects, you can similarly use + :meth:`bytes.join` or :class:`io.BytesIO`, or you can do in-place + concatenation with a :class:`bytearray` object. :class:`bytearray` + objects are mutable and have an efficient overallocation mechanism + + * if concatenating :class:`tuple` objects, extend a :class:`list` instead + + * for other types, investigate the relevant class documentation + + +(7) + Some sequence types (such as :class:`range`) only support item sequences + that follow specific patterns, and hence don't support sequence + concatenation or repetition. + +(8) + ``index`` raises :exc:`ValueError` when *x* is not found in *s*. + Not all implementations support passing the additional arguments *i* and *j*. + These arguments allow efficient searching of subsections of the sequence. Passing + the extra arguments is roughly equivalent to using ``s[i:j].index(x)``, only + without copying any data and with the returned index being relative to + the start of the sequence rather than the start of the slice. + + +.. _typesseq-immutable: + +Immutable Sequence Types +------------------------ + +.. index:: + triple: immutable; sequence; types + object: tuple + builtin: hash + +The only operation that immutable sequence types generally implement that is +not also implemented by mutable sequence types is support for the :func:`hash` +built-in. + +This support allows immutable sequences, such as :class:`tuple` instances, to +be used as :class:`dict` keys and stored in :class:`set` and :class:`frozenset` +instances. + +Attempting to hash an immutable sequence that contains unhashable values will +result in :exc:`TypeError`. + + +.. _typesseq-mutable: + +Mutable Sequence Types +---------------------- + +.. index:: + triple: mutable; sequence; types + object: list + object: bytearray + +The operations in the following table are defined on mutable sequence types. +The :class:`collections.abc.MutableSequence` ABC is provided to make it +easier to correctly implement these operations on custom sequence types. + +In the table *s* is an instance of a mutable sequence type, *t* is any +iterable object and *x* is an arbitrary object that meets any type +and value restrictions imposed by *s* (for example, :class:`bytearray` only +accepts integers that meet the value restriction ``0 <= x <= 255``). + + +.. index:: + triple: operations on; sequence; types + triple: operations on; list; type + pair: subscript; assignment + pair: slice; assignment + statement: del + single: append() (sequence method) + single: clear() (sequence method) + single: copy() (sequence method) + single: extend() (sequence method) + single: insert() (sequence method) + single: pop() (sequence method) + single: remove() (sequence method) + single: reverse() (sequence method) + ++------------------------------+--------------------------------+---------------------+ +| Operation | Result | Notes | ++==============================+================================+=====================+ +| ``s[i] = x`` | item *i* of *s* is replaced by | | +| | *x* | | ++------------------------------+--------------------------------+---------------------+ +| ``s[i:j] = t`` | slice of *s* from *i* to *j* | | +| | is replaced by the contents of | | +| | the iterable *t* | | ++------------------------------+--------------------------------+---------------------+ +| ``del s[i:j]`` | same as ``s[i:j] = []`` | | ++------------------------------+--------------------------------+---------------------+ +| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) | +| | are replaced by those of *t* | | ++------------------------------+--------------------------------+---------------------+ +| ``del s[i:j:k]`` | removes the elements of | | +| | ``s[i:j:k]`` from the list | | ++------------------------------+--------------------------------+---------------------+ +| ``s.append(x)`` | appends *x* to the end of the | | +| | sequence (same as | | +| | ``s[len(s):len(s)] = [x]``) | | ++------------------------------+--------------------------------+---------------------+ +| ``s.clear()`` | removes all items from *s* | \(5) | +| | (same as ``del s[:]``) | | ++------------------------------+--------------------------------+---------------------+ +| ``s.copy()`` | creates a shallow copy of *s* | \(5) | +| | (same as ``s[:]``) | | ++------------------------------+--------------------------------+---------------------+ +| ``s.extend(t)`` or | extends *s* with the | | +| ``s += t`` | contents of *t* (for the | | +| | most part the same as | | +| | ``s[len(s):len(s)] = t``) | | ++------------------------------+--------------------------------+---------------------+ +| ``s *= n`` | updates *s* with its contents | \(6) | +| | repeated *n* times | | ++------------------------------+--------------------------------+---------------------+ +| ``s.insert(i, x)`` | inserts *x* into *s* at the | | +| | index given by *i* | | +| | (same as ``s[i:i] = [x]``) | | ++------------------------------+--------------------------------+---------------------+ +| ``s.pop([i])`` | retrieves the item at *i* and | \(2) | +| | also removes it from *s* | | ++------------------------------+--------------------------------+---------------------+ +| ``s.remove(x)`` | remove the first item from *s* | \(3) | +| | where ``s[i]`` is equal to *x* | | ++------------------------------+--------------------------------+---------------------+ +| ``s.reverse()`` | reverses the items of *s* in | \(4) | +| | place | | ++------------------------------+--------------------------------+---------------------+ + + +Notes: + +(1) + *t* must have the same length as the slice it is replacing. + +(2) + The optional argument *i* defaults to ``-1``, so that by default the last + item is removed and returned. + +(3) + :meth:`remove` raises :exc:`ValueError` when *x* is not found in *s*. + +(4) + The :meth:`reverse` method modifies the sequence in place for economy of + space when reversing a large sequence. To remind users that it operates by + side effect, it does not return the reversed sequence. + +(5) + :meth:`clear` and :meth:`!copy` are included for consistency with the + interfaces of mutable containers that don't support slicing operations + (such as :class:`dict` and :class:`set`). :meth:`!copy` is not part of the + :class:`collections.abc.MutableSequence` ABC, but most concrete + mutable sequence classes provide it. + + .. versionadded:: 3.3 + :meth:`clear` and :meth:`!copy` methods. + +(6) + The value *n* is an integer, or an object implementing + :meth:`~object.__index__`. Zero and negative values of *n* clear + the sequence. Items in the sequence are not copied; they are referenced + multiple times, as explained for ``s * n`` under :ref:`typesseq-common`. + + +.. _typesseq-list: + +Lists +----- + +.. index:: object: list + +Lists are mutable sequences, typically used to store collections of +homogeneous items (where the precise degree of similarity will vary by +application). + +.. class:: list([iterable]) + + Lists may be constructed in several ways: + + * Using a pair of square brackets to denote the empty list: ``[]`` + * Using square brackets, separating items with commas: ``[a]``, ``[a, b, c]`` + * Using a list comprehension: ``[x for x in iterable]`` + * Using the type constructor: ``list()`` or ``list(iterable)`` + + The constructor builds a list whose items are the same and in the same + order as *iterable*'s items. *iterable* may be either a sequence, a + container that supports iteration, or an iterator object. If *iterable* + is already a list, a copy is made and returned, similar to ``iterable[:]``. + For example, ``list('abc')`` returns ``['a', 'b', 'c']`` and + ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``. + If no argument is given, the constructor creates a new empty list, ``[]``. + + + Many other operations also produce lists, including the :func:`sorted` + built-in. + + Lists implement all of the :ref:`common ` and + :ref:`mutable ` sequence operations. Lists also provide the + following additional method: + + .. method:: list.sort(*, key=None, reverse=False) + + This method sorts the list in place, using only ``<`` comparisons + between items. Exceptions are not suppressed - if any comparison operations + fail, the entire sort operation will fail (and the list will likely be left + in a partially modified state). + + :meth:`sort` accepts two arguments that can only be passed by keyword + (:ref:`keyword-only arguments `): + + *key* specifies a function of one argument that is used to extract a + comparison key from each list element (for example, ``key=str.lower``). + The key corresponding to each item in the list is calculated once and + then used for the entire sorting process. The default value of ``None`` + means that list items are sorted directly without calculating a separate + key value. + + The :func:`functools.cmp_to_key` utility is available to convert a 2.x + style *cmp* function to a *key* function. + + *reverse* is a boolean value. If set to ``True``, then the list elements + are sorted as if each comparison were reversed. + + This method modifies the sequence in place for economy of space when + sorting a large sequence. To remind users that it operates by side + effect, it does not return the sorted sequence (use :func:`sorted` to + explicitly request a new sorted list instance). + + The :meth:`sort` method is guaranteed to be stable. A sort is stable if it + guarantees not to change the relative order of elements that compare equal + --- this is helpful for sorting in multiple passes (for example, sort by + department, then by salary grade). + + For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`. + + .. impl-detail:: + + While a list is being sorted, the effect of attempting to mutate, or even + inspect, the list is undefined. The C implementation of Python 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. + + +.. _typesseq-tuple: + +Tuples +------ + +.. index:: object: tuple + +Tuples are immutable sequences, typically used to store collections of +heterogeneous data (such as the 2-tuples produced by the :func:`enumerate` +built-in). Tuples are also used for cases where an immutable sequence of +homogeneous data is needed (such as allowing storage in a :class:`set` or +:class:`dict` instance). + +.. class:: tuple([iterable]) + + Tuples may be constructed in a number of ways: + + * Using a pair of parentheses to denote the empty tuple: ``()`` + * Using a trailing comma for a singleton tuple: ``a,`` or ``(a,)`` + * Separating items with commas: ``a, b, c`` or ``(a, b, c)`` + * Using the :func:`tuple` built-in: ``tuple()`` or ``tuple(iterable)`` + + The constructor builds a tuple whose items are the same and in the same + order as *iterable*'s items. *iterable* may be either a sequence, a + container that supports iteration, or an iterator object. If *iterable* + is already a tuple, it is returned unchanged. For example, + ``tuple('abc')`` returns ``('a', 'b', 'c')`` and + ``tuple( [1, 2, 3] )`` returns ``(1, 2, 3)``. + If no argument is given, the constructor creates a new empty tuple, ``()``. + + Note that it is actually the comma which makes a tuple, not the parentheses. + The parentheses are optional, except in the empty tuple case, or + when they are needed to avoid syntactic ambiguity. For example, + ``f(a, b, c)`` is a function call with three arguments, while + ``f((a, b, c))`` is a function call with a 3-tuple as the sole argument. + + Tuples implement all of the :ref:`common ` sequence + operations. + +For heterogeneous collections of data where access by name is clearer than +access by index, :func:`collections.namedtuple` may be a more appropriate +choice than a simple tuple object. + + +.. _typesseq-range: + +Ranges +------ + +.. index:: object: range + +The :class:`range` type represents an immutable sequence of numbers and is +commonly used for looping a specific number of times in :keyword:`for` +loops. + +.. class:: range(stop) + range(start, stop[, step]) + + The arguments to the range constructor must be integers (either built-in + :class:`int` or any object that implements the ``__index__`` special + method). If the *step* argument is omitted, it defaults to ``1``. + If the *start* argument is omitted, it defaults to ``0``. + If *step* is zero, :exc:`ValueError` is raised. + + For a positive *step*, the contents of a range ``r`` are determined by the + formula ``r[i] = start + step*i`` where ``i >= 0`` and + ``r[i] < stop``. + + For a negative *step*, the contents of the range are still determined by + the formula ``r[i] = start + step*i``, but the constraints are ``i >= 0`` + and ``r[i] > stop``. + + A range object will be empty if ``r[0]`` does not meet the value + constraint. Ranges do support negative indices, but these are interpreted + as indexing from the end of the sequence determined by the positive + indices. + + Ranges containing absolute values larger than :data:`sys.maxsize` are + permitted but some features (such as :func:`len`) may raise + :exc:`OverflowError`. + + Range examples:: + + >>> list(range(10)) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + >>> list(range(1, 11)) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> list(range(0, 30, 5)) + [0, 5, 10, 15, 20, 25] + >>> list(range(0, 10, 3)) + [0, 3, 6, 9] + >>> list(range(0, -10, -1)) + [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] + >>> list(range(0)) + [] + >>> list(range(1, 0)) + [] + + Ranges implement all of the :ref:`common ` sequence operations + except concatenation and repetition (due to the fact that range objects can + only represent sequences that follow a strict pattern and repetition and + concatenation will usually violate that pattern). + + .. attribute:: start + + The value of the *start* parameter (or ``0`` if the parameter was + not supplied) + + .. attribute:: stop + + The value of the *stop* parameter + + .. attribute:: step + + The value of the *step* parameter (or ``1`` if the parameter was + not supplied) + +The advantage of the :class:`range` type over a regular :class:`list` or +:class:`tuple` is that a :class:`range` object will always take the same +(small) amount of memory, no matter the size of the range it represents (as it +only stores the ``start``, ``stop`` and ``step`` values, calculating individual +items and subranges as needed). + +Range objects implement the :class:`collections.abc.Sequence` ABC, and provide +features such as containment tests, element index lookup, slicing and +support for negative indices (see :ref:`typesseq`): + + >>> r = range(0, 20, 2) + >>> r + range(0, 20, 2) + >>> 11 in r + False + >>> 10 in r + True + >>> r.index(10) + 5 + >>> r[5] + 10 + >>> r[:5] + range(0, 10, 2) + >>> r[-1] + 18 + +Testing range objects for equality with ``==`` and ``!=`` compares +them as sequences. That is, two range objects are considered equal if +they represent the same sequence of values. (Note that two range +objects that compare equal might have different :attr:`~range.start`, +:attr:`~range.stop` and :attr:`~range.step` attributes, for example +``range(0) == range(2, 1, 3)`` or ``range(0, 3, 2) == range(0, 4, 2)``.) + +.. versionchanged:: 3.2 + Implement the Sequence ABC. + Support slicing and negative indices. + Test :class:`int` objects for membership in constant time instead of + iterating through all items. + +.. versionchanged:: 3.3 + Define '==' and '!=' to compare range objects based on the + sequence of values they define (instead of comparing based on + object identity). + +.. versionadded:: 3.3 + The :attr:`~range.start`, :attr:`~range.stop` and :attr:`~range.step` + attributes. + +.. seealso:: + + * The `linspace recipe `_ + shows how to implement a lazy version of range suitable for floating + point applications. + +.. index:: + single: string; text sequence type + single: str (built-in class); (see also string) + object: string + +.. _textseq: + +Text Sequence Type --- :class:`str` +=================================== + +Textual data in Python is handled with :class:`str` objects, or :dfn:`strings`. +Strings are immutable +:ref:`sequences ` of Unicode code points. String literals are +written in a variety of ways: + +* Single quotes: ``'allows embedded "double" quotes'`` +* Double quotes: ``"allows embedded 'single' quotes"``. +* Triple quoted: ``'''Three single quotes'''``, ``"""Three double quotes"""`` + +Triple quoted strings may span multiple lines - all associated whitespace will +be included in the string literal. + +String literals that are part of a single expression and have only whitespace +between them will be implicitly converted to a single string literal. That +is, ``("spam " "eggs") == "spam eggs"``. + +See :ref:`strings` for more about the various forms of string literal, +including supported escape sequences, and the ``r`` ("raw") prefix that +disables most escape sequence processing. + +Strings may also be created from other objects using the :class:`str` +constructor. + +Since there is no separate "character" type, indexing a string produces +strings of length 1. That is, for a non-empty string *s*, ``s[0] == s[0:1]``. + +.. index:: + object: io.StringIO + +There is also no mutable string type, but :meth:`str.join` or +:class:`io.StringIO` can be used to efficiently construct strings from +multiple fragments. + +.. versionchanged:: 3.3 + For backwards compatibility with the Python 2 series, the ``u`` prefix is + once again permitted on string literals. It has no effect on the meaning + of string literals and cannot be combined with the ``r`` prefix. + + +.. index:: + single: string; str (built-in class) + +.. class:: str(object='') + str(object=b'', encoding='utf-8', errors='strict') + + Return a :ref:`string ` version of *object*. If *object* is not + provided, returns the empty string. Otherwise, the behavior of ``str()`` + depends on whether *encoding* or *errors* is given, as follows. + + If neither *encoding* nor *errors* is given, ``str(object)`` returns + :meth:`object.__str__() `, which is the "informal" or nicely + printable string representation of *object*. For string objects, this is + the string itself. If *object* does not have a :meth:`~object.__str__` + method, then :func:`str` falls back to returning + :meth:`repr(object) `. + + .. index:: + single: buffer protocol; str (built-in class) + single: bytes; str (built-in class) + + If at least one of *encoding* or *errors* is given, *object* should be a + :term:`bytes-like object` (e.g. :class:`bytes` or :class:`bytearray`). In + this case, if *object* is a :class:`bytes` (or :class:`bytearray`) object, + then ``str(bytes, encoding, errors)`` is equivalent to + :meth:`bytes.decode(encoding, errors) `. Otherwise, the bytes + object underlying the buffer object is obtained before calling + :meth:`bytes.decode`. See :ref:`binaryseq` and + :ref:`bufferobjects` for information on buffer objects. + + Passing a :class:`bytes` object to :func:`str` without the *encoding* + or *errors* arguments falls under the first case of returning the informal + string representation (see also the :option:`-b` command-line option to + Python). For example:: + + >>> str(b'Zoot!') + "b'Zoot!'" + + For more information on the ``str`` class and its methods, see + :ref:`textseq` and the :ref:`string-methods` section below. To output + formatted strings, see the :ref:`f-strings` and :ref:`formatstrings` + sections. In addition, see the :ref:`stringservices` section. + + +.. index:: + pair: string; methods + +.. _string-methods: + +String Methods +-------------- + +.. index:: + module: re + +Strings implement all of the :ref:`common ` sequence +operations, along with the additional methods described below. + +Strings also support two styles of string formatting, one providing a large +degree of flexibility and customization (see :meth:`str.format`, +:ref:`formatstrings` and :ref:`string-formatting`) and the other based on C +``printf`` style formatting that handles a narrower range of types and is +slightly harder to use correctly, but is often faster for the cases it can +handle (:ref:`old-string-formatting`). + +The :ref:`textservices` section of the standard library covers a number of +other modules that provide various text related utilities (including regular +expression support in the :mod:`re` module). + +.. method:: str.capitalize() + + Return a copy of the string with its first character capitalized and the + rest lowercased. + + .. versionchanged:: 3.8 + The first character is now put into titlecase rather than uppercase. + This means that characters like digraphs will only have their first + letter capitalized, instead of the full character. + +.. method:: str.casefold() + + Return a casefolded copy of the string. Casefolded strings may be used for + caseless matching. + + Casefolding is similar to lowercasing but more aggressive because it is + intended to remove all case distinctions in a string. For example, the German + lowercase letter ``'ß'`` is equivalent to ``"ss"``. Since it is already + lowercase, :meth:`lower` would do nothing to ``'ß'``; :meth:`casefold` + converts it to ``"ss"``. + + The casefolding algorithm is described in section 3.13 of the Unicode + Standard. + + .. versionadded:: 3.3 + + +.. method:: str.center(width[, fillchar]) + + Return centered in a string of length *width*. Padding is done using the + specified *fillchar* (default is an ASCII space). The original string is + returned if *width* is less than or equal to ``len(s)``. + + + +.. method:: str.count(sub[, start[, end]]) + + Return the number of non-overlapping occurrences of substring *sub* in the + range [*start*, *end*]. Optional arguments *start* and *end* are + interpreted as in slice notation. + + +.. method:: str.removeprefix(prefix, /) + + If the string starts with the *prefix* string, return + ``string[len(prefix):]``. Otherwise, return a copy of the original + string:: + + >>> 'TestHook'.removeprefix('Test') + 'Hook' + >>> 'BaseTestCase'.removeprefix('Test') + 'BaseTestCase' + + .. versionadded:: 3.9 + +.. method:: str.removesuffix(suffix, /) + + If the string ends with the *suffix* string and that *suffix* is not empty, + return ``string[:-len(suffix)]``. Otherwise, return a copy of the + original string:: + + >>> 'MiscTests'.removesuffix('Tests') + 'Misc' + >>> 'TmpDirMixin'.removesuffix('Tests') + 'TmpDirMixin' + + .. versionadded:: 3.9 + + +.. method:: str.encode(encoding="utf-8", errors="strict") + + Return an encoded version of the string as a bytes object. Default encoding + is ``'utf-8'``. *errors* may be given to set a different error handling scheme. + The default for *errors* is ``'strict'``, meaning that encoding errors raise + a :exc:`UnicodeError`. Other possible + values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, + ``'backslashreplace'`` and any other name registered via + :func:`codecs.register_error`, see section :ref:`error-handlers`. For a + list of possible encodings, see section :ref:`standard-encodings`. + + By default, the *errors* argument is not checked for best performances, but + only used at the first encoding error. Enable the :ref:`Python Development + Mode `, or use a debug build to check *errors*. + + .. versionchanged:: 3.1 + Support for keyword arguments added. + + .. versionchanged:: 3.9 + The *errors* is now checked in development mode and in debug mode. + + +.. method:: str.endswith(suffix[, start[, end]]) + + Return ``True`` if the string ends with the specified *suffix*, otherwise return + ``False``. *suffix* can also be a tuple of suffixes to look for. With optional + *start*, test beginning at that position. With optional *end*, stop comparing + at that position. + + +.. method:: str.expandtabs(tabsize=8) + + Return a copy of the string where all tab characters are replaced by one or + more spaces, depending on the current column and the given tab size. Tab + positions occur every *tabsize* characters (default is 8, giving tab + positions at columns 0, 8, 16 and so on). To expand the string, the current + column is set to zero and the string is examined character by character. If + the character is a tab (``\t``), one or more space characters are inserted + in the result until the current column is equal to the next tab position. + (The tab character itself is not copied.) If the character is a newline + (``\n``) or return (``\r``), it is copied and the current column is reset to + zero. Any other character is copied unchanged and the current column is + incremented by one regardless of how the character is represented when + printed. + + >>> '01\t012\t0123\t01234'.expandtabs() + '01 012 0123 01234' + >>> '01\t012\t0123\t01234'.expandtabs(4) + '01 012 0123 01234' + + +.. method:: str.find(sub[, start[, end]]) + + Return the lowest index in the string where substring *sub* is found within + the slice ``s[start:end]``. Optional arguments *start* and *end* are + interpreted as in slice notation. Return ``-1`` if *sub* is not found. + + .. note:: + + The :meth:`~str.find` method should be used only if you need to know the + position of *sub*. To check if *sub* is a substring or not, use the + :keyword:`in` operator:: + + >>> 'Py' in 'Python' + True + + +.. method:: str.format(*args, **kwargs) + + Perform a string formatting operation. The string on which this method is + called can contain literal text or replacement fields delimited by braces + ``{}``. Each replacement field contains either the numeric index of a + positional argument, or the name of a keyword argument. Returns a copy of + the string where each replacement field is replaced with the string value of + the corresponding argument. + + >>> "The sum of 1 + 2 is {0}".format(1+2) + 'The sum of 1 + 2 is 3' + + See :ref:`formatstrings` for a description of the various formatting options + that can be specified in format strings. + + .. note:: + When formatting a number (:class:`int`, :class:`float`, :class:`complex`, + :class:`decimal.Decimal` and subclasses) with the ``n`` type + (ex: ``'{:n}'.format(1234)``), the function temporarily sets the + ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale to decode + ``decimal_point`` and ``thousands_sep`` fields of :c:func:`localeconv` if + they are non-ASCII or longer than 1 byte, and the ``LC_NUMERIC`` locale is + different than the ``LC_CTYPE`` locale. This temporary change affects + other threads. + + .. versionchanged:: 3.7 + When formatting a number with the ``n`` type, the function sets + temporarily the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale in some + cases. + + +.. method:: str.format_map(mapping) + + Similar to ``str.format(**mapping)``, except that ``mapping`` is + used directly and not copied to a :class:`dict`. This is useful + if for example ``mapping`` is a dict subclass: + + >>> class Default(dict): + ... def __missing__(self, key): + ... return key + ... + >>> '{name} was born in {country}'.format_map(Default(name='Guido')) + 'Guido was born in country' + + .. versionadded:: 3.2 + + +.. method:: str.index(sub[, start[, end]]) + + Like :meth:`~str.find`, but raise :exc:`ValueError` when the substring is + not found. + + +.. method:: str.isalnum() + + Return ``True`` if all characters in the string are alphanumeric and there is at + least one character, ``False`` otherwise. A character ``c`` is alphanumeric if one + of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``, + ``c.isdigit()``, or ``c.isnumeric()``. + + +.. method:: str.isalpha() + + Return ``True`` if all characters in the string are alphabetic and there is at least + one character, ``False`` otherwise. Alphabetic characters are those characters defined + in the Unicode character database as "Letter", i.e., those with general category + property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different + from the "Alphabetic" property defined in the Unicode Standard. + + +.. method:: str.isascii() + + Return ``True`` if the string is empty or all characters in the string are ASCII, + ``False`` otherwise. + ASCII characters have code points in the range U+0000-U+007F. + + .. versionadded:: 3.7 + + +.. method:: str.isdecimal() + + Return ``True`` if all characters in the string are decimal + characters and there is at least one character, ``False`` + otherwise. Decimal characters are those that can be used to form + numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT + ZERO. Formally a decimal character is a character in the Unicode + General Category "Nd". + + +.. method:: str.isdigit() + + Return ``True`` if all characters in the string are digits and there is at least one + character, ``False`` otherwise. Digits include decimal characters and digits that need + special handling, such as the compatibility superscript digits. + This covers digits which cannot be used to form numbers in base 10, + like the Kharosthi numbers. Formally, a digit is a character that has the + property value Numeric_Type=Digit or Numeric_Type=Decimal. + + +.. method:: str.isidentifier() + + Return ``True`` if the string is a valid identifier according to the language + definition, section :ref:`identifiers`. + + Call :func:`keyword.iskeyword` to test whether string ``s`` is a reserved + identifier, such as :keyword:`def` and :keyword:`class`. + + Example: + :: + + >>> from keyword import iskeyword + + >>> 'hello'.isidentifier(), iskeyword('hello') + True, False + >>> 'def'.isidentifier(), iskeyword('def') + True, True + + +.. method:: str.islower() + + Return ``True`` if all cased characters [4]_ in the string are lowercase and + there is at least one cased character, ``False`` otherwise. + + +.. method:: str.isnumeric() + + Return ``True`` if all characters in the string are numeric + characters, and there is at least one character, ``False`` + otherwise. Numeric characters include digit characters, and all characters + that have the Unicode numeric value property, e.g. U+2155, + VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property + value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. + + +.. method:: str.isprintable() + + Return ``True`` if all characters in the string are printable or the string is + empty, ``False`` otherwise. Nonprintable characters are those characters defined + in the Unicode character database as "Other" or "Separator", excepting the + ASCII space (0x20) which is considered printable. (Note that printable + characters in this context are those which should not be escaped when + :func:`repr` is invoked on a string. It has no bearing on the handling of + strings written to :data:`sys.stdout` or :data:`sys.stderr`.) + + +.. method:: str.isspace() + + Return ``True`` if there are only whitespace characters in the string and there is + at least one character, ``False`` otherwise. + + A character is *whitespace* if in the Unicode character database + (see :mod:`unicodedata`), either its general category is ``Zs`` + ("Separator, space"), or its bidirectional class is one of ``WS``, + ``B``, or ``S``. + + +.. method:: str.istitle() + + Return ``True`` if the string is a titlecased string and there is at least one + character, for example uppercase characters may only follow uncased characters + and lowercase characters only cased ones. Return ``False`` otherwise. + + +.. method:: str.isupper() + + Return ``True`` if all cased characters [4]_ in the string are uppercase and + there is at least one cased character, ``False`` otherwise. + + >>> 'BANANA'.isupper() + True + >>> 'banana'.isupper() + False + >>> 'baNana'.isupper() + False + >>> ' '.isupper() + False + + + +.. method:: str.join(iterable) + + Return a string which is the concatenation of the strings in *iterable*. + A :exc:`TypeError` will be raised if there are any non-string values in + *iterable*, including :class:`bytes` objects. The separator between + elements is the string providing this method. + + +.. method:: str.ljust(width[, fillchar]) + + Return the string left justified in a string of length *width*. Padding is + done using the specified *fillchar* (default is an ASCII space). The + original string is returned if *width* is less than or equal to ``len(s)``. + + +.. method:: str.lower() + + Return a copy of the string with all the cased characters [4]_ converted to + lowercase. + + The lowercasing algorithm used is described in section 3.13 of the Unicode + Standard. + + +.. method:: str.lstrip([chars]) + + Return a copy of the string with leading characters removed. The *chars* + argument is a string specifying the set of characters to be removed. If omitted + or ``None``, the *chars* argument defaults to removing whitespace. The *chars* + argument is not a prefix; rather, all combinations of its values are stripped:: + + >>> ' spacious '.lstrip() + 'spacious ' + >>> 'www.example.com'.lstrip('cmowz.') + 'example.com' + + See :meth:`str.removeprefix` for a method that will remove a single prefix + string rather than all of a set of characters. For example:: + + >>> 'Arthur: three!'.lstrip('Arthur: ') + 'ee!' + >>> 'Arthur: three!'.removeprefix('Arthur: ') + 'three!' + + +.. staticmethod:: str.maketrans(x[, y[, z]]) + + This static method returns a translation table usable for :meth:`str.translate`. + + If there is only one argument, it must be a dictionary mapping Unicode + ordinals (integers) or characters (strings of length 1) to Unicode ordinals, + strings (of arbitrary lengths) or ``None``. Character keys will then be + converted to ordinals. + + If there are two arguments, they must be strings of equal length, and in the + resulting dictionary, each character in x will be mapped to the character at + the same position in y. If there is a third argument, it must be a string, + whose characters will be mapped to ``None`` in the result. + + +.. method:: str.partition(sep) + + Split the string at the first occurrence of *sep*, and return a 3-tuple + containing the part before the separator, the separator itself, and the part + after the separator. If the separator is not found, return a 3-tuple containing + the string itself, followed by two empty strings. + + +.. method:: str.replace(old, new[, count]) + + Return a copy of the string with all occurrences of substring *old* replaced by + *new*. If the optional argument *count* is given, only the first *count* + occurrences are replaced. + + +.. method:: str.rfind(sub[, start[, end]]) + + Return the highest index in the string where substring *sub* is found, such + that *sub* is contained within ``s[start:end]``. Optional arguments *start* + and *end* are interpreted as in slice notation. Return ``-1`` on failure. + + +.. method:: str.rindex(sub[, start[, end]]) + + Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not + found. + + +.. method:: str.rjust(width[, fillchar]) + + Return the string right justified in a string of length *width*. Padding is + done using the specified *fillchar* (default is an ASCII space). The + original string is returned if *width* is less than or equal to ``len(s)``. + + +.. method:: str.rpartition(sep) + + Split the string at the last occurrence of *sep*, and return a 3-tuple + containing the part before the separator, the separator itself, and the part + after the separator. If the separator is not found, return a 3-tuple containing + two empty strings, followed by the string itself. + + +.. method:: str.rsplit(sep=None, maxsplit=-1) + + Return a list of the words in the string, using *sep* as the delimiter string. + If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* + ones. If *sep* is not specified or ``None``, any whitespace string is a + separator. Except for splitting from the right, :meth:`rsplit` behaves like + :meth:`split` which is described in detail below. + + +.. method:: str.rstrip([chars]) + + Return a copy of the string with trailing characters removed. The *chars* + argument is a string specifying the set of characters to be removed. If omitted + or ``None``, the *chars* argument defaults to removing whitespace. The *chars* + argument is not a suffix; rather, all combinations of its values are stripped:: + + >>> ' spacious '.rstrip() + ' spacious' + >>> 'mississippi'.rstrip('ipz') + 'mississ' + + See :meth:`str.removesuffix` for a method that will remove a single suffix + string rather than all of a set of characters. For example:: + + >>> 'Monty Python'.rstrip(' Python') + 'M' + >>> 'Monty Python'.removesuffix(' Python') + 'Monty' + +.. method:: str.split(sep=None, maxsplit=-1) + + Return a list of the words in the string, using *sep* as the delimiter + string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, + the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not + specified or ``-1``, then there is no limit on the number of splits + (all possible splits are made). + + If *sep* is given, consecutive delimiters are not grouped together and are + deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns + ``['1', '', '2']``). The *sep* argument may consist of multiple characters + (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``). + Splitting an empty string with a specified separator returns ``['']``. + + For example:: + + >>> '1,2,3'.split(',') + ['1', '2', '3'] + >>> '1,2,3'.split(',', maxsplit=1) + ['1', '2,3'] + >>> '1,2,,3,'.split(',') + ['1', '2', '', '3', ''] + + If *sep* is not specified or is ``None``, a different splitting algorithm is + applied: runs of consecutive whitespace are regarded as a single separator, + and the result will contain no empty strings at the start or end if the + string has leading or trailing whitespace. Consequently, splitting an empty + string or a string consisting of just whitespace with a ``None`` separator + returns ``[]``. + + For example:: + + >>> '1 2 3'.split() + ['1', '2', '3'] + >>> '1 2 3'.split(maxsplit=1) + ['1', '2 3'] + >>> ' 1 2 3 '.split() + ['1', '2', '3'] + + +.. index:: + single: universal newlines; str.splitlines method + +.. method:: str.splitlines([keepends]) + + Return a list of the lines in the string, breaking at line boundaries. Line + breaks are not included in the resulting list unless *keepends* is given and + true. + + This method splits on the following line boundaries. In particular, the + boundaries are a superset of :term:`universal newlines`. + + +-----------------------+-----------------------------+ + | Representation | Description | + +=======================+=============================+ + | ``\n`` | Line Feed | + +-----------------------+-----------------------------+ + | ``\r`` | Carriage Return | + +-----------------------+-----------------------------+ + | ``\r\n`` | Carriage Return + Line Feed | + +-----------------------+-----------------------------+ + | ``\v`` or ``\x0b`` | Line Tabulation | + +-----------------------+-----------------------------+ + | ``\f`` or ``\x0c`` | Form Feed | + +-----------------------+-----------------------------+ + | ``\x1c`` | File Separator | + +-----------------------+-----------------------------+ + | ``\x1d`` | Group Separator | + +-----------------------+-----------------------------+ + | ``\x1e`` | Record Separator | + +-----------------------+-----------------------------+ + | ``\x85`` | Next Line (C1 Control Code) | + +-----------------------+-----------------------------+ + | ``\u2028`` | Line Separator | + +-----------------------+-----------------------------+ + | ``\u2029`` | Paragraph Separator | + +-----------------------+-----------------------------+ + + .. versionchanged:: 3.2 + + ``\v`` and ``\f`` added to list of line boundaries. + + For example:: + + >>> 'ab c\n\nde fg\rkl\r\n'.splitlines() + ['ab c', '', 'de fg', 'kl'] + >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True) + ['ab c\n', '\n', 'de fg\r', 'kl\r\n'] + + Unlike :meth:`~str.split` when a delimiter string *sep* is given, this + method returns an empty list for the empty string, and a terminal line + break does not result in an extra line:: + + >>> "".splitlines() + [] + >>> "One line\n".splitlines() + ['One line'] + + For comparison, ``split('\n')`` gives:: + + >>> ''.split('\n') + [''] + >>> 'Two lines\n'.split('\n') + ['Two lines', ''] + + +.. method:: str.startswith(prefix[, start[, end]]) + + Return ``True`` if string starts with the *prefix*, otherwise return ``False``. + *prefix* can also be a tuple of prefixes to look for. With optional *start*, + test string beginning at that position. With optional *end*, stop comparing + string at that position. + + +.. method:: str.strip([chars]) + + Return a copy of the string with the leading and trailing characters removed. + The *chars* argument is a string specifying the set of characters to be removed. + If omitted or ``None``, the *chars* argument defaults to removing whitespace. + The *chars* argument is not a prefix or suffix; rather, all combinations of its + values are stripped:: + + >>> ' spacious '.strip() + 'spacious' + >>> 'www.example.com'.strip('cmowz.') + 'example' + + The outermost leading and trailing *chars* argument values are stripped + from the string. Characters are removed from the leading end until + reaching a string character that is not contained in the set of + characters in *chars*. A similar action takes place on the trailing end. + For example:: + + >>> comment_string = '#....... Section 3.2.1 Issue #32 .......' + >>> comment_string.strip('.#! ') + 'Section 3.2.1 Issue #32' + + +.. method:: str.swapcase() + + Return a copy of the string with uppercase characters converted to lowercase and + vice versa. Note that it is not necessarily true that + ``s.swapcase().swapcase() == s``. + + +.. method:: str.title() + + Return a titlecased version of the string where words start with an uppercase + character and the remaining characters are lowercase. + + For example:: + + >>> 'Hello world'.title() + 'Hello World' + + The algorithm uses a simple language-independent definition of a word as + groups of consecutive letters. The definition works in many contexts but + it means that apostrophes in contractions and possessives form word + boundaries, which may not be the desired result:: + + >>> "they're bill's friends from the UK".title() + "They'Re Bill'S Friends From The Uk" + + A workaround for apostrophes can be constructed using regular expressions:: + + >>> import re + >>> def titlecase(s): + ... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", + ... lambda mo: mo.group(0).capitalize(), + ... s) + ... + >>> titlecase("they're bill's friends.") + "They're Bill's Friends." + + +.. method:: str.translate(table) + + Return a copy of the string in which each character has been mapped through + the given translation table. The table must be an object that implements + indexing via :meth:`__getitem__`, typically a :term:`mapping` or + :term:`sequence`. When indexed by a Unicode ordinal (an integer), the + table object can do any of the following: return a Unicode ordinal or a + string, to map the character to one or more other characters; return + ``None``, to delete the character from the return string; or raise a + :exc:`LookupError` exception, to map the character to itself. + + You can use :meth:`str.maketrans` to create a translation map from + character-to-character mappings in different formats. + + See also the :mod:`codecs` module for a more flexible approach to custom + character mappings. + + +.. method:: str.upper() + + Return a copy of the string with all the cased characters [4]_ converted to + uppercase. Note that ``s.upper().isupper()`` might be ``False`` if ``s`` + contains uncased characters or if the Unicode category of the resulting + character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, + titlecase). + + The uppercasing algorithm used is described in section 3.13 of the Unicode + Standard. + + +.. method:: str.zfill(width) + + Return a copy of the string left filled with ASCII ``'0'`` digits to + make a string of length *width*. A leading sign prefix (``'+'``/``'-'``) + is handled by inserting the padding *after* the sign character rather + than before. The original string is returned if *width* is less than + or equal to ``len(s)``. + + For example:: + + >>> "42".zfill(5) + '00042' + >>> "-42".zfill(5) + '-0042' + + + +.. _old-string-formatting: + +``printf``-style String Formatting +---------------------------------- + +.. index:: + single: formatting, string (%) + single: interpolation, string (%) + single: string; formatting, printf + single: string; interpolation, printf + single: printf-style formatting + single: sprintf-style formatting + single: % (percent); printf-style formatting + +.. note:: + + The formatting operations described here exhibit a variety of quirks that + lead to a number of common errors (such as failing to display tuples and + dictionaries correctly). Using the newer :ref:`formatted string literals + `, the :meth:`str.format` interface, or :ref:`template strings + ` may help avoid these errors. Each of these + alternatives provides their own trade-offs and benefits of simplicity, + flexibility, and/or extensibility. + +String objects have one unique built-in operation: the ``%`` operator (modulo). +This is also known as the string *formatting* or *interpolation* operator. +Given ``format % values`` (where *format* is a string), ``%`` conversion +specifications in *format* are replaced with zero or more elements of *values*. +The effect is similar to using the :c:func:`sprintf` in the C language. + +If *format* requires a single argument, *values* may be a single non-tuple +object. [5]_ Otherwise, *values* must be a tuple with exactly the number of +items specified by the format string, or a single mapping object (for example, a +dictionary). + +.. index:: + single: () (parentheses); in printf-style formatting + single: * (asterisk); in printf-style formatting + single: . (dot); in printf-style formatting + +A conversion specifier contains two or more characters and has the following +components, which must occur in this order: + +#. The ``'%'`` character, which marks the start of the specifier. + +#. Mapping key (optional), consisting of a parenthesised sequence of characters + (for example, ``(somename)``). + +#. Conversion flags (optional), which affect the result of some conversion + types. + +#. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the + actual width is read from the next element of the tuple in *values*, and the + object to convert comes after the minimum field width and optional precision. + +#. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If + specified as ``'*'`` (an asterisk), the actual precision is read from the next + element of the tuple in *values*, and the value to convert comes after the + precision. + +#. Length modifier (optional). + +#. Conversion type. + +When the right argument is a dictionary (or other mapping type), then the +formats in the string *must* include a parenthesised mapping key into that +dictionary inserted immediately after the ``'%'`` character. The mapping key +selects the value to be formatted from the mapping. For example: + + >>> print('%(language)s has %(number)03d quote types.' % + ... {'language': "Python", "number": 2}) + Python has 002 quote types. + +In this case no ``*`` specifiers may occur in a format (since they require a +sequential parameter list). + +The conversion flag characters are: + +.. index:: + single: # (hash); in printf-style formatting + single: - (minus); in printf-style formatting + single: + (plus); in printf-style formatting + single: space; in printf-style formatting + ++---------+---------------------------------------------------------------------+ +| Flag | Meaning | ++=========+=====================================================================+ +| ``'#'`` | The value conversion will use the "alternate form" (where defined | +| | below). | ++---------+---------------------------------------------------------------------+ +| ``'0'`` | The conversion will be zero padded for numeric values. | ++---------+---------------------------------------------------------------------+ +| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` | +| | conversion if both are given). | ++---------+---------------------------------------------------------------------+ +| ``' '`` | (a space) A blank should be left before a positive number (or empty | +| | string) produced by a signed conversion. | ++---------+---------------------------------------------------------------------+ +| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion | +| | (overrides a "space" flag). | ++---------+---------------------------------------------------------------------+ + +A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it +is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``. + +The conversion types are: + ++------------+-----------------------------------------------------+-------+ +| Conversion | Meaning | Notes | ++============+=====================================================+=======+ +| ``'d'`` | Signed integer decimal. | | ++------------+-----------------------------------------------------+-------+ +| ``'i'`` | Signed integer decimal. | | ++------------+-----------------------------------------------------+-------+ +| ``'o'`` | Signed octal value. | \(1) | ++------------+-----------------------------------------------------+-------+ +| ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(6) | ++------------+-----------------------------------------------------+-------+ +| ``'x'`` | Signed hexadecimal (lowercase). | \(2) | ++------------+-----------------------------------------------------+-------+ +| ``'X'`` | Signed hexadecimal (uppercase). | \(2) | ++------------+-----------------------------------------------------+-------+ +| ``'e'`` | Floating point exponential format (lowercase). | \(3) | ++------------+-----------------------------------------------------+-------+ +| ``'E'`` | Floating point exponential format (uppercase). | \(3) | ++------------+-----------------------------------------------------+-------+ +| ``'f'`` | Floating point decimal format. | \(3) | ++------------+-----------------------------------------------------+-------+ +| ``'F'`` | Floating point decimal format. | \(3) | ++------------+-----------------------------------------------------+-------+ +| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) | +| | format if exponent is less than -4 or not less than | | +| | precision, decimal format otherwise. | | ++------------+-----------------------------------------------------+-------+ +| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | +| | format if exponent is less than -4 or not less than | | +| | precision, decimal format otherwise. | | ++------------+-----------------------------------------------------+-------+ +| ``'c'`` | Single character (accepts integer or single | | +| | character string). | | ++------------+-----------------------------------------------------+-------+ +| ``'r'`` | String (converts any Python object using | \(5) | +| | :func:`repr`). | | ++------------+-----------------------------------------------------+-------+ +| ``'s'`` | String (converts any Python object using | \(5) | +| | :func:`str`). | | ++------------+-----------------------------------------------------+-------+ +| ``'a'`` | String (converts any Python object using | \(5) | +| | :func:`ascii`). | | ++------------+-----------------------------------------------------+-------+ +| ``'%'`` | No argument is converted, results in a ``'%'`` | | +| | character in the result. | | ++------------+-----------------------------------------------------+-------+ + +Notes: + +(1) + The alternate form causes a leading octal specifier (``'0o'``) to be + inserted before the first digit. + +(2) + The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether + the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit. + +(3) + The alternate form causes the result to always contain a decimal point, even if + no digits follow it. + + The precision determines the number of digits after the decimal point and + defaults to 6. + +(4) + The alternate form causes the result to always contain a decimal point, and + trailing zeroes are not removed as they would otherwise be. + + The precision determines the number of significant digits before and after the + decimal point and defaults to 6. + +(5) + If precision is ``N``, the output is truncated to ``N`` characters. + +(6) + See :pep:`237`. + +Since Python strings have an explicit length, ``%s`` conversions do not assume +that ``'\0'`` is the end of the string. + +.. XXX Examples? + +.. versionchanged:: 3.1 + ``%f`` conversions for numbers whose absolute value is over 1e50 are no + longer replaced by ``%g`` conversions. + + +.. index:: + single: buffer protocol; binary sequence types + +.. _binaryseq: + +Binary Sequence Types --- :class:`bytes`, :class:`bytearray`, :class:`memoryview` +================================================================================= + +.. index:: + object: bytes + object: bytearray + object: memoryview + module: array + +The core built-in types for manipulating binary data are :class:`bytes` and +:class:`bytearray`. They are supported by :class:`memoryview` which uses +the :ref:`buffer protocol ` to access the memory of other +binary objects without needing to make a copy. + +The :mod:`array` module supports efficient storage of basic data types like +32-bit integers and IEEE754 double-precision floating values. + +.. _typebytes: + +Bytes Objects +------------- + +.. index:: object: bytes + +Bytes objects are immutable sequences of single bytes. Since many major +binary protocols are based on the ASCII text encoding, bytes objects offer +several methods that are only valid when working with ASCII compatible +data and are closely related to string objects in a variety of other ways. + +.. class:: bytes([source[, encoding[, errors]]]) + + Firstly, the syntax for bytes literals is largely the same as that for string + literals, except that a ``b`` prefix is added: + + * Single quotes: ``b'still allows embedded "double" quotes'`` + * Double quotes: ``b"still allows embedded 'single' quotes"``. + * Triple quoted: ``b'''3 single quotes'''``, ``b"""3 double quotes"""`` + + Only ASCII characters are permitted in bytes literals (regardless of the + declared source code encoding). Any binary values over 127 must be entered + into bytes literals using the appropriate escape sequence. + + As with string literals, bytes literals may also use a ``r`` prefix to disable + processing of escape sequences. See :ref:`strings` for more about the various + forms of bytes literal, including supported escape sequences. + + While bytes literals and representations are based on ASCII text, bytes + objects actually behave like immutable sequences of integers, with each + value in the sequence restricted such that ``0 <= x < 256`` (attempts to + violate this restriction will trigger :exc:`ValueError`). This is done + deliberately to emphasise that while many binary formats include ASCII based + elements and can be usefully manipulated with some text-oriented algorithms, + this is not generally the case for arbitrary binary data (blindly applying + text processing algorithms to binary data formats that are not ASCII + compatible will usually lead to data corruption). + + In addition to the literal forms, bytes objects can be created in a number of + other ways: + + * A zero-filled bytes object of a specified length: ``bytes(10)`` + * From an iterable of integers: ``bytes(range(20))`` + * Copying existing binary data via the buffer protocol: ``bytes(obj)`` + + Also see the :ref:`bytes ` built-in. + + Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal + numbers are a commonly used format for describing binary data. Accordingly, + the bytes type has an additional class method to read data in that format: + + .. classmethod:: fromhex(string) + + This :class:`bytes` class method returns a bytes object, decoding the + given string object. The string must contain two hexadecimal digits per + byte, with ASCII whitespace being ignored. + + >>> bytes.fromhex('2Ef0 F1f2 ') + b'.\xf0\xf1\xf2' + + .. versionchanged:: 3.7 + :meth:`bytes.fromhex` now skips all ASCII whitespace in the string, + not just spaces. + + A reverse conversion function exists to transform a bytes object into its + hexadecimal representation. + + .. method:: hex([sep[, bytes_per_sep]]) + + Return a string object containing two hexadecimal digits for each + byte in the instance. + + >>> b'\xf0\xf1\xf2'.hex() + 'f0f1f2' + + If you want to make the hex string easier to read, you can specify a + single character separator *sep* parameter to include in the output. + By default between each byte. A second optional *bytes_per_sep* + parameter controls the spacing. Positive values calculate the + separator position from the right, negative values from the left. + + >>> value = b'\xf0\xf1\xf2' + >>> value.hex('-') + 'f0-f1-f2' + >>> value.hex('_', 2) + 'f0_f1f2' + >>> b'UUDDLRLRAB'.hex(' ', -4) + '55554444 4c524c52 4142' + + .. versionadded:: 3.5 + + .. versionchanged:: 3.8 + :meth:`bytes.hex` now supports optional *sep* and *bytes_per_sep* + parameters to insert separators between bytes in the hex output. + +Since bytes objects are sequences of integers (akin to a tuple), for a bytes +object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes +object of length 1. (This contrasts with text strings, where both indexing +and slicing will produce a string of length 1) + +The representation of bytes objects uses the literal format (``b'...'``) +since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can +always convert a bytes object into a list of integers using ``list(b)``. + +.. note:: + For Python 2.x users: In the Python 2.x series, a variety of implicit + conversions between 8-bit strings (the closest thing 2.x offers to a + built-in binary data type) and Unicode strings were permitted. This was a + backwards compatibility workaround to account for the fact that Python + originally only supported 8-bit text, and Unicode text was a later + addition. In Python 3.x, those implicit conversions are gone - conversions + between 8-bit binary data and Unicode text must be explicit, and bytes and + string objects will always compare unequal. + + +.. _typebytearray: + +Bytearray Objects +----------------- + +.. index:: object: bytearray + +:class:`bytearray` objects are a mutable counterpart to :class:`bytes` +objects. + +.. class:: bytearray([source[, encoding[, errors]]]) + + There is no dedicated literal syntax for bytearray objects, instead + they are always created by calling the constructor: + + * Creating an empty instance: ``bytearray()`` + * Creating a zero-filled instance with a given length: ``bytearray(10)`` + * From an iterable of integers: ``bytearray(range(20))`` + * Copying existing binary data via the buffer protocol: ``bytearray(b'Hi!')`` + + As bytearray objects are mutable, they support the + :ref:`mutable ` sequence operations in addition to the + common bytes and bytearray operations described in :ref:`bytes-methods`. + + Also see the :ref:`bytearray ` built-in. + + Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal + numbers are a commonly used format for describing binary data. Accordingly, + the bytearray type has an additional class method to read data in that format: + + .. classmethod:: fromhex(string) + + This :class:`bytearray` class method returns bytearray object, decoding + the given string object. The string must contain two hexadecimal digits + per byte, with ASCII whitespace being ignored. + + >>> bytearray.fromhex('2Ef0 F1f2 ') + bytearray(b'.\xf0\xf1\xf2') + + .. versionchanged:: 3.7 + :meth:`bytearray.fromhex` now skips all ASCII whitespace in the string, + not just spaces. + + A reverse conversion function exists to transform a bytearray object into its + hexadecimal representation. + + .. method:: hex([sep[, bytes_per_sep]]) + + Return a string object containing two hexadecimal digits for each + byte in the instance. + + >>> bytearray(b'\xf0\xf1\xf2').hex() + 'f0f1f2' + + .. versionadded:: 3.5 + + .. versionchanged:: 3.8 + Similar to :meth:`bytes.hex`, :meth:`bytearray.hex` now supports + optional *sep* and *bytes_per_sep* parameters to insert separators + between bytes in the hex output. + +Since bytearray objects are sequences of integers (akin to a list), for a +bytearray object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be +a bytearray object of length 1. (This contrasts with text strings, where +both indexing and slicing will produce a string of length 1) + +The representation of bytearray objects uses the bytes literal format +(``bytearray(b'...')``) since it is often more useful than e.g. +``bytearray([46, 46, 46])``. You can always convert a bytearray object into +a list of integers using ``list(b)``. + + +.. _bytes-methods: + +Bytes and Bytearray Operations +------------------------------ + +.. index:: pair: bytes; methods + pair: bytearray; methods + +Both bytes and bytearray objects support the :ref:`common ` +sequence operations. They interoperate not just with operands of the same +type, but with any :term:`bytes-like object`. Due to this flexibility, they can be +freely mixed in operations without causing errors. However, the return type +of the result may depend on the order of operands. + +.. note:: + + The methods on bytes and bytearray objects don't accept strings as their + arguments, just as the methods on strings don't accept bytes as their + arguments. For example, you have to write:: + + a = "abc" + b = a.replace("a", "f") + + and:: + + a = b"abc" + b = a.replace(b"a", b"f") + +Some bytes and bytearray operations assume the use of ASCII compatible +binary formats, and hence should be avoided when working with arbitrary +binary data. These restrictions are covered below. + +.. note:: + Using these ASCII based operations to manipulate binary data that is not + stored in an ASCII based format may lead to data corruption. + +The following methods on bytes and bytearray objects can be used with +arbitrary binary data. + +.. method:: bytes.count(sub[, start[, end]]) + bytearray.count(sub[, start[, end]]) + + Return the number of non-overlapping occurrences of subsequence *sub* in + the range [*start*, *end*]. Optional arguments *start* and *end* are + interpreted as in slice notation. + + The subsequence to search for may be any :term:`bytes-like object` or an + integer in the range 0 to 255. + + .. versionchanged:: 3.3 + Also accept an integer in the range 0 to 255 as the subsequence. + + +.. method:: bytes.removeprefix(prefix, /) + bytearray.removeprefix(prefix, /) + + If the binary data starts with the *prefix* string, return + ``bytes[len(prefix):]``. Otherwise, return a copy of the original + binary data:: + + >>> b'TestHook'.removeprefix(b'Test') + b'Hook' + >>> b'BaseTestCase'.removeprefix(b'Test') + b'BaseTestCase' + + The *prefix* may be any :term:`bytes-like object`. + + .. note:: + + The bytearray version of this method does *not* operate in place - + it always produces a new object, even if no changes were made. + + .. versionadded:: 3.9 + + +.. method:: bytes.removesuffix(suffix, /) + bytearray.removesuffix(suffix, /) + + If the binary data ends with the *suffix* string and that *suffix* is + not empty, return ``bytes[:-len(suffix)]``. Otherwise, return a copy of + the original binary data:: + + >>> b'MiscTests'.removesuffix(b'Tests') + b'Misc' + >>> b'TmpDirMixin'.removesuffix(b'Tests') + b'TmpDirMixin' + + The *suffix* may be any :term:`bytes-like object`. + + .. note:: + + The bytearray version of this method does *not* operate in place - + it always produces a new object, even if no changes were made. + + .. versionadded:: 3.9 + + +.. method:: bytes.decode(encoding="utf-8", errors="strict") + bytearray.decode(encoding="utf-8", errors="strict") + + Return a string decoded from the given bytes. Default encoding is + ``'utf-8'``. *errors* may be given to set a different + error handling scheme. The default for *errors* is ``'strict'``, meaning + that encoding errors raise a :exc:`UnicodeError`. Other possible values are + ``'ignore'``, ``'replace'`` and any other name registered via + :func:`codecs.register_error`, see section :ref:`error-handlers`. For a + list of possible encodings, see section :ref:`standard-encodings`. + + By default, the *errors* argument is not checked for best performances, but + only used at the first decoding error. Enable the :ref:`Python Development + Mode `, or use a debug build to check *errors*. + + .. note:: + + Passing the *encoding* argument to :class:`str` allows decoding any + :term:`bytes-like object` directly, without needing to make a temporary + bytes or bytearray object. + + .. versionchanged:: 3.1 + Added support for keyword arguments. + + .. versionchanged:: 3.9 + The *errors* is now checked in development mode and in debug mode. + + +.. method:: bytes.endswith(suffix[, start[, end]]) + bytearray.endswith(suffix[, start[, end]]) + + Return ``True`` if the binary data ends with the specified *suffix*, + otherwise return ``False``. *suffix* can also be a tuple of suffixes to + look for. With optional *start*, test beginning at that position. With + optional *end*, stop comparing at that position. + + The suffix(es) to search for may be any :term:`bytes-like object`. + + +.. method:: bytes.find(sub[, start[, end]]) + bytearray.find(sub[, start[, end]]) + + Return the lowest index in the data where the subsequence *sub* is found, + such that *sub* is contained in the slice ``s[start:end]``. Optional + arguments *start* and *end* are interpreted as in slice notation. Return + ``-1`` if *sub* is not found. + + The subsequence to search for may be any :term:`bytes-like object` or an + integer in the range 0 to 255. + + .. note:: + + The :meth:`~bytes.find` method should be used only if you need to know the + position of *sub*. To check if *sub* is a substring or not, use the + :keyword:`in` operator:: + + >>> b'Py' in b'Python' + True + + .. versionchanged:: 3.3 + Also accept an integer in the range 0 to 255 as the subsequence. + + +.. method:: bytes.index(sub[, start[, end]]) + bytearray.index(sub[, start[, end]]) + + Like :meth:`~bytes.find`, but raise :exc:`ValueError` when the + subsequence is not found. + + The subsequence to search for may be any :term:`bytes-like object` or an + integer in the range 0 to 255. + + .. versionchanged:: 3.3 + Also accept an integer in the range 0 to 255 as the subsequence. + + +.. method:: bytes.join(iterable) + bytearray.join(iterable) + + Return a bytes or bytearray object which is the concatenation of the + binary data sequences in *iterable*. A :exc:`TypeError` will be raised + if there are any values in *iterable* that are not :term:`bytes-like + objects `, including :class:`str` objects. The + separator between elements is the contents of the bytes or + bytearray object providing this method. + + +.. staticmethod:: bytes.maketrans(from, to) + bytearray.maketrans(from, to) + + This static method returns a translation table usable for + :meth:`bytes.translate` that will map each character in *from* into the + character at the same position in *to*; *from* and *to* must both be + :term:`bytes-like objects ` and have the same length. + + .. versionadded:: 3.1 + + +.. method:: bytes.partition(sep) + bytearray.partition(sep) + + Split the sequence at the first occurrence of *sep*, and return a 3-tuple + containing the part before the separator, the separator itself or its + bytearray copy, and the part after the separator. + If the separator is not found, return a 3-tuple + containing a copy of the original sequence, followed by two empty bytes or + bytearray objects. + + The separator to search for may be any :term:`bytes-like object`. + + +.. method:: bytes.replace(old, new[, count]) + bytearray.replace(old, new[, count]) + + Return a copy of the sequence with all occurrences of subsequence *old* + replaced by *new*. If the optional argument *count* is given, only the + first *count* occurrences are replaced. + + The subsequence to search for and its replacement may be any + :term:`bytes-like object`. + + .. note:: + + The bytearray version of this method does *not* operate in place - it + always produces a new object, even if no changes were made. + + +.. method:: bytes.rfind(sub[, start[, end]]) + bytearray.rfind(sub[, start[, end]]) + + Return the highest index in the sequence where the subsequence *sub* is + found, such that *sub* is contained within ``s[start:end]``. Optional + arguments *start* and *end* are interpreted as in slice notation. Return + ``-1`` on failure. + + The subsequence to search for may be any :term:`bytes-like object` or an + integer in the range 0 to 255. + + .. versionchanged:: 3.3 + Also accept an integer in the range 0 to 255 as the subsequence. + + +.. method:: bytes.rindex(sub[, start[, end]]) + bytearray.rindex(sub[, start[, end]]) + + Like :meth:`~bytes.rfind` but raises :exc:`ValueError` when the + subsequence *sub* is not found. + + The subsequence to search for may be any :term:`bytes-like object` or an + integer in the range 0 to 255. + + .. versionchanged:: 3.3 + Also accept an integer in the range 0 to 255 as the subsequence. + + +.. method:: bytes.rpartition(sep) + bytearray.rpartition(sep) + + Split the sequence at the last occurrence of *sep*, and return a 3-tuple + containing the part before the separator, the separator itself or its + bytearray copy, and the part after the separator. + If the separator is not found, return a 3-tuple + containing two empty bytes or bytearray objects, followed by a copy of the + original sequence. + + The separator to search for may be any :term:`bytes-like object`. + + +.. method:: bytes.startswith(prefix[, start[, end]]) + bytearray.startswith(prefix[, start[, end]]) + + Return ``True`` if the binary data starts with the specified *prefix*, + otherwise return ``False``. *prefix* can also be a tuple of prefixes to + look for. With optional *start*, test beginning at that position. With + optional *end*, stop comparing at that position. + + The prefix(es) to search for may be any :term:`bytes-like object`. + + +.. method:: bytes.translate(table, /, delete=b'') + bytearray.translate(table, /, delete=b'') + + Return a copy of the bytes or bytearray object where all bytes occurring in + the optional argument *delete* are removed, and the remaining bytes have + been mapped through the given translation table, which must be a bytes + object of length 256. + + You can use the :func:`bytes.maketrans` method to create a translation + table. + + Set the *table* argument to ``None`` for translations that only delete + characters:: + + >>> b'read this short text'.translate(None, b'aeiou') + b'rd ths shrt txt' + + .. versionchanged:: 3.6 + *delete* is now supported as a keyword argument. + + +The following methods on bytes and bytearray objects have default behaviours +that assume the use of ASCII compatible binary formats, but can still be used +with arbitrary binary data by passing appropriate arguments. Note that all of +the bytearray methods in this section do *not* operate in place, and instead +produce new objects. + +.. method:: bytes.center(width[, fillbyte]) + bytearray.center(width[, fillbyte]) + + Return a copy of the object centered in a sequence of length *width*. + Padding is done using the specified *fillbyte* (default is an ASCII + space). For :class:`bytes` objects, the original sequence is returned if + *width* is less than or equal to ``len(s)``. + + .. note:: + + The bytearray version of this method does *not* operate in place - + it always produces a new object, even if no changes were made. + + +.. method:: bytes.ljust(width[, fillbyte]) + bytearray.ljust(width[, fillbyte]) + + Return a copy of the object left justified in a sequence of length *width*. + Padding is done using the specified *fillbyte* (default is an ASCII + space). For :class:`bytes` objects, the original sequence is returned if + *width* is less than or equal to ``len(s)``. + + .. note:: + + The bytearray version of this method does *not* operate in place - + it always produces a new object, even if no changes were made. + + +.. method:: bytes.lstrip([chars]) + bytearray.lstrip([chars]) + + Return a copy of the sequence with specified leading bytes removed. The + *chars* argument is a binary sequence specifying the set of byte values to + be removed - the name refers to the fact this method is usually used with + ASCII characters. If omitted or ``None``, the *chars* argument defaults + to removing ASCII whitespace. The *chars* argument is not a prefix; + rather, all combinations of its values are stripped:: + + >>> b' spacious '.lstrip() + b'spacious ' + >>> b'www.example.com'.lstrip(b'cmowz.') + b'example.com' + + The binary sequence of byte values to remove may be any + :term:`bytes-like object`. See :meth:`~bytes.removeprefix` for a method + that will remove a single prefix string rather than all of a set of + characters. For example:: + + >>> b'Arthur: three!'.lstrip(b'Arthur: ') + b'ee!' + >>> b'Arthur: three!'.removeprefix(b'Arthur: ') + b'three!' + + .. note:: + + The bytearray version of this method does *not* operate in place - + it always produces a new object, even if no changes were made. + + +.. method:: bytes.rjust(width[, fillbyte]) + bytearray.rjust(width[, fillbyte]) + + Return a copy of the object right justified in a sequence of length *width*. + Padding is done using the specified *fillbyte* (default is an ASCII + space). For :class:`bytes` objects, the original sequence is returned if + *width* is less than or equal to ``len(s)``. + + .. note:: + + The bytearray version of this method does *not* operate in place - + it always produces a new object, even if no changes were made. + + +.. method:: bytes.rsplit(sep=None, maxsplit=-1) + bytearray.rsplit(sep=None, maxsplit=-1) + + Split the binary sequence into subsequences of the same type, using *sep* + as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits + are done, the *rightmost* ones. If *sep* is not specified or ``None``, + any subsequence consisting solely of ASCII whitespace is a separator. + Except for splitting from the right, :meth:`rsplit` behaves like + :meth:`split` which is described in detail below. + + +.. method:: bytes.rstrip([chars]) + bytearray.rstrip([chars]) + + Return a copy of the sequence with specified trailing bytes removed. The + *chars* argument is a binary sequence specifying the set of byte values to + be removed - the name refers to the fact this method is usually used with + ASCII characters. If omitted or ``None``, the *chars* argument defaults to + removing ASCII whitespace. The *chars* argument is not a suffix; rather, + all combinations of its values are stripped:: + + >>> b' spacious '.rstrip() + b' spacious' + >>> b'mississippi'.rstrip(b'ipz') + b'mississ' + + The binary sequence of byte values to remove may be any + :term:`bytes-like object`. See :meth:`~bytes.removesuffix` for a method + that will remove a single suffix string rather than all of a set of + characters. For example:: + + >>> b'Monty Python'.rstrip(b' Python') + b'M' + >>> b'Monty Python'.removesuffix(b' Python') + b'Monty' + + .. note:: + + The bytearray version of this method does *not* operate in place - + it always produces a new object, even if no changes were made. + + +.. method:: bytes.split(sep=None, maxsplit=-1) + bytearray.split(sep=None, maxsplit=-1) + + Split the binary sequence into subsequences of the same type, using *sep* + as the delimiter string. If *maxsplit* is given and non-negative, at most + *maxsplit* splits are done (thus, the list will have at most ``maxsplit+1`` + elements). If *maxsplit* is not specified or is ``-1``, then there is no + limit on the number of splits (all possible splits are made). + + If *sep* is given, consecutive delimiters are not grouped together and are + deemed to delimit empty subsequences (for example, ``b'1,,2'.split(b',')`` + returns ``[b'1', b'', b'2']``). The *sep* argument may consist of a + multibyte sequence (for example, ``b'1<>2<>3'.split(b'<>')`` returns + ``[b'1', b'2', b'3']``). Splitting an empty sequence with a specified + separator returns ``[b'']`` or ``[bytearray(b'')]`` depending on the type + of object being split. The *sep* argument may be any + :term:`bytes-like object`. + + For example:: + + >>> b'1,2,3'.split(b',') + [b'1', b'2', b'3'] + >>> b'1,2,3'.split(b',', maxsplit=1) + [b'1', b'2,3'] + >>> b'1,2,,3,'.split(b',') + [b'1', b'2', b'', b'3', b''] + + If *sep* is not specified or is ``None``, a different splitting algorithm + is applied: runs of consecutive ASCII whitespace are regarded as a single + separator, and the result will contain no empty strings at the start or + end if the sequence has leading or trailing whitespace. Consequently, + splitting an empty sequence or a sequence consisting solely of ASCII + whitespace without a specified separator returns ``[]``. + + For example:: + + + >>> b'1 2 3'.split() + [b'1', b'2', b'3'] + >>> b'1 2 3'.split(maxsplit=1) + [b'1', b'2 3'] + >>> b' 1 2 3 '.split() + [b'1', b'2', b'3'] + + +.. method:: bytes.strip([chars]) + bytearray.strip([chars]) + + Return a copy of the sequence with specified leading and trailing bytes + removed. The *chars* argument is a binary sequence specifying the set of + byte values to be removed - the name refers to the fact this method is + usually used with ASCII characters. If omitted or ``None``, the *chars* + argument defaults to removing ASCII whitespace. The *chars* argument is + not a prefix or suffix; rather, all combinations of its values are + stripped:: + + >>> b' spacious '.strip() + b'spacious' + >>> b'www.example.com'.strip(b'cmowz.') + b'example' + + The binary sequence of byte values to remove may be any + :term:`bytes-like object`. + + .. note:: + + The bytearray version of this method does *not* operate in place - + it always produces a new object, even if no changes were made. + + +The following methods on bytes and bytearray objects assume the use of ASCII +compatible binary formats and should not be applied to arbitrary binary data. +Note that all of the bytearray methods in this section do *not* operate in +place, and instead produce new objects. + +.. method:: bytes.capitalize() + bytearray.capitalize() + + Return a copy of the sequence with each byte interpreted as an ASCII + character, and the first byte capitalized and the rest lowercased. + Non-ASCII byte values are passed through unchanged. + + .. note:: + + The bytearray version of this method does *not* operate in place - it + always produces a new object, even if no changes were made. + + +.. method:: bytes.expandtabs(tabsize=8) + bytearray.expandtabs(tabsize=8) + + Return a copy of the sequence where all ASCII tab characters are replaced + by one or more ASCII spaces, depending on the current column and the given + tab size. Tab positions occur every *tabsize* bytes (default is 8, + giving tab positions at columns 0, 8, 16 and so on). To expand the + sequence, the current column is set to zero and the sequence is examined + byte by byte. If the byte is an ASCII tab character (``b'\t'``), one or + more space characters are inserted in the result until the current column + is equal to the next tab position. (The tab character itself is not + copied.) If the current byte is an ASCII newline (``b'\n'``) or + carriage return (``b'\r'``), it is copied and the current column is reset + to zero. Any other byte value is copied unchanged and the current column + is incremented by one regardless of how the byte value is represented when + printed:: + + >>> b'01\t012\t0123\t01234'.expandtabs() + b'01 012 0123 01234' + >>> b'01\t012\t0123\t01234'.expandtabs(4) + b'01 012 0123 01234' + + .. note:: + + The bytearray version of this method does *not* operate in place - it + always produces a new object, even if no changes were made. + + +.. method:: bytes.isalnum() + bytearray.isalnum() + + Return ``True`` if all bytes in the sequence are alphabetical ASCII characters + or ASCII decimal digits and the sequence is not empty, ``False`` otherwise. + Alphabetic ASCII characters are those byte values in the sequence + ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``. ASCII decimal + digits are those byte values in the sequence ``b'0123456789'``. + + For example:: + + >>> b'ABCabc1'.isalnum() + True + >>> b'ABC abc1'.isalnum() + False + + +.. method:: bytes.isalpha() + bytearray.isalpha() + + Return ``True`` if all bytes in the sequence are alphabetic ASCII characters + and the sequence is not empty, ``False`` otherwise. Alphabetic ASCII + characters are those byte values in the sequence + ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``. + + For example:: + + >>> b'ABCabc'.isalpha() + True + >>> b'ABCabc1'.isalpha() + False + + +.. method:: bytes.isascii() + bytearray.isascii() + + Return ``True`` if the sequence is empty or all bytes in the sequence are ASCII, + ``False`` otherwise. + ASCII bytes are in the range 0-0x7F. + + .. versionadded:: 3.7 + + +.. method:: bytes.isdigit() + bytearray.isdigit() + + Return ``True`` if all bytes in the sequence are ASCII decimal digits + and the sequence is not empty, ``False`` otherwise. ASCII decimal digits are + those byte values in the sequence ``b'0123456789'``. + + For example:: + + >>> b'1234'.isdigit() + True + >>> b'1.23'.isdigit() + False + + +.. method:: bytes.islower() + bytearray.islower() + + Return ``True`` if there is at least one lowercase ASCII character + in the sequence and no uppercase ASCII characters, ``False`` otherwise. + + For example:: + + >>> b'hello world'.islower() + True + >>> b'Hello world'.islower() + False + + Lowercase ASCII characters are those byte values in the sequence + ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters + are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. + + +.. method:: bytes.isspace() + bytearray.isspace() + + Return ``True`` if all bytes in the sequence are ASCII whitespace and the + sequence is not empty, ``False`` otherwise. ASCII whitespace characters are + those byte values in the sequence ``b' \t\n\r\x0b\f'`` (space, tab, newline, + carriage return, vertical tab, form feed). + + +.. method:: bytes.istitle() + bytearray.istitle() + + Return ``True`` if the sequence is ASCII titlecase and the sequence is not + empty, ``False`` otherwise. See :meth:`bytes.title` for more details on the + definition of "titlecase". + + For example:: + + >>> b'Hello World'.istitle() + True + >>> b'Hello world'.istitle() + False + + +.. method:: bytes.isupper() + bytearray.isupper() + + Return ``True`` if there is at least one uppercase alphabetic ASCII character + in the sequence and no lowercase ASCII characters, ``False`` otherwise. + + For example:: + + >>> b'HELLO WORLD'.isupper() + True + >>> b'Hello world'.isupper() + False + + Lowercase ASCII characters are those byte values in the sequence + ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters + are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. + + +.. method:: bytes.lower() + bytearray.lower() + + Return a copy of the sequence with all the uppercase ASCII characters + converted to their corresponding lowercase counterpart. + + For example:: + + >>> b'Hello World'.lower() + b'hello world' + + Lowercase ASCII characters are those byte values in the sequence + ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters + are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. + + .. note:: + + The bytearray version of this method does *not* operate in place - it + always produces a new object, even if no changes were made. + + +.. index:: + single: universal newlines; bytes.splitlines method + single: universal newlines; bytearray.splitlines method + +.. method:: bytes.splitlines(keepends=False) + bytearray.splitlines(keepends=False) + + Return a list of the lines in the binary sequence, breaking at ASCII + line boundaries. This method uses the :term:`universal newlines` approach + to splitting lines. Line breaks are not included in the resulting list + unless *keepends* is given and true. + + For example:: + + >>> b'ab c\n\nde fg\rkl\r\n'.splitlines() + [b'ab c', b'', b'de fg', b'kl'] + >>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True) + [b'ab c\n', b'\n', b'de fg\r', b'kl\r\n'] + + Unlike :meth:`~bytes.split` when a delimiter string *sep* is given, this + method returns an empty list for the empty string, and a terminal line + break does not result in an extra line:: + + >>> b"".split(b'\n'), b"Two lines\n".split(b'\n') + ([b''], [b'Two lines', b'']) + >>> b"".splitlines(), b"One line\n".splitlines() + ([], [b'One line']) + + +.. method:: bytes.swapcase() + bytearray.swapcase() + + Return a copy of the sequence with all the lowercase ASCII characters + converted to their corresponding uppercase counterpart and vice-versa. + + For example:: + + >>> b'Hello World'.swapcase() + b'hELLO wORLD' + + Lowercase ASCII characters are those byte values in the sequence + ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters + are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. + + Unlike :func:`str.swapcase()`, it is always the case that + ``bin.swapcase().swapcase() == bin`` for the binary versions. Case + conversions are symmetrical in ASCII, even though that is not generally + true for arbitrary Unicode code points. + + .. note:: + + The bytearray version of this method does *not* operate in place - it + always produces a new object, even if no changes were made. + + +.. method:: bytes.title() + bytearray.title() + + Return a titlecased version of the binary sequence where words start with + an uppercase ASCII character and the remaining characters are lowercase. + Uncased byte values are left unmodified. + + For example:: + + >>> b'Hello world'.title() + b'Hello World' + + Lowercase ASCII characters are those byte values in the sequence + ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters + are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. + All other byte values are uncased. + + The algorithm uses a simple language-independent definition of a word as + groups of consecutive letters. The definition works in many contexts but + it means that apostrophes in contractions and possessives form word + boundaries, which may not be the desired result:: + + >>> b"they're bill's friends from the UK".title() + b"They'Re Bill'S Friends From The Uk" + + A workaround for apostrophes can be constructed using regular expressions:: + + >>> import re + >>> def titlecase(s): + ... return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?", + ... lambda mo: mo.group(0)[0:1].upper() + + ... mo.group(0)[1:].lower(), + ... s) + ... + >>> titlecase(b"they're bill's friends.") + b"They're Bill's Friends." + + .. note:: + + The bytearray version of this method does *not* operate in place - it + always produces a new object, even if no changes were made. + + +.. method:: bytes.upper() + bytearray.upper() + + Return a copy of the sequence with all the lowercase ASCII characters + converted to their corresponding uppercase counterpart. + + For example:: + + >>> b'Hello World'.upper() + b'HELLO WORLD' + + Lowercase ASCII characters are those byte values in the sequence + ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters + are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. + + .. note:: + + The bytearray version of this method does *not* operate in place - it + always produces a new object, even if no changes were made. + + +.. method:: bytes.zfill(width) + bytearray.zfill(width) + + Return a copy of the sequence left filled with ASCII ``b'0'`` digits to + make a sequence of length *width*. A leading sign prefix (``b'+'``/ + ``b'-'``) is handled by inserting the padding *after* the sign character + rather than before. For :class:`bytes` objects, the original sequence is + returned if *width* is less than or equal to ``len(seq)``. + + For example:: + + >>> b"42".zfill(5) + b'00042' + >>> b"-42".zfill(5) + b'-0042' + + .. note:: + + The bytearray version of this method does *not* operate in place - it + always produces a new object, even if no changes were made. + + +.. _bytes-formatting: + +``printf``-style Bytes Formatting +---------------------------------- + +.. index:: + single: formatting; bytes (%) + single: formatting; bytearray (%) + single: interpolation; bytes (%) + single: interpolation; bytearray (%) + single: bytes; formatting + single: bytearray; formatting + single: bytes; interpolation + single: bytearray; interpolation + single: printf-style formatting + single: sprintf-style formatting + single: % (percent); printf-style formatting + +.. note:: + + The formatting operations described here exhibit a variety of quirks that + lead to a number of common errors (such as failing to display tuples and + dictionaries correctly). If the value being printed may be a tuple or + dictionary, wrap it in a tuple. + +Bytes objects (``bytes``/``bytearray``) have one unique built-in operation: +the ``%`` operator (modulo). +This is also known as the bytes *formatting* or *interpolation* operator. +Given ``format % values`` (where *format* is a bytes object), ``%`` conversion +specifications in *format* are replaced with zero or more elements of *values*. +The effect is similar to using the :c:func:`sprintf` in the C language. + +If *format* requires a single argument, *values* may be a single non-tuple +object. [5]_ Otherwise, *values* must be a tuple with exactly the number of +items specified by the format bytes object, or a single mapping object (for +example, a dictionary). + +.. index:: + single: () (parentheses); in printf-style formatting + single: * (asterisk); in printf-style formatting + single: . (dot); in printf-style formatting + +A conversion specifier contains two or more characters and has the following +components, which must occur in this order: + +#. The ``'%'`` character, which marks the start of the specifier. + +#. Mapping key (optional), consisting of a parenthesised sequence of characters + (for example, ``(somename)``). + +#. Conversion flags (optional), which affect the result of some conversion + types. + +#. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the + actual width is read from the next element of the tuple in *values*, and the + object to convert comes after the minimum field width and optional precision. + +#. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If + specified as ``'*'`` (an asterisk), the actual precision is read from the next + element of the tuple in *values*, and the value to convert comes after the + precision. + +#. Length modifier (optional). + +#. Conversion type. + +When the right argument is a dictionary (or other mapping type), then the +formats in the bytes object *must* include a parenthesised mapping key into that +dictionary inserted immediately after the ``'%'`` character. The mapping key +selects the value to be formatted from the mapping. For example: + + >>> print(b'%(language)s has %(number)03d quote types.' % + ... {b'language': b"Python", b"number": 2}) + b'Python has 002 quote types.' + +In this case no ``*`` specifiers may occur in a format (since they require a +sequential parameter list). + +The conversion flag characters are: + +.. index:: + single: # (hash); in printf-style formatting + single: - (minus); in printf-style formatting + single: + (plus); in printf-style formatting + single: space; in printf-style formatting + ++---------+---------------------------------------------------------------------+ +| Flag | Meaning | ++=========+=====================================================================+ +| ``'#'`` | The value conversion will use the "alternate form" (where defined | +| | below). | ++---------+---------------------------------------------------------------------+ +| ``'0'`` | The conversion will be zero padded for numeric values. | ++---------+---------------------------------------------------------------------+ +| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` | +| | conversion if both are given). | ++---------+---------------------------------------------------------------------+ +| ``' '`` | (a space) A blank should be left before a positive number (or empty | +| | string) produced by a signed conversion. | ++---------+---------------------------------------------------------------------+ +| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion | +| | (overrides a "space" flag). | ++---------+---------------------------------------------------------------------+ + +A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it +is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``. + +The conversion types are: + ++------------+-----------------------------------------------------+-------+ +| Conversion | Meaning | Notes | ++============+=====================================================+=======+ +| ``'d'`` | Signed integer decimal. | | ++------------+-----------------------------------------------------+-------+ +| ``'i'`` | Signed integer decimal. | | ++------------+-----------------------------------------------------+-------+ +| ``'o'`` | Signed octal value. | \(1) | ++------------+-----------------------------------------------------+-------+ +| ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(8) | ++------------+-----------------------------------------------------+-------+ +| ``'x'`` | Signed hexadecimal (lowercase). | \(2) | ++------------+-----------------------------------------------------+-------+ +| ``'X'`` | Signed hexadecimal (uppercase). | \(2) | ++------------+-----------------------------------------------------+-------+ +| ``'e'`` | Floating point exponential format (lowercase). | \(3) | ++------------+-----------------------------------------------------+-------+ +| ``'E'`` | Floating point exponential format (uppercase). | \(3) | ++------------+-----------------------------------------------------+-------+ +| ``'f'`` | Floating point decimal format. | \(3) | ++------------+-----------------------------------------------------+-------+ +| ``'F'`` | Floating point decimal format. | \(3) | ++------------+-----------------------------------------------------+-------+ +| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) | +| | format if exponent is less than -4 or not less than | | +| | precision, decimal format otherwise. | | ++------------+-----------------------------------------------------+-------+ +| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | +| | format if exponent is less than -4 or not less than | | +| | precision, decimal format otherwise. | | ++------------+-----------------------------------------------------+-------+ +| ``'c'`` | Single byte (accepts integer or single | | +| | byte objects). | | ++------------+-----------------------------------------------------+-------+ +| ``'b'`` | Bytes (any object that follows the | \(5) | +| | :ref:`buffer protocol ` or has | | +| | :meth:`__bytes__`). | | ++------------+-----------------------------------------------------+-------+ +| ``'s'`` | ``'s'`` is an alias for ``'b'`` and should only | \(6) | +| | be used for Python2/3 code bases. | | ++------------+-----------------------------------------------------+-------+ +| ``'a'`` | Bytes (converts any Python object using | \(5) | +| | ``repr(obj).encode('ascii','backslashreplace)``). | | ++------------+-----------------------------------------------------+-------+ +| ``'r'`` | ``'r'`` is an alias for ``'a'`` and should only | \(7) | +| | be used for Python2/3 code bases. | | ++------------+-----------------------------------------------------+-------+ +| ``'%'`` | No argument is converted, results in a ``'%'`` | | +| | character in the result. | | ++------------+-----------------------------------------------------+-------+ + +Notes: + +(1) + The alternate form causes a leading octal specifier (``'0o'``) to be + inserted before the first digit. + +(2) + The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether + the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit. + +(3) + The alternate form causes the result to always contain a decimal point, even if + no digits follow it. + + The precision determines the number of digits after the decimal point and + defaults to 6. + +(4) + The alternate form causes the result to always contain a decimal point, and + trailing zeroes are not removed as they would otherwise be. + + The precision determines the number of significant digits before and after the + decimal point and defaults to 6. + +(5) + If precision is ``N``, the output is truncated to ``N`` characters. + +(6) + ``b'%s'`` is deprecated, but will not be removed during the 3.x series. + +(7) + ``b'%r'`` is deprecated, but will not be removed during the 3.x series. + +(8) + See :pep:`237`. + +.. note:: + + The bytearray version of this method does *not* operate in place - it + always produces a new object, even if no changes were made. + +.. seealso:: + + :pep:`461` - Adding % formatting to bytes and bytearray + +.. versionadded:: 3.5 + +.. _typememoryview: + +Memory Views +------------ + +:class:`memoryview` objects allow Python code to access the internal data +of an object that supports the :ref:`buffer protocol ` without +copying. + +.. class:: memoryview(obj) + + Create a :class:`memoryview` that references *obj*. *obj* must support the + buffer protocol. Built-in objects that support the buffer protocol include + :class:`bytes` and :class:`bytearray`. + + A :class:`memoryview` has the notion of an *element*, which is the + atomic memory unit handled by the originating object *obj*. For many + simple types such as :class:`bytes` and :class:`bytearray`, an element + is a single byte, but other types such as :class:`array.array` may have + bigger elements. + + ``len(view)`` is equal to the length of :class:`~memoryview.tolist`. + If ``view.ndim = 0``, the length is 1. If ``view.ndim = 1``, the length + is equal to the number of elements in the view. For higher dimensions, + the length is equal to the length of the nested list representation of + the view. The :class:`~memoryview.itemsize` attribute will give you the + number of bytes in a single element. + + A :class:`memoryview` supports slicing and indexing to expose its data. + One-dimensional slicing will result in a subview:: + + >>> v = memoryview(b'abcefg') + >>> v[1] + 98 + >>> v[-1] + 103 + >>> v[1:4] + + >>> bytes(v[1:4]) + b'bce' + + If :class:`~memoryview.format` is one of the native format specifiers + from the :mod:`struct` module, indexing with an integer or a tuple of + integers is also supported and returns a single *element* with + the correct type. One-dimensional memoryviews can be indexed + with an integer or a one-integer tuple. Multi-dimensional memoryviews + can be indexed with tuples of exactly *ndim* integers where *ndim* is + the number of dimensions. Zero-dimensional memoryviews can be indexed + with the empty tuple. + + Here is an example with a non-byte format:: + + >>> import array + >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444]) + >>> m = memoryview(a) + >>> m[0] + -11111111 + >>> m[-1] + 44444444 + >>> m[::2].tolist() + [-11111111, -33333333] + + If the underlying object is writable, the memoryview supports + one-dimensional slice assignment. Resizing is not allowed:: + + >>> data = bytearray(b'abcefg') + >>> v = memoryview(data) + >>> v.readonly + False + >>> v[0] = ord(b'z') + >>> data + bytearray(b'zbcefg') + >>> v[1:4] = b'123' + >>> data + bytearray(b'z123fg') + >>> v[2:3] = b'spam' + Traceback (most recent call last): + File "", line 1, in + ValueError: memoryview assignment: lvalue and rvalue have different structures + >>> v[2:6] = b'spam' + >>> data + bytearray(b'z1spam') + + One-dimensional memoryviews of hashable (read-only) types with formats + 'B', 'b' or 'c' are also hashable. The hash is defined as + ``hash(m) == hash(m.tobytes())``:: + + >>> v = memoryview(b'abcefg') + >>> hash(v) == hash(b'abcefg') + True + >>> hash(v[2:4]) == hash(b'ce') + True + >>> hash(v[::-2]) == hash(b'abcefg'[::-2]) + True + + .. versionchanged:: 3.3 + One-dimensional memoryviews can now be sliced. + One-dimensional memoryviews with formats 'B', 'b' or 'c' are now hashable. + + .. versionchanged:: 3.4 + memoryview is now registered automatically with + :class:`collections.abc.Sequence` + + .. versionchanged:: 3.5 + memoryviews can now be indexed with tuple of integers. + + :class:`memoryview` has several methods: + + .. method:: __eq__(exporter) + + A memoryview and a :pep:`3118` exporter are equal if their shapes are + equivalent and if all corresponding values are equal when the operands' + respective format codes are interpreted using :mod:`struct` syntax. + + For the subset of :mod:`struct` format strings currently supported by + :meth:`tolist`, ``v`` and ``w`` are equal if ``v.tolist() == w.tolist()``:: + + >>> import array + >>> a = array.array('I', [1, 2, 3, 4, 5]) + >>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0]) + >>> c = array.array('b', [5, 3, 1]) + >>> x = memoryview(a) + >>> y = memoryview(b) + >>> x == a == y == b + True + >>> x.tolist() == a.tolist() == y.tolist() == b.tolist() + True + >>> z = y[::-2] + >>> z == c + True + >>> z.tolist() == c.tolist() + True + + If either format string is not supported by the :mod:`struct` module, + then the objects will always compare as unequal (even if the format + strings and buffer contents are identical):: + + >>> from ctypes import BigEndianStructure, c_long + >>> class BEPoint(BigEndianStructure): + ... _fields_ = [("x", c_long), ("y", c_long)] + ... + >>> point = BEPoint(100, 200) + >>> a = memoryview(point) + >>> b = memoryview(point) + >>> a == point + False + >>> a == b + False + + Note that, as with floating point numbers, ``v is w`` does *not* imply + ``v == w`` for memoryview objects. + + .. versionchanged:: 3.3 + Previous versions compared the raw memory disregarding the item format + and the logical array structure. + + .. method:: tobytes(order=None) + + Return the data in the buffer as a bytestring. This is equivalent to + calling the :class:`bytes` constructor on the memoryview. :: + + >>> m = memoryview(b"abc") + >>> m.tobytes() + b'abc' + >>> bytes(m) + b'abc' + + For non-contiguous arrays the result is equal to the flattened list + representation with all elements converted to bytes. :meth:`tobytes` + supports all format strings, including those that are not in + :mod:`struct` module syntax. + + .. versionadded:: 3.8 + *order* can be {'C', 'F', 'A'}. When *order* is 'C' or 'F', the data + of the original array is converted to C or Fortran order. For contiguous + views, 'A' returns an exact copy of the physical memory. In particular, + in-memory Fortran order is preserved. For non-contiguous views, the + data is converted to C first. *order=None* is the same as *order='C'*. + + .. method:: hex([sep[, bytes_per_sep]]) + + Return a string object containing two hexadecimal digits for each + byte in the buffer. :: + + >>> m = memoryview(b"abc") + >>> m.hex() + '616263' + + .. versionadded:: 3.5 + + .. versionchanged:: 3.8 + Similar to :meth:`bytes.hex`, :meth:`memoryview.hex` now supports + optional *sep* and *bytes_per_sep* parameters to insert separators + between bytes in the hex output. + + .. method:: tolist() + + Return the data in the buffer as a list of elements. :: + + >>> memoryview(b'abc').tolist() + [97, 98, 99] + >>> import array + >>> a = array.array('d', [1.1, 2.2, 3.3]) + >>> m = memoryview(a) + >>> m.tolist() + [1.1, 2.2, 3.3] + + .. versionchanged:: 3.3 + :meth:`tolist` now supports all single character native formats in + :mod:`struct` module syntax as well as multi-dimensional + representations. + + .. method:: toreadonly() + + Return a readonly version of the memoryview object. The original + memoryview object is unchanged. :: + + >>> m = memoryview(bytearray(b'abc')) + >>> mm = m.toreadonly() + >>> mm.tolist() + [89, 98, 99] + >>> mm[0] = 42 + Traceback (most recent call last): + File "", line 1, in + TypeError: cannot modify read-only memory + >>> m[0] = 43 + >>> mm.tolist() + [43, 98, 99] + + .. versionadded:: 3.8 + + .. method:: release() + + Release the underlying buffer exposed by the memoryview object. Many + objects take special actions when a view is held on them (for example, + a :class:`bytearray` would temporarily forbid resizing); therefore, + calling release() is handy to remove these restrictions (and free any + dangling resources) as soon as possible. + + After this method has been called, any further operation on the view + raises a :class:`ValueError` (except :meth:`release()` itself which can + be called multiple times):: + + >>> m = memoryview(b'abc') + >>> m.release() + >>> m[0] + Traceback (most recent call last): + File "", line 1, in + ValueError: operation forbidden on released memoryview object + + The context management protocol can be used for a similar effect, + using the ``with`` statement:: + + >>> with memoryview(b'abc') as m: + ... m[0] + ... + 97 + >>> m[0] + Traceback (most recent call last): + File "", line 1, in + ValueError: operation forbidden on released memoryview object + + .. versionadded:: 3.2 + + .. method:: cast(format[, shape]) + + Cast a memoryview to a new format or shape. *shape* defaults to + ``[byte_length//new_itemsize]``, which means that the result view + will be one-dimensional. The return value is a new memoryview, but + the buffer itself is not copied. Supported casts are 1D -> C-:term:`contiguous` + and C-contiguous -> 1D. + + The destination format is restricted to a single element native format in + :mod:`struct` syntax. One of the formats must be a byte format + ('B', 'b' or 'c'). The byte length of the result must be the same + as the original length. + + Cast 1D/long to 1D/unsigned bytes:: + + >>> import array + >>> a = array.array('l', [1,2,3]) + >>> x = memoryview(a) + >>> x.format + 'l' + >>> x.itemsize + 8 + >>> len(x) + 3 + >>> x.nbytes + 24 + >>> y = x.cast('B') + >>> y.format + 'B' + >>> y.itemsize + 1 + >>> len(y) + 24 + >>> y.nbytes + 24 + + Cast 1D/unsigned bytes to 1D/char:: + + >>> b = bytearray(b'zyz') + >>> x = memoryview(b) + >>> x[0] = b'a' + Traceback (most recent call last): + File "", line 1, in + ValueError: memoryview: invalid value for format "B" + >>> y = x.cast('c') + >>> y[0] = b'a' + >>> b + bytearray(b'ayz') + + Cast 1D/bytes to 3D/ints to 1D/signed char:: + + >>> import struct + >>> buf = struct.pack("i"*12, *list(range(12))) + >>> x = memoryview(buf) + >>> y = x.cast('i', shape=[2,2,3]) + >>> y.tolist() + [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]] + >>> y.format + 'i' + >>> y.itemsize + 4 + >>> len(y) + 2 + >>> y.nbytes + 48 + >>> z = y.cast('b') + >>> z.format + 'b' + >>> z.itemsize + 1 + >>> len(z) + 48 + >>> z.nbytes + 48 + + Cast 1D/unsigned long to 2D/unsigned long:: + + >>> buf = struct.pack("L"*6, *list(range(6))) + >>> x = memoryview(buf) + >>> y = x.cast('L', shape=[2,3]) + >>> len(y) + 2 + >>> y.nbytes + 48 + >>> y.tolist() + [[0, 1, 2], [3, 4, 5]] + + .. versionadded:: 3.3 + + .. versionchanged:: 3.5 + The source format is no longer restricted when casting to a byte view. + + There are also several readonly attributes available: + + .. attribute:: obj + + The underlying object of the memoryview:: + + >>> b = bytearray(b'xyz') + >>> m = memoryview(b) + >>> m.obj is b + True + + .. versionadded:: 3.3 + + .. attribute:: nbytes + + ``nbytes == product(shape) * itemsize == len(m.tobytes())``. This is + the amount of space in bytes that the array would use in a contiguous + representation. It is not necessarily equal to ``len(m)``:: + + >>> import array + >>> a = array.array('i', [1,2,3,4,5]) + >>> m = memoryview(a) + >>> len(m) + 5 + >>> m.nbytes + 20 + >>> y = m[::2] + >>> len(y) + 3 + >>> y.nbytes + 12 + >>> len(y.tobytes()) + 12 + + Multi-dimensional arrays:: + + >>> import struct + >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)]) + >>> x = memoryview(buf) + >>> y = x.cast('d', shape=[3,4]) + >>> y.tolist() + [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]] + >>> len(y) + 3 + >>> y.nbytes + 96 + + .. versionadded:: 3.3 + + .. attribute:: readonly + + A bool indicating whether the memory is read only. + + .. attribute:: format + + A string containing the format (in :mod:`struct` module style) for each + element in the view. A memoryview can be created from exporters with + arbitrary format strings, but some methods (e.g. :meth:`tolist`) are + restricted to native single element formats. + + .. versionchanged:: 3.3 + format ``'B'`` is now handled according to the struct module syntax. + This means that ``memoryview(b'abc')[0] == b'abc'[0] == 97``. + + .. attribute:: itemsize + + The size in bytes of each element of the memoryview:: + + >>> import array, struct + >>> m = memoryview(array.array('H', [32000, 32001, 32002])) + >>> m.itemsize + 2 + >>> m[0] + 32000 + >>> struct.calcsize('H') == m.itemsize + True + + .. attribute:: ndim + + An integer indicating how many dimensions of a multi-dimensional array the + memory represents. + + .. attribute:: shape + + A tuple of integers the length of :attr:`ndim` giving the shape of the + memory as an N-dimensional array. + + .. versionchanged:: 3.3 + An empty tuple instead of ``None`` when ndim = 0. + + .. attribute:: strides + + A tuple of integers the length of :attr:`ndim` giving the size in bytes to + access each element for each dimension of the array. + + .. versionchanged:: 3.3 + An empty tuple instead of ``None`` when ndim = 0. + + .. attribute:: suboffsets + + Used internally for PIL-style arrays. The value is informational only. + + .. attribute:: c_contiguous + + A bool indicating whether the memory is C-:term:`contiguous`. + + .. versionadded:: 3.3 + + .. attribute:: f_contiguous + + A bool indicating whether the memory is Fortran :term:`contiguous`. + + .. versionadded:: 3.3 + + .. attribute:: contiguous + + A bool indicating whether the memory is :term:`contiguous`. + + .. versionadded:: 3.3 + + +.. _types-set: + +Set Types --- :class:`set`, :class:`frozenset` +============================================== + +.. index:: object: set + +A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects. +Common uses include membership testing, removing duplicates from a sequence, and +computing mathematical operations such as intersection, union, difference, and +symmetric difference. +(For other containers see the built-in :class:`dict`, :class:`list`, +and :class:`tuple` classes, and the :mod:`collections` module.) + +Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in +set``. Being an unordered collection, sets do not record element position or +order of insertion. Accordingly, sets do not support indexing, slicing, or +other sequence-like behavior. + +There are currently two built-in set types, :class:`set` and :class:`frozenset`. +The :class:`set` type is mutable --- the contents can be changed using methods +like :meth:`~set.add` and :meth:`~set.remove`. Since it is mutable, it has no +hash value and cannot be used as either a dictionary key or as an element of +another set. The :class:`frozenset` type is immutable and :term:`hashable` --- +its contents cannot be altered after it is created; it can therefore be used as +a dictionary key or as an element of another set. + +Non-empty sets (not frozensets) can be created by placing a comma-separated list +of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the +:class:`set` constructor. + +The constructors for both classes work the same: + +.. class:: set([iterable]) + frozenset([iterable]) + + Return a new set or frozenset object whose elements are taken from + *iterable*. The elements of a set must be :term:`hashable`. To + represent sets of sets, the inner sets must be :class:`frozenset` + objects. If *iterable* is not specified, a new empty set is + returned. + + Instances of :class:`set` and :class:`frozenset` provide the following + operations: + + .. describe:: len(s) + + Return the number of elements in set *s* (cardinality of *s*). + + .. describe:: x in s + + Test *x* for membership in *s*. + + .. describe:: x not in s + + Test *x* for non-membership in *s*. + + .. method:: isdisjoint(other) + + Return ``True`` if the set has no elements in common with *other*. Sets are + disjoint if and only if their intersection is the empty set. + + .. method:: issubset(other) + set <= other + + Test whether every element in the set is in *other*. + + .. method:: set < other + + Test whether the set is a proper subset of *other*, that is, + ``set <= other and set != other``. + + .. method:: issuperset(other) + set >= other + + Test whether every element in *other* is in the set. + + .. method:: set > other + + Test whether the set is a proper superset of *other*, that is, ``set >= + other and set != other``. + + .. method:: union(*others) + set | other | ... + + Return a new set with elements from the set and all others. + + .. method:: intersection(*others) + set & other & ... + + Return a new set with elements common to the set and all others. + + .. method:: difference(*others) + set - other - ... + + Return a new set with elements in the set that are not in the others. + + .. method:: symmetric_difference(other) + set ^ other + + Return a new set with elements in either the set or *other* but not both. + + .. method:: copy() + + Return a shallow copy of the set. + + + Note, the non-operator versions of :meth:`union`, :meth:`intersection`, + :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and + :meth:`issuperset` methods will accept any iterable as an argument. In + contrast, their operator based counterparts require their arguments to be + sets. This precludes error-prone constructions like ``set('abc') & 'cbs'`` + in favor of the more readable ``set('abc').intersection('cbs')``. + + Both :class:`set` and :class:`frozenset` support set to set comparisons. Two + sets are equal if and only if every element of each set is contained in the + other (each is a subset of the other). A set is less than another set if and + only if the first set is a proper subset of the second set (is a subset, but + is not equal). A set is greater than another set if and only if the first set + is a proper superset of the second set (is a superset, but is not equal). + + Instances of :class:`set` are compared to instances of :class:`frozenset` + based on their members. For example, ``set('abc') == frozenset('abc')`` + returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``. + + The subset and equality comparisons do not generalize to a total ordering + function. For example, any two nonempty disjoint sets are not equal and are not + subsets of each other, so *all* of the following return ``False``: ``ab``. + + Since sets only define partial ordering (subset relationships), the output of + the :meth:`list.sort` method is undefined for lists of sets. + + Set elements, like dictionary keys, must be :term:`hashable`. + + Binary operations that mix :class:`set` instances with :class:`frozenset` + return the type of the first operand. For example: ``frozenset('ab') | + set('bc')`` returns an instance of :class:`frozenset`. + + The following table lists operations available for :class:`set` that do not + apply to immutable instances of :class:`frozenset`: + + .. method:: update(*others) + set |= other | ... + + Update the set, adding elements from all others. + + .. method:: intersection_update(*others) + set &= other & ... + + Update the set, keeping only elements found in it and all others. + + .. method:: difference_update(*others) + set -= other | ... + + Update the set, removing elements found in others. + + .. method:: symmetric_difference_update(other) + set ^= other + + Update the set, keeping only elements found in either set, but not in both. + + .. method:: add(elem) + + Add element *elem* to the set. + + .. method:: remove(elem) + + Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is + not contained in the set. + + .. method:: discard(elem) + + Remove element *elem* from the set if it is present. + + .. method:: pop() + + Remove and return an arbitrary element from the set. Raises + :exc:`KeyError` if the set is empty. + + .. method:: clear() + + Remove all elements from the set. + + + Note, the non-operator versions of the :meth:`update`, + :meth:`intersection_update`, :meth:`difference_update`, and + :meth:`symmetric_difference_update` methods will accept any iterable as an + argument. + + Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and + :meth:`discard` methods may be a set. To support searching for an equivalent + frozenset, a temporary one is created from *elem*. + + +.. _typesmapping: + +Mapping Types --- :class:`dict` +=============================== + +.. index:: + object: mapping + object: dictionary + triple: operations on; mapping; types + triple: operations on; dictionary; type + statement: del + builtin: len + +A :term:`mapping` object maps :term:`hashable` values to arbitrary objects. +Mappings are mutable objects. There is currently only one standard mapping +type, the :dfn:`dictionary`. (For other containers see the built-in +:class:`list`, :class:`set`, and :class:`tuple` classes, and the +:mod:`collections` module.) + +A dictionary's keys are *almost* arbitrary values. Values that are not +:term:`hashable`, that is, values containing lists, dictionaries or other +mutable types (that are compared by value rather than by object identity) may +not be used as keys. Numeric types used for keys obey the normal rules for +numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``) +then they can be used interchangeably to index the same dictionary entry. (Note +however, that since computers store floating-point numbers as approximations it +is usually unwise to use them as dictionary keys.) + +Dictionaries can be created by placing a comma-separated list of ``key: value`` +pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: +'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor. + +.. class:: dict(**kwarg) + dict(mapping, **kwarg) + dict(iterable, **kwarg) + + Return a new dictionary initialized from an optional positional argument + and a possibly empty set of keyword arguments. + + If no positional argument is given, an empty dictionary is created. + If a positional argument is given and it is a mapping object, a dictionary + is created with the same key-value pairs as the mapping object. Otherwise, + the positional argument must be an :term:`iterable` object. Each item in + the iterable must itself be an iterable with exactly two objects. The + first object of each item becomes a key in the new dictionary, and the + second object the corresponding value. If a key occurs more than once, the + last value for that key becomes the corresponding value in the new + dictionary. + + If keyword arguments are given, the keyword arguments and their values are + added to the dictionary created from the positional argument. If a key + being added is already present, the value from the keyword argument + replaces the value from the positional argument. + + To illustrate, the following examples all return a dictionary equal to + ``{"one": 1, "two": 2, "three": 3}``:: + + >>> a = dict(one=1, two=2, three=3) + >>> b = {'one': 1, 'two': 2, 'three': 3} + >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) + >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) + >>> e = dict({'three': 3, 'one': 1, 'two': 2}) + >>> f = dict({'one': 1, 'three': 3}, two=2) + >>> a == b == c == d == e == f + True + + Providing keyword arguments as in the first example only works for keys that + are valid Python identifiers. Otherwise, any valid keys can be used. + + + These are the operations that dictionaries support (and therefore, custom + mapping types should support too): + + .. describe:: list(d) + + Return a list of all the keys used in the dictionary *d*. + + .. describe:: len(d) + + Return the number of items in the dictionary *d*. + + .. describe:: d[key] + + Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is + not in the map. + + .. index:: __missing__() + + If a subclass of dict defines a method :meth:`__missing__` and *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 + returned or raised by the ``__missing__(key)`` call. + No other operations or methods invoke :meth:`__missing__`. If + :meth:`__missing__` is not defined, :exc:`KeyError` is raised. + :meth:`__missing__` must be a method; it cannot be an instance variable:: + + >>> class Counter(dict): + ... def __missing__(self, key): + ... return 0 + >>> c = Counter() + >>> c['red'] + 0 + >>> c['red'] += 1 + >>> c['red'] + 1 + + The example above shows part of the implementation of + :class:`collections.Counter`. A different ``__missing__`` method is used + by :class:`collections.defaultdict`. + + .. describe:: d[key] = value + + Set ``d[key]`` to *value*. + + .. describe:: del d[key] + + Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the + map. + + .. describe:: key in d + + Return ``True`` if *d* has a key *key*, else ``False``. + + .. describe:: key not in d + + Equivalent to ``not key in d``. + + .. describe:: iter(d) + + Return an iterator over the keys of the dictionary. This is a shortcut + for ``iter(d.keys())``. + + .. method:: clear() + + Remove all items from the dictionary. + + .. method:: copy() + + Return a shallow copy of the dictionary. + + .. classmethod:: fromkeys(iterable[, value]) + + Create a new dictionary with keys from *iterable* and values set to *value*. + + :meth:`fromkeys` is a class method that returns a new dictionary. *value* + defaults to ``None``. All of the values refer to just a single instance, + so it generally doesn't make sense for *value* to be a mutable object + such as an empty list. To get distinct values, use a :ref:`dict + comprehension ` instead. + + .. method:: get(key[, default]) + + Return the value for *key* if *key* is in the dictionary, else *default*. + If *default* is not given, it defaults to ``None``, so that this method + never raises a :exc:`KeyError`. + + .. method:: items() + + Return a new view of the dictionary's items (``(key, value)`` pairs). + See the :ref:`documentation of view objects `. + + .. method:: keys() + + Return a new view of the dictionary's keys. See the :ref:`documentation + of view objects `. + + .. method:: pop(key[, default]) + + If *key* is in the dictionary, remove it and return its value, else return + *default*. If *default* is not given and *key* is not in the dictionary, + a :exc:`KeyError` is raised. + + .. method:: popitem() + + Remove and return a ``(key, value)`` pair from the dictionary. + Pairs are returned in :abbr:`LIFO (last-in, first-out)` order. + + :meth:`popitem` is useful to destructively iterate over a dictionary, as + often used in set algorithms. If the dictionary is empty, calling + :meth:`popitem` raises a :exc:`KeyError`. + + .. versionchanged:: 3.7 + LIFO order is now guaranteed. In prior versions, :meth:`popitem` would + return an arbitrary key/value pair. + + .. describe:: reversed(d) + + Return a reverse iterator over the keys of the dictionary. This is a + shortcut for ``reversed(d.keys())``. + + .. versionadded:: 3.8 + + .. method:: setdefault(key[, default]) + + If *key* is in the dictionary, return its value. If not, insert *key* + with a value of *default* and return *default*. *default* defaults to + ``None``. + + .. method:: update([other]) + + Update the dictionary with the key/value pairs from *other*, overwriting + existing keys. Return ``None``. + + :meth:`update` accepts either another dictionary object or an iterable of + key/value pairs (as tuples or other iterables of length two). If keyword + arguments are specified, the dictionary is then updated with those + key/value pairs: ``d.update(red=1, blue=2)``. + + .. method:: values() + + Return a new view of the dictionary's values. See the + :ref:`documentation of view objects `. + + An equality comparison between one ``dict.values()`` view and another + will always return ``False``. This also applies when comparing + ``dict.values()`` to itself:: + + >>> d = {'a': 1} + >>> d.values() == d.values() + False + + .. describe:: d | other + + Create a new dictionary with the merged keys and values of *d* and + *other*, which must both be dictionaries. The values of *other* take + priority when *d* and *other* share keys. + + .. versionadded:: 3.9 + + .. describe:: d |= other + + Update the dictionary *d* with keys and values from *other*, which may be + either a :term:`mapping` or an :term:`iterable` of key/value pairs. The + values of *other* take priority when *d* and *other* share keys. + + .. versionadded:: 3.9 + + Dictionaries compare equal if and only if they have the same ``(key, + value)`` pairs (regardless of ordering). Order comparisons ('<', '<=', '>=', '>') raise + :exc:`TypeError`. + + Dictionaries preserve insertion order. Note that updating a key does not + affect the order. Keys added after deletion are inserted at the end. :: + + >>> d = {"one": 1, "two": 2, "three": 3, "four": 4} + >>> d + {'one': 1, 'two': 2, 'three': 3, 'four': 4} + >>> list(d) + ['one', 'two', 'three', 'four'] + >>> list(d.values()) + [1, 2, 3, 4] + >>> d["one"] = 42 + >>> d + {'one': 42, 'two': 2, 'three': 3, 'four': 4} + >>> del d["two"] + >>> d["two"] = None + >>> d + {'one': 42, 'three': 3, 'four': 4, 'two': None} + + .. versionchanged:: 3.7 + Dictionary order is guaranteed to be insertion order. This behavior was + an implementation detail of CPython from 3.6. + + Dictionaries and dictionary views are reversible. :: + + >>> d = {"one": 1, "two": 2, "three": 3, "four": 4} + >>> d + {'one': 1, 'two': 2, 'three': 3, 'four': 4} + >>> list(reversed(d)) + ['four', 'three', 'two', 'one'] + >>> list(reversed(d.values())) + [4, 3, 2, 1] + >>> list(reversed(d.items())) + [('four', 4), ('three', 3), ('two', 2), ('one', 1)] + + .. versionchanged:: 3.8 + Dictionaries are now reversible. + + +.. seealso:: + :class:`types.MappingProxyType` can be used to create a read-only view + of a :class:`dict`. + + +.. _dict-views: + +Dictionary view objects +----------------------- + +The objects returned by :meth:`dict.keys`, :meth:`dict.values` and +:meth:`dict.items` are *view objects*. They provide a dynamic view on the +dictionary's entries, which means that when the dictionary changes, the view +reflects these changes. + +Dictionary views can be iterated over to yield their respective data, and +support membership tests: + +.. describe:: len(dictview) + + Return the number of entries in the dictionary. + +.. describe:: iter(dictview) + + Return an iterator over the keys, values or items (represented as tuples of + ``(key, value)``) in the dictionary. + + Keys and values are iterated over in insertion order. + This allows the creation of ``(value, key)`` pairs + using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to + create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``. + + Iterating views while adding or deleting entries in the dictionary may raise + a :exc:`RuntimeError` or fail to iterate over all entries. + + .. versionchanged:: 3.7 + Dictionary order is guaranteed to be insertion order. + +.. describe:: x in dictview + + Return ``True`` if *x* is in the underlying dictionary's keys, values or + items (in the latter case, *x* should be a ``(key, value)`` tuple). + +.. describe:: reversed(dictview) + + Return a reverse iterator over the keys, values or items of the dictionary. + The view will be iterated in reverse order of the insertion. + + .. versionchanged:: 3.8 + Dictionary views are now reversible. + + +Keys views are set-like since their entries are unique and hashable. If all +values are hashable, so that ``(key, value)`` pairs are unique and hashable, +then the items view is also set-like. (Values views are not treated as set-like +since the entries are generally not unique.) For set-like views, all of the +operations defined for the abstract base class :class:`collections.abc.Set` are +available (for example, ``==``, ``<``, or ``^``). + +An example of dictionary view usage:: + + >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} + >>> keys = dishes.keys() + >>> values = dishes.values() + + >>> # iteration + >>> n = 0 + >>> for val in values: + ... n += val + >>> print(n) + 504 + + >>> # keys and values are iterated over in the same order (insertion order) + >>> list(keys) + ['eggs', 'sausage', 'bacon', 'spam'] + >>> list(values) + [2, 1, 1, 500] + + >>> # view objects are dynamic and reflect dict changes + >>> del dishes['eggs'] + >>> del dishes['sausage'] + >>> list(keys) + ['bacon', 'spam'] + + >>> # set operations + >>> keys & {'eggs', 'bacon', 'salad'} + {'bacon'} + >>> keys ^ {'sausage', 'juice'} + {'juice', 'sausage', 'bacon', 'spam'} + + +.. _typecontextmanager: + +Context Manager Types +===================== + +.. index:: + single: context manager + single: context management protocol + single: protocol; context management + +Python's :keyword:`with` statement supports the concept of a runtime context +defined by a context manager. This is implemented using a pair of methods +that allow user-defined classes to define a runtime context that is entered +before the statement body is executed and exited when the statement ends: + + +.. method:: contextmanager.__enter__() + + Enter the runtime context and return either this object or another object + related to the runtime context. The value returned by this method is bound to + the identifier in the :keyword:`!as` clause of :keyword:`with` statements using + this context manager. + + An example of a context manager that returns itself is a :term:`file object`. + File objects return themselves from __enter__() to allow :func:`open` to be + used as the context expression in a :keyword:`with` statement. + + An example of a context manager that returns a related object is the one + returned by :func:`decimal.localcontext`. These managers set the active + decimal context to a copy of the original decimal context and then return the + copy. This allows changes to be made to the current decimal context in the body + of the :keyword:`with` statement without affecting code outside the + :keyword:`!with` statement. + + +.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb) + + Exit the runtime context and return a Boolean flag indicating if any exception + that occurred should be suppressed. If an exception occurred while executing the + body of the :keyword:`with` statement, the arguments contain the exception type, + value and traceback information. Otherwise, all three arguments are ``None``. + + Returning a true value from this method will cause the :keyword:`with` statement + to suppress the exception and continue execution with the statement immediately + following the :keyword:`!with` statement. Otherwise the exception continues + propagating after this method has finished executing. Exceptions that occur + during execution of this method will replace any exception that occurred in the + body of the :keyword:`!with` statement. + + The exception passed in should never be reraised explicitly - instead, this + method should return a false value to indicate that the method completed + successfully and does not want to suppress the raised exception. This allows + context management code to easily detect whether or not an :meth:`__exit__` + method has actually failed. + +Python defines several context managers to support easy thread synchronisation, +prompt closure of files or other objects, and simpler manipulation of the active +decimal arithmetic context. The specific types are not treated specially beyond +their implementation of the context management protocol. See the +:mod:`contextlib` module for some examples. + +Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorator +provide a convenient way to implement these protocols. If a generator function is +decorated with the :class:`contextlib.contextmanager` decorator, it will return a +context manager implementing the necessary :meth:`__enter__` and +:meth:`__exit__` methods, rather than the iterator produced by an undecorated +generator function. + +Note that there is no specific slot for any of these methods in the type +structure for Python objects in the Python/C API. Extension types wanting to +define these methods must provide them as a normal Python accessible method. +Compared to the overhead of setting up the runtime context, the overhead of a +single class dictionary lookup is negligible. + + +.. _typesother: + +Other Built-in Types +==================== + +The interpreter supports several other kinds of objects. Most of these support +only one or two operations. + + +.. _typesmodules: + +Modules +------- + +The only special operation on a module is attribute access: ``m.name``, where +*m* is a module and *name* accesses a name defined in *m*'s symbol table. +Module attributes can be assigned to. (Note that the :keyword:`import` +statement is not, strictly speaking, an operation on a module object; ``import +foo`` does not require a module object named *foo* to exist, rather it requires +an (external) *definition* for a module named *foo* somewhere.) + +A special attribute of every module is :attr:`~object.__dict__`. This is the +dictionary containing the module's symbol table. Modifying this dictionary will +actually change the module's symbol table, but direct assignment to the +:attr:`~object.__dict__` attribute is not possible (you can write +``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but you can't write +``m.__dict__ = {}``). Modifying :attr:`~object.__dict__` directly is +not recommended. + +Modules built into the interpreter are written like this: ````. If loaded from a file, they are written as ````. + + +.. _typesobjects: + +Classes and Class Instances +--------------------------- + +See :ref:`objects` and :ref:`class` for these. + + +.. _typesfunctions: + +Functions +--------- + +Function objects are created by function definitions. The only operation on a +function object is to call it: ``func(argument-list)``. + +There are really two flavors of function objects: built-in functions and +user-defined functions. Both support the same operation (to call the function), +but the implementation is different, hence the different object types. + +See :ref:`function` for more information. + + +.. _typesmethods: + +Methods +------- + +.. index:: object: method + +Methods are functions that are called using the attribute notation. There are +two flavors: built-in methods (such as :meth:`append` on lists) and class +instance methods. Built-in methods are described with the types that support +them. + +If you access a method (a function defined in a class namespace) through an +instance, you get a special object: a :dfn:`bound method` (also called +:dfn:`instance method`) object. When called, it will add the ``self`` argument +to the argument list. Bound methods have two special read-only attributes: +``m.__self__`` is the object on which the method operates, and ``m.__func__`` is +the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)`` +is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ..., +arg-n)``. + +Like function objects, bound method objects support getting arbitrary +attributes. However, since method attributes are actually stored on the +underlying function object (``meth.__func__``), setting method attributes on +bound methods is disallowed. Attempting to set an attribute on a method +results in an :exc:`AttributeError` being raised. In order to set a method +attribute, you need to explicitly set it on the underlying function object:: + + >>> class C: + ... def method(self): + ... pass + ... + >>> c = C() + >>> c.method.whoami = 'my name is method' # can't set on the method + Traceback (most recent call last): + File "", line 1, in + AttributeError: 'method' object has no attribute 'whoami' + >>> c.method.__func__.whoami = 'my name is method' + >>> c.method.whoami + 'my name is method' + +See :ref:`types` for more information. + + +.. index:: object; code, code object + +.. _bltin-code-objects: + +Code Objects +------------ + +.. index:: + builtin: compile + single: __code__ (function object attribute) + +Code objects are used by the implementation to represent "pseudo-compiled" +executable Python code such as a function body. They differ from function +objects because they don't contain a reference to their global execution +environment. Code objects are returned by the built-in :func:`compile` function +and can be extracted from function objects through their :attr:`__code__` +attribute. See also the :mod:`code` module. + +.. index:: + builtin: exec + builtin: eval + +A code object can be executed or evaluated by passing it (instead of a source +string) to the :func:`exec` or :func:`eval` built-in functions. + +See :ref:`types` for more information. + + +.. _bltin-type-objects: + +Type Objects +------------ + +.. index:: + builtin: type + module: types + +Type objects represent the various object types. An object's type is accessed +by the built-in function :func:`type`. There are no special operations on +types. The standard module :mod:`types` defines names for all standard built-in +types. + +Types are written like this: ````. + + +.. _bltin-null-object: + +The Null Object +--------------- + +This object is returned by functions that don't explicitly return a value. It +supports no special operations. There is exactly one null object, named +``None`` (a built-in name). ``type(None)()`` produces the same singleton. + +It is written as ``None``. + + +.. index:: single: ...; ellipsis literal +.. _bltin-ellipsis-object: + +The Ellipsis Object +------------------- + +This object is commonly used by slicing (see :ref:`slicings`). It supports no +special operations. There is exactly one ellipsis object, named +:const:`Ellipsis` (a built-in name). ``type(Ellipsis)()`` produces the +:const:`Ellipsis` singleton. + +It is written as ``Ellipsis`` or ``...``. + + +.. _bltin-notimplemented-object: + +The NotImplemented Object +------------------------- + +This object is returned from comparisons and binary operations when they are +asked to operate on types they don't support. See :ref:`comparisons` for more +information. There is exactly one ``NotImplemented`` object. +``type(NotImplemented)()`` produces the singleton instance. + +It is written as ``NotImplemented``. + + +.. _bltin-boolean-values: + +Boolean Values +-------------- + +Boolean values are the two constant objects ``False`` and ``True``. They are +used to represent truth values (although other values can also be considered +false or true). In numeric contexts (for example when used as the argument to +an arithmetic operator), they behave like the integers 0 and 1, respectively. +The built-in function :func:`bool` can be used to convert any value to a +Boolean, if the value can be interpreted as a truth value (see section +:ref:`truth` above). + +.. index:: + single: False + single: True + pair: Boolean; values + +They are written as ``False`` and ``True``, respectively. + + +.. _typesinternal: + +Internal Objects +---------------- + +See :ref:`types` for this information. It describes stack frame objects, +traceback objects, and slice objects. + + +.. _specialattrs: + +Special Attributes +================== + +The implementation adds a few special read-only attributes to several object +types, where they are relevant. Some of these are not reported by the +:func:`dir` built-in function. + + +.. attribute:: object.__dict__ + + A dictionary or other mapping object used to store an object's (writable) + attributes. + + +.. attribute:: instance.__class__ + + The class to which a class instance belongs. + + +.. attribute:: class.__bases__ + + The tuple of base classes of a class object. + + +.. attribute:: definition.__name__ + + The name of the class, function, method, descriptor, or + generator instance. + + +.. attribute:: definition.__qualname__ + + The :term:`qualified name` of the class, function, method, descriptor, + or generator instance. + + .. versionadded:: 3.3 + + +.. attribute:: class.__mro__ + + This attribute is a tuple of classes that are considered when looking for + base classes during method resolution. + + +.. method:: class.mro() + + This method can be overridden by a metaclass to customize the method + resolution order for its instances. It is called at class instantiation, and + its result is stored in :attr:`~class.__mro__`. + + +.. method:: class.__subclasses__ + + Each class keeps a list of weak references to its immediate subclasses. This + method returns a list of all those references still alive. + Example:: + + >>> int.__subclasses__() + [] + + +.. rubric:: Footnotes + +.. [1] Additional information on these special methods may be found in the Python + Reference Manual (:ref:`customization`). + +.. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and + similarly for tuples. + +.. [3] They must have since the parser can't tell the type of the operands. + +.. [4] Cased characters are those with general category property being one of + "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase). + +.. [5] To format only a tuple you should therefore provide a singleton tuple whose only + element is the tuple to be formatted. diff --git a/cpython_2/environment/repo/Doc/library/string.rst b/cpython_2/environment/repo/Doc/library/string.rst new file mode 100644 index 0000000000000000000000000000000000000000..fa906f799c1082c627d391fb1d9558fa16354ee4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/string.rst @@ -0,0 +1,847 @@ +:mod:`string` --- Common string operations +========================================== + +.. module:: string + :synopsis: Common string operations. + +**Source code:** :source:`Lib/string.py` + +-------------- + +.. seealso:: + + :ref:`textseq` + + :ref:`string-methods` + +String constants +---------------- + +The constants defined in this module are: + + +.. data:: ascii_letters + + The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase` + constants described below. This value is not locale-dependent. + + +.. data:: ascii_lowercase + + The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not + locale-dependent and will not change. + + +.. data:: ascii_uppercase + + The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not + locale-dependent and will not change. + + +.. data:: digits + + The string ``'0123456789'``. + + +.. data:: hexdigits + + The string ``'0123456789abcdefABCDEF'``. + + +.. data:: octdigits + + The string ``'01234567'``. + + +.. data:: punctuation + + String of ASCII characters which are considered punctuation characters + in the ``C`` locale: ``!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~``. + +.. data:: printable + + String of ASCII characters which are considered printable. This is a + combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`, + and :const:`whitespace`. + + +.. data:: whitespace + + A string containing all ASCII characters that are considered whitespace. + This includes the characters space, tab, linefeed, return, formfeed, and + vertical tab. + + +.. _string-formatting: + +Custom String Formatting +------------------------ + +The built-in string class provides the ability to do complex variable +substitutions and value formatting via the :meth:`~str.format` method described in +:pep:`3101`. The :class:`Formatter` class in the :mod:`string` module allows +you to create and customize your own string formatting behaviors using the same +implementation as the built-in :meth:`~str.format` method. + + +.. class:: Formatter + + The :class:`Formatter` class has the following public methods: + + .. method:: format(format_string, /, *args, **kwargs) + + The primary API method. It takes a format string and + an arbitrary set of positional and keyword arguments. + It is just a wrapper that calls :meth:`vformat`. + + .. versionchanged:: 3.7 + A format string argument is now :ref:`positional-only + `. + + .. 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 + dictionary as individual arguments using the ``*args`` and ``**kwargs`` + syntax. :meth:`vformat` does the work of breaking up the format string + into character data and replacement fields. It calls the various + methods described below. + + In addition, the :class:`Formatter` defines a number of methods that are + 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 into 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 + *literal_text* will be a zero-length string. If there is no replacement + field, then the values of *field_name*, *format_spec* and *conversion* + will be ``None``. + + .. method:: get_field(field_name, args, kwargs) + + Given *field_name* as returned by :meth:`parse` (see above), convert it to + an object to be formatted. Returns a tuple (obj, used_key). The default + version takes strings of the form defined in :pep:`3101`, such as + "0[name]" or "label.title". *args* and *kwargs* are as passed in to + :meth:`vformat`. The return value *used_key* has the same meaning as the + *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 + named argument in *kwargs*. + + The *args* parameter is set to the list of positional arguments to + :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of + keyword arguments. + + For compound field names, these functions are only called for the first + component of the field name; subsequent components are handled through + normal attribute and indexing operations. + + So for example, the field expression '0.name' would cause + :meth:`get_value` to be called with a *key* argument of 0. The ``name`` + attribute will be looked up after :meth:`get_value` returns by calling the + built-in :func:`getattr` function. + + If the index or keyword refers to an item that does not exist, then an + :exc:`IndexError` or :exc:`KeyError` should be raised. + + .. method:: check_unused_args(used_args, args, kwargs) + + Implement checking for unused arguments if desired. The arguments to this + function is the set of all argument keys that were actually referred to in + the format string (integers for positional arguments, and strings for + named arguments), and a reference to the *args* and *kwargs* that was + passed to vformat. The set of unused args can be calculated from these + parameters. :meth:`check_unused_args` is assumed to raise an exception if + the check fails. + + .. method:: format_field(value, format_spec) + + :meth:`format_field` simply calls the global :func:`format` built-in. The + 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 's' (str), 'r' (repr) and 'a' (ascii) conversion + types. + + +.. _formatstrings: + +Format String Syntax +-------------------- + +The :meth:`str.format` method and the :class:`Formatter` class share the same +syntax for format strings (although in the case of :class:`Formatter`, +subclasses can define their own format string syntax). The syntax is +related to that of :ref:`formatted string literals `, but +there are differences. + +.. index:: + single: {} (curly brackets); in string formatting + single: . (dot); in string formatting + single: [] (square brackets); in string formatting + single: ! (exclamation); in string formatting + single: : (colon); in string formatting + +Format strings contain "replacement fields" surrounded by curly braces ``{}``. +Anything that is not contained in braces is considered literal text, which is +copied unchanged to the output. If you need to include a brace character in the +literal text, it can be escaped by doubling: ``{{`` and ``}}``. + +The grammar for a replacement field is as follows: + + .. productionlist:: sf + replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}" + field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")* + arg_name: [`identifier` | `digit`+] + attribute_name: `identifier` + element_index: `digit`+ | `index_string` + index_string: + + conversion: "r" | "s" | "a" + format_spec: + +In less formal terms, the replacement field can start with a *field_name* that specifies +the object whose value is to be formatted and inserted +into the output instead of the replacement field. +The *field_name* is optionally followed by a *conversion* field, which is +preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded +by a colon ``':'``. These specify a non-default format for the replacement value. + +See also the :ref:`formatspec` section. + +The *field_name* itself begins with an *arg_name* that is either a number or a +keyword. If it's a number, it refers to a positional argument, and if it's a keyword, +it refers to a named keyword argument. If the numerical arg_names in a format string +are 0, 1, 2, ... in sequence, they can all be omitted (not just some) +and the numbers 0, 1, 2, ... will be automatically inserted in that order. +Because *arg_name* is not quote-delimited, it is not possible to specify arbitrary +dictionary keys (e.g., the strings ``'10'`` or ``':-]'``) within a format string. +The *arg_name* can be followed by any number of index or +attribute expressions. An expression of the form ``'.name'`` selects the named +attribute using :func:`getattr`, while an expression of the form ``'[index]'`` +does an index lookup using :func:`__getitem__`. + +.. versionchanged:: 3.1 + The positional argument specifiers can be omitted for :meth:`str.format`, + so ``'{} {}'.format(a, b)`` is equivalent to ``'{0} {1}'.format(a, b)``. + +.. versionchanged:: 3.4 + The positional argument specifiers can be omitted for :class:`Formatter`. + +Some simple format string examples:: + + "First, thou shalt count to {0}" # References first positional argument + "Bring me a {}" # Implicitly references the first positional argument + "From {} to {}" # Same as "From {0} to {1}" + "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 +as a string, overriding its own definition of formatting. By converting the +value to a string before calling :meth:`__format__`, the normal formatting logic +is bypassed. + +Three conversion flags are currently supported: ``'!s'`` which calls :func:`str` +on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls +:func:`ascii`. + +Some examples:: + + "Harold's a clever {0!s}" # Calls str() on the argument first + "Bring out the holy {name!r}" # Calls repr() on the argument first + "More {!a}" # Calls ascii() on the argument first + +The *format_spec* field contains a specification of how the value should be +presented, including such details as field width, alignment, padding, decimal +precision and so on. Each value type can define its own "formatting +mini-language" or interpretation of the *format_spec*. + +Most built-in types support a common formatting mini-language, which is +described in the next section. + +A *format_spec* field can also include nested replacement fields within it. +These nested replacement fields may contain a field name, conversion flag +and format specification, but deeper nesting is +not allowed. The replacement fields within the +format_spec are substituted before the *format_spec* string is interpreted. +This allows the formatting of a value to be dynamically specified. + +See the :ref:`formatexamples` section for some examples. + + +.. _formatspec: + +Format Specification Mini-Language +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +"Format specifications" are used within replacement fields contained within a +format string to define how individual values are presented (see +:ref:`formatstrings` and :ref:`f-strings`). +They can also be passed directly to the built-in +:func:`format` function. Each formattable type may define how the format +specification is to be interpreted. + +Most built-in types implement the following options for format specifications, +although some of the formatting options are only supported by the numeric types. + +A general convention is that an empty format specification produces +the same result as if you had called :func:`str` on the value. A +non-empty format specification typically modifies the result. + +The general form of a *standard format specifier* is: + +.. productionlist:: sf + format_spec: [[`fill`]`align`][`sign`][#][0][`width`][`grouping_option`][.`precision`][`type`] + fill: + align: "<" | ">" | "=" | "^" + sign: "+" | "-" | " " + width: `digit`+ + grouping_option: "_" | "," + precision: `digit`+ + type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" + +If a valid *align* value is specified, it can be preceded by a *fill* +character that can be any character and defaults to a space if omitted. +It is not possible to use a literal curly brace ("``{``" or "``}``") as +the *fill* character in a :ref:`formatted string literal +` or when using the :meth:`str.format` +method. However, it is possible to insert a curly brace +with a nested replacement field. This limitation doesn't +affect the :func:`format` function. + +The meaning of the various alignment options is as follows: + + .. index:: + single: < (less); in string formatting + single: > (greater); in string formatting + single: = (equals); in string formatting + single: ^ (caret); in string formatting + + +---------+----------------------------------------------------------+ + | Option | Meaning | + +=========+==========================================================+ + | ``'<'`` | Forces the field to be left-aligned within the available | + | | space (this is the default for most objects). | + +---------+----------------------------------------------------------+ + | ``'>'`` | Forces the field to be right-aligned within the | + | | available space (this is the default for numbers). | + +---------+----------------------------------------------------------+ + | ``'='`` | Forces the padding to be placed after the sign (if any) | + | | but before the digits. This is used for printing fields | + | | in the form '+000000120'. This alignment option is only | + | | valid for numeric types. It becomes the default when '0'| + | | immediately precedes the field width. | + +---------+----------------------------------------------------------+ + | ``'^'`` | Forces the field to be centered within the available | + | | space. | + +---------+----------------------------------------------------------+ + +Note that unless a minimum field width is defined, the field width will always +be the same size as the data to fill it, so that the alignment option has no +meaning in this case. + +The *sign* option is only valid for number types, and can be one of the +following: + + .. index:: + single: + (plus); in string formatting + single: - (minus); in string formatting + single: space; in string formatting + + +---------+----------------------------------------------------------+ + | Option | Meaning | + +=========+==========================================================+ + | ``'+'`` | indicates that a sign should be used for both | + | | positive as well as negative numbers. | + +---------+----------------------------------------------------------+ + | ``'-'`` | indicates that a sign should be used only for negative | + | | numbers (this is the default behavior). | + +---------+----------------------------------------------------------+ + | space | indicates that a leading space should be used on | + | | positive numbers, and a minus sign on negative numbers. | + +---------+----------------------------------------------------------+ + + +.. index:: single: # (hash); in string formatting + +The ``'#'`` option causes the "alternate form" to be used for the +conversion. The alternate form is defined differently for different +types. This option is only valid for integer, float, complex and +Decimal types. For integers, when binary, octal, or hexadecimal output +is used, this option adds the prefix respective ``'0b'``, ``'0o'``, or +``'0x'`` to the output value. For floats, complex and Decimal the +alternate form causes the result of the conversion to always contain a +decimal-point character, even if no digits follow it. Normally, a +decimal-point character appears in the result of these conversions +only if a digit follows it. In addition, for ``'g'`` and ``'G'`` +conversions, trailing zeros are not removed from the result. + +.. index:: single: , (comma); in string formatting + +The ``','`` option signals the use of a comma for a thousands separator. +For a locale aware separator, use the ``'n'`` integer presentation type +instead. + +.. versionchanged:: 3.1 + Added the ``','`` option (see also :pep:`378`). + +.. index:: single: _ (underscore); in string formatting + +The ``'_'`` option signals the use of an underscore for a thousands +separator for floating point presentation types and for integer +presentation type ``'d'``. For integer presentation types ``'b'``, +``'o'``, ``'x'``, and ``'X'``, underscores will be inserted every 4 +digits. For other presentation types, specifying this option is an +error. + +.. versionchanged:: 3.6 + Added the ``'_'`` option (see also :pep:`515`). + +*width* is a decimal integer defining the minimum total field width, +including any prefixes, separators, and other formatting characters. +If not specified, then the field width will be determined by the content. + +When no explicit alignment is given, preceding the *width* field by a zero +(``'0'``) character enables +sign-aware zero-padding for numeric types. This is equivalent to a *fill* +character of ``'0'`` with an *alignment* type of ``'='``. + +The *precision* is a decimal number indicating how many digits should be +displayed after the decimal point for a floating point value formatted with +``'f'`` and ``'F'``, or before and after the decimal point for a floating point +value formatted with ``'g'`` or ``'G'``. For non-number types the field +indicates the maximum field size - in other words, how many characters will be +used from the field content. The *precision* is not allowed for integer values. + +Finally, the *type* determines how the data should be presented. + +The available string presentation types are: + + +---------+----------------------------------------------------------+ + | Type | Meaning | + +=========+==========================================================+ + | ``'s'`` | String format. This is the default type for strings and | + | | may be omitted. | + +---------+----------------------------------------------------------+ + | None | The same as ``'s'``. | + +---------+----------------------------------------------------------+ + +The available integer presentation types are: + + +---------+----------------------------------------------------------+ + | Type | Meaning | + +=========+==========================================================+ + | ``'b'`` | Binary format. Outputs the number in base 2. | + +---------+----------------------------------------------------------+ + | ``'c'`` | Character. Converts the integer to the corresponding | + | | unicode character before printing. | + +---------+----------------------------------------------------------+ + | ``'d'`` | Decimal Integer. Outputs the number in base 10. | + +---------+----------------------------------------------------------+ + | ``'o'`` | Octal format. Outputs the number in base 8. | + +---------+----------------------------------------------------------+ + | ``'x'`` | Hex format. Outputs the number in base 16, using | + | | lower-case letters for the digits above 9. | + +---------+----------------------------------------------------------+ + | ``'X'`` | Hex format. Outputs the number in base 16, using | + | | upper-case letters for the digits above 9. | + +---------+----------------------------------------------------------+ + | ``'n'`` | Number. This is the same as ``'d'``, except that it uses | + | | the current locale setting to insert the appropriate | + | | number separator characters. | + +---------+----------------------------------------------------------+ + | None | The same as ``'d'``. | + +---------+----------------------------------------------------------+ + +In addition to the above presentation types, integers can be formatted +with the floating point presentation types listed below (except +``'n'`` and ``None``). When doing so, :func:`float` is used to convert the +integer to a floating point number before formatting. + +The available presentation types for floating point and decimal values are: + + +---------+----------------------------------------------------------+ + | Type | Meaning | + +=========+==========================================================+ + | ``'e'`` | Exponent notation. Prints the number in scientific | + | | notation using the letter 'e' to indicate the exponent. | + | | The default precision is ``6``. | + +---------+----------------------------------------------------------+ + | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an | + | | upper case 'E' as the separator character. | + +---------+----------------------------------------------------------+ + | ``'f'`` | Fixed-point notation. Displays the number as a | + | | fixed-point number. The default precision is ``6``. | + +---------+----------------------------------------------------------+ + | ``'F'`` | Fixed-point notation. Same as ``'f'``, but converts | + | | ``nan`` to ``NAN`` and ``inf`` to ``INF``. | + +---------+----------------------------------------------------------+ + | ``'g'`` | General format. For a given precision ``p >= 1``, | + | | this rounds the number to ``p`` significant digits and | + | | then formats the result in either fixed-point format | + | | or in scientific notation, depending on its magnitude. | + | | | + | | The precise rules are as follows: suppose that the | + | | result formatted with presentation type ``'e'`` and | + | | precision ``p-1`` would have exponent ``exp``. Then, | + | | if ``m <= exp < p``, where ``m`` is -4 for floats and -6 | + | | for :class:`Decimals `, the number is | + | | formatted with presentation type ``'f'`` and precision | + | | ``p-1-exp``. Otherwise, the number is formatted | + | | with presentation type ``'e'`` and precision ``p-1``. | + | | In both cases insignificant trailing zeros are removed | + | | from the significand, and the decimal point is also | + | | removed if there are no remaining digits following it, | + | | unless the ``'#'`` option is used. | + | | | + | | Positive and negative infinity, positive and negative | + | | zero, and nans, are formatted as ``inf``, ``-inf``, | + | | ``0``, ``-0`` and ``nan`` respectively, regardless of | + | | the precision. | + | | | + | | A precision of ``0`` is treated as equivalent to a | + | | precision of ``1``. The default precision is ``6``. | + +---------+----------------------------------------------------------+ + | ``'G'`` | General format. Same as ``'g'`` except switches to | + | | ``'E'`` if the number gets too large. The | + | | representations of infinity and NaN are uppercased, too. | + +---------+----------------------------------------------------------+ + | ``'n'`` | Number. This is the same as ``'g'``, except that it uses | + | | the current locale setting to insert the appropriate | + | | number separator characters. | + +---------+----------------------------------------------------------+ + | ``'%'`` | Percentage. Multiplies the number by 100 and displays | + | | in fixed (``'f'``) format, followed by a percent sign. | + +---------+----------------------------------------------------------+ + | None | Similar to ``'g'``, except that fixed-point notation, | + | | when used, has at least one digit past the decimal point.| + | | The default precision is as high as needed to represent | + | | the particular value. The overall effect is to match the | + | | output of :func:`str` as altered by the other format | + | | modifiers. | + +---------+----------------------------------------------------------+ + + +.. _formatexamples: + +Format examples +^^^^^^^^^^^^^^^ + +This section contains examples of the :meth:`str.format` syntax and +comparison with the old ``%``-formatting. + +In most of the cases the syntax is similar to the old ``%``-formatting, with the +addition of the ``{}`` and with ``:`` used instead of ``%``. +For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``. + +The new format syntax also supports new and different options, shown in the +following examples. + +Accessing arguments by position:: + + >>> '{0}, {1}, {2}'.format('a', 'b', 'c') + 'a, b, c' + >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only + 'a, b, c' + >>> '{2}, {1}, {0}'.format('a', 'b', 'c') + 'c, b, a' + >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence + 'c, b, a' + >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated + 'abracadabra' + +Accessing arguments by name:: + + >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') + 'Coordinates: 37.24N, -115.81W' + >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} + >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) + 'Coordinates: 37.24N, -115.81W' + +Accessing arguments' attributes:: + + >>> c = 3-5j + >>> ('The complex number {0} is formed from the real part {0.real} ' + ... 'and the imaginary part {0.imag}.').format(c) + 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.' + >>> class Point: + ... def __init__(self, x, y): + ... self.x, self.y = x, y + ... def __str__(self): + ... return 'Point({self.x}, {self.y})'.format(self=self) + ... + >>> str(Point(4, 2)) + 'Point(4, 2)' + +Accessing arguments' items:: + + >>> coord = (3, 5) + >>> 'X: {0[0]}; Y: {0[1]}'.format(coord) + 'X: 3; Y: 5' + +Replacing ``%s`` and ``%r``:: + + >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') + "repr() shows quotes: 'test1'; str() doesn't: test2" + +Aligning the text and specifying a width:: + + >>> '{:<30}'.format('left aligned') + 'left aligned ' + >>> '{:>30}'.format('right aligned') + ' right aligned' + >>> '{:^30}'.format('centered') + ' centered ' + >>> '{:*^30}'.format('centered') # use '*' as a fill char + '***********centered***********' + +Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign:: + + >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always + '+3.140000; -3.140000' + >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers + ' 3.140000; -3.140000' + >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}' + '3.140000; -3.140000' + +Replacing ``%x`` and ``%o`` and converting the value to different bases:: + + >>> # format also supports binary numbers + >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42) + 'int: 42; hex: 2a; oct: 52; bin: 101010' + >>> # with 0x, 0o, or 0b as prefix: + >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42) + 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010' + +Using the comma as a thousands separator:: + + >>> '{:,}'.format(1234567890) + '1,234,567,890' + +Expressing a percentage:: + + >>> points = 19 + >>> total = 22 + >>> 'Correct answers: {:.2%}'.format(points/total) + 'Correct answers: 86.36%' + +Using type-specific formatting:: + + >>> import datetime + >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58) + >>> '{:%Y-%m-%d %H:%M:%S}'.format(d) + '2010-07-04 12:15:58' + +Nesting arguments and more complex examples:: + + >>> for align, text in zip('<^>', ['left', 'center', 'right']): + ... '{0:{fill}{align}16}'.format(text, fill=align, align=align) + ... + 'left<<<<<<<<<<<<' + '^^^^^center^^^^^' + '>>>>>>>>>>>right' + >>> + >>> octets = [192, 168, 0, 1] + >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets) + 'C0A80001' + >>> int(_, 16) + 3232235521 + >>> + >>> width = 5 + >>> for num in range(5,12): #doctest: +NORMALIZE_WHITESPACE + ... for base in 'dXob': + ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ') + ... print() + ... + 5 5 5 101 + 6 6 6 110 + 7 7 7 111 + 8 8 10 1000 + 9 9 11 1001 + 10 A 12 1010 + 11 B 13 1011 + + + +.. _template-strings: + +Template strings +---------------- + +Template strings provide simpler string substitutions as described in +:pep:`292`. A primary use case for template strings is for +internationalization (i18n) since in that context, the simpler syntax and +functionality makes it easier to translate than other built-in string +formatting facilities in Python. As an example of a library built on template +strings for i18n, see the +`flufl.i18n `_ package. + +.. index:: single: $ (dollar); in template strings + +Template strings support ``$``-based substitutions, using the following rules: + +* ``$$`` is an escape; it is replaced with a single ``$``. + +* ``$identifier`` names a substitution placeholder matching a mapping key of + ``"identifier"``. By default, ``"identifier"`` is restricted to any + case-insensitive ASCII alphanumeric string (including underscores) that + starts with an underscore or ASCII letter. The first non-identifier + character after the ``$`` character terminates this placeholder + specification. + +* ``${identifier}`` is equivalent to ``$identifier``. It is required when + valid identifier characters follow the placeholder but are not part of the + placeholder, such as ``"${noun}ification"``. + +Any other appearance of ``$`` in the string will result in a :exc:`ValueError` +being raised. + +The :mod:`string` module provides a :class:`Template` class that implements +these rules. The methods of :class:`Template` are: + + +.. class:: Template(template) + + The constructor takes a single argument which is the template string. + + + .. method:: substitute(mapping={}, /, **kwds) + + Performs the template substitution, returning a new string. *mapping* is + any dictionary-like object with keys that match the placeholders in the + template. Alternatively, you can provide keyword arguments, where the + keywords are the placeholders. When both *mapping* and *kwds* are given + and there are duplicates, the placeholders from *kwds* take precedence. + + + .. method:: safe_substitute(mapping={}, /, **kwds) + + Like :meth:`substitute`, except that if placeholders are missing from + *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the + original placeholder will appear in the resulting string intact. Also, + unlike with :meth:`substitute`, any other appearances of the ``$`` will + simply return ``$`` instead of raising :exc:`ValueError`. + + While other exceptions may still occur, this method is called "safe" + because it always tries to return a usable string instead of + raising an exception. In another sense, :meth:`safe_substitute` may be + anything other than safe, since it will silently ignore malformed + templates containing dangling delimiters, unmatched braces, or + placeholders that are not valid Python identifiers. + + :class:`Template` instances also provide one public data attribute: + + .. attribute:: template + + This is the object passed to the constructor's *template* argument. In + general, you shouldn't change it, but read-only access is not enforced. + +Here is an example of how to use a Template:: + + >>> from string import Template + >>> s = Template('$who likes $what') + >>> s.substitute(who='tim', what='kung pao') + 'tim likes kung pao' + >>> d = dict(who='tim') + >>> Template('Give $who $100').substitute(d) + Traceback (most recent call last): + ... + ValueError: Invalid placeholder in string: line 1, col 11 + >>> Template('$who likes $what').substitute(d) + Traceback (most recent call last): + ... + KeyError: 'what' + >>> Template('$who likes $what').safe_substitute(d) + 'tim likes $what' + +Advanced usage: you can derive subclasses of :class:`Template` to customize +the placeholder syntax, delimiter character, or the entire regular expression +used to parse template strings. To do this, you can override these class +attributes: + +* *delimiter* -- This is the literal string describing a placeholder + introducing delimiter. The default value is ``$``. Note that this should + *not* be a regular expression, as the implementation will call + :meth:`re.escape` on this string as needed. Note further that you cannot + change the delimiter after class creation (i.e. a different delimiter must + be set in the subclass's class namespace). + +* *idpattern* -- This is the regular expression describing the pattern for + non-braced placeholders. The default value is the regular expression + ``(?a:[_a-z][_a-z0-9]*)``. If this is given and *braceidpattern* is + ``None`` this pattern will also apply to braced placeholders. + + .. note:: + + Since default *flags* is ``re.IGNORECASE``, pattern ``[a-z]`` can match + with some non-ASCII characters. That's why we use the local ``a`` flag + here. + + .. versionchanged:: 3.7 + *braceidpattern* can be used to define separate patterns used inside and + outside the braces. + +* *braceidpattern* -- This is like *idpattern* but describes the pattern for + braced placeholders. Defaults to ``None`` which means to fall back to + *idpattern* (i.e. the same pattern is used both inside and outside braces). + If given, this allows you to define different patterns for braced and + unbraced placeholders. + + .. versionadded:: 3.7 + +* *flags* -- The regular expression flags that will be applied when compiling + the regular expression used for recognizing substitutions. The default value + is ``re.IGNORECASE``. Note that ``re.VERBOSE`` will always be added to the + flags, so custom *idpattern*\ s must follow conventions for verbose regular + expressions. + + .. versionadded:: 3.2 + +Alternatively, you can provide the entire regular expression pattern by +overriding the class attribute *pattern*. If you do this, the value must be a +regular expression object with four named capturing groups. The capturing +groups correspond to the rules given above, along with the invalid placeholder +rule: + +* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the + default pattern. + +* *named* -- This group matches the unbraced placeholder name; it should not + include the delimiter in capturing group. + +* *braced* -- This group matches the brace enclosed placeholder name; it should + not include either the delimiter or braces in the capturing group. + +* *invalid* -- This group matches any other delimiter pattern (usually a single + delimiter), and it should appear last in the regular expression. + + +Helper functions +---------------- + +.. function:: capwords(s, sep=None) + + Split the argument into words using :meth:`str.split`, capitalize each word + using :meth:`str.capitalize`, and join the capitalized words using + :meth:`str.join`. If the optional second argument *sep* is absent + or ``None``, runs of whitespace characters are replaced by a single space + and leading and trailing whitespace are removed, otherwise *sep* is used to + split and join the words. diff --git a/cpython_2/environment/repo/Doc/library/stringprep.rst b/cpython_2/environment/repo/Doc/library/stringprep.rst new file mode 100644 index 0000000000000000000000000000000000000000..5cfb533d802db438cdf575e7ccd01aa9661acc15 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/stringprep.rst @@ -0,0 +1,143 @@ +:mod:`stringprep` --- Internet String Preparation +================================================= + +.. module:: stringprep + :synopsis: String preparation, as per RFC 3453 + +.. moduleauthor:: Martin v. Löwis +.. sectionauthor:: Martin v. Löwis + +**Source code:** :source:`Lib/stringprep.py` + +-------------- + +When identifying things (such as host names) in the internet, it is often +necessary to compare such identifications for "equality". Exactly how this +comparison is executed may depend on the application domain, e.g. whether it +should be case-insensitive or not. It may be also necessary to restrict the +possible identifications, to allow only identifications consisting of +"printable" characters. + +:rfc:`3454` defines a procedure for "preparing" Unicode strings in internet +protocols. Before passing strings onto the wire, they are processed with the +preparation procedure, after which they have a certain normalized form. The RFC +defines a set of tables, which can be combined into profiles. Each profile must +define which tables it uses, and what other optional parts of the ``stringprep`` +procedure are part of the profile. One example of a ``stringprep`` profile is +``nameprep``, which is used for internationalized domain names. + +The module :mod:`stringprep` only exposes the tables from :rfc:`3454`. As these +tables would be very large to represent them as dictionaries or lists, the +module uses the Unicode character database internally. The module source code +itself was generated using the ``mkstringprep.py`` utility. + +As a result, these tables are exposed as functions, not as data structures. +There are two kinds of tables in the RFC: sets and mappings. For a set, +:mod:`stringprep` provides the "characteristic function", i.e. a function that +returns ``True`` if the parameter is part of the set. For mappings, it provides the +mapping function: given the key, it returns the associated value. Below is a +list of all functions available in the module. + + +.. function:: in_table_a1(code) + + Determine whether *code* is in tableA.1 (Unassigned code points in Unicode 3.2). + + +.. function:: in_table_b1(code) + + Determine whether *code* is in tableB.1 (Commonly mapped to nothing). + + +.. function:: map_table_b2(code) + + Return the mapped value for *code* according to tableB.2 (Mapping for + case-folding used with NFKC). + + +.. function:: map_table_b3(code) + + Return the mapped value for *code* according to tableB.3 (Mapping for + case-folding used with no normalization). + + +.. function:: in_table_c11(code) + + Determine whether *code* is in tableC.1.1 (ASCII space characters). + + +.. function:: in_table_c12(code) + + Determine whether *code* is in tableC.1.2 (Non-ASCII space characters). + + +.. function:: in_table_c11_c12(code) + + Determine whether *code* is in tableC.1 (Space characters, union of C.1.1 and + C.1.2). + + +.. function:: in_table_c21(code) + + Determine whether *code* is in tableC.2.1 (ASCII control characters). + + +.. function:: in_table_c22(code) + + Determine whether *code* is in tableC.2.2 (Non-ASCII control characters). + + +.. function:: in_table_c21_c22(code) + + Determine whether *code* is in tableC.2 (Control characters, union of C.2.1 and + C.2.2). + + +.. function:: in_table_c3(code) + + Determine whether *code* is in tableC.3 (Private use). + + +.. function:: in_table_c4(code) + + Determine whether *code* is in tableC.4 (Non-character code points). + + +.. function:: in_table_c5(code) + + Determine whether *code* is in tableC.5 (Surrogate codes). + + +.. function:: in_table_c6(code) + + Determine whether *code* is in tableC.6 (Inappropriate for plain text). + + +.. function:: in_table_c7(code) + + Determine whether *code* is in tableC.7 (Inappropriate for canonical + representation). + + +.. function:: in_table_c8(code) + + Determine whether *code* is in tableC.8 (Change display properties or are + deprecated). + + +.. function:: in_table_c9(code) + + Determine whether *code* is in tableC.9 (Tagging characters). + + +.. function:: in_table_d1(code) + + Determine whether *code* is in tableD.1 (Characters with bidirectional property + "R" or "AL"). + + +.. function:: in_table_d2(code) + + Determine whether *code* is in tableD.2 (Characters with bidirectional property + "L"). + diff --git a/cpython_2/environment/repo/Doc/library/struct.rst b/cpython_2/environment/repo/Doc/library/struct.rst new file mode 100644 index 0000000000000000000000000000000000000000..856b6da8bb255d541364e6c7f41cd05776a68bd6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/struct.rst @@ -0,0 +1,469 @@ +:mod:`struct` --- Interpret bytes as packed binary data +======================================================= + +.. module:: struct + :synopsis: Interpret bytes as packed binary data. + +**Source code:** :source:`Lib/struct.py` + +.. index:: + pair: C; structures + triple: packing; binary; data + +-------------- + +This module performs conversions between Python values and C structs represented +as Python :class:`bytes` objects. This can be used in handling binary data +stored in files or from network connections, among other sources. It uses +:ref:`struct-format-strings` as compact descriptions of the layout of the C +structs and the intended conversion to/from Python values. + +.. note:: + + By default, the result of packing a given C struct includes pad bytes in + order to maintain proper alignment for the C types involved; similarly, + alignment is taken into account when unpacking. This behavior is chosen so + that the bytes of a packed struct correspond exactly to the layout in memory + of the corresponding C struct. To handle platform-independent data formats + or omit implicit pad bytes, use ``standard`` size and alignment instead of + ``native`` size and alignment: see :ref:`struct-alignment` for details. + +Several :mod:`struct` functions (and methods of :class:`Struct`) take a *buffer* +argument. This refers to objects that implement the :ref:`bufferobjects` and +provide either a readable or read-writable buffer. The most common types used +for that purpose are :class:`bytes` and :class:`bytearray`, but many other types +that can be viewed as an array of bytes implement the buffer protocol, so that +they can be read/filled without additional copying from a :class:`bytes` object. + + +Functions and Exceptions +------------------------ + +The module defines the following exception and functions: + + +.. exception:: error + + Exception raised on various occasions; argument is a string describing what + is wrong. + + +.. function:: pack(format, v1, v2, ...) + + Return a bytes object containing the values *v1*, *v2*, ... packed according + to the format string *format*. The arguments must match the values required by + the format exactly. + + +.. function:: pack_into(format, buffer, offset, v1, v2, ...) + + Pack the values *v1*, *v2*, ... according to the format string *format* and + write the packed bytes into the writable buffer *buffer* starting at + position *offset*. Note that *offset* is a required argument. + + +.. function:: unpack(format, buffer) + + Unpack from the buffer *buffer* (presumably packed by ``pack(format, ...)``) + according to the format string *format*. The result is a tuple even if it + contains exactly one item. The buffer's size in bytes must match the + size required by the format, as reflected by :func:`calcsize`. + + +.. function:: unpack_from(format, /, buffer, offset=0) + + Unpack from *buffer* starting at position *offset*, according to the format + string *format*. The result is a tuple even if it contains exactly one + item. The buffer's size in bytes, starting at position *offset*, must be at + least the size required by the format, as reflected by :func:`calcsize`. + + +.. function:: iter_unpack(format, buffer) + + Iteratively unpack from the buffer *buffer* according to the format + string *format*. This function returns an iterator which will read + equally-sized chunks from the buffer until all its contents have been + consumed. The buffer's size in bytes must be a multiple of the size + required by the format, as reflected by :func:`calcsize`. + + Each iteration yields a tuple as specified by the format string. + + .. versionadded:: 3.4 + + +.. function:: calcsize(format) + + Return the size of the struct (and hence of the bytes object produced by + ``pack(format, ...)``) corresponding to the format string *format*. + + +.. _struct-format-strings: + +Format Strings +-------------- + +Format strings are the mechanism used to specify the expected layout when +packing and unpacking data. They are built up from :ref:`format-characters`, +which specify the type of data being packed/unpacked. In addition, there are +special characters for controlling the :ref:`struct-alignment`. + + +.. _struct-alignment: + +Byte Order, Size, and Alignment +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, C types are represented in the machine's native format and byte +order, and properly aligned by skipping pad bytes if necessary (according to the +rules used by the C compiler). + +.. index:: + single: @ (at); in struct format strings + single: = (equals); in struct format strings + single: < (less); in struct format strings + single: > (greater); in struct format strings + single: ! (exclamation); in struct format strings + +Alternatively, the first character of the format string can be used to indicate +the byte order, size and alignment of the packed data, according to the +following table: + ++-----------+------------------------+----------+-----------+ +| Character | Byte order | Size | Alignment | ++===========+========================+==========+===========+ +| ``@`` | native | native | native | ++-----------+------------------------+----------+-----------+ +| ``=`` | native | standard | none | ++-----------+------------------------+----------+-----------+ +| ``<`` | little-endian | standard | none | ++-----------+------------------------+----------+-----------+ +| ``>`` | big-endian | standard | none | ++-----------+------------------------+----------+-----------+ +| ``!`` | network (= big-endian) | standard | none | ++-----------+------------------------+----------+-----------+ + +If the first character is not one of these, ``'@'`` is assumed. + +Native byte order is big-endian or little-endian, depending on the host +system. For example, Intel x86 and AMD64 (x86-64) are little-endian; +Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature +switchable endianness (bi-endian). Use ``sys.byteorder`` to check the +endianness of your system. + +Native size and alignment are determined using the C compiler's +``sizeof`` expression. This is always combined with native byte order. + +Standard size depends only on the format character; see the table in +the :ref:`format-characters` section. + +Note the difference between ``'@'`` and ``'='``: both use native byte order, but +the size and alignment of the latter is standardized. + +The form ``'!'`` is available for those poor souls who claim they can't remember +whether network byte order is big-endian or little-endian. + +There is no way to indicate non-native byte order (force byte-swapping); use the +appropriate choice of ``'<'`` or ``'>'``. + +Notes: + +(1) Padding is only automatically added between successive structure members. + No padding is added at the beginning or the end of the encoded struct. + +(2) No padding is added when using non-native size and alignment, e.g. + with '<', '>', '=', and '!'. + +(3) To align the end of a structure to the alignment requirement of a + particular type, end the format with the code for that type with a repeat + count of zero. See :ref:`struct-examples`. + + +.. _format-characters: + +Format Characters +^^^^^^^^^^^^^^^^^ + +Format characters have the following meaning; the conversion between C and +Python values should be obvious given their types. The 'Standard size' column +refers to the size of the packed value in bytes when using standard size; that +is, when the format string starts with one of ``'<'``, ``'>'``, ``'!'`` or +``'='``. When using native size, the size of the packed value is +platform-dependent. + ++--------+--------------------------+--------------------+----------------+------------+ +| Format | C Type | Python type | Standard size | Notes | ++========+==========================+====================+================+============+ +| ``x`` | pad byte | no value | | | ++--------+--------------------------+--------------------+----------------+------------+ +| ``c`` | :c:type:`char` | bytes of length 1 | 1 | | ++--------+--------------------------+--------------------+----------------+------------+ +| ``b`` | :c:type:`signed char` | integer | 1 | \(1), \(2) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``B`` | :c:type:`unsigned char` | integer | 1 | \(2) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``?`` | :c:type:`_Bool` | bool | 1 | \(1) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``h`` | :c:type:`short` | integer | 2 | \(2) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``H`` | :c:type:`unsigned short` | integer | 2 | \(2) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``i`` | :c:type:`int` | integer | 4 | \(2) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``I`` | :c:type:`unsigned int` | integer | 4 | \(2) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``l`` | :c:type:`long` | integer | 4 | \(2) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``L`` | :c:type:`unsigned long` | integer | 4 | \(2) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``q`` | :c:type:`long long` | integer | 8 | \(2) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``Q`` | :c:type:`unsigned long | integer | 8 | \(2) | +| | long` | | | | ++--------+--------------------------+--------------------+----------------+------------+ +| ``n`` | :c:type:`ssize_t` | integer | | \(3) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``N`` | :c:type:`size_t` | integer | | \(3) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``e`` | \(6) | float | 2 | \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``f`` | :c:type:`float` | float | 4 | \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``d`` | :c:type:`double` | float | 8 | \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``s`` | :c:type:`char[]` | bytes | | | ++--------+--------------------------+--------------------+----------------+------------+ +| ``p`` | :c:type:`char[]` | bytes | | | ++--------+--------------------------+--------------------+----------------+------------+ +| ``P`` | :c:type:`void \*` | integer | | \(5) | ++--------+--------------------------+--------------------+----------------+------------+ + +.. versionchanged:: 3.3 + Added support for the ``'n'`` and ``'N'`` formats. + +.. versionchanged:: 3.6 + Added support for the ``'e'`` format. + + +Notes: + +(1) + .. index:: single: ? (question mark); in struct format strings + + The ``'?'`` conversion code corresponds to the :c:type:`_Bool` type defined by + C99. If this type is not available, it is simulated using a :c:type:`char`. In + standard mode, it is always represented by one byte. + +(2) + When attempting to pack a non-integer using any of the integer conversion + codes, if the non-integer has a :meth:`__index__` method then that method is + called to convert the argument to an integer before packing. + + .. versionchanged:: 3.2 + Added use of the :meth:`__index__` method for non-integers. + +(3) + The ``'n'`` and ``'N'`` conversion codes are only available for the native + size (selected as the default or with the ``'@'`` byte order character). + For the standard size, you can use whichever of the other integer formats + fits your application. + +(4) + For the ``'f'``, ``'d'`` and ``'e'`` conversion codes, the packed + representation uses the IEEE 754 binary32, binary64 or binary16 format (for + ``'f'``, ``'d'`` or ``'e'`` respectively), regardless of the floating-point + format used by the platform. + +(5) + The ``'P'`` format character is only available for the native byte ordering + (selected as the default or with the ``'@'`` byte order character). The byte + order character ``'='`` chooses to use little- or big-endian ordering based + on the host system. The struct module does not interpret this as native + ordering, so the ``'P'`` format is not available. + +(6) + The IEEE 754 binary16 "half precision" type was introduced in the 2008 + revision of the `IEEE 754 standard `_. It has a sign + bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored), + and can represent numbers between approximately ``6.1e-05`` and ``6.5e+04`` + at full precision. This type is not widely supported by C compilers: on a + typical machine, an unsigned short can be used for storage, but not for math + operations. See the Wikipedia page on the `half-precision floating-point + format `_ for more information. + + +A format character may be preceded by an integral repeat count. For example, +the format string ``'4h'`` means exactly the same as ``'hhhh'``. + +Whitespace characters between formats are ignored; a count and its format must +not contain whitespace though. + +For the ``'s'`` format character, the count is interpreted as the length of the +bytes, not a repeat count like for the other format characters; for example, +``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters. +If a count is not given, it defaults to 1. For packing, the string is +truncated or padded with null bytes as appropriate to make it fit. For +unpacking, the resulting bytes object always has exactly the specified number +of bytes. As a special case, ``'0s'`` means a single, empty string (while +``'0c'`` means 0 characters). + +When packing a value ``x`` using one of the integer formats (``'b'``, +``'B'``, ``'h'``, ``'H'``, ``'i'``, ``'I'``, ``'l'``, ``'L'``, +``'q'``, ``'Q'``), if ``x`` is outside the valid range for that format +then :exc:`struct.error` is raised. + +.. versionchanged:: 3.1 + Previously, some of the integer formats wrapped out-of-range values and + raised :exc:`DeprecationWarning` instead of :exc:`struct.error`. + +The ``'p'`` format character encodes a "Pascal string", meaning a short +variable-length string stored in a *fixed number of bytes*, given by the count. +The first byte stored is the length of the string, or 255, whichever is +smaller. The bytes of the string follow. If the string passed in to +:func:`pack` is too long (longer than the count minus 1), only the leading +``count-1`` bytes of the string are stored. If the string is shorter than +``count-1``, it is padded with null bytes so that exactly count bytes in all +are used. Note that for :func:`unpack`, the ``'p'`` format character consumes +``count`` bytes, but that the string returned can never contain more than 255 +bytes. + +.. index:: single: ? (question mark); in struct format strings + +For the ``'?'`` format character, the return value is either :const:`True` or +:const:`False`. When packing, the truth value of the argument object is used. +Either 0 or 1 in the native or standard bool representation will be packed, and +any non-zero value will be ``True`` when unpacking. + + + +.. _struct-examples: + +Examples +^^^^^^^^ + +.. note:: + All examples assume a native byte order, size, and alignment with a + big-endian machine. + +A basic example of packing/unpacking three integers:: + + >>> from struct import * + >>> pack('hhl', 1, 2, 3) + b'\x00\x01\x00\x02\x00\x00\x00\x03' + >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03') + (1, 2, 3) + >>> calcsize('hhl') + 8 + +Unpacked fields can be named by assigning them to variables or by wrapping +the result in a named tuple:: + + >>> record = b'raymond \x32\x12\x08\x01\x08' + >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record) + + >>> from collections import namedtuple + >>> Student = namedtuple('Student', 'name serialnum school gradelevel') + >>> Student._make(unpack('<10sHHb', record)) + Student(name=b'raymond ', serialnum=4658, school=264, gradelevel=8) + +The ordering of format characters may have an impact on size since the padding +needed to satisfy alignment requirements is different:: + + >>> pack('ci', b'*', 0x12131415) + b'*\x00\x00\x00\x12\x13\x14\x15' + >>> pack('ic', 0x12131415, b'*') + b'\x12\x13\x14\x15*' + >>> calcsize('ci') + 8 + >>> calcsize('ic') + 5 + +The following format ``'llh0l'`` specifies two pad bytes at the end, assuming +longs are aligned on 4-byte boundaries:: + + >>> pack('llh0l', 1, 2, 3) + b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00' + +This only works when native size and alignment are in effect; standard size and +alignment does not enforce any alignment. + + +.. seealso:: + + Module :mod:`array` + Packed binary storage of homogeneous data. + + Module :mod:`xdrlib` + Packing and unpacking of XDR data. + + +.. _struct-objects: + +Classes +------- + +The :mod:`struct` module also defines the following type: + + +.. class:: Struct(format) + + Return a new Struct object which writes and reads binary data according to + the format string *format*. Creating a Struct object once and calling its + methods is more efficient than calling the :mod:`struct` functions with the + same format since the format string only needs to be compiled once. + + .. note:: + + The compiled versions of the most recent format strings passed to + :class:`Struct` and the module-level functions are cached, so programs + that use only a few format strings needn't worry about reusing a single + :class:`Struct` instance. + + Compiled Struct objects support the following methods and attributes: + + .. method:: pack(v1, v2, ...) + + Identical to the :func:`pack` function, using the compiled format. + (``len(result)`` will equal :attr:`size`.) + + + .. method:: pack_into(buffer, offset, v1, v2, ...) + + Identical to the :func:`pack_into` function, using the compiled format. + + + .. method:: unpack(buffer) + + Identical to the :func:`unpack` function, using the compiled format. + The buffer's size in bytes must equal :attr:`size`. + + + .. method:: unpack_from(buffer, offset=0) + + Identical to the :func:`unpack_from` function, using the compiled format. + The buffer's size in bytes, starting at position *offset*, must be at least + :attr:`size`. + + + .. method:: iter_unpack(buffer) + + Identical to the :func:`iter_unpack` function, using the compiled format. + The buffer's size in bytes must be a multiple of :attr:`size`. + + .. versionadded:: 3.4 + + .. attribute:: format + + The format string used to construct this Struct object. + + .. versionchanged:: 3.7 + The format string type is now :class:`str` instead of :class:`bytes`. + + .. attribute:: size + + The calculated size of the struct (and hence of the bytes object produced + by the :meth:`pack` method) corresponding to :attr:`format`. + + +.. _half precision format: https://en.wikipedia.org/wiki/Half-precision_floating-point_format + +.. _ieee 754 standard: https://en.wikipedia.org/wiki/IEEE_floating_point#IEEE_754-2008 diff --git a/cpython_2/environment/repo/Doc/library/subprocess.rst b/cpython_2/environment/repo/Doc/library/subprocess.rst new file mode 100644 index 0000000000000000000000000000000000000000..24497a2edd357712a72c91dde24ef1d1c7eb8fe6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/subprocess.rst @@ -0,0 +1,1487 @@ +:mod:`subprocess` --- Subprocess management +=========================================== + +.. module:: subprocess + :synopsis: Subprocess management. + +.. moduleauthor:: Peter Åstrand +.. sectionauthor:: Peter Åstrand + +**Source code:** :source:`Lib/subprocess.py` + +-------------- + +The :mod:`subprocess` module allows you to spawn new processes, connect to their +input/output/error pipes, and obtain their return codes. This module intends to +replace several older modules and functions:: + + os.system + os.spawn* + +Information about how the :mod:`subprocess` module can be used to replace these +modules and functions can be found in the following sections. + +.. seealso:: + + :pep:`324` -- PEP proposing the subprocess module + + +Using the :mod:`subprocess` Module +---------------------------------- + +The recommended approach to invoking subprocesses is to use the :func:`run` +function for all use cases it can handle. For more advanced use cases, the +underlying :class:`Popen` interface can be used directly. + +The :func:`run` function was added in Python 3.5; if you need to retain +compatibility with older versions, see the :ref:`call-function-trio` section. + + +.. function:: run(args, *, stdin=None, input=None, stdout=None, stderr=None,\ + capture_output=False, shell=False, cwd=None, timeout=None, \ + check=False, encoding=None, errors=None, text=None, env=None, \ + universal_newlines=None) + + Run the command described by *args*. Wait for command to complete, then + return a :class:`CompletedProcess` instance. + + The arguments shown above are merely the most common ones, described below + in :ref:`frequently-used-arguments` (hence the use of keyword-only notation + in the abbreviated signature). The full function signature is largely the + same as that of the :class:`Popen` constructor - most of the arguments to + this function are passed through to that interface. (*timeout*, *input*, + *check*, and *capture_output* are not.) + + If *capture_output* is true, stdout and stderr will be captured. + When used, the internal :class:`Popen` object is automatically created with + ``stdout=PIPE`` and ``stderr=PIPE``. The *stdout* and *stderr* arguments may + not be supplied at the same time as *capture_output*. If you wish to capture + and combine both streams into one, use ``stdout=PIPE`` and ``stderr=STDOUT`` + instead of *capture_output*. + + The *timeout* argument is passed to :meth:`Popen.communicate`. If the timeout + expires, the child process will be killed and waited for. The + :exc:`TimeoutExpired` exception will be re-raised after the child process + has terminated. + + The *input* argument is passed to :meth:`Popen.communicate` and thus to the + subprocess's stdin. If used it must be a byte sequence, or a string if + *encoding* or *errors* is specified or *text* is true. When + used, the internal :class:`Popen` object is automatically created with + ``stdin=PIPE``, and the *stdin* argument may not be used as well. + + If *check* is true, and the process exits with a non-zero exit code, a + :exc:`CalledProcessError` exception will be raised. Attributes of that + exception hold the arguments, the exit code, and stdout and stderr if they + were captured. + + If *encoding* or *errors* are specified, or *text* is true, + file objects for stdin, stdout and stderr are opened in text mode using the + specified *encoding* and *errors* or the :class:`io.TextIOWrapper` default. + The *universal_newlines* argument is equivalent to *text* and is provided + for backwards compatibility. By default, file objects are opened in binary mode. + + If *env* is not ``None``, it must be a mapping that defines the environment + variables for the new process; these are used instead of the default + behavior of inheriting the current process' environment. It is passed directly + to :class:`Popen`. + + Examples:: + + >>> subprocess.run(["ls", "-l"]) # doesn't capture output + CompletedProcess(args=['ls', '-l'], returncode=0) + + >>> subprocess.run("exit 1", shell=True, check=True) + Traceback (most recent call last): + ... + subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 + + >>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True) + CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0, + stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'') + + .. versionadded:: 3.5 + + .. versionchanged:: 3.6 + + Added *encoding* and *errors* parameters + + .. versionchanged:: 3.7 + + Added the *text* parameter, as a more understandable alias of *universal_newlines*. + Added the *capture_output* parameter. + +.. class:: CompletedProcess + + The return value from :func:`run`, representing a process that has finished. + + .. attribute:: args + + The arguments used to launch the process. This may be a list or a string. + + .. attribute:: returncode + + Exit status of the child process. Typically, an exit status of 0 indicates + that it ran successfully. + + A negative value ``-N`` indicates that the child was terminated by signal + ``N`` (POSIX only). + + .. attribute:: stdout + + Captured stdout from the child process. A bytes sequence, or a string if + :func:`run` was called with an encoding, errors, or text=True. + ``None`` if stdout was not captured. + + If you ran the process with ``stderr=subprocess.STDOUT``, stdout and + stderr will be combined in this attribute, and :attr:`stderr` will be + ``None``. + + .. attribute:: stderr + + Captured stderr from the child process. A bytes sequence, or a string if + :func:`run` was called with an encoding, errors, or text=True. + ``None`` if stderr was not captured. + + .. method:: check_returncode() + + If :attr:`returncode` is non-zero, raise a :exc:`CalledProcessError`. + + .. versionadded:: 3.5 + +.. data:: DEVNULL + + Special value that can be used as the *stdin*, *stdout* or *stderr* argument + to :class:`Popen` and indicates that the special file :data:`os.devnull` + will be used. + + .. versionadded:: 3.3 + + +.. data:: PIPE + + Special value that can be used as the *stdin*, *stdout* or *stderr* argument + to :class:`Popen` and indicates that a pipe to the standard stream should be + opened. Most useful with :meth:`Popen.communicate`. + + +.. data:: STDOUT + + 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. + + +.. exception:: SubprocessError + + Base class for all other exceptions from this module. + + .. versionadded:: 3.3 + + +.. exception:: TimeoutExpired + + Subclass of :exc:`SubprocessError`, raised when a timeout expires + while waiting for a child process. + + .. attribute:: cmd + + Command that was used to spawn the child process. + + .. attribute:: timeout + + Timeout in seconds. + + .. attribute:: output + + Output of the child process if it was captured by :func:`run` or + :func:`check_output`. Otherwise, ``None``. + + .. attribute:: stdout + + Alias for output, for symmetry with :attr:`stderr`. + + .. attribute:: stderr + + Stderr output of the child process if it was captured by :func:`run`. + Otherwise, ``None``. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.5 + *stdout* and *stderr* attributes added + +.. exception:: CalledProcessError + + Subclass of :exc:`SubprocessError`, raised when a process run by + :func:`check_call` or :func:`check_output` returns a non-zero exit status. + + .. attribute:: returncode + + Exit status of the child process. If the process exited due to a + signal, this will be the negative signal number. + + .. attribute:: cmd + + Command that was used to spawn the child process. + + .. attribute:: output + + Output of the child process if it was captured by :func:`run` or + :func:`check_output`. Otherwise, ``None``. + + .. attribute:: stdout + + Alias for output, for symmetry with :attr:`stderr`. + + .. attribute:: stderr + + Stderr output of the child process if it was captured by :func:`run`. + Otherwise, ``None``. + + .. versionchanged:: 3.5 + *stdout* and *stderr* attributes added + + +.. _frequently-used-arguments: + +Frequently Used Arguments +^^^^^^^^^^^^^^^^^^^^^^^^^ + +To support a wide variety of use cases, the :class:`Popen` constructor (and +the convenience functions) accept a large number of optional arguments. For +most typical use cases, many of these arguments can be safely left at their +default values. The arguments that are most commonly needed are: + + *args* is required for all calls and should be a string, or a sequence of + program arguments. Providing a sequence of arguments is generally + preferred, as it allows the module to take care of any required escaping + and quoting of arguments (e.g. to permit spaces in file names). If passing + a single string, either *shell* must be :const:`True` (see below) or else + the string must simply name the program to be executed without specifying + any arguments. + + *stdin*, *stdout* and *stderr* specify the executed program's standard input, + standard output and standard error file handles, respectively. Valid values + are :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a positive + integer), an existing file object, and ``None``. :data:`PIPE` indicates + that a new pipe to the child should be created. :data:`DEVNULL` indicates + that the special file :data:`os.devnull` will be used. With the default + settings of ``None``, no redirection will occur; the child's file handles + will be inherited from the parent. Additionally, *stderr* can be + :data:`STDOUT`, which indicates that the stderr data from the child + process should be captured into the same file handle as for *stdout*. + + .. index:: + single: universal newlines; subprocess module + + If *encoding* or *errors* are specified, or *text* (also known as + *universal_newlines*) is true, + the file objects *stdin*, *stdout* and *stderr* will be opened in text + mode using the *encoding* and *errors* specified in the call or the + defaults for :class:`io.TextIOWrapper`. + + For *stdin*, line ending characters ``'\n'`` in the input will be converted + to the default line separator :data:`os.linesep`. For *stdout* and *stderr*, + all line endings in the output will be converted to ``'\n'``. For more + information see the documentation of the :class:`io.TextIOWrapper` class + when the *newline* argument to its constructor is ``None``. + + If text mode is not used, *stdin*, *stdout* and *stderr* will be opened as + binary streams. No encoding or line ending conversion is performed. + + .. versionadded:: 3.6 + Added *encoding* and *errors* parameters. + + .. versionadded:: 3.7 + Added the *text* parameter as an alias for *universal_newlines*. + + .. note:: + + The newlines attribute of the file objects :attr:`Popen.stdin`, + :attr:`Popen.stdout` and :attr:`Popen.stderr` are not updated by + the :meth:`Popen.communicate` method. + + If *shell* is ``True``, the specified command will be executed through + the shell. This can be useful if you are using Python primarily for the + enhanced control flow it offers over most system shells and still want + convenient access to other shell features such as shell pipes, filename + wildcards, environment variable expansion, and expansion of ``~`` to a + user's home directory. However, note that Python itself offers + implementations of many shell-like features (in particular, :mod:`glob`, + :mod:`fnmatch`, :func:`os.walk`, :func:`os.path.expandvars`, + :func:`os.path.expanduser`, and :mod:`shutil`). + + .. versionchanged:: 3.3 + When *universal_newlines* is ``True``, the class uses the encoding + :func:`locale.getpreferredencoding(False) ` + instead of ``locale.getpreferredencoding()``. See the + :class:`io.TextIOWrapper` class for more information on this change. + + .. note:: + + Read the `Security Considerations`_ section before using ``shell=True``. + +These options, along with all of the other options, are described in more +detail in the :class:`Popen` constructor documentation. + + +Popen Constructor +^^^^^^^^^^^^^^^^^ + +The underlying process creation and management in this module is handled by +the :class:`Popen` class. It offers a lot of flexibility so that developers +are able to handle the less common cases not covered by the convenience +functions. + + +.. class:: Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, \ + stderr=None, preexec_fn=None, close_fds=True, shell=False, \ + cwd=None, env=None, universal_newlines=None, \ + startupinfo=None, creationflags=0, restore_signals=True, \ + start_new_session=False, pass_fds=(), \*, group=None, \ + extra_groups=None, user=None, umask=-1, \ + encoding=None, errors=None, text=None) + + Execute a child program in a new process. On POSIX, the class uses + :meth:`os.execvp`-like behavior to execute the child program. On Windows, + the class uses the Windows ``CreateProcess()`` function. The arguments to + :class:`Popen` are as follows. + + *args* should be a sequence of program arguments or else a single string + or :term:`path-like object`. + By default, the program to execute is the first item in *args* if *args* is + a sequence. If *args* is a string, the interpretation is + platform-dependent and described below. See the *shell* and *executable* + arguments for additional differences from the default behavior. Unless + otherwise stated, it is recommended to pass *args* as a sequence. + + An example of passing some arguments to an external program + as a sequence is:: + + Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."]) + + On POSIX, if *args* is a string, the string is interpreted as the name or + path of the program to execute. However, this can only be done if not + passing arguments to the program. + + .. note:: + + It may not be obvious how to break a shell command into a sequence of arguments, + especially in complex cases. :meth:`shlex.split` can illustrate how to + determine the correct tokenization for *args*:: + + >>> import shlex, subprocess + >>> command_line = input() + /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" + >>> args = shlex.split(command_line) + >>> print(args) + ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] + >>> p = subprocess.Popen(args) # Success! + + Note in particular that options (such as *-input*) and arguments (such + as *eggs.txt*) that are separated by whitespace in the shell go in separate + list elements, while arguments that need quoting or backslash escaping when + used in the shell (such as filenames containing spaces or the *echo* command + shown above) are single list elements. + + On Windows, if *args* is a sequence, it will be converted to a string in a + manner described in :ref:`converting-argument-sequence`. This is because + the underlying ``CreateProcess()`` operates on strings. + + .. versionchanged:: 3.6 + *args* parameter accepts a :term:`path-like object` if *shell* is + ``False`` and a sequence containing path-like objects on POSIX. + + .. versionchanged:: 3.8 + *args* parameter accepts a :term:`path-like object` if *shell* is + ``False`` and a sequence containing bytes and path-like objects + on Windows. + + The *shell* argument (which defaults to ``False``) specifies whether to use + the shell as the program to execute. If *shell* is ``True``, it is + recommended to pass *args* as a string rather than as a sequence. + + On POSIX with ``shell=True``, the shell defaults to :file:`/bin/sh`. If + *args* is a string, the string specifies the command + to execute through the shell. This means that the string must be + formatted exactly as it would be when typed at the shell prompt. This + includes, for example, quoting or backslash escaping filenames with spaces in + them. If *args* is a sequence, the first item specifies the command string, and + any additional items will be treated as additional arguments to the shell + itself. That is to say, :class:`Popen` does the equivalent of:: + + Popen(['/bin/sh', '-c', args[0], args[1], ...]) + + On Windows with ``shell=True``, the :envvar:`COMSPEC` environment variable + specifies the default shell. The only time you need to specify + ``shell=True`` on Windows is when the command you wish to execute is built + into the shell (e.g. :command:`dir` or :command:`copy`). You do not need + ``shell=True`` to run a batch file or console-based executable. + + .. note:: + + Read the `Security Considerations`_ section before using ``shell=True``. + + *bufsize* will be supplied as the corresponding argument to the + :func:`open` function when creating the stdin/stdout/stderr pipe + file objects: + + - :const:`0` means unbuffered (read and write are one + system call and can return short) + - :const:`1` means line buffered + (only usable if ``universal_newlines=True`` i.e., in a text mode) + - any other positive value means use a buffer of approximately that + size + - negative bufsize (the default) means the system default of + io.DEFAULT_BUFFER_SIZE will be used. + + .. versionchanged:: 3.3.1 + *bufsize* now defaults to -1 to enable buffering by default to match the + behavior that most code expects. In versions prior to Python 3.2.4 and + 3.3.1 it incorrectly defaulted to :const:`0` which was unbuffered + and allowed short reads. This was unintentional and did not match the + behavior of Python 2 as most code expected. + + The *executable* argument specifies a replacement program to execute. It + is very seldom needed. When ``shell=False``, *executable* replaces the + program to execute specified by *args*. However, the original *args* is + still passed to the program. Most programs treat the program specified + by *args* as the command name, which can then be different from the program + actually executed. On POSIX, the *args* name + becomes the display name for the executable in utilities such as + :program:`ps`. If ``shell=True``, on POSIX the *executable* argument + specifies a replacement shell for the default :file:`/bin/sh`. + + .. versionchanged:: 3.6 + *executable* parameter accepts a :term:`path-like object` on POSIX. + + .. versionchanged:: 3.8 + *executable* parameter accepts a bytes and :term:`path-like object` + on Windows. + + *stdin*, *stdout* and *stderr* specify the executed program's standard input, + standard output and standard error file handles, respectively. Valid values + are :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a positive + integer), an existing :term:`file object`, and ``None``. :data:`PIPE` + indicates that a new pipe to the child should be created. :data:`DEVNULL` + indicates that the special file :data:`os.devnull` will be used. With the + default settings of ``None``, no redirection will occur; the child's file + handles will be inherited from the parent. Additionally, *stderr* can be + :data:`STDOUT`, which indicates that the stderr data from the applications + should be captured into the same file handle as for stdout. + + If *preexec_fn* is set to a callable object, this object will be called in the + child process just before the child is executed. + (POSIX only) + + .. warning:: + + The *preexec_fn* parameter is not safe to use in the presence of threads + in your application. The child process could deadlock before exec is + called. + If you must use it, keep it trivial! Minimize the number of libraries + you call into. + + .. note:: + + If you need to modify the environment for the child use the *env* + parameter rather than doing it in a *preexec_fn*. + The *start_new_session* parameter can take the place of a previously + common use of *preexec_fn* to call os.setsid() in the child. + + .. versionchanged:: 3.8 + + The *preexec_fn* parameter is no longer supported in subinterpreters. + The use of the parameter in a subinterpreter raises + :exc:`RuntimeError`. The new restriction may affect applications that + are deployed in mod_wsgi, uWSGI, and other embedded environments. + + If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and + :const:`2` will be closed before the child process is executed. Otherwise + when *close_fds* is false, file descriptors obey their inheritable flag + as described in :ref:`fd_inheritance`. + + On Windows, if *close_fds* is true then no handles will be inherited by the + child process unless explicitly passed in the ``handle_list`` element of + :attr:`STARTUPINFO.lpAttributeList`, or by standard handle redirection. + + .. versionchanged:: 3.2 + The default for *close_fds* was changed from :const:`False` to + what is described above. + + .. versionchanged:: 3.7 + On Windows the default for *close_fds* was changed from :const:`False` to + :const:`True` when redirecting the standard handles. It's now possible to + set *close_fds* to :const:`True` when redirecting the standard handles. + + *pass_fds* is an optional sequence of file descriptors to keep open + between the parent and child. Providing any *pass_fds* forces + *close_fds* to be :const:`True`. (POSIX only) + + .. versionchanged:: 3.2 + The *pass_fds* parameter was added. + + If *cwd* is not ``None``, the function changes the working directory to + *cwd* before executing the child. *cwd* can be a string, bytes or + :term:`path-like ` object. In particular, the function + looks for *executable* (or for the first item in *args*) relative to *cwd* + if the executable path is a relative path. + + .. versionchanged:: 3.6 + *cwd* parameter accepts a :term:`path-like object` on POSIX. + + .. versionchanged:: 3.7 + *cwd* parameter accepts a :term:`path-like object` on Windows. + + .. versionchanged:: 3.8 + *cwd* parameter accepts a bytes object on Windows. + + If *restore_signals* is true (the default) all signals that Python has set to + SIG_IGN are restored to SIG_DFL in the child process before the exec. + Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. + (POSIX only) + + .. versionchanged:: 3.2 + *restore_signals* was added. + + If *start_new_session* is true the setsid() system call will be made in the + child process prior to the execution of the subprocess. (POSIX only) + + .. versionchanged:: 3.2 + *start_new_session* was added. + + If *group* is not ``None``, the setregid() system call will be made in the + child process prior to the execution of the subprocess. If the provided + value is a string, it will be looked up via :func:`grp.getgrnam()` and + the value in ``gr_gid`` will be used. If the value is an integer, it + will be passed verbatim. (POSIX only) + + .. availability:: POSIX + .. versionadded:: 3.9 + + If *extra_groups* is not ``None``, the setgroups() system call will be + made in the child process prior to the execution of the subprocess. + Strings provided in *extra_groups* will be looked up via + :func:`grp.getgrnam()` and the values in ``gr_gid`` will be used. + Integer values will be passed verbatim. (POSIX only) + + .. availability:: POSIX + .. versionadded:: 3.9 + + If *user* is not ``None``, the setreuid() system call will be made in the + child process prior to the execution of the subprocess. If the provided + value is a string, it will be looked up via :func:`pwd.getpwnam()` and + the value in ``pw_uid`` will be used. If the value is an integer, it will + be passed verbatim. (POSIX only) + + .. availability:: POSIX + .. versionadded:: 3.9 + + If *umask* is not negative, the umask() system call will be made in the + child process prior to the execution of the subprocess. + + .. availability:: POSIX + .. versionadded:: 3.9 + + If *env* is not ``None``, it must be a mapping that defines the environment + variables for the new process; these are used instead of the default + behavior of inheriting the current process' environment. + + .. note:: + + If specified, *env* must provide any variables required for the program to + execute. On Windows, in order to run a `side-by-side assembly`_ the + specified *env* **must** include a valid :envvar:`SystemRoot`. + + .. _side-by-side assembly: https://en.wikipedia.org/wiki/Side-by-Side_Assembly + + If *encoding* or *errors* are specified, or *text* is true, the file objects + *stdin*, *stdout* and *stderr* are opened in text mode with the specified + encoding and *errors*, as described above in :ref:`frequently-used-arguments`. + The *universal_newlines* argument is equivalent to *text* and is provided + for backwards compatibility. By default, file objects are opened in binary mode. + + .. versionadded:: 3.6 + *encoding* and *errors* were added. + + .. versionadded:: 3.7 + *text* was added as a more readable alias for *universal_newlines*. + + If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is + passed to the underlying ``CreateProcess`` function. + *creationflags*, if given, can be one or more of the following flags: + + * :data:`CREATE_NEW_CONSOLE` + * :data:`CREATE_NEW_PROCESS_GROUP` + * :data:`ABOVE_NORMAL_PRIORITY_CLASS` + * :data:`BELOW_NORMAL_PRIORITY_CLASS` + * :data:`HIGH_PRIORITY_CLASS` + * :data:`IDLE_PRIORITY_CLASS` + * :data:`NORMAL_PRIORITY_CLASS` + * :data:`REALTIME_PRIORITY_CLASS` + * :data:`CREATE_NO_WINDOW` + * :data:`DETACHED_PROCESS` + * :data:`CREATE_DEFAULT_ERROR_MODE` + * :data:`CREATE_BREAKAWAY_FROM_JOB` + + Popen objects are supported as context managers via the :keyword:`with` statement: + on exit, standard file descriptors are closed, and the process is waited for. + :: + + with Popen(["ifconfig"], stdout=PIPE) as proc: + log.write(proc.stdout.read()) + + .. audit-event:: subprocess.Popen executable,args,cwd,env subprocess.Popen + + Popen and the other functions in this module that use it raise an + :ref:`auditing event ` ``subprocess.Popen`` with arguments + ``executable``, ``args``, ``cwd``, and ``env``. The value for ``args`` + may be a single string or a list of strings, depending on platform. + + .. versionchanged:: 3.2 + Added context manager support. + + .. versionchanged:: 3.6 + Popen destructor now emits a :exc:`ResourceWarning` warning if the child + process is still running. + + .. versionchanged:: 3.8 + Popen can use :func:`os.posix_spawn` in some cases for better + performance. On Windows Subsystem for Linux and QEMU User Emulation, + Popen constructor using :func:`os.posix_spawn` no longer raise an + exception on errors like missing program, but the child process fails + with a non-zero :attr:`~Popen.returncode`. + + +Exceptions +^^^^^^^^^^ + +Exceptions raised in the child process, before the new program has started to +execute, will be re-raised in the parent. + +The most common exception raised is :exc:`OSError`. This occurs, for example, +when trying to execute a non-existent file. Applications should prepare for +:exc:`OSError` exceptions. + +A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid +arguments. + +:func:`check_call` and :func:`check_output` will raise +:exc:`CalledProcessError` if the called process returns a non-zero return +code. + +All of the functions and methods that accept a *timeout* parameter, such as +:func:`call` and :meth:`Popen.communicate` will raise :exc:`TimeoutExpired` if +the timeout expires before the process exits. + +Exceptions defined in this module all inherit from :exc:`SubprocessError`. + + .. versionadded:: 3.3 + The :exc:`SubprocessError` base class was added. + + +Security Considerations +----------------------- + +Unlike some other popen functions, this implementation will never +implicitly call a system shell. This means that all characters, +including shell metacharacters, can safely be passed to child processes. +If the shell is invoked explicitly, via ``shell=True``, it is the application's +responsibility to ensure that all whitespace and metacharacters are +quoted appropriately to avoid +`shell injection `_ +vulnerabilities. + +When using ``shell=True``, the :func:`shlex.quote` function can be +used to properly escape whitespace and shell metacharacters in strings +that are going to be used to construct shell commands. + + +Popen Objects +------------- + +Instances of the :class:`Popen` class have the following methods: + + +.. method:: Popen.poll() + + Check if child process has terminated. Set and return + :attr:`~Popen.returncode` attribute. Otherwise, returns ``None``. + + +.. method:: Popen.wait(timeout=None) + + Wait for child process to terminate. Set and return + :attr:`~Popen.returncode` attribute. + + If the process does not terminate after *timeout* seconds, raise a + :exc:`TimeoutExpired` exception. It is safe to catch this exception and + retry the wait. + + .. note:: + + This will deadlock when using ``stdout=PIPE`` or ``stderr=PIPE`` + and the child process generates enough output to a pipe such that + it blocks waiting for the OS pipe buffer to accept more data. + Use :meth:`Popen.communicate` when using pipes to avoid that. + + .. note:: + + The function is implemented using a busy loop (non-blocking call and + short sleeps). Use the :mod:`asyncio` module for an asynchronous wait: + see :class:`asyncio.create_subprocess_exec`. + + .. versionchanged:: 3.3 + *timeout* was added. + +.. method:: Popen.communicate(input=None, timeout=None) + + Interact with process: Send data to stdin. Read data from stdout and stderr, + until end-of-file is reached. Wait for process to terminate. The optional + *input* argument should be data to be sent to the child process, or + ``None``, if no data should be sent to the child. If streams were opened in + text mode, *input* must be a string. Otherwise, it must be bytes. + + :meth:`communicate` returns a tuple ``(stdout_data, stderr_data)``. + The data will be strings if streams were opened in text mode; otherwise, + bytes. + + Note that if you want to send data to the process's stdin, you need to create + the Popen object with ``stdin=PIPE``. Similarly, to get anything other than + ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or + ``stderr=PIPE`` too. + + If the process does not terminate after *timeout* seconds, a + :exc:`TimeoutExpired` exception will be raised. Catching this exception and + retrying communication will not lose any output. + + The child process is not killed if the timeout expires, so in order to + cleanup properly a well-behaved application should kill the child process and + finish communication:: + + proc = subprocess.Popen(...) + try: + outs, errs = proc.communicate(timeout=15) + except TimeoutExpired: + proc.kill() + outs, errs = proc.communicate() + + .. note:: + + The data read is buffered in memory, so do not use this method if the data + size is large or unlimited. + + .. versionchanged:: 3.3 + *timeout* was added. + + +.. method:: Popen.send_signal(signal) + + Sends the signal *signal* to the child. + + Do nothing if the process completed. + + .. note:: + + On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and + CTRL_BREAK_EVENT can be sent to processes started with a *creationflags* + parameter which includes `CREATE_NEW_PROCESS_GROUP`. + + +.. method:: Popen.terminate() + + Stop the child. On Posix OSs the method sends SIGTERM to the + child. On Windows the Win32 API function :c:func:`TerminateProcess` is called + to stop the child. + + +.. method:: Popen.kill() + + Kills the child. On Posix OSs the function sends SIGKILL to the child. + On Windows :meth:`kill` is an alias for :meth:`terminate`. + + +The following attributes are also available: + +.. attribute:: Popen.args + + The *args* argument as it was passed to :class:`Popen` -- a + sequence of program arguments or else a single string. + + .. versionadded:: 3.3 + +.. attribute:: Popen.stdin + + If the *stdin* argument was :data:`PIPE`, this attribute is a writeable + stream object as returned by :func:`open`. If the *encoding* or *errors* + arguments were specified or the *universal_newlines* argument was ``True``, + the stream is a text stream, otherwise it is a byte stream. If the *stdin* + argument was not :data:`PIPE`, this attribute is ``None``. + + +.. attribute:: Popen.stdout + + If the *stdout* argument was :data:`PIPE`, this attribute is a readable + stream object as returned by :func:`open`. Reading from the stream provides + output from the child process. If the *encoding* or *errors* arguments were + specified or the *universal_newlines* argument was ``True``, the stream is a + text stream, otherwise it is a byte stream. If the *stdout* argument was not + :data:`PIPE`, this attribute is ``None``. + + +.. attribute:: Popen.stderr + + If the *stderr* argument was :data:`PIPE`, this attribute is a readable + stream object as returned by :func:`open`. Reading from the stream provides + error output from the child process. If the *encoding* or *errors* arguments + were specified or the *universal_newlines* argument was ``True``, the stream + is a text stream, otherwise it is a byte stream. If the *stderr* argument was + not :data:`PIPE`, this attribute is ``None``. + +.. warning:: + + Use :meth:`~Popen.communicate` rather than :attr:`.stdin.write `, + :attr:`.stdout.read ` or :attr:`.stderr.read ` to avoid + deadlocks due to any of the other OS pipe buffers filling up and blocking the + child process. + + +.. attribute:: Popen.pid + + The process ID of the child process. + + Note that if you set the *shell* argument to ``True``, this is the process ID + of the spawned shell. + + +.. attribute:: Popen.returncode + + 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`` (POSIX only). + + +Windows Popen Helpers +--------------------- + +The :class:`STARTUPINFO` class and following constants are only available +on Windows. + +.. class:: STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, \ + hStdError=None, wShowWindow=0, lpAttributeList=None) + + Partial support of the Windows + `STARTUPINFO `__ + structure is used for :class:`Popen` creation. The following attributes can + be set by passing them as keyword-only arguments. + + .. versionchanged:: 3.7 + Keyword-only argument support was added. + + .. attribute:: dwFlags + + A bit field that determines whether certain :class:`STARTUPINFO` + attributes are used when the process creates a window. :: + + si = subprocess.STARTUPINFO() + si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW + + .. attribute:: hStdInput + + If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute + is the standard input handle for the process. If + :data:`STARTF_USESTDHANDLES` is not specified, the default for standard + input is the keyboard buffer. + + .. attribute:: hStdOutput + + If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute + is the standard output handle for the process. Otherwise, this attribute + is ignored and the default for standard output is the console window's + buffer. + + .. attribute:: hStdError + + If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute + is the standard error handle for the process. Otherwise, this attribute is + ignored and the default for standard error is the console window's buffer. + + .. attribute:: wShowWindow + + If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute + can be any of the values that can be specified in the ``nCmdShow`` + parameter for the + `ShowWindow `__ + function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is + ignored. + + :data:`SW_HIDE` is provided for this attribute. It is used when + :class:`Popen` is called with ``shell=True``. + + .. attribute:: lpAttributeList + + A dictionary of additional attributes for process creation as given in + ``STARTUPINFOEX``, see + `UpdateProcThreadAttribute `__. + + Supported attributes: + + **handle_list** + Sequence of handles that will be inherited. *close_fds* must be true if + non-empty. + + The handles must be temporarily made inheritable by + :func:`os.set_handle_inheritable` when passed to the :class:`Popen` + constructor, else :class:`OSError` will be raised with Windows error + ``ERROR_INVALID_PARAMETER`` (87). + + .. warning:: + + In a multithreaded process, use caution to avoid leaking handles + that are marked inheritable when combining this feature with + concurrent calls to other process creation functions that inherit + all handles such as :func:`os.system`. This also applies to + standard handle redirection, which temporarily creates inheritable + handles. + + .. versionadded:: 3.7 + +Windows Constants +^^^^^^^^^^^^^^^^^ + +The :mod:`subprocess` module exposes the following constants. + +.. data:: STD_INPUT_HANDLE + + The standard input device. Initially, this is the console input buffer, + ``CONIN$``. + +.. data:: STD_OUTPUT_HANDLE + + The standard output device. Initially, this is the active console screen + buffer, ``CONOUT$``. + +.. data:: STD_ERROR_HANDLE + + The standard error device. Initially, this is the active console screen + buffer, ``CONOUT$``. + +.. data:: SW_HIDE + + Hides the window. Another window will be activated. + +.. data:: STARTF_USESTDHANDLES + + Specifies that the :attr:`STARTUPINFO.hStdInput`, + :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes + contain additional information. + +.. data:: STARTF_USESHOWWINDOW + + Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains + additional information. + +.. data:: CREATE_NEW_CONSOLE + + The new process has a new console, instead of inheriting its parent's + console (the default). + +.. data:: CREATE_NEW_PROCESS_GROUP + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + group will be created. This flag is necessary for using :func:`os.kill` + on the subprocess. + + This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified. + +.. data:: ABOVE_NORMAL_PRIORITY_CLASS + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + will have an above average priority. + + .. versionadded:: 3.7 + +.. data:: BELOW_NORMAL_PRIORITY_CLASS + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + will have a below average priority. + + .. versionadded:: 3.7 + +.. data:: HIGH_PRIORITY_CLASS + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + will have a high priority. + + .. versionadded:: 3.7 + +.. data:: IDLE_PRIORITY_CLASS + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + will have an idle (lowest) priority. + + .. versionadded:: 3.7 + +.. data:: NORMAL_PRIORITY_CLASS + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + will have an normal priority. (default) + + .. versionadded:: 3.7 + +.. data:: REALTIME_PRIORITY_CLASS + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + will have realtime priority. + You should almost never use REALTIME_PRIORITY_CLASS, because this interrupts + system threads that manage mouse input, keyboard input, and background disk + flushing. This class can be appropriate for applications that "talk" directly + to hardware or that perform brief tasks that should have limited interruptions. + + .. versionadded:: 3.7 + +.. data:: CREATE_NO_WINDOW + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + will not create a window. + + .. versionadded:: 3.7 + +.. data:: DETACHED_PROCESS + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + will not inherit its parent's console. + This value cannot be used with CREATE_NEW_CONSOLE. + + .. versionadded:: 3.7 + +.. data:: CREATE_DEFAULT_ERROR_MODE + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + does not inherit the error mode of the calling process. Instead, the new + process gets the default error mode. + This feature is particularly useful for multithreaded shell applications + that run with hard errors disabled. + + .. versionadded:: 3.7 + +.. data:: CREATE_BREAKAWAY_FROM_JOB + + A :class:`Popen` ``creationflags`` parameter to specify that a new process + is not associated with the job. + + .. versionadded:: 3.7 + +.. _call-function-trio: + +Older high-level API +-------------------- + +Prior to Python 3.5, these three functions comprised the high level API to +subprocess. You can now use :func:`run` in many cases, but lots of existing code +calls these functions. + +.. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None) + + Run the command described by *args*. Wait for command to complete, then + return the :attr:`~Popen.returncode` attribute. + + Code needing to capture stdout or stderr should use :func:`run` instead:: + + run(...).returncode + + To suppress stdout or stderr, supply a value of :data:`DEVNULL`. + + The arguments shown above are merely some common ones. + The full function signature is the + same as that of the :class:`Popen` constructor - this function passes all + supplied arguments other than *timeout* directly through to that interface. + + .. note:: + + Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this + function. The child process will block if it generates enough + output to a pipe to fill up the OS pipe buffer as the pipes are + not being read from. + + .. versionchanged:: 3.3 + *timeout* was added. + +.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None) + + Run command with arguments. Wait for command to complete. If the return + code was zero then return, otherwise raise :exc:`CalledProcessError`. The + :exc:`CalledProcessError` object will have the return code in the + :attr:`~CalledProcessError.returncode` attribute. + + Code needing to capture stdout or stderr should use :func:`run` instead:: + + run(..., check=True) + + To suppress stdout or stderr, supply a value of :data:`DEVNULL`. + + The arguments shown above are merely some common ones. + The full function signature is the + same as that of the :class:`Popen` constructor - this function passes all + supplied arguments other than *timeout* directly through to that interface. + + .. note:: + + Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this + function. The child process will block if it generates enough + output to a pipe to fill up the OS pipe buffer as the pipes are + not being read from. + + .. versionchanged:: 3.3 + *timeout* was added. + + +.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, \ + cwd=None, encoding=None, errors=None, \ + universal_newlines=None, timeout=None, text=None) + + Run command with arguments and return its output. + + If the return code was non-zero it raises a :exc:`CalledProcessError`. The + :exc:`CalledProcessError` object will have the return code in the + :attr:`~CalledProcessError.returncode` attribute and any output in the + :attr:`~CalledProcessError.output` attribute. + + This is equivalent to:: + + run(..., check=True, stdout=PIPE).stdout + + The arguments shown above are merely some common ones. + The full function signature is largely the same as that of :func:`run` - + most arguments are passed directly through to that interface. + However, explicitly passing ``input=None`` to inherit the parent's + standard input file handle is not supported. + + By default, this function will return the data as encoded bytes. The actual + encoding of the output data may depend on the command being invoked, so the + decoding to text will often need to be handled at the application level. + + This behaviour may be overridden by setting *text*, *encoding*, *errors*, + or *universal_newlines* to ``True`` as described in + :ref:`frequently-used-arguments` and :func:`run`. + + To also capture standard error in the result, use + ``stderr=subprocess.STDOUT``:: + + >>> subprocess.check_output( + ... "ls non_existent_file; exit 0", + ... stderr=subprocess.STDOUT, + ... shell=True) + 'ls: non_existent_file: No such file or directory\n' + + .. versionadded:: 3.1 + + .. versionchanged:: 3.3 + *timeout* was added. + + .. versionchanged:: 3.4 + Support for the *input* keyword argument was added. + + .. versionchanged:: 3.6 + *encoding* and *errors* were added. See :func:`run` for details. + + .. versionadded:: 3.7 + *text* was added as a more readable alias for *universal_newlines*. + + +.. _subprocess-replacements: + +Replacing Older Functions with the :mod:`subprocess` Module +----------------------------------------------------------- + +In this section, "a becomes b" means that b can be used as a replacement for a. + +.. note:: + + All "a" functions in this section fail (more or less) silently if the + executed program cannot be found; the "b" replacements raise :exc:`OSError` + instead. + + In addition, the replacements using :func:`check_output` will fail with a + :exc:`CalledProcessError` if the requested operation produces a non-zero + return code. The output is still available as the + :attr:`~CalledProcessError.output` attribute of the raised exception. + +In the following examples, we assume that the relevant functions have already +been imported from the :mod:`subprocess` module. + + +Replacing :program:`/bin/sh` shell command substitution +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: bash + + output=$(mycmd myarg) + +becomes:: + + output = check_output(["mycmd", "myarg"]) + +Replacing shell pipeline +^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: bash + + output=$(dmesg | grep hda) + +becomes:: + + p1 = Popen(["dmesg"], stdout=PIPE) + p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) + p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. + output = p2.communicate()[0] + +The ``p1.stdout.close()`` call after starting the p2 is important in order for +p1 to receive a SIGPIPE if p2 exits before p1. + +Alternatively, for trusted input, the shell's own pipeline support may still +be used directly: + +.. code-block:: bash + + output=$(dmesg | grep hda) + +becomes:: + + output=check_output("dmesg | grep hda", shell=True) + + +Replacing :func:`os.system` +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + sts = os.system("mycmd" + " myarg") + # becomes + sts = call("mycmd" + " myarg", shell=True) + +Notes: + +* Calling the program through the shell is usually not required. + +A more realistic example would look like this:: + + try: + retcode = call("mycmd" + " myarg", shell=True) + if retcode < 0: + print("Child was terminated by signal", -retcode, file=sys.stderr) + else: + print("Child returned", retcode, file=sys.stderr) + except OSError as e: + print("Execution failed:", e, file=sys.stderr) + + +Replacing the :func:`os.spawn ` family +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +P_NOWAIT example:: + + pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") + ==> + pid = Popen(["/bin/mycmd", "myarg"]).pid + +P_WAIT example:: + + retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") + ==> + retcode = call(["/bin/mycmd", "myarg"]) + +Vector example:: + + os.spawnvp(os.P_NOWAIT, path, args) + ==> + Popen([path] + args[1:]) + +Environment example:: + + os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) + ==> + Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) + + + +Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) + ==> + p = Popen(cmd, shell=True, bufsize=bufsize, + stdin=PIPE, stdout=PIPE, close_fds=True) + (child_stdin, child_stdout) = (p.stdin, p.stdout) + +:: + + (child_stdin, + child_stdout, + child_stderr) = os.popen3(cmd, mode, bufsize) + ==> + p = Popen(cmd, shell=True, bufsize=bufsize, + stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) + (child_stdin, + child_stdout, + child_stderr) = (p.stdin, p.stdout, p.stderr) + +:: + + (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) + ==> + p = Popen(cmd, shell=True, bufsize=bufsize, + stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) + (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) + +Return code handling translates as follows:: + + pipe = os.popen(cmd, 'w') + ... + rc = pipe.close() + if rc is not None and rc >> 8: + print("There were some errors") + ==> + process = Popen(cmd, stdin=PIPE) + ... + process.stdin.close() + if process.wait() != 0: + print("There were some errors") + + +Replacing functions from the :mod:`popen2` module +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. note:: + + If the cmd argument to popen2 functions is a string, the command is executed + through /bin/sh. If it is a list, the command is directly executed. + +:: + + (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) + ==> + p = Popen("somestring", shell=True, bufsize=bufsize, + stdin=PIPE, stdout=PIPE, close_fds=True) + (child_stdout, child_stdin) = (p.stdout, p.stdin) + +:: + + (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) + ==> + p = Popen(["mycmd", "myarg"], bufsize=bufsize, + stdin=PIPE, stdout=PIPE, close_fds=True) + (child_stdout, child_stdin) = (p.stdout, p.stdin) + +:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as +:class:`subprocess.Popen`, except that: + +* :class:`Popen` raises an exception if the execution fails. + +* The *capturestderr* argument is replaced with the *stderr* argument. + +* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified. + +* popen2 closes all file descriptors by default, but you have to specify + ``close_fds=True`` with :class:`Popen` to guarantee this behavior on + all platforms or past Python versions. + + +Legacy Shell Invocation Functions +--------------------------------- + +This module also provides the following legacy functions from the 2.x +``commands`` module. These operations implicitly invoke the system shell and +none of the guarantees described above regarding security and exception +handling consistency are valid for these functions. + +.. function:: getstatusoutput(cmd) + + Return ``(exitcode, output)`` of executing *cmd* in a shell. + + Execute the string *cmd* in a shell with :meth:`Popen.check_output` and + return a 2-tuple ``(exitcode, output)``. The locale encoding is used; + see the notes on :ref:`frequently-used-arguments` for more details. + + A trailing newline is stripped from the output. + The exit code for the command can be interpreted as the return code + of subprocess. Example:: + + >>> subprocess.getstatusoutput('ls /bin/ls') + (0, '/bin/ls') + >>> subprocess.getstatusoutput('cat /bin/junk') + (1, 'cat: /bin/junk: No such file or directory') + >>> subprocess.getstatusoutput('/bin/junk') + (127, 'sh: /bin/junk: not found') + >>> subprocess.getstatusoutput('/bin/kill $$') + (-15, '') + + .. availability:: POSIX & Windows. + + .. versionchanged:: 3.3.4 + Windows support was added. + + The function now returns (exitcode, output) instead of (status, output) + as it did in Python 3.3.3 and earlier. exitcode has the same value as + :attr:`~Popen.returncode`. + + +.. function:: getoutput(cmd) + + Return output (stdout and stderr) of executing *cmd* in a shell. + + Like :func:`getstatusoutput`, except the exit code is ignored and the return + value is a string containing the command's output. Example:: + + >>> subprocess.getoutput('ls /bin/ls') + '/bin/ls' + + .. availability:: POSIX & Windows. + + .. versionchanged:: 3.3.4 + Windows support added + + +Notes +----- + +.. _converting-argument-sequence: + +Converting an argument sequence to a string on Windows +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +On Windows, an *args* sequence is converted to a string that can be parsed +using the following rules (which correspond to the rules used by the MS C +runtime): + +1. Arguments are delimited by white space, which is either a + space or a tab. + +2. A string surrounded by double quotation marks is + interpreted as a single argument, regardless of white space + contained within. A quoted string can be embedded in an + argument. + +3. A double quotation mark preceded by a backslash is + interpreted as a literal double quotation mark. + +4. Backslashes are interpreted literally, unless they + immediately precede a double quotation mark. + +5. If backslashes immediately precede a double quotation mark, + every pair of backslashes is interpreted as a literal + backslash. If the number of backslashes is odd, the last + backslash escapes the next double quotation mark as + described in rule 3. + + +.. seealso:: + + :mod:`shlex` + Module which provides function to parse and escape command lines. diff --git a/cpython_2/environment/repo/Doc/library/sunau.rst b/cpython_2/environment/repo/Doc/library/sunau.rst new file mode 100644 index 0000000000000000000000000000000000000000..aad6f93b6bff18ebc2f431481fd4d7631ccbbbe1 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/sunau.rst @@ -0,0 +1,269 @@ +:mod:`sunau` --- Read and write Sun AU files +============================================ + +.. module:: sunau + :synopsis: Provide an interface to the Sun AU sound format. + +.. sectionauthor:: Moshe Zadka + +**Source code:** :source:`Lib/sunau.py` + +-------------- + +The :mod:`sunau` module provides a convenient interface to the Sun AU sound +format. Note that this module is interface-compatible with the modules +:mod:`aifc` and :mod:`wave`. + +An audio file consists of a header followed by the data. The fields of the +header are: + ++---------------+-----------------------------------------------+ +| Field | Contents | ++===============+===============================================+ +| magic word | The four bytes ``.snd``. | ++---------------+-----------------------------------------------+ +| header size | Size of the header, including info, in bytes. | ++---------------+-----------------------------------------------+ +| data size | Physical size of the data, in bytes. | ++---------------+-----------------------------------------------+ +| encoding | Indicates how the audio samples are encoded. | ++---------------+-----------------------------------------------+ +| sample rate | The sampling rate. | ++---------------+-----------------------------------------------+ +| # of channels | The number of channels in the samples. | ++---------------+-----------------------------------------------+ +| info | ASCII string giving a description of the | +| | audio file (padded with null bytes). | ++---------------+-----------------------------------------------+ + +Apart from the info field, all header fields are 4 bytes in size. They are all +32-bit unsigned integers encoded in big-endian byte order. + +The :mod:`sunau` module defines the following functions: + + +.. function:: open(file, mode) + + If *file* is a string, open the file by that name, otherwise treat it as a + seekable file-like object. *mode* can be any of + + ``'r'`` + Read only mode. + + ``'w'`` + Write only mode. + + Note that it does not allow read/write files. + + A *mode* of ``'r'`` returns an :class:`AU_read` object, while a *mode* of ``'w'`` + or ``'wb'`` returns an :class:`AU_write` object. + + +The :mod:`sunau` module defines the following exception: + +.. exception:: Error + + An error raised when something is impossible because of Sun AU specs or + implementation deficiency. + + +The :mod:`sunau` module defines the following data items: + +.. data:: AUDIO_FILE_MAGIC + + An integer every valid Sun AU file begins with, stored in big-endian form. This + is the string ``.snd`` interpreted as an integer. + + +.. data:: AUDIO_FILE_ENCODING_MULAW_8 + AUDIO_FILE_ENCODING_LINEAR_8 + AUDIO_FILE_ENCODING_LINEAR_16 + AUDIO_FILE_ENCODING_LINEAR_24 + AUDIO_FILE_ENCODING_LINEAR_32 + AUDIO_FILE_ENCODING_ALAW_8 + + Values of the encoding field from the AU header which are supported by this + module. + + +.. data:: AUDIO_FILE_ENCODING_FLOAT + AUDIO_FILE_ENCODING_DOUBLE + AUDIO_FILE_ENCODING_ADPCM_G721 + AUDIO_FILE_ENCODING_ADPCM_G722 + AUDIO_FILE_ENCODING_ADPCM_G723_3 + AUDIO_FILE_ENCODING_ADPCM_G723_5 + + Additional known values of the encoding field from the AU header, but which are + not supported by this module. + + +.. _au-read-objects: + +AU_read Objects +--------------- + +AU_read objects, as returned by :func:`.open` above, have the following methods: + + +.. method:: AU_read.close() + + Close the stream, and make the instance unusable. (This is called automatically + on deletion.) + + +.. method:: AU_read.getnchannels() + + Returns number of audio channels (1 for mono, 2 for stereo). + + +.. method:: AU_read.getsampwidth() + + Returns sample width in bytes. + + +.. method:: AU_read.getframerate() + + Returns sampling frequency. + + +.. method:: AU_read.getnframes() + + Returns number of audio frames. + + +.. method:: AU_read.getcomptype() + + Returns compression type. Supported compression types are ``'ULAW'``, ``'ALAW'`` + and ``'NONE'``. + + +.. method:: AU_read.getcompname() + + Human-readable version of :meth:`getcomptype`. The supported types have the + respective names ``'CCITT G.711 u-law'``, ``'CCITT G.711 A-law'`` and ``'not + compressed'``. + + +.. method:: AU_read.getparams() + + Returns a :func:`~collections.namedtuple` ``(nchannels, sampwidth, + framerate, nframes, comptype, compname)``, equivalent to output of the + :meth:`get\*` methods. + + +.. method:: AU_read.readframes(n) + + Reads and returns at most *n* frames of audio, as a :class:`bytes` object. The data + will be returned in linear format. If the original data is in u-LAW format, it + will be converted. + + +.. method:: AU_read.rewind() + + Rewind the file pointer to the beginning of the audio stream. + +The following two methods define a term "position" which is compatible between +them, and is otherwise implementation dependent. + + +.. method:: AU_read.setpos(pos) + + Set the file pointer to the specified position. Only values returned from + :meth:`tell` should be used for *pos*. + + +.. method:: AU_read.tell() + + Return current file pointer position. Note that the returned value has nothing + to do with the actual position in the file. + +The following two functions are defined for compatibility with the :mod:`aifc`, +and don't do anything interesting. + + +.. method:: AU_read.getmarkers() + + Returns ``None``. + + +.. method:: AU_read.getmark(id) + + Raise an error. + + +.. _au-write-objects: + +AU_write Objects +---------------- + +AU_write objects, as returned by :func:`.open` above, have the following methods: + + +.. method:: AU_write.setnchannels(n) + + Set the number of channels. + + +.. method:: AU_write.setsampwidth(n) + + Set the sample width (in bytes.) + + .. versionchanged:: 3.4 + Added support for 24-bit samples. + + +.. method:: AU_write.setframerate(n) + + Set the frame rate. + + +.. method:: AU_write.setnframes(n) + + Set the number of frames. This can be later changed, when and if more frames + are written. + + +.. method:: AU_write.setcomptype(type, name) + + Set the compression type and description. Only ``'NONE'`` and ``'ULAW'`` are + supported on output. + + +.. method:: AU_write.setparams(tuple) + + The *tuple* should be ``(nchannels, sampwidth, framerate, nframes, comptype, + compname)``, with values valid for the :meth:`set\*` methods. Set all + parameters. + + +.. method:: AU_write.tell() + + Return current position in the file, with the same disclaimer for the + :meth:`AU_read.tell` and :meth:`AU_read.setpos` methods. + + +.. method:: AU_write.writeframesraw(data) + + Write audio frames, without correcting *nframes*. + + .. versionchanged:: 3.4 + Any :term:`bytes-like object` is now accepted. + + +.. method:: AU_write.writeframes(data) + + Write audio frames and make sure *nframes* is correct. + + .. versionchanged:: 3.4 + Any :term:`bytes-like object` is now accepted. + + +.. method:: AU_write.close() + + Make sure *nframes* is correct, and close the file. + + This method is called upon deletion. + +Note that it is invalid to set any parameters after calling :meth:`writeframes` +or :meth:`writeframesraw`. + diff --git a/cpython_2/environment/repo/Doc/library/superseded.rst b/cpython_2/environment/repo/Doc/library/superseded.rst new file mode 100644 index 0000000000000000000000000000000000000000..50a5983236e76ae605e2399383c2f8f83ff66a2b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/superseded.rst @@ -0,0 +1,14 @@ +.. _superseded: + +****************** +Superseded Modules +****************** + +The modules described in this chapter are deprecated and only kept for +backwards compatibility. They have been superseded by other modules. + + +.. toctree:: + + optparse.rst + imp.rst diff --git a/cpython_2/environment/repo/Doc/library/symbol.rst b/cpython_2/environment/repo/Doc/library/symbol.rst new file mode 100644 index 0000000000000000000000000000000000000000..44996936e2d28f85535ebd61b57e15d515ea6d18 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/symbol.rst @@ -0,0 +1,27 @@ +:mod:`symbol` --- Constants used with Python parse trees +======================================================== + +.. module:: symbol + :synopsis: Constants representing internal nodes of the parse tree. + +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/symbol.py` + +-------------- + +This module provides constants which represent the numeric values of internal +nodes of the parse tree. Unlike most Python constants, these use lower-case +names. Refer to the file :file:`Grammar/Grammar` in the Python distribution for +the definitions of the names in the context of the language grammar. The +specific numeric values which the names map to may change between Python +versions. + +This module also provides one additional data object: + + +.. data:: sym_name + + Dictionary mapping the numeric values of the constants defined in this module + back to name strings, allowing more human-readable representation of parse trees + to be generated. diff --git a/cpython_2/environment/repo/Doc/library/symtable.rst b/cpython_2/environment/repo/Doc/library/symtable.rst new file mode 100644 index 0000000000000000000000000000000000000000..3efdecb5af7102f19bff70c342c38c6b9c0f9b3e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/symtable.rst @@ -0,0 +1,192 @@ +:mod:`symtable` --- Access to the compiler's symbol tables +========================================================== + +.. module:: symtable + :synopsis: Interface to the compiler's internal symbol tables. + +**Source code:** :source:`Lib/symtable.py` + +-------------- + +.. moduleauthor:: Jeremy Hylton +.. sectionauthor:: Benjamin Peterson + + +Symbol tables are generated by the compiler from AST just before bytecode is +generated. The symbol table is responsible for calculating the scope of every +identifier in the code. :mod:`symtable` provides an interface to examine these +tables. + + +Generating Symbol Tables +------------------------ + +.. function:: symtable(code, filename, compile_type) + + Return the toplevel :class:`SymbolTable` for the Python source *code*. + *filename* is the name of the file containing the code. *compile_type* is + like the *mode* argument to :func:`compile`. + + +Examining Symbol Tables +----------------------- + +.. class:: SymbolTable + + A namespace table for a block. The constructor is not public. + + .. method:: get_type() + + Return the type of the symbol table. Possible values are ``'class'``, + ``'module'``, and ``'function'``. + + .. method:: get_id() + + Return the table's identifier. + + .. method:: get_name() + + Return the table's name. This is the name of the class if the table is + for a class, the name of the function if the table is for a function, or + ``'top'`` if the table is global (:meth:`get_type` returns ``'module'``). + + .. method:: get_lineno() + + Return the number of the first line in the block this table represents. + + .. method:: is_optimized() + + Return ``True`` if the locals in this table can be optimized. + + .. method:: is_nested() + + Return ``True`` if the block is a nested class or function. + + .. method:: has_children() + + Return ``True`` if the block has nested namespaces within it. These can + be obtained with :meth:`get_children`. + + .. method:: get_identifiers() + + Return a list of names of symbols in this table. + + .. method:: lookup(name) + + Lookup *name* in the table and return a :class:`Symbol` instance. + + .. method:: get_symbols() + + Return a list of :class:`Symbol` instances for names in the table. + + .. method:: get_children() + + Return a list of the nested symbol tables. + + +.. class:: Function + + A namespace for a function or method. This class inherits + :class:`SymbolTable`. + + .. method:: get_parameters() + + Return a tuple containing names of parameters to this function. + + .. method:: get_locals() + + Return a tuple containing names of locals in this function. + + .. method:: get_globals() + + Return a tuple containing names of globals in this function. + + .. method:: get_nonlocals() + + Return a tuple containing names of nonlocals in this function. + + .. method:: get_frees() + + Return a tuple containing names of free variables in this function. + + +.. class:: Class + + A namespace of a class. This class inherits :class:`SymbolTable`. + + .. method:: get_methods() + + Return a tuple containing the names of methods declared in the class. + + +.. class:: Symbol + + An entry in a :class:`SymbolTable` corresponding to an identifier in the + source. The constructor is not public. + + .. method:: get_name() + + Return the symbol's name. + + .. method:: is_referenced() + + Return ``True`` if the symbol is used in its block. + + .. method:: is_imported() + + Return ``True`` if the symbol is created from an import statement. + + .. method:: is_parameter() + + Return ``True`` if the symbol is a parameter. + + .. method:: is_global() + + Return ``True`` if the symbol is global. + + .. method:: is_nonlocal() + + Return ``True`` if the symbol is nonlocal. + + .. method:: is_declared_global() + + Return ``True`` if the symbol is declared global with a global statement. + + .. method:: is_local() + + Return ``True`` if the symbol is local to its block. + + .. method:: is_free() + + Return ``True`` if the symbol is referenced in its block, but not assigned + to. + + .. method:: is_assigned() + + Return ``True`` if the symbol is assigned to in its block. + + .. method:: is_namespace() + + Return ``True`` if name binding introduces new namespace. + + If the name is used as the target of a function or class statement, this + will be true. + + For example:: + + >>> table = symtable.symtable("def some_func(): pass", "string", "exec") + >>> table.lookup("some_func").is_namespace() + True + + Note that a single name can be bound to multiple objects. If the result + is ``True``, the name may also be bound to other objects, like an int or + list, that does not introduce a new namespace. + + .. method:: get_namespaces() + + Return a list of namespaces bound to this name. + + .. method:: get_namespace() + + Return the namespace bound to this name. If more than one namespace is + bound, :exc:`ValueError` is raised. diff --git a/cpython_2/environment/repo/Doc/library/sys.rst b/cpython_2/environment/repo/Doc/library/sys.rst new file mode 100644 index 0000000000000000000000000000000000000000..98f63fb83f87a0fdb82207393c45e0d4981fdfb8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/sys.rst @@ -0,0 +1,1675 @@ +:mod:`sys` --- System-specific parameters and functions +======================================================= + +.. module:: sys + :synopsis: Access system-specific parameters and functions. + +-------------- + +This module provides access to some variables used or maintained by the +interpreter and to functions that interact strongly with the interpreter. It is +always available. + + +.. data:: abiflags + + On POSIX systems where Python was built with the standard ``configure`` + script, this contains the ABI flags as specified by :pep:`3149`. + + .. versionchanged:: 3.8 + Default flags became an empty string (``m`` flag for pymalloc has been + removed). + + .. versionadded:: 3.2 + + +.. function:: addaudithook(hook) + + Append the callable *hook* to the list of active auditing hooks for the + current interpreter. + + When an auditing event is raised through the :func:`sys.audit` function, each + hook will be called in the order it was added with the event name and the + tuple of arguments. Native hooks added by :c:func:`PySys_AddAuditHook` are + called first, followed by hooks added in the current interpreter. + + .. audit-event:: sys.addaudithook "" sys.addaudithook + + Raise an auditing event ``sys.addaudithook`` with no arguments. If any + existing hooks raise an exception derived from :class:`RuntimeError`, the + new hook will not be added and the exception suppressed. As a result, + callers cannot assume that their hook has been added unless they control + all existing hooks. + + .. versionadded:: 3.8 + + .. versionchanged:: 3.8.1 + + Exceptions derived from :class:`Exception` but not :class:`RuntimeError` + are no longer suppressed. + + .. impl-detail:: + + When tracing is enabled (see :func:`settrace`), Python hooks are only + traced if the callable has a ``__cantrace__`` member that is set to a + true value. Otherwise, trace functions will skip the hook. + + +.. data:: argv + + The list of command line arguments passed to a Python script. ``argv[0]`` is the + script name (it is operating system dependent whether this is a full pathname or + not). If the command was executed using the :option:`-c` command line option to + the interpreter, ``argv[0]`` is set to the string ``'-c'``. If no script name + was passed to the Python interpreter, ``argv[0]`` is the empty string. + + To loop over the standard input, or the list of files given on the + command line, see the :mod:`fileinput` module. + + .. note:: + On Unix, command line arguments are passed by bytes from OS. Python decodes + them with filesystem encoding and "surrogateescape" error handler. + When you need original bytes, you can get it by + ``[os.fsencode(arg) for arg in sys.argv]``. + + +.. _auditing: + +.. function:: audit(event, *args) + + .. index:: single: auditing + + Raise an auditing event with any active hooks. The event name is a string + identifying the event and its associated schema, which is the number and + types of arguments. The schema for a given event is considered public and + stable API and should not be modified between releases. + + This function will raise the first exception raised by any hook. In general, + these errors should not be handled and should terminate the process as + quickly as possible. + + Hooks are added using the :func:`sys.addaudithook` or + :c:func:`PySys_AddAuditHook` functions. + + The native equivalent of this function is :c:func:`PySys_Audit`. Using the + native function is preferred when possible. + + See the :ref:`audit events table ` for all events raised by + CPython. + + .. versionadded:: 3.8 + + +.. data:: base_exec_prefix + + Set during Python startup, before ``site.py`` is run, to the same value as + :data:`exec_prefix`. If not running in a + :ref:`virtual environment `, the values will stay the same; if + ``site.py`` finds that a virtual environment is in use, the values of + :data:`prefix` and :data:`exec_prefix` will be changed to point to the + virtual environment, whereas :data:`base_prefix` and + :data:`base_exec_prefix` will remain pointing to the base Python + installation (the one which the virtual environment was created from). + + .. versionadded:: 3.3 + + +.. data:: base_prefix + + Set during Python startup, before ``site.py`` is run, to the same value as + :data:`prefix`. If not running in a :ref:`virtual environment `, the values + will stay the same; if ``site.py`` finds that a virtual environment is in + use, the values of :data:`prefix` and :data:`exec_prefix` will be changed to + point to the virtual environment, whereas :data:`base_prefix` and + :data:`base_exec_prefix` will remain pointing to the base Python + installation (the one which the virtual environment was created from). + + .. versionadded:: 3.3 + + +.. data:: byteorder + + An indicator of the native byte order. This will have the value ``'big'`` on + big-endian (most-significant byte first) platforms, and ``'little'`` on + little-endian (least-significant byte first) platforms. + + +.. data:: builtin_module_names + + A tuple of strings giving the names of all modules that are compiled into this + Python interpreter. (This information is not available in any other way --- + ``modules.keys()`` only lists the imported modules.) + + +.. function:: call_tracing(func, args) + + Call ``func(*args)``, while tracing is enabled. The tracing state is saved, + and restored afterwards. This is intended to be called from a debugger from + a checkpoint, to recursively debug some other code. + + +.. data:: copyright + + A string containing the copyright pertaining to the Python interpreter. + + +.. function:: _clear_type_cache() + + Clear the internal type cache. The type cache is used to speed up attribute + and method lookups. Use the function *only* to drop unnecessary references + during reference leak debugging. + + This function should be used for internal and specialized purposes only. + + +.. function:: _current_frames() + + Return a dictionary mapping each thread's identifier to the topmost stack frame + currently active in that thread at the time the function is called. Note that + functions in the :mod:`traceback` module can build the call stack given such a + frame. + + This is most useful for debugging deadlock: this function does not require the + deadlocked threads' cooperation, and such threads' call stacks are frozen for as + long as they remain deadlocked. The frame returned for a non-deadlocked thread + may bear no relationship to that thread's current activity by the time calling + code examines the frame. + + This function should be used for internal and specialized purposes only. + + .. audit-event:: sys._current_frames "" sys._current_frames + + +.. function:: breakpointhook() + + This hook function is called by built-in :func:`breakpoint`. By default, + it drops you into the :mod:`pdb` debugger, but it can be set to any other + function so that you can choose which debugger gets used. + + The signature of this function is dependent on what it calls. For example, + the default binding (e.g. ``pdb.set_trace()``) expects no arguments, but + you might bind it to a function that expects additional arguments + (positional and/or keyword). The built-in ``breakpoint()`` function passes + its ``*args`` and ``**kws`` straight through. Whatever + ``breakpointhooks()`` returns is returned from ``breakpoint()``. + + The default implementation first consults the environment variable + :envvar:`PYTHONBREAKPOINT`. If that is set to ``"0"`` then this function + returns immediately; i.e. it is a no-op. If the environment variable is + not set, or is set to the empty string, ``pdb.set_trace()`` is called. + Otherwise this variable should name a function to run, using Python's + dotted-import nomenclature, e.g. ``package.subpackage.module.function``. + In this case, ``package.subpackage.module`` would be imported and the + resulting module must have a callable named ``function()``. This is run, + passing in ``*args`` and ``**kws``, and whatever ``function()`` returns, + ``sys.breakpointhook()`` returns to the built-in :func:`breakpoint` + function. + + Note that if anything goes wrong while importing the callable named by + :envvar:`PYTHONBREAKPOINT`, a :exc:`RuntimeWarning` is reported and the + breakpoint is ignored. + + Also note that if ``sys.breakpointhook()`` is overridden programmatically, + :envvar:`PYTHONBREAKPOINT` is *not* consulted. + + .. versionadded:: 3.7 + +.. function:: _debugmallocstats() + + Print low-level information to stderr about the state of CPython's memory + allocator. + + If Python is configured --with-pydebug, it also performs some expensive + internal consistency checks. + + .. versionadded:: 3.3 + + .. impl-detail:: + + This function is specific to CPython. The exact output format is not + defined here, and may change. + + +.. data:: dllhandle + + Integer specifying the handle of the Python DLL. + + .. availability:: Windows. + + +.. function:: displayhook(value) + + If *value* is not ``None``, this function prints ``repr(value)`` to + ``sys.stdout``, and saves *value* in ``builtins._``. If ``repr(value)`` is + not encodable to ``sys.stdout.encoding`` with ``sys.stdout.errors`` error + handler (which is probably ``'strict'``), encode it to + ``sys.stdout.encoding`` with ``'backslashreplace'`` error handler. + + ``sys.displayhook`` is called on the result of evaluating an :term:`expression` + entered in an interactive Python session. The display of these values can be + customized by assigning another one-argument function to ``sys.displayhook``. + + Pseudo-code:: + + def displayhook(value): + if value is None: + return + # Set '_' to None to avoid recursion + builtins._ = None + text = repr(value) + try: + sys.stdout.write(text) + except UnicodeEncodeError: + bytes = text.encode(sys.stdout.encoding, 'backslashreplace') + if hasattr(sys.stdout, 'buffer'): + sys.stdout.buffer.write(bytes) + else: + text = bytes.decode(sys.stdout.encoding, 'strict') + sys.stdout.write(text) + sys.stdout.write("\n") + builtins._ = value + + .. versionchanged:: 3.2 + Use ``'backslashreplace'`` error handler on :exc:`UnicodeEncodeError`. + + +.. data:: dont_write_bytecode + + If this is true, Python won't try to write ``.pyc`` files on the + import of source modules. This value is initially set to ``True`` or + ``False`` depending on the :option:`-B` command line option and the + :envvar:`PYTHONDONTWRITEBYTECODE` environment variable, but you can set it + yourself to control bytecode file generation. + + +.. data:: pycache_prefix + + If this is set (not ``None``), Python will write bytecode-cache ``.pyc`` + files to (and read them from) a parallel directory tree rooted at this + directory, rather than from ``__pycache__`` directories in the source code + tree. Any ``__pycache__`` directories in the source code tree will be ignored + and new `.pyc` files written within the pycache prefix. Thus if you use + :mod:`compileall` as a pre-build step, you must ensure you run it with the + same pycache prefix (if any) that you will use at runtime. + + A relative path is interpreted relative to the current working directory. + + This value is initially set based on the value of the :option:`-X` + ``pycache_prefix=PATH`` command-line option or the + :envvar:`PYTHONPYCACHEPREFIX` environment variable (command-line takes + precedence). If neither are set, it is ``None``. + + .. versionadded:: 3.8 + + +.. function:: excepthook(type, value, traceback) + + This function prints out a given traceback and exception to ``sys.stderr``. + + When an exception is raised and uncaught, the interpreter calls + ``sys.excepthook`` with three arguments, the exception class, exception + instance, and a traceback object. In an interactive session this happens just + before control is returned to the prompt; in a Python program this happens just + before the program exits. The handling of such top-level exceptions can be + customized by assigning another three-argument function to ``sys.excepthook``. + + .. audit-event:: sys.excepthook hook,type,value,traceback sys.excepthook + + Raise an auditing event ``sys.excepthook`` with arguments ``hook``, + ``type``, ``value``, ``traceback`` when an uncaught exception occurs. + If no hook has been set, ``hook`` may be ``None``. If any hook raises + an exception derived from :class:`RuntimeError` the call to the hook will + be suppressed. Otherwise, the audit hook exception will be reported as + unraisable and ``sys.excepthook`` will be called. + + .. seealso:: + + The :func:`sys.unraisablehook` function handles unraisable exceptions + and the :func:`threading.excepthook` function handles exception raised + by :func:`threading.Thread.run`. + + +.. data:: __breakpointhook__ + __displayhook__ + __excepthook__ + __unraisablehook__ + + These objects contain the original values of ``breakpointhook``, + ``displayhook``, ``excepthook``, and ``unraisablehook`` at the start of the + program. They are saved so that ``breakpointhook``, ``displayhook`` and + ``excepthook``, ``unraisablehook`` can be restored in case they happen to + get replaced with broken or alternative objects. + + .. versionadded:: 3.7 + __breakpointhook__ + + .. versionadded:: 3.8 + __unraisablehook__ + +.. function:: exc_info() + + This function returns a tuple of three values that give information about the + exception that is currently being handled. The information returned is specific + both to the current thread and to the current stack frame. If the current stack + frame is not handling an exception, the information is taken from the calling + stack frame, or its caller, and so on until a stack frame is found that is + handling an exception. Here, "handling an exception" is defined as "executing + an except clause." For any stack frame, only information about the exception + being currently handled is accessible. + + .. index:: object: traceback + + If no exception is being handled anywhere on the stack, a tuple containing + three ``None`` values is returned. Otherwise, the values returned are + ``(type, value, traceback)``. Their meaning is: *type* gets the type of the + exception being handled (a subclass of :exc:`BaseException`); *value* gets + the exception instance (an instance of the exception type); *traceback* gets + a :ref:`traceback object ` which encapsulates the call + stack at the point where the exception originally occurred. + + +.. data:: exec_prefix + + A string giving the site-specific directory prefix where the platform-dependent + Python files are installed; by default, this is also ``'/usr/local'``. This can + be set at build time with the ``--exec-prefix`` argument to the + :program:`configure` script. Specifically, all configuration files (e.g. the + :file:`pyconfig.h` header file) are installed in the directory + :file:`{exec_prefix}/lib/python{X.Y}/config`, and shared library modules are + installed in :file:`{exec_prefix}/lib/python{X.Y}/lib-dynload`, where *X.Y* + is the version number of Python, for example ``3.2``. + + .. note:: + + If a :ref:`virtual environment ` is in effect, this + value will be changed in ``site.py`` to point to the virtual environment. + The value for the Python installation will still be available, via + :data:`base_exec_prefix`. + + +.. data:: executable + + A string giving the absolute path of the executable binary for the Python + interpreter, on systems where this makes sense. If Python is unable to retrieve + the real path to its executable, :data:`sys.executable` will be an empty string + or ``None``. + + +.. function:: exit([arg]) + + Exit from Python. This is implemented by raising the :exc:`SystemExit` + exception, so cleanup actions specified by finally clauses of :keyword:`try` + statements are honored, and it is possible to intercept the exit attempt at + an outer level. + + The optional argument *arg* can be an integer giving the exit status + (defaulting to zero), or another type of object. If it is an integer, zero + is considered "successful termination" and any nonzero value is considered + "abnormal termination" by shells and the like. Most systems require it to be + in the range 0--127, and produce undefined results otherwise. Some systems + have a convention for assigning specific meanings to specific exit codes, but + these are generally underdeveloped; Unix programs generally use 2 for command + line syntax errors and 1 for all other kind of errors. If another type of + object is passed, ``None`` is equivalent to passing zero, and any other + object is printed to :data:`stderr` and results in an exit code of 1. In + particular, ``sys.exit("some error message")`` is a quick way to exit a + program when an error occurs. + + Since :func:`exit` ultimately "only" raises an exception, it will only exit + the process when called from the main thread, and the exception is not + intercepted. + + .. versionchanged:: 3.6 + If an error occurs in the cleanup after the Python interpreter + has caught :exc:`SystemExit` (such as an error flushing buffered data + in the standard streams), the exit status is changed to 120. + + +.. data:: flags + + The :term:`named tuple` *flags* exposes the status of command line + flags. The attributes are read only. + + ============================= ================================================================ + attribute flag + ============================= ================================================================ + :const:`debug` :option:`-d` + :const:`inspect` :option:`-i` + :const:`interactive` :option:`-i` + :const:`isolated` :option:`-I` + :const:`optimize` :option:`-O` or :option:`-OO` + :const:`dont_write_bytecode` :option:`-B` + :const:`no_user_site` :option:`-s` + :const:`no_site` :option:`-S` + :const:`ignore_environment` :option:`-E` + :const:`verbose` :option:`-v` + :const:`bytes_warning` :option:`-b` + :const:`quiet` :option:`-q` + :const:`hash_randomization` :option:`-R` + :const:`dev_mode` :option:`-X dev <-X>` (:ref:`Python Development Mode `) + :const:`utf8_mode` :option:`-X utf8 <-X>` + ============================= ================================================================ + + .. versionchanged:: 3.2 + Added ``quiet`` attribute for the new :option:`-q` flag. + + .. versionadded:: 3.2.3 + The ``hash_randomization`` attribute. + + .. versionchanged:: 3.3 + Removed obsolete ``division_warning`` attribute. + + .. versionchanged:: 3.4 + Added ``isolated`` attribute for :option:`-I` ``isolated`` flag. + + .. versionchanged:: 3.7 + Added the ``dev_mode`` attribute for the new :ref:`Python Development + Mode ` and the ``utf8_mode`` attribute for the new :option:`-X` + ``utf8`` flag. + + +.. data:: float_info + + A :term:`named tuple` holding information about the float type. It + contains low level information about the precision and internal + representation. The values correspond to the various floating-point + constants defined in the standard header file :file:`float.h` for the 'C' + programming language; see section 5.2.4.2.2 of the 1999 ISO/IEC C standard + [C99]_, 'Characteristics of floating types', for details. + + .. tabularcolumns:: |l|l|L| + + +---------------------+----------------+--------------------------------------------------+ + | attribute | float.h macro | explanation | + +=====================+================+==================================================+ + | :const:`epsilon` | DBL_EPSILON | difference between 1.0 and the least value | + | | | greater than 1.0 that is representable as a float| + | | | | + | | | See also :func:`math.ulp`. | + +---------------------+----------------+--------------------------------------------------+ + | :const:`dig` | DBL_DIG | maximum number of decimal digits that can be | + | | | faithfully represented in a float; see below | + +---------------------+----------------+--------------------------------------------------+ + | :const:`mant_dig` | DBL_MANT_DIG | float precision: the number of base-``radix`` | + | | | digits in the significand of a float | + +---------------------+----------------+--------------------------------------------------+ + | :const:`max` | DBL_MAX | maximum representable positive finite float | + +---------------------+----------------+--------------------------------------------------+ + | :const:`max_exp` | DBL_MAX_EXP | maximum integer *e* such that ``radix**(e-1)`` is| + | | | a representable finite float | + +---------------------+----------------+--------------------------------------------------+ + | :const:`max_10_exp` | DBL_MAX_10_EXP | maximum integer *e* such that ``10**e`` is in the| + | | | range of representable finite floats | + +---------------------+----------------+--------------------------------------------------+ + | :const:`min` | DBL_MIN | minimum representable positive *normalized* float| + | | | | + | | | Use :func:`math.ulp(0.0) ` to get the | + | | | smallest positive *denormalized* representable | + | | | float. | + +---------------------+----------------+--------------------------------------------------+ + | :const:`min_exp` | DBL_MIN_EXP | minimum integer *e* such that ``radix**(e-1)`` is| + | | | a normalized float | + +---------------------+----------------+--------------------------------------------------+ + | :const:`min_10_exp` | DBL_MIN_10_EXP | minimum integer *e* such that ``10**e`` is a | + | | | normalized float | + +---------------------+----------------+--------------------------------------------------+ + | :const:`radix` | FLT_RADIX | radix of exponent representation | + +---------------------+----------------+--------------------------------------------------+ + | :const:`rounds` | FLT_ROUNDS | integer constant representing the rounding mode | + | | | used for arithmetic operations. This reflects | + | | | the value of the system FLT_ROUNDS macro at | + | | | interpreter startup time. See section 5.2.4.2.2 | + | | | of the C99 standard for an explanation of the | + | | | possible values and their meanings. | + +---------------------+----------------+--------------------------------------------------+ + + The attribute :attr:`sys.float_info.dig` needs further explanation. If + ``s`` is any string representing a decimal number with at most + :attr:`sys.float_info.dig` significant digits, then converting ``s`` to a + float and back again will recover a string representing the same decimal + value:: + + >>> import sys + >>> sys.float_info.dig + 15 + >>> s = '3.14159265358979' # decimal string with 15 significant digits + >>> format(float(s), '.15g') # convert to float and back -> same value + '3.14159265358979' + + But for strings with more than :attr:`sys.float_info.dig` significant digits, + this isn't always true:: + + >>> s = '9876543211234567' # 16 significant digits is too many! + >>> format(float(s), '.16g') # conversion changes value + '9876543211234568' + +.. data:: float_repr_style + + A string indicating how the :func:`repr` function behaves for + floats. If the string has value ``'short'`` then for a finite + float ``x``, ``repr(x)`` aims to produce a short string with the + property that ``float(repr(x)) == x``. This is the usual behaviour + in Python 3.1 and later. Otherwise, ``float_repr_style`` has value + ``'legacy'`` and ``repr(x)`` behaves in the same way as it did in + versions of Python prior to 3.1. + + .. versionadded:: 3.1 + + +.. function:: getallocatedblocks() + + Return the number of memory blocks currently allocated by the interpreter, + regardless of their size. This function is mainly useful for tracking + and debugging memory leaks. Because of the interpreter's internal + caches, the result can vary from call to call; you may have to call + :func:`_clear_type_cache()` and :func:`gc.collect()` to get more + predictable results. + + If a Python build or implementation cannot reasonably compute this + information, :func:`getallocatedblocks()` is allowed to return 0 instead. + + .. versionadded:: 3.4 + + +.. function:: getandroidapilevel() + + Return the build time API version of Android as an integer. + + .. availability:: Android. + + .. versionadded:: 3.7 + + +.. function:: getdefaultencoding() + + Return the name of the current default string encoding used by the Unicode + implementation. + + +.. function:: getdlopenflags() + + Return the current value of the flags that are used for + :c:func:`dlopen` calls. Symbolic names for the flag values can be + found in the :mod:`os` module (``RTLD_xxx`` constants, e.g. + :data:`os.RTLD_LAZY`). + + .. availability:: Unix. + + +.. function:: getfilesystemencoding() + + Return the name of the encoding used to convert between Unicode + filenames and bytes filenames. For best compatibility, str should be + used for filenames in all cases, although representing filenames as bytes + is also supported. Functions accepting or returning filenames should support + either str or bytes and internally convert to the system's preferred + representation. + + This encoding is always ASCII-compatible. + + :func:`os.fsencode` and :func:`os.fsdecode` should be used to ensure that + the correct encoding and errors mode are used. + + * In the UTF-8 mode, the encoding is ``utf-8`` on any platform. + + * On macOS, the encoding is ``'utf-8'``. + + * On Unix, the encoding is the locale encoding. + + * On Windows, the encoding may be ``'utf-8'`` or ``'mbcs'``, depending + on user configuration. + + * On Android, the encoding is ``'utf-8'``. + + * On VxWorks, the encoding is ``'utf-8'``. + + .. versionchanged:: 3.2 + :func:`getfilesystemencoding` result cannot be ``None`` anymore. + + .. versionchanged:: 3.6 + Windows is no longer guaranteed to return ``'mbcs'``. See :pep:`529` + and :func:`_enablelegacywindowsfsencoding` for more information. + + .. versionchanged:: 3.7 + Return 'utf-8' in the UTF-8 mode. + + +.. function:: getfilesystemencodeerrors() + + Return the name of the error mode used to convert between Unicode filenames + and bytes filenames. The encoding name is returned from + :func:`getfilesystemencoding`. + + :func:`os.fsencode` and :func:`os.fsdecode` should be used to ensure that + the correct encoding and errors mode are used. + + .. versionadded:: 3.6 + +.. function:: getrefcount(object) + + Return the reference count of the *object*. The count returned is generally one + higher than you might expect, because it includes the (temporary) reference as + an argument to :func:`getrefcount`. + + +.. function:: getrecursionlimit() + + Return the current value of the recursion limit, the maximum depth of the Python + interpreter stack. This limit prevents infinite recursion from causing an + overflow of the C stack and crashing Python. It can be set by + :func:`setrecursionlimit`. + + +.. function:: getsizeof(object[, default]) + + Return the size of an object in bytes. The object can be any type of + object. All built-in objects will return correct results, but this + does not have to hold true for third-party extensions as it is implementation + specific. + + Only the memory consumption directly attributed to the object is + accounted for, not the memory consumption of objects it refers to. + + If given, *default* will be returned if the object does not provide means to + retrieve the size. Otherwise a :exc:`TypeError` will be raised. + + :func:`getsizeof` calls the object's ``__sizeof__`` method and adds an + additional garbage collector overhead if the object is managed by the garbage + collector. + + See `recursive sizeof recipe `_ + for an example of using :func:`getsizeof` recursively to find the size of + containers and all their contents. + +.. function:: getswitchinterval() + + Return the interpreter's "thread switch interval"; see + :func:`setswitchinterval`. + + .. versionadded:: 3.2 + + +.. function:: _getframe([depth]) + + Return a frame object from the call stack. If optional integer *depth* is + given, return the frame object that many calls below the top of the stack. If + that is deeper than the call stack, :exc:`ValueError` is raised. The default + for *depth* is zero, returning the frame at the top of the call stack. + + .. audit-event:: sys._getframe "" sys._getframe + + .. impl-detail:: + + This function should be used for internal and specialized purposes only. + It is not guaranteed to exist in all implementations of Python. + + +.. function:: getprofile() + + .. index:: + single: profile function + single: profiler + + Get the profiler function as set by :func:`setprofile`. + + +.. function:: gettrace() + + .. index:: + single: trace function + single: debugger + + Get the trace function as set by :func:`settrace`. + + .. impl-detail:: + + The :func:`gettrace` function is intended only for implementing debuggers, + profilers, coverage tools and the like. Its behavior is part of the + implementation platform, rather than part of the language definition, and + thus may not be available in all Python implementations. + + +.. function:: getwindowsversion() + + Return a named tuple describing the Windows version + currently running. The named elements are *major*, *minor*, + *build*, *platform*, *service_pack*, *service_pack_minor*, + *service_pack_major*, *suite_mask*, *product_type* and + *platform_version*. *service_pack* contains a string, + *platform_version* a 3-tuple and all other values are + integers. The components can also be accessed by name, so + ``sys.getwindowsversion()[0]`` is equivalent to + ``sys.getwindowsversion().major``. For compatibility with prior + versions, only the first 5 elements are retrievable by indexing. + + *platform* will be :const:`2 (VER_PLATFORM_WIN32_NT)`. + + *product_type* may be one of the following values: + + +---------------------------------------+---------------------------------+ + | Constant | Meaning | + +=======================================+=================================+ + | :const:`1 (VER_NT_WORKSTATION)` | The system is a workstation. | + +---------------------------------------+---------------------------------+ + | :const:`2 (VER_NT_DOMAIN_CONTROLLER)` | The system is a domain | + | | controller. | + +---------------------------------------+---------------------------------+ + | :const:`3 (VER_NT_SERVER)` | The system is a server, but not | + | | a domain controller. | + +---------------------------------------+---------------------------------+ + + This function wraps the Win32 :c:func:`GetVersionEx` function; see the + Microsoft documentation on :c:func:`OSVERSIONINFOEX` for more information + about these fields. + + *platform_version* returns the accurate major version, minor version and + build number of the current operating system, rather than the version that + is being emulated for the process. It is intended for use in logging rather + than for feature detection. + + .. availability:: Windows. + + .. versionchanged:: 3.2 + Changed to a named tuple and added *service_pack_minor*, + *service_pack_major*, *suite_mask*, and *product_type*. + + .. versionchanged:: 3.6 + Added *platform_version* + + +.. function:: get_asyncgen_hooks() + + Returns an *asyncgen_hooks* object, which is similar to a + :class:`~collections.namedtuple` of the form `(firstiter, finalizer)`, + where *firstiter* and *finalizer* are expected to be either ``None`` or + functions which take an :term:`asynchronous generator iterator` as an + argument, and are used to schedule finalization of an asynchronous + generator by an event loop. + + .. versionadded:: 3.6 + See :pep:`525` for more details. + + .. note:: + This function has been added on a provisional basis (see :pep:`411` + for details.) + + +.. function:: get_coroutine_origin_tracking_depth() + + Get the current coroutine origin tracking depth, as set by + :func:`set_coroutine_origin_tracking_depth`. + + .. versionadded:: 3.7 + + .. note:: + This function has been added on a provisional basis (see :pep:`411` + for details.) Use it only for debugging purposes. + + +.. data:: hash_info + + A :term:`named tuple` giving parameters of the numeric hash + implementation. For more details about hashing of numeric types, see + :ref:`numeric-hash`. + + +---------------------+--------------------------------------------------+ + | attribute | explanation | + +=====================+==================================================+ + | :const:`width` | width in bits used for hash values | + +---------------------+--------------------------------------------------+ + | :const:`modulus` | prime modulus P used for numeric hash scheme | + +---------------------+--------------------------------------------------+ + | :const:`inf` | hash value returned for a positive infinity | + +---------------------+--------------------------------------------------+ + | :const:`nan` | hash value returned for a nan | + +---------------------+--------------------------------------------------+ + | :const:`imag` | multiplier used for the imaginary part of a | + | | complex number | + +---------------------+--------------------------------------------------+ + | :const:`algorithm` | name of the algorithm for hashing of str, bytes, | + | | and memoryview | + +---------------------+--------------------------------------------------+ + | :const:`hash_bits` | internal output size of the hash algorithm | + +---------------------+--------------------------------------------------+ + | :const:`seed_bits` | size of the seed key of the hash algorithm | + +---------------------+--------------------------------------------------+ + + + .. versionadded:: 3.2 + + .. versionchanged:: 3.4 + Added *algorithm*, *hash_bits* and *seed_bits* + + +.. data:: hexversion + + The version number encoded as a single integer. This is guaranteed to increase + with each version, including proper support for non-production releases. For + example, to test that the Python interpreter is at least version 1.5.2, use:: + + if sys.hexversion >= 0x010502F0: + # use some advanced feature + ... + else: + # use an alternative implementation or warn the user + ... + + This is called ``hexversion`` since it only really looks meaningful when viewed + as the result of passing it to the built-in :func:`hex` function. The + :term:`named tuple` :data:`sys.version_info` may be used for a more + human-friendly encoding of the same information. + + More details of ``hexversion`` can be found at :ref:`apiabiversion`. + + +.. data:: implementation + + An object containing information about the implementation of the + currently running Python interpreter. The following attributes are + required to exist in all Python implementations. + + *name* is the implementation's identifier, e.g. ``'cpython'``. The actual + string is defined by the Python implementation, but it is guaranteed to be + lower case. + + *version* is a named tuple, in the same format as + :data:`sys.version_info`. It represents the version of the Python + *implementation*. This has a distinct meaning from the specific + version of the Python *language* to which the currently running + interpreter conforms, which ``sys.version_info`` represents. For + example, for PyPy 1.8 ``sys.implementation.version`` might be + ``sys.version_info(1, 8, 0, 'final', 0)``, whereas ``sys.version_info`` + would be ``sys.version_info(2, 7, 2, 'final', 0)``. For CPython they + are the same value, since it is the reference implementation. + + *hexversion* is the implementation version in hexadecimal format, like + :data:`sys.hexversion`. + + *cache_tag* is the tag used by the import machinery in the filenames of + cached modules. By convention, it would be a composite of the + implementation's name and version, like ``'cpython-33'``. However, a + Python implementation may use some other value if appropriate. If + ``cache_tag`` is set to ``None``, it indicates that module caching should + be disabled. + + :data:`sys.implementation` may contain additional attributes specific to + the Python implementation. These non-standard attributes must start with + an underscore, and are not described here. Regardless of its contents, + :data:`sys.implementation` will not change during a run of the interpreter, + nor between implementation versions. (It may change between Python + language versions, however.) See :pep:`421` for more information. + + .. versionadded:: 3.3 + + .. note:: + + The addition of new required attributes must go through the normal PEP + process. See :pep:`421` for more information. + +.. data:: int_info + + A :term:`named tuple` that holds information about Python's internal + representation of integers. The attributes are read only. + + .. tabularcolumns:: |l|L| + + +-------------------------+----------------------------------------------+ + | Attribute | Explanation | + +=========================+==============================================+ + | :const:`bits_per_digit` | number of bits held in each digit. Python | + | | integers are stored internally in base | + | | ``2**int_info.bits_per_digit`` | + +-------------------------+----------------------------------------------+ + | :const:`sizeof_digit` | size in bytes of the C type used to | + | | represent a digit | + +-------------------------+----------------------------------------------+ + + .. versionadded:: 3.1 + + +.. data:: __interactivehook__ + + When this attribute exists, its value is automatically called (with no + arguments) when the interpreter is launched in :ref:`interactive mode + `. This is done after the :envvar:`PYTHONSTARTUP` file is + read, so that you can set this hook there. The :mod:`site` module + :ref:`sets this `. + + .. audit-event:: cpython.run_interactivehook hook sys.__interactivehook__ + + Raises an :ref:`auditing event ` + ``cpython.run_interactivehook`` with the hook object as the argument when + the hook is called on startup. + + .. versionadded:: 3.4 + + +.. function:: intern(string) + + Enter *string* in the table of "interned" strings and return the interned string + -- which is *string* itself or a copy. Interning strings is useful to gain a + little performance on dictionary lookup -- if the keys in a dictionary are + interned, and the lookup key is interned, the key comparisons (after hashing) + can be done by a pointer compare instead of a string compare. Normally, the + names used in Python programs are automatically interned, and the dictionaries + used to hold module, class or instance attributes have interned keys. + + Interned strings are not immortal; you must keep a reference to the return + value of :func:`intern` around to benefit from it. + + +.. function:: is_finalizing() + + Return :const:`True` if the Python interpreter is + :term:`shutting down `, :const:`False` otherwise. + + .. versionadded:: 3.5 + + +.. data:: last_type + last_value + last_traceback + + These three variables are not always defined; they are set when an exception is + not handled and the interpreter prints an error message and a stack traceback. + Their intended use is to allow an interactive user to import a debugger module + and engage in post-mortem debugging without having to re-execute the command + that caused the error. (Typical use is ``import pdb; pdb.pm()`` to enter the + post-mortem debugger; see :mod:`pdb` module for + more information.) + + The meaning of the variables is the same as that of the return values from + :func:`exc_info` above. + + +.. data:: maxsize + + An integer giving the maximum value a variable of type :c:type:`Py_ssize_t` can + take. It's usually ``2**31 - 1`` on a 32-bit platform and ``2**63 - 1`` on a + 64-bit platform. + + +.. data:: maxunicode + + An integer giving the value of the largest Unicode code point, + i.e. ``1114111`` (``0x10FFFF`` in hexadecimal). + + .. versionchanged:: 3.3 + Before :pep:`393`, ``sys.maxunicode`` used to be either ``0xFFFF`` + or ``0x10FFFF``, depending on the configuration option that specified + whether Unicode characters were stored as UCS-2 or UCS-4. + + +.. data:: meta_path + + A list of :term:`meta path finder` objects that have their + :meth:`~importlib.abc.MetaPathFinder.find_spec` methods called to see if one + of the objects can find the module to be imported. The + :meth:`~importlib.abc.MetaPathFinder.find_spec` method is called with at + least the absolute name of the module being imported. If the module to be + imported is contained in a package, then the parent package's :attr:`__path__` + attribute is passed in as a second argument. The method returns a + :term:`module spec`, or ``None`` if the module cannot be found. + + .. seealso:: + + :class:`importlib.abc.MetaPathFinder` + The abstract base class defining the interface of finder objects on + :data:`meta_path`. + :class:`importlib.machinery.ModuleSpec` + The concrete class which + :meth:`~importlib.abc.MetaPathFinder.find_spec` should return + instances of. + + .. versionchanged:: 3.4 + + :term:`Module specs ` were introduced in Python 3.4, by + :pep:`451`. Earlier versions of Python looked for a method called + :meth:`~importlib.abc.MetaPathFinder.find_module`. + This is still called as a fallback if a :data:`meta_path` entry doesn't + have a :meth:`~importlib.abc.MetaPathFinder.find_spec` method. + +.. data:: modules + + This is a dictionary that maps module names to modules which have already been + loaded. This can be manipulated to force reloading of modules and other tricks. + However, replacing the dictionary will not necessarily work as expected and + deleting essential items from the dictionary may cause Python to fail. + + +.. data:: path + + .. index:: triple: module; search; path + + A list of strings that specifies the search path for modules. Initialized from + the environment variable :envvar:`PYTHONPATH`, plus an installation-dependent + default. + + As initialized upon program startup, the first item of this list, ``path[0]``, + is the directory containing the script that was used to invoke the Python + interpreter. If the script directory is not available (e.g. if the interpreter + is invoked interactively or if the script is read from standard input), + ``path[0]`` is the empty string, which directs Python to search modules in the + current directory first. Notice that the script directory is inserted *before* + the entries inserted as a result of :envvar:`PYTHONPATH`. + + A program is free to modify this list for its own purposes. Only strings + and bytes should be added to :data:`sys.path`; all other data types are + ignored during import. + + + .. seealso:: + Module :mod:`site` This describes how to use .pth files to extend + :data:`sys.path`. + + +.. data:: path_hooks + + A list of callables that take a path argument to try to create a + :term:`finder` for the path. If a finder can be created, it is to be + returned by the callable, else raise :exc:`ImportError`. + + Originally specified in :pep:`302`. + + +.. data:: path_importer_cache + + A dictionary acting as a cache for :term:`finder` objects. The keys are + paths that have been passed to :data:`sys.path_hooks` and the values are + the finders that are found. If a path is a valid file system path but no + finder is found on :data:`sys.path_hooks` then ``None`` is + stored. + + Originally specified in :pep:`302`. + + .. versionchanged:: 3.3 + ``None`` is stored instead of :class:`imp.NullImporter` when no finder + is found. + + +.. data:: platform + + This string contains a platform identifier that can be used to append + platform-specific components to :data:`sys.path`, for instance. + + For Unix systems, except on Linux and AIX, this is the lowercased OS name as + returned by ``uname -s`` with the first part of the version as returned by + ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, *at the time + when Python was built*. Unless you want to test for a specific system + version, it is therefore recommended to use the following idiom:: + + if sys.platform.startswith('freebsd'): + # FreeBSD-specific code here... + elif sys.platform.startswith('linux'): + # Linux-specific code here... + elif sys.platform.startswith('aix'): + # AIX-specific code here... + + For other systems, the values are: + + ================ =========================== + System ``platform`` value + ================ =========================== + AIX ``'aix'`` + Linux ``'linux'`` + Windows ``'win32'`` + Windows/Cygwin ``'cygwin'`` + macOS ``'darwin'`` + ================ =========================== + + .. versionchanged:: 3.3 + On Linux, :attr:`sys.platform` doesn't contain the major version anymore. + It is always ``'linux'``, instead of ``'linux2'`` or ``'linux3'``. Since + older Python versions include the version number, it is recommended to + always use the ``startswith`` idiom presented above. + + .. versionchanged:: 3.8 + On AIX, :attr:`sys.platform` doesn't contain the major version anymore. + It is always ``'aix'``, instead of ``'aix5'`` or ``'aix7'``. Since + older Python versions include the version number, it is recommended to + always use the ``startswith`` idiom presented above. + + .. seealso:: + + :attr:`os.name` has a coarser granularity. :func:`os.uname` gives + system-dependent version information. + + The :mod:`platform` module provides detailed checks for the + system's identity. + + +.. data:: platlibdir + + Name of the platform-specific library directory. It is used to build the + path of platform-specific dynamic libraries and the path of the standard + library. + + It is equal to ``"lib"`` on most platforms. On Fedora and SuSE, it is equal + to ``"lib64"`` on 64-bit platforms which gives the following ``sys.path`` + paths (where ``X.Y`` is the Python ``major.minor`` version): + + * ``/usr/lib64/pythonX.Y/``: + Standard library (like ``os.py`` of the :mod:`os` module) + * ``/usr/lib64/pythonX.Y/lib-dynload/``: + C extension modules of the standard library (like the :mod:`errno` module, + the exact filename is platform specific) + * ``/usr/lib/pythonX.Y/site-packages`` (always use ``lib``, not + :data:`sys.platlibdir`): Third-party modules + + .. versionadded:: 3.9 + + +.. data:: prefix + + A string giving the site-specific directory prefix where the platform + independent Python files are installed; by default, this is the string + ``'/usr/local'``. This can be set at build time with the ``--prefix`` + argument to the :program:`configure` script. The main collection of Python + library modules is installed in the directory :file:`{prefix}/lib/python{X.Y}` + while the platform independent header files (all except :file:`pyconfig.h`) are + stored in :file:`{prefix}/include/python{X.Y}`, where *X.Y* is the version + number of Python, for example ``3.2``. + + .. note:: If a :ref:`virtual environment ` is in effect, this + value will be changed in ``site.py`` to point to the virtual + environment. The value for the Python installation will still be + available, via :data:`base_prefix`. + + +.. data:: ps1 + ps2 + + .. index:: + single: interpreter prompts + single: prompts, interpreter + single: >>>; interpreter prompt + single: ...; interpreter prompt + + Strings specifying the primary and secondary prompt of the interpreter. These + are only defined if the interpreter is in interactive mode. Their initial + values in this case are ``'>>> '`` and ``'... '``. If a non-string object is + assigned to either variable, its :func:`str` is re-evaluated each time the + interpreter prepares to read a new interactive command; this can be used to + implement a dynamic prompt. + + +.. function:: setdlopenflags(n) + + Set the flags used by the interpreter for :c:func:`dlopen` calls, such as when + the interpreter loads extension modules. Among other things, this will enable a + lazy resolving of symbols when importing a module, if called as + ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as + ``sys.setdlopenflags(os.RTLD_GLOBAL)``. Symbolic names for the flag values + can be found in the :mod:`os` module (``RTLD_xxx`` constants, e.g. + :data:`os.RTLD_LAZY`). + + .. availability:: Unix. + +.. function:: setprofile(profilefunc) + + .. index:: + single: profile function + single: profiler + + Set the system's profile function, which allows you to implement a Python source + code profiler in Python. See chapter :ref:`profile` for more information on the + Python profiler. The system's profile function is called similarly to the + system's trace function (see :func:`settrace`), but it is called with different events, + for example it isn't called for each executed line of code (only on call and return, + but the return event is reported even when an exception has been set). The function is + thread-specific, but there is no way for the profiler to know about context switches between + threads, so it does not make sense to use this in the presence of multiple threads. Also, + its return value is not used, so it can simply return ``None``. Error in the profile + function will cause itself unset. + + Profile functions should have three arguments: *frame*, *event*, and + *arg*. *frame* is the current stack frame. *event* is a string: ``'call'``, + ``'return'``, ``'c_call'``, ``'c_return'``, or ``'c_exception'``. *arg* depends + on the event type. + + .. audit-event:: sys.setprofile "" sys.setprofile + + The events have the following meaning: + + ``'call'`` + A function is called (or some other code block entered). The + profile function is called; *arg* is ``None``. + + ``'return'`` + A function (or other code block) is about to return. The profile + function is called; *arg* is the value that will be returned, or ``None`` + if the event is caused by an exception being raised. + + ``'c_call'`` + A C function is about to be called. This may be an extension function or + a built-in. *arg* is the C function object. + + ``'c_return'`` + A C function has returned. *arg* is the C function object. + + ``'c_exception'`` + A C function has raised an exception. *arg* is the C function object. + +.. function:: setrecursionlimit(limit) + + Set the maximum depth of the Python interpreter stack to *limit*. This limit + prevents infinite recursion from causing an overflow of the C stack and crashing + Python. + + The highest possible limit is platform-dependent. A user may need to set the + limit higher when they have a program that requires deep recursion and a platform + that supports a higher limit. This should be done with care, because a too-high + limit can lead to a crash. + + If the new limit is too low at the current recursion depth, a + :exc:`RecursionError` exception is raised. + + .. versionchanged:: 3.5.1 + A :exc:`RecursionError` exception is now raised if the new limit is too + low at the current recursion depth. + + +.. function:: setswitchinterval(interval) + + Set the interpreter's thread switch interval (in seconds). This floating-point + value determines the ideal duration of the "timeslices" allocated to + concurrently running Python threads. Please note that the actual value + can be higher, especially if long-running internal functions or methods + are used. Also, which thread becomes scheduled at the end of the interval + is the operating system's decision. The interpreter doesn't have its + own scheduler. + + .. versionadded:: 3.2 + + +.. function:: settrace(tracefunc) + + .. index:: + single: trace function + single: debugger + + Set the system's trace function, which allows you to implement a Python + source code debugger in Python. The function is thread-specific; for a + debugger to support multiple threads, it must register a trace function using + :func:`settrace` for each thread being debugged or use :func:`threading.settrace`. + + Trace functions should have three arguments: *frame*, *event*, and + *arg*. *frame* is the current stack frame. *event* is a string: ``'call'``, + ``'line'``, ``'return'``, ``'exception'`` or ``'opcode'``. *arg* depends on + the event type. + + The trace function is invoked (with *event* set to ``'call'``) whenever a new + local scope is entered; it should return a reference to a local trace + function to be used for the new scope, or ``None`` if the scope shouldn't be + traced. + + The local trace function should return a reference to itself (or to another + function for further tracing in that scope), or ``None`` to turn off tracing + in that scope. + + If there is any error occurred in the trace function, it will be unset, just + like ``settrace(None)`` is called. + + The events have the following meaning: + + ``'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. + + ``'line'`` + The interpreter is about to execute a new line of code or re-execute the + condition of a loop. The local trace function is called; *arg* is + ``None``; the return value specifies the new local trace function. See + :file:`Objects/lnotab_notes.txt` for a detailed explanation of how this + works. + Per-line events may be disabled for a frame by setting + :attr:`f_trace_lines` to :const:`False` on that frame. + + ``'return'`` + A function (or other code block) is about to return. The local trace + function is called; *arg* is the value that will be returned, or ``None`` + if the event is caused by an exception being raised. The trace function's + return value is ignored. + + ``'exception'`` + An exception has occurred. The local trace function is called; *arg* is a + tuple ``(exception, value, traceback)``; the return value specifies the + new local trace function. + + ``'opcode'`` + The interpreter is about to execute a new opcode (see :mod:`dis` for + opcode details). The local trace function is called; *arg* is + ``None``; the return value specifies the new local trace function. + Per-opcode events are not emitted by default: they must be explicitly + requested by setting :attr:`f_trace_opcodes` to :const:`True` on the + frame. + + Note that as an exception is propagated down the chain of callers, an + ``'exception'`` event is generated at each level. + + For more fine-grained usage, it's possible to set a trace function by + assigning ``frame.f_trace = tracefunc`` explicitly, rather than relying on + it being set indirectly via the return value from an already installed + trace function. This is also required for activating the trace function on + the current frame, which :func:`settrace` doesn't do. Note that in order + for this to work, a global tracing function must have been installed + with :func:`settrace` in order to enable the runtime tracing machinery, + but it doesn't need to be the same tracing function (e.g. it could be a + low overhead tracing function that simply returns ``None`` to disable + itself immediately on each frame). + + For more information on code and frame objects, refer to :ref:`types`. + + .. audit-event:: sys.settrace "" sys.settrace + + .. impl-detail:: + + The :func:`settrace` function is intended only for implementing debuggers, + profilers, coverage tools and the like. Its behavior is part of the + implementation platform, rather than part of the language definition, and + thus may not be available in all Python implementations. + + .. versionchanged:: 3.7 + + ``'opcode'`` event type added; :attr:`f_trace_lines` and + :attr:`f_trace_opcodes` attributes added to frames + +.. function:: set_asyncgen_hooks(firstiter, finalizer) + + Accepts two optional keyword arguments which are callables that accept an + :term:`asynchronous generator iterator` as an argument. The *firstiter* + callable will be called when an asynchronous generator is iterated for the + first time. The *finalizer* will be called when an asynchronous generator + is about to be garbage collected. + + .. audit-event:: sys.set_asyncgen_hooks_firstiter "" sys.set_asyncgen_hooks + + .. audit-event:: sys.set_asyncgen_hooks_finalizer "" sys.set_asyncgen_hooks + + Two auditing events are raised because the underlying API consists of two + calls, each of which must raise its own event. + + .. versionadded:: 3.6 + See :pep:`525` for more details, and for a reference example of a + *finalizer* method see the implementation of + ``asyncio.Loop.shutdown_asyncgens`` in + :source:`Lib/asyncio/base_events.py` + + .. note:: + This function has been added on a provisional basis (see :pep:`411` + for details.) + +.. function:: set_coroutine_origin_tracking_depth(depth) + + Allows enabling or disabling coroutine origin tracking. When + enabled, the ``cr_origin`` attribute on coroutine objects will + contain a tuple of (filename, line number, function name) tuples + describing the traceback where the coroutine object was created, + with the most recent call first. When disabled, ``cr_origin`` will + be None. + + To enable, pass a *depth* value greater than zero; this sets the + number of frames whose information will be captured. To disable, + pass set *depth* to zero. + + This setting is thread-specific. + + .. versionadded:: 3.7 + + .. note:: + This function has been added on a provisional basis (see :pep:`411` + for details.) Use it only for debugging purposes. + +.. function:: _enablelegacywindowsfsencoding() + + Changes the default filesystem encoding and errors mode to 'mbcs' and + 'replace' respectively, for consistency with versions of Python prior to 3.6. + + This is equivalent to defining the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` + environment variable before launching Python. + + .. availability:: Windows. + + .. versionadded:: 3.6 + See :pep:`529` for more details. + +.. data:: stdin + stdout + stderr + + :term:`File objects ` used by the interpreter for standard + input, output and errors: + + * ``stdin`` is used for all interactive input (including calls to + :func:`input`); + * ``stdout`` is used for the output of :func:`print` and :term:`expression` + statements and for the prompts of :func:`input`; + * The interpreter's own prompts and its error messages go to ``stderr``. + + These streams are regular :term:`text files ` like those + returned by the :func:`open` function. Their parameters are chosen as + follows: + + * The character encoding is platform-dependent. Non-Windows + platforms use the locale encoding (see + :meth:`locale.getpreferredencoding()`). + + On Windows, UTF-8 is used for the console device. Non-character + devices such as disk files and pipes use the system locale + encoding (i.e. the ANSI codepage). Non-console character + devices such as NUL (i.e. where ``isatty()`` returns ``True``) use the + value of the console input and output codepages at startup, + respectively for stdin and stdout/stderr. This defaults to the + system locale encoding if the process is not initially attached + to a console. + + The special behaviour of the console can be overridden + by setting the environment variable PYTHONLEGACYWINDOWSSTDIO + before starting Python. In that case, the console codepages are + used as for any other character device. + + Under all platforms, you can override the character encoding by + setting the :envvar:`PYTHONIOENCODING` environment variable before + starting Python or by using the new :option:`-X` ``utf8`` command + line option and :envvar:`PYTHONUTF8` environment variable. However, + for the Windows console, this only applies when + :envvar:`PYTHONLEGACYWINDOWSSTDIO` is also set. + + * When interactive, the ``stdout`` stream is line-buffered. Otherwise, + it is block-buffered like regular text files. The ``stderr`` stream + is line-buffered in both cases. You can make both streams unbuffered + by passing the :option:`-u` command-line option or setting the + :envvar:`PYTHONUNBUFFERED` environment variable. + + .. versionchanged:: 3.9 + Non-interactive ``stderr`` is now line-buffered instead of fully + buffered. + + .. note:: + + To write or read binary data from/to the standard streams, use the + underlying binary :data:`~io.TextIOBase.buffer` object. For example, to + write bytes to :data:`stdout`, use ``sys.stdout.buffer.write(b'abc')``. + + However, if you are writing a library (and do not control in which + context its code will be executed), be aware that the standard streams + may be replaced with file-like objects like :class:`io.StringIO` which + do not support the :attr:`~io.BufferedIOBase.buffer` attribute. + + +.. data:: __stdin__ + __stdout__ + __stderr__ + + These objects contain the original values of ``stdin``, ``stderr`` and + ``stdout`` at the start of the program. They are used during finalization, + and could be useful to print to the actual standard stream no matter if the + ``sys.std*`` object has been redirected. + + It can also be used to restore the actual files to known working file objects + in case they have been overwritten with a broken object. However, the + preferred way to do this is to explicitly save the previous stream before + replacing it, and restore the saved object. + + .. note:: + Under some conditions ``stdin``, ``stdout`` and ``stderr`` as well as the + original values ``__stdin__``, ``__stdout__`` and ``__stderr__`` can be + ``None``. It is usually the case for Windows GUI apps that aren't connected + to a console and Python apps started with :program:`pythonw`. + + +.. data:: thread_info + + A :term:`named tuple` holding information about the thread + implementation. + + .. tabularcolumns:: |l|p{0.7\linewidth}| + + +------------------+---------------------------------------------------------+ + | Attribute | Explanation | + +==================+=========================================================+ + | :const:`name` | Name of the thread implementation: | + | | | + | | * ``'nt'``: Windows threads | + | | * ``'pthread'``: POSIX threads | + | | * ``'solaris'``: Solaris threads | + +------------------+---------------------------------------------------------+ + | :const:`lock` | Name of the lock implementation: | + | | | + | | * ``'semaphore'``: a lock uses a semaphore | + | | * ``'mutex+cond'``: a lock uses a mutex | + | | and a condition variable | + | | * ``None`` if this information is unknown | + +------------------+---------------------------------------------------------+ + | :const:`version` | Name and version of the thread library. It is a string, | + | | or ``None`` if this information is unknown. | + +------------------+---------------------------------------------------------+ + + .. versionadded:: 3.3 + + +.. data:: tracebacklimit + + When this variable is set to an integer value, it determines the maximum number + of levels of traceback information printed when an unhandled exception occurs. + The default is ``1000``. When set to ``0`` or less, all traceback information + is suppressed and only the exception type and value are printed. + + +.. function:: unraisablehook(unraisable, /) + + Handle an unraisable exception. + + Called when an exception has occurred but there is no way for Python to + handle it. For example, when a destructor raises an exception or during + garbage collection (:func:`gc.collect`). + + The *unraisable* argument has the following attributes: + + * *exc_type*: Exception type. + * *exc_value*: Exception value, can be ``None``. + * *exc_traceback*: Exception traceback, can be ``None``. + * *err_msg*: Error message, can be ``None``. + * *object*: Object causing the exception, can be ``None``. + + The default hook formats *err_msg* and *object* as: + ``f'{err_msg}: {object!r}'``; use "Exception ignored in" error message + if *err_msg* is ``None``. + + :func:`sys.unraisablehook` can be overridden to control how unraisable + exceptions are handled. + + Storing *exc_value* using a custom hook can create a reference cycle. It + should be cleared explicitly to break the reference cycle when the + exception is no longer needed. + + Storing *object* using a custom hook can resurrect it if it is set to an + object which is being finalized. Avoid storing *object* after the custom + hook completes to avoid resurrecting objects. + + See also :func:`excepthook` which handles uncaught exceptions. + + .. audit-event:: sys.unraisablehook hook,unraisable sys.unraisablehook + + Raise an auditing event ``sys.unraisablehook`` with arguments + ``hook``, ``unraisable`` when an exception that cannot be handled occurs. + The ``unraisable`` object is the same as what will be passed to the hook. + If no hook has been set, ``hook`` may be ``None``. + + .. versionadded:: 3.8 + +.. data:: version + + A string containing the version number of the Python interpreter plus additional + information on the build number and compiler used. This string is displayed + when the interactive interpreter is started. Do not extract version information + out of it, rather, use :data:`version_info` and the functions provided by the + :mod:`platform` module. + + +.. data:: api_version + + The C API version for this interpreter. Programmers may find this useful when + debugging version conflicts between Python and extension modules. + + +.. data:: version_info + + A tuple containing the five components of the version number: *major*, *minor*, + *micro*, *releaselevel*, and *serial*. All values except *releaselevel* are + integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or + ``'final'``. The ``version_info`` value corresponding to the Python version 2.0 + is ``(2, 0, 0, 'final', 0)``. The components can also be accessed by name, + so ``sys.version_info[0]`` is equivalent to ``sys.version_info.major`` + and so on. + + .. versionchanged:: 3.1 + Added named component attributes. + +.. data:: warnoptions + + This is an implementation detail of the warnings framework; do not modify this + value. Refer to the :mod:`warnings` module for more information on the warnings + framework. + + +.. data:: winver + + The version number used to form registry keys on Windows platforms. This is + stored as string resource 1000 in the Python DLL. The value is normally the + first three characters of :const:`version`. It is provided in the :mod:`sys` + module for informational purposes; modifying this value has no effect on the + registry keys used by Python. + + .. availability:: Windows. + + +.. data:: _xoptions + + A dictionary of the various implementation-specific flags passed through + the :option:`-X` command-line option. Option names are either mapped to + their values, if given explicitly, or to :const:`True`. Example: + + .. code-block:: shell-session + + $ ./python -Xa=b -Xc + Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50) + [GCC 4.4.3] on linux2 + Type "help", "copyright", "credits" or "license" for more information. + >>> import sys + >>> sys._xoptions + {'a': 'b', 'c': True} + + .. impl-detail:: + + This is a CPython-specific way of accessing options passed through + :option:`-X`. Other implementations may export them through other + means, or not at all. + + .. versionadded:: 3.2 + + +.. rubric:: Citations + +.. [C99] ISO/IEC 9899:1999. "Programming languages -- C." A public draft of this standard is available at http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf\ . diff --git a/cpython_2/environment/repo/Doc/library/sysconfig.rst b/cpython_2/environment/repo/Doc/library/sysconfig.rst new file mode 100644 index 0000000000000000000000000000000000000000..b5a1da80c686d40728dddc9c7ad2355c56342c7b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/sysconfig.rst @@ -0,0 +1,258 @@ +:mod:`sysconfig` --- Provide access to Python's configuration information +========================================================================= + +.. module:: sysconfig + :synopsis: Python's configuration information + +.. moduleauthor:: Tarek Ziadé +.. sectionauthor:: Tarek Ziadé + +.. versionadded:: 3.2 + +**Source code:** :source:`Lib/sysconfig.py` + +.. index:: + single: configuration information + +-------------- + +The :mod:`sysconfig` module provides access to Python's configuration +information like the list of installation paths and the configuration variables +relevant for the current platform. + +Configuration variables +----------------------- + +A Python distribution contains a :file:`Makefile` and a :file:`pyconfig.h` +header file that are necessary to build both the Python binary itself and +third-party C extensions compiled using :mod:`distutils`. + +:mod:`sysconfig` puts all variables found in these files in a dictionary that +can be accessed using :func:`get_config_vars` or :func:`get_config_var`. + +Notice that on Windows, it's a much smaller set. + +.. function:: get_config_vars(\*args) + + With no arguments, return a dictionary of all configuration variables + relevant for the current platform. + + With arguments, return a list of values that result from looking up each + argument in the configuration variable dictionary. + + For each argument, if the value is not found, return ``None``. + + +.. function:: get_config_var(name) + + Return the value of a single variable *name*. Equivalent to + ``get_config_vars().get(name)``. + + If *name* is not found, return ``None``. + +Example of usage:: + + >>> import sysconfig + >>> sysconfig.get_config_var('Py_ENABLE_SHARED') + 0 + >>> sysconfig.get_config_var('LIBDIR') + '/usr/local/lib' + >>> sysconfig.get_config_vars('AR', 'CXX') + ['ar', 'g++'] + + +Installation paths +------------------ + +Python uses an installation scheme that differs depending on the platform and on +the installation options. These schemes are stored in :mod:`sysconfig` under +unique identifiers based on the value returned by :const:`os.name`. + +Every new component that is installed using :mod:`distutils` or a +Distutils-based system will follow the same scheme to copy its file in the right +places. + +Python currently supports seven schemes: + +- *posix_prefix*: scheme for Posix platforms like Linux or Mac OS X. This is + the default scheme used when Python or a component is installed. +- *posix_home*: scheme for Posix platforms used when a *home* option is used + upon installation. This scheme is used when a component is installed through + Distutils with a specific home prefix. +- *posix_user*: scheme for Posix platforms used when a component is installed + through Distutils and the *user* option is used. This scheme defines paths + located under the user home directory. +- *nt*: scheme for NT platforms like Windows. +- *nt_user*: scheme for NT platforms, when the *user* option is used. + +Each scheme is itself composed of a series of paths and each path has a unique +identifier. Python currently uses eight paths: + +- *stdlib*: directory containing the standard Python library files that are not + platform-specific. +- *platstdlib*: directory containing the standard Python library files that are + platform-specific. +- *platlib*: directory for site-specific, platform-specific files. +- *purelib*: directory for site-specific, non-platform-specific files. +- *include*: directory for non-platform-specific header files. +- *platinclude*: directory for platform-specific header files. +- *scripts*: directory for script files. +- *data*: directory for data files. + +:mod:`sysconfig` provides some functions to determine these paths. + +.. function:: get_scheme_names() + + Return a tuple containing all schemes currently supported in + :mod:`sysconfig`. + + +.. function:: get_path_names() + + Return a tuple containing all path names currently supported in + :mod:`sysconfig`. + + +.. function:: get_path(name, [scheme, [vars, [expand]]]) + + Return an installation path corresponding to the path *name*, from the + install scheme named *scheme*. + + *name* has to be a value from the list returned by :func:`get_path_names`. + + :mod:`sysconfig` stores installation paths corresponding to each path name, + for each platform, with variables to be expanded. For instance the *stdlib* + path for the *nt* scheme is: ``{base}/Lib``. + + :func:`get_path` will use the variables returned by :func:`get_config_vars` + to expand the path. All variables have default values for each platform so + one may call this function and get the default value. + + If *scheme* is provided, it must be a value from the list returned by + :func:`get_scheme_names`. Otherwise, the default scheme for the current + platform is used. + + If *vars* is provided, it must be a dictionary of variables that will update + the dictionary return by :func:`get_config_vars`. + + If *expand* is set to ``False``, the path will not be expanded using the + variables. + + If *name* is not found, return ``None``. + + +.. function:: get_paths([scheme, [vars, [expand]]]) + + Return a dictionary containing all installation paths corresponding to an + installation scheme. See :func:`get_path` for more information. + + If *scheme* is not provided, will use the default scheme for the current + platform. + + If *vars* is provided, it must be a dictionary of variables that will + update the dictionary used to expand the paths. + + If *expand* is set to false, the paths will not be expanded. + + If *scheme* is not an existing scheme, :func:`get_paths` will raise a + :exc:`KeyError`. + + +Other functions +--------------- + +.. function:: get_python_version() + + Return the ``MAJOR.MINOR`` Python version number as a string. Similar to + ``'%d.%d' % sys.version_info[:2]``. + + +.. function:: get_platform() + + Return a string that identifies the current platform. + + This is used mainly to distinguish platform-specific build directories and + platform-specific built distributions. Typically includes the OS name and + version and the architecture (as supplied by 'os.uname()'), although the + exact information included depends on the OS; e.g., on Linux, the kernel + version isn't particularly important. + + Examples of returned values: + + - linux-i586 + - linux-alpha (?) + - solaris-2.6-sun4u + + Windows will return one of: + + - win-amd64 (64bit Windows on AMD64, aka x86_64, Intel64, and EM64T) + - win32 (all others - specifically, sys.platform is returned) + + Mac OS X can return: + + - macosx-10.6-ppc + - macosx-10.4-ppc64 + - macosx-10.3-i386 + - macosx-10.4-fat + + For other non-POSIX platforms, currently just returns :data:`sys.platform`. + + +.. function:: is_python_build() + + Return ``True`` if the running Python interpreter was built from source and + is being run from its built location, and not from a location resulting from + e.g. running ``make install`` or installing via a binary installer. + + +.. function:: parse_config_h(fp[, vars]) + + Parse a :file:`config.h`\-style file. + + *fp* is a file-like object pointing to the :file:`config.h`\-like file. + + A dictionary containing name/value pairs is returned. If an optional + dictionary is passed in as the second argument, it is used instead of a new + dictionary, and updated with the values read in the file. + + +.. function:: get_config_h_filename() + + Return the path of :file:`pyconfig.h`. + +.. function:: get_makefile_filename() + + Return the path of :file:`Makefile`. + +Using :mod:`sysconfig` as a script +---------------------------------- + +You can use :mod:`sysconfig` as a script with Python's *-m* option: + +.. code-block:: shell-session + + $ python -m sysconfig + Platform: "macosx-10.4-i386" + Python version: "3.2" + Current installation scheme: "posix_prefix" + + Paths: + data = "/usr/local" + include = "/Users/tarek/Dev/svn.python.org/py3k/Include" + platinclude = "." + platlib = "/usr/local/lib/python3.2/site-packages" + platstdlib = "/usr/local/lib/python3.2" + purelib = "/usr/local/lib/python3.2/site-packages" + scripts = "/usr/local/bin" + stdlib = "/usr/local/lib/python3.2" + + Variables: + AC_APPLE_UNIVERSAL_BUILD = "0" + AIX_GENUINE_CPLUSPLUS = "0" + AR = "ar" + ARFLAGS = "rc" + ... + +This call will print in the standard output the information returned by +:func:`get_platform`, :func:`get_python_version`, :func:`get_path` and +:func:`get_config_vars`. diff --git a/cpython_2/environment/repo/Doc/library/syslog.rst b/cpython_2/environment/repo/Doc/library/syslog.rst new file mode 100644 index 0000000000000000000000000000000000000000..d264a3340c98b01fcc6f568025760ad70140b91d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/syslog.rst @@ -0,0 +1,120 @@ +:mod:`syslog` --- Unix syslog library routines +============================================== + +.. module:: syslog + :platform: Unix + :synopsis: An interface to the Unix syslog library routines. + +-------------- + +This module provides an interface to the Unix ``syslog`` library routines. +Refer to the Unix manual pages for a detailed description of the ``syslog`` +facility. + +This module wraps the system ``syslog`` family of routines. A pure Python +library that can speak to a syslog server is available in the +:mod:`logging.handlers` module as :class:`SysLogHandler`. + +The module defines the following functions: + + +.. function:: syslog(message) + syslog(priority, message) + + Send the string *message* to the system logger. A trailing newline is added + if necessary. Each message is tagged with a priority composed of a + *facility* and a *level*. The optional *priority* argument, which defaults + to :const:`LOG_INFO`, determines the message priority. If the facility is + not encoded in *priority* using logical-or (``LOG_INFO | LOG_USER``), the + value given in the :func:`openlog` call is used. + + If :func:`openlog` has not been called prior to the call to :func:`syslog`, + ``openlog()`` will be called with no arguments. + + .. audit-event:: syslog.syslog priority,message syslog.syslog + + +.. function:: openlog([ident[, logoption[, facility]]]) + + Logging options of subsequent :func:`syslog` calls can be set by calling + :func:`openlog`. :func:`syslog` will call :func:`openlog` with no arguments + if the log is not currently open. + + The optional *ident* keyword argument is a string which is prepended to every + message, and defaults to ``sys.argv[0]`` with leading path components + stripped. The optional *logoption* keyword argument (default is 0) is a bit + field -- see below for possible values to combine. The optional *facility* + keyword argument (default is :const:`LOG_USER`) sets the default facility for + messages which do not have a facility explicitly encoded. + + .. audit-event:: syslog.openlog ident,logoption,facility syslog.openlog + + .. versionchanged:: 3.2 + In previous versions, keyword arguments were not allowed, and *ident* was + required. The default for *ident* was dependent on the system libraries, + and often was ``python`` instead of the name of the Python program file. + + +.. function:: closelog() + + Reset the syslog module values and call the system library ``closelog()``. + + This causes the module to behave as it does when initially imported. For + example, :func:`openlog` will be called on the first :func:`syslog` call (if + :func:`openlog` hasn't already been called), and *ident* and other + :func:`openlog` parameters are reset to defaults. + + .. audit-event:: syslog.closelog "" syslog.closelog + + +.. function:: setlogmask(maskpri) + + Set the priority mask to *maskpri* and return the previous mask value. Calls + to :func:`syslog` with a priority level not set in *maskpri* are ignored. + The default is to log all priorities. The function ``LOG_MASK(pri)`` + calculates the mask for the individual priority *pri*. The function + ``LOG_UPTO(pri)`` calculates the mask for all priorities up to and including + *pri*. + + .. audit-event:: syslog.setlogmask maskpri syslog.setlogmask + +The module defines the following constants: + +Priority levels (high to low): + :const:`LOG_EMERG`, :const:`LOG_ALERT`, :const:`LOG_CRIT`, :const:`LOG_ERR`, + :const:`LOG_WARNING`, :const:`LOG_NOTICE`, :const:`LOG_INFO`, + :const:`LOG_DEBUG`. + +Facilities: + :const:`LOG_KERN`, :const:`LOG_USER`, :const:`LOG_MAIL`, :const:`LOG_DAEMON`, + :const:`LOG_AUTH`, :const:`LOG_LPR`, :const:`LOG_NEWS`, :const:`LOG_UUCP`, + :const:`LOG_CRON`, :const:`LOG_SYSLOG`, :const:`LOG_LOCAL0` to + :const:`LOG_LOCAL7`, and, if defined in ````, + :const:`LOG_AUTHPRIV`. + +Log options: + :const:`LOG_PID`, :const:`LOG_CONS`, :const:`LOG_NDELAY`, and, if defined + in ````, :const:`LOG_ODELAY`, :const:`LOG_NOWAIT`, and + :const:`LOG_PERROR`. + + +Examples +-------- + +Simple example +~~~~~~~~~~~~~~ + +A simple set of examples:: + + import syslog + + syslog.syslog('Processing started') + if error: + syslog.syslog(syslog.LOG_ERR, 'Processing started') + +An example of setting some log options, these would include the process ID in +logged messages, and write the messages to the destination facility used for +mail logging:: + + syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL) + syslog.syslog('E-mail processing initiated...') diff --git a/cpython_2/environment/repo/Doc/library/tabnanny.rst b/cpython_2/environment/repo/Doc/library/tabnanny.rst new file mode 100644 index 0000000000000000000000000000000000000000..dfe688a2f93e0cbc0ce59eeb83664ea2b96c4cfe --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tabnanny.rst @@ -0,0 +1,67 @@ +:mod:`tabnanny` --- Detection of ambiguous indentation +====================================================== + +.. module:: tabnanny + :synopsis: Tool for detecting white space related problems in Python + source files in a directory tree. + +.. moduleauthor:: Tim Peters +.. sectionauthor:: Peter Funk + +.. rudimentary documentation based on module comments + +**Source code:** :source:`Lib/tabnanny.py` + +-------------- + +For the time being this module is intended to be called as a script. However it +is possible to import it into an IDE and use the function :func:`check` +described below. + +.. note:: + + The API provided by this module is likely to change in future releases; such + changes may not be backward compatible. + + +.. function:: check(file_or_dir) + + If *file_or_dir* is a directory and not a symbolic link, then recursively + descend the directory tree named by *file_or_dir*, checking all :file:`.py` + files along the way. If *file_or_dir* is an ordinary Python source file, it + is checked for whitespace related problems. The diagnostic messages are + written to standard output using the :func:`print` function. + + +.. data:: verbose + + Flag indicating whether to print verbose messages. This is incremented by the + ``-v`` option if called as a script. + + +.. data:: filename_only + + Flag indicating whether to print only the filenames of files containing + whitespace related problems. This is set to true by the ``-q`` option if called + as a script. + + +.. exception:: NannyNag + + Raised by :func:`process_tokens` if detecting an ambiguous indent. Captured and + handled in :func:`check`. + + +.. function:: process_tokens(tokens) + + This function is used by :func:`check` to process tokens generated by the + :mod:`tokenize` module. + +.. XXX document errprint, format_witnesses, Whitespace, check_equal, indents, + reset_globals + + +.. seealso:: + + Module :mod:`tokenize` + Lexical scanner for Python source code. diff --git a/cpython_2/environment/repo/Doc/library/tarfile.rst b/cpython_2/environment/repo/Doc/library/tarfile.rst new file mode 100644 index 0000000000000000000000000000000000000000..459e4ad991d9dcf2ac818b4044a90f9e2965ca01 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tarfile.rst @@ -0,0 +1,888 @@ +:mod:`tarfile` --- Read and write tar archive files +=================================================== + +.. module:: tarfile + :synopsis: Read and write tar-format archive files. + +.. moduleauthor:: Lars Gustäbel +.. sectionauthor:: Lars Gustäbel + +**Source code:** :source:`Lib/tarfile.py` + +-------------- + +The :mod:`tarfile` module makes it possible to read and write tar +archives, including those using gzip, bz2 and lzma compression. +Use the :mod:`zipfile` module to read or write :file:`.zip` files, or the +higher-level functions in :ref:`shutil `. + +Some facts and figures: + +* reads and writes :mod:`gzip`, :mod:`bz2` and :mod:`lzma` compressed archives + if the respective modules are available. + +* read/write support for the POSIX.1-1988 (ustar) format. + +* read/write support for the GNU tar format including *longname* and *longlink* + extensions, read-only support for all variants of the *sparse* extension + including restoration of sparse files. + +* read/write support for the POSIX.1-2001 (pax) format. + +* handles directories, regular files, hardlinks, symbolic links, fifos, + character devices and block devices and is able to acquire and restore file + information like timestamp, access permissions and owner. + +.. versionchanged:: 3.3 + Added support for :mod:`lzma` compression. + + +.. function:: open(name=None, mode='r', fileobj=None, bufsize=10240, \*\*kwargs) + + Return a :class:`TarFile` object for the pathname *name*. For detailed + information on :class:`TarFile` objects and the keyword arguments that are + allowed, see :ref:`tarfile-objects`. + + *mode* has to be a string of the form ``'filemode[:compression]'``, it defaults + to ``'r'``. Here is a full list of mode combinations: + + +------------------+---------------------------------------------+ + | mode | action | + +==================+=============================================+ + | ``'r' or 'r:*'`` | Open for reading with transparent | + | | compression (recommended). | + +------------------+---------------------------------------------+ + | ``'r:'`` | Open for reading exclusively without | + | | compression. | + +------------------+---------------------------------------------+ + | ``'r:gz'`` | Open for reading with gzip compression. | + +------------------+---------------------------------------------+ + | ``'r:bz2'`` | Open for reading with bzip2 compression. | + +------------------+---------------------------------------------+ + | ``'r:xz'`` | Open for reading with lzma compression. | + +------------------+---------------------------------------------+ + | ``'x'`` or | Create a tarfile exclusively without | + | ``'x:'`` | compression. | + | | Raise an :exc:`FileExistsError` exception | + | | if it already exists. | + +------------------+---------------------------------------------+ + | ``'x:gz'`` | Create a tarfile with gzip compression. | + | | Raise an :exc:`FileExistsError` exception | + | | if it already exists. | + +------------------+---------------------------------------------+ + | ``'x:bz2'`` | Create a tarfile with bzip2 compression. | + | | Raise an :exc:`FileExistsError` exception | + | | if it already exists. | + +------------------+---------------------------------------------+ + | ``'x:xz'`` | Create a tarfile with lzma compression. | + | | Raise an :exc:`FileExistsError` exception | + | | if it already exists. | + +------------------+---------------------------------------------+ + | ``'a' or 'a:'`` | Open for appending with no compression. The | + | | file is created if it does not exist. | + +------------------+---------------------------------------------+ + | ``'w' or 'w:'`` | Open for uncompressed writing. | + +------------------+---------------------------------------------+ + | ``'w:gz'`` | Open for gzip compressed writing. | + +------------------+---------------------------------------------+ + | ``'w:bz2'`` | Open for bzip2 compressed writing. | + +------------------+---------------------------------------------+ + | ``'w:xz'`` | Open for lzma compressed writing. | + +------------------+---------------------------------------------+ + + Note that ``'a:gz'``, ``'a:bz2'`` or ``'a:xz'`` is not possible. If *mode* + is not suitable to open a certain (compressed) file for reading, + :exc:`ReadError` is raised. Use *mode* ``'r'`` to avoid this. If a + compression method is not supported, :exc:`CompressionError` is raised. + + If *fileobj* is specified, it is used as an alternative to a :term:`file object` + opened in binary mode for *name*. It is supposed to be at position 0. + + For modes ``'w:gz'``, ``'r:gz'``, ``'w:bz2'``, ``'r:bz2'``, ``'x:gz'``, + ``'x:bz2'``, :func:`tarfile.open` accepts the keyword argument + *compresslevel* (default ``9``) to specify the compression level of the file. + + For special purposes, there is a second format for *mode*: + ``'filemode|[compression]'``. :func:`tarfile.open` will return a :class:`TarFile` + object that processes its data as a stream of blocks. No random seeking will + be done on the file. If given, *fileobj* may be any object that has a + :meth:`read` or :meth:`write` method (depending on the *mode*). *bufsize* + specifies the blocksize and defaults to ``20 * 512`` bytes. Use this variant + in combination with e.g. ``sys.stdin``, a socket :term:`file object` or a tape + device. However, such a :class:`TarFile` object is limited in that it does + not allow random access, see :ref:`tar-examples`. The currently + possible modes: + + +-------------+--------------------------------------------+ + | Mode | Action | + +=============+============================================+ + | ``'r|*'`` | Open a *stream* of tar blocks for reading | + | | with transparent compression. | + +-------------+--------------------------------------------+ + | ``'r|'`` | Open a *stream* of uncompressed tar blocks | + | | for reading. | + +-------------+--------------------------------------------+ + | ``'r|gz'`` | Open a gzip compressed *stream* for | + | | reading. | + +-------------+--------------------------------------------+ + | ``'r|bz2'`` | Open a bzip2 compressed *stream* for | + | | reading. | + +-------------+--------------------------------------------+ + | ``'r|xz'`` | Open an lzma compressed *stream* for | + | | reading. | + +-------------+--------------------------------------------+ + | ``'w|'`` | Open an uncompressed *stream* for writing. | + +-------------+--------------------------------------------+ + | ``'w|gz'`` | Open a gzip compressed *stream* for | + | | writing. | + +-------------+--------------------------------------------+ + | ``'w|bz2'`` | Open a bzip2 compressed *stream* for | + | | writing. | + +-------------+--------------------------------------------+ + | ``'w|xz'`` | Open an lzma compressed *stream* for | + | | writing. | + +-------------+--------------------------------------------+ + + .. versionchanged:: 3.5 + The ``'x'`` (exclusive creation) mode was added. + + .. versionchanged:: 3.6 + The *name* parameter accepts a :term:`path-like object`. + + +.. class:: TarFile + + Class for reading and writing tar archives. Do not use this class directly: + use :func:`tarfile.open` instead. See :ref:`tarfile-objects`. + + +.. function:: is_tarfile(name) + + Return :const:`True` if *name* is a tar archive file, that the :mod:`tarfile` + module can read. *name* may be a :class:`str`, file, or file-like object. + + .. versionchanged:: 3.9 + Support for file and file-like objects. + + +The :mod:`tarfile` module defines the following exceptions: + + +.. exception:: TarError + + Base class for all :mod:`tarfile` exceptions. + + +.. exception:: ReadError + + Is raised when a tar archive is opened, that either cannot be handled by the + :mod:`tarfile` module or is somehow invalid. + + +.. exception:: CompressionError + + Is raised when a compression method is not supported or when the data cannot be + decoded properly. + + +.. exception:: StreamError + + Is raised for the limitations that are typical for stream-like :class:`TarFile` + objects. + + +.. exception:: ExtractError + + Is raised for *non-fatal* errors when using :meth:`TarFile.extract`, but only if + :attr:`TarFile.errorlevel`\ ``== 2``. + + +.. exception:: HeaderError + + Is raised by :meth:`TarInfo.frombuf` if the buffer it gets is invalid. + + +The following constants are available at the module level: + +.. data:: ENCODING + + The default character encoding: ``'utf-8'`` on Windows, the value returned by + :func:`sys.getfilesystemencoding` otherwise. + + +Each of the following constants defines a tar archive format that the +:mod:`tarfile` module is able to create. See section :ref:`tar-formats` for +details. + + +.. data:: USTAR_FORMAT + + POSIX.1-1988 (ustar) format. + + +.. data:: GNU_FORMAT + + GNU tar format. + + +.. data:: PAX_FORMAT + + POSIX.1-2001 (pax) format. + + +.. data:: DEFAULT_FORMAT + + The default format for creating archives. This is currently :const:`PAX_FORMAT`. + + .. versionchanged:: 3.8 + The default format for new archives was changed to + :const:`PAX_FORMAT` from :const:`GNU_FORMAT`. + + +.. seealso:: + + Module :mod:`zipfile` + Documentation of the :mod:`zipfile` standard module. + + :ref:`archiving-operations` + Documentation of the higher-level archiving facilities provided by the + standard :mod:`shutil` module. + + `GNU tar manual, Basic Tar Format `_ + Documentation for tar archive files, including GNU tar extensions. + + +.. _tarfile-objects: + +TarFile Objects +--------------- + +The :class:`TarFile` object provides an interface to a tar archive. A tar +archive is a sequence of blocks. An archive member (a stored file) is made up of +a header block followed by data blocks. It is possible to store a file in a tar +archive several times. Each archive member is represented by a :class:`TarInfo` +object, see :ref:`tarinfo-objects` for details. + +A :class:`TarFile` object can be used as a context manager in a :keyword:`with` +statement. It will automatically be closed when the block is completed. Please +note that in the event of an exception an archive opened for writing will not +be finalized; only the internally used file object will be closed. See the +:ref:`tar-examples` section for a use case. + +.. versionadded:: 3.2 + Added support for the context management protocol. + +.. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors='surrogateescape', pax_headers=None, debug=0, errorlevel=0) + + All following arguments are optional and can be accessed as instance attributes + as well. + + *name* is the pathname of the archive. *name* may be a :term:`path-like object`. + It can be omitted if *fileobj* is given. + In this case, the file object's :attr:`name` attribute is used if it exists. + + *mode* is either ``'r'`` to read from an existing archive, ``'a'`` to append + data to an existing file, ``'w'`` to create a new file overwriting an existing + one, or ``'x'`` to create a new file only if it does not already exist. + + If *fileobj* is given, it is used for reading or writing data. If it can be + determined, *mode* is overridden by *fileobj*'s mode. *fileobj* will be used + from position 0. + + .. note:: + + *fileobj* is not closed, when :class:`TarFile` is closed. + + *format* controls the archive format for writing. It must be one of the constants + :const:`USTAR_FORMAT`, :const:`GNU_FORMAT` or :const:`PAX_FORMAT` that are + defined at module level. When reading, format will be automatically detected, even + if different formats are present in a single archive. + + The *tarinfo* argument can be used to replace the default :class:`TarInfo` class + with a different one. + + If *dereference* is :const:`False`, add symbolic and hard links to the archive. If it + is :const:`True`, add the content of the target files to the archive. This has no + effect on systems that do not support symbolic links. + + If *ignore_zeros* is :const:`False`, treat an empty block as the end of the archive. + If it is :const:`True`, skip empty (and invalid) blocks and try to get as many members + as possible. This is only useful for reading concatenated or damaged archives. + + *debug* can be set from ``0`` (no debug messages) up to ``3`` (all debug + messages). The messages are written to ``sys.stderr``. + + If *errorlevel* is ``0``, all errors are ignored when using :meth:`TarFile.extract`. + Nevertheless, they appear as error messages in the debug output, when debugging + is enabled. If ``1``, all *fatal* errors are raised as :exc:`OSError` + exceptions. If ``2``, all *non-fatal* errors are raised as :exc:`TarError` + exceptions as well. + + The *encoding* and *errors* arguments define the character encoding to be + used for reading or writing the archive and how conversion errors are going + to be handled. The default settings will work for most users. + See section :ref:`tar-unicode` for in-depth information. + + The *pax_headers* argument is an optional dictionary of strings which + will be added as a pax global header if *format* is :const:`PAX_FORMAT`. + + .. versionchanged:: 3.2 + Use ``'surrogateescape'`` as the default for the *errors* argument. + + .. versionchanged:: 3.5 + The ``'x'`` (exclusive creation) mode was added. + + .. versionchanged:: 3.6 + The *name* parameter accepts a :term:`path-like object`. + + +.. classmethod:: TarFile.open(...) + + Alternative constructor. The :func:`tarfile.open` function is actually a + shortcut to this classmethod. + + +.. method:: TarFile.getmember(name) + + Return a :class:`TarInfo` object for member *name*. If *name* can not be found + in the archive, :exc:`KeyError` is raised. + + .. note:: + + If a member occurs more than once in the archive, its last occurrence is assumed + to be the most up-to-date version. + + +.. method:: TarFile.getmembers() + + Return the members of the archive as a list of :class:`TarInfo` objects. The + list has the same order as the members in the archive. + + +.. method:: TarFile.getnames() + + Return the members as a list of their names. It has the same order as the list + returned by :meth:`getmembers`. + + +.. method:: TarFile.list(verbose=True, *, members=None) + + Print a table of contents to ``sys.stdout``. If *verbose* is :const:`False`, + only the names of the members are printed. If it is :const:`True`, output + similar to that of :program:`ls -l` is produced. If optional *members* is + given, it must be a subset of the list returned by :meth:`getmembers`. + + .. versionchanged:: 3.5 + Added the *members* parameter. + + +.. method:: TarFile.next() + + Return the next member of the archive as a :class:`TarInfo` object, when + :class:`TarFile` is opened for reading. Return :const:`None` if there is no more + available. + + +.. method:: TarFile.extractall(path=".", members=None, *, numeric_owner=False) + + Extract all members from the archive to the current working directory or + directory *path*. If optional *members* is given, it must be a subset of the + list returned by :meth:`getmembers`. Directory information like owner, + modification time and permissions are set after all members have been extracted. + This is done to work around two problems: A directory's modification time is + reset each time a file is created in it. And, if a directory's permissions do + not allow writing, extracting files to it will fail. + + If *numeric_owner* is :const:`True`, the uid and gid numbers from the tarfile + are used to set the owner/group for the extracted files. Otherwise, the named + values from the tarfile are used. + + .. warning:: + + Never extract archives from untrusted sources without prior inspection. + It is possible that files are created outside of *path*, e.g. members + that have absolute filenames starting with ``"/"`` or filenames with two + dots ``".."``. + + .. versionchanged:: 3.5 + Added the *numeric_owner* parameter. + + .. versionchanged:: 3.6 + The *path* parameter accepts a :term:`path-like object`. + + +.. method:: TarFile.extract(member, path="", set_attrs=True, *, numeric_owner=False) + + Extract a member from the archive to the current working directory, using its + full name. Its file information is extracted as accurately as possible. *member* + may be a filename or a :class:`TarInfo` object. You can specify a different + directory using *path*. *path* may be a :term:`path-like object`. + File attributes (owner, mtime, mode) are set unless *set_attrs* is false. + + If *numeric_owner* is :const:`True`, the uid and gid numbers from the tarfile + are used to set the owner/group for the extracted files. Otherwise, the named + values from the tarfile are used. + + .. note:: + + The :meth:`extract` method does not take care of several extraction issues. + In most cases you should consider using the :meth:`extractall` method. + + .. warning:: + + See the warning for :meth:`extractall`. + + .. versionchanged:: 3.2 + Added the *set_attrs* parameter. + + .. versionchanged:: 3.5 + Added the *numeric_owner* parameter. + + .. versionchanged:: 3.6 + The *path* parameter accepts a :term:`path-like object`. + + +.. method:: TarFile.extractfile(member) + + Extract a member from the archive as a file object. *member* may be a filename + or a :class:`TarInfo` object. If *member* is a regular file or a link, an + :class:`io.BufferedReader` object is returned. Otherwise, :const:`None` is + returned. + + .. versionchanged:: 3.3 + Return an :class:`io.BufferedReader` object. + + +.. method:: TarFile.add(name, arcname=None, recursive=True, *, filter=None) + + Add the file *name* to the archive. *name* may be any type of file + (directory, fifo, symbolic link, etc.). If given, *arcname* specifies an + alternative name for the file in the archive. Directories are added + recursively by default. This can be avoided by setting *recursive* to + :const:`False`. Recursion adds entries in sorted order. + If *filter* is given, it + should be a function that takes a :class:`TarInfo` object argument and + returns the changed :class:`TarInfo` object. If it instead returns + :const:`None` the :class:`TarInfo` object will be excluded from the + archive. See :ref:`tar-examples` for an example. + + .. versionchanged:: 3.2 + Added the *filter* parameter. + + .. versionchanged:: 3.7 + Recursion adds entries in sorted order. + + +.. method:: TarFile.addfile(tarinfo, fileobj=None) + + Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given, + it should be a :term:`binary file`, and + ``tarinfo.size`` bytes are read from it and added to the archive. You can + create :class:`TarInfo` objects directly, or by using :meth:`gettarinfo`. + + +.. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None) + + Create a :class:`TarInfo` object from the result of :func:`os.stat` or + equivalent on an existing file. The file is either named by *name*, or + specified as a :term:`file object` *fileobj* with a file descriptor. + *name* may be a :term:`path-like object`. If + given, *arcname* specifies an alternative name for the file in the + archive, otherwise, the name is taken from *fileobj*’s + :attr:`~io.FileIO.name` attribute, or the *name* argument. The name + should be a text string. + + You can modify + some of the :class:`TarInfo`’s attributes before you add it using :meth:`addfile`. + If the file object is not an ordinary file object positioned at the + beginning of the file, attributes such as :attr:`~TarInfo.size` may need + modifying. This is the case for objects such as :class:`~gzip.GzipFile`. + The :attr:`~TarInfo.name` may also be modified, in which case *arcname* + could be a dummy string. + + .. versionchanged:: 3.6 + The *name* parameter accepts a :term:`path-like object`. + + +.. method:: TarFile.close() + + Close the :class:`TarFile`. In write mode, two finishing zero blocks are + appended to the archive. + + +.. attribute:: TarFile.pax_headers + + A dictionary containing key-value pairs of pax global headers. + + + +.. _tarinfo-objects: + +TarInfo Objects +--------------- + +A :class:`TarInfo` object represents one member in a :class:`TarFile`. Aside +from storing all required attributes of a file (like file type, size, time, +permissions, owner etc.), it provides some useful methods to determine its type. +It does *not* contain the file's data itself. + +:class:`TarInfo` objects are returned by :class:`TarFile`'s methods +:meth:`getmember`, :meth:`getmembers` and :meth:`gettarinfo`. + + +.. class:: TarInfo(name="") + + Create a :class:`TarInfo` object. + + +.. classmethod:: TarInfo.frombuf(buf, encoding, errors) + + Create and return a :class:`TarInfo` object from string buffer *buf*. + + Raises :exc:`HeaderError` if the buffer is invalid. + + +.. classmethod:: TarInfo.fromtarfile(tarfile) + + Read the next member from the :class:`TarFile` object *tarfile* and return it as + a :class:`TarInfo` object. + + +.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape') + + Create a string buffer from a :class:`TarInfo` object. For information on the + arguments see the constructor of the :class:`TarFile` class. + + .. versionchanged:: 3.2 + Use ``'surrogateescape'`` as the default for the *errors* argument. + + +A ``TarInfo`` object has the following public data attributes: + + +.. attribute:: TarInfo.name + + Name of the archive member. + + +.. attribute:: TarInfo.size + + Size in bytes. + + +.. attribute:: TarInfo.mtime + + Time of last modification. + + +.. attribute:: TarInfo.mode + + Permission bits. + + +.. attribute:: TarInfo.type + + File type. *type* is usually one of these constants: :const:`REGTYPE`, + :const:`AREGTYPE`, :const:`LNKTYPE`, :const:`SYMTYPE`, :const:`DIRTYPE`, + :const:`FIFOTYPE`, :const:`CONTTYPE`, :const:`CHRTYPE`, :const:`BLKTYPE`, + :const:`GNUTYPE_SPARSE`. To determine the type of a :class:`TarInfo` object + more conveniently, use the ``is*()`` methods below. + + +.. attribute:: TarInfo.linkname + + Name of the target file name, which is only present in :class:`TarInfo` objects + of type :const:`LNKTYPE` and :const:`SYMTYPE`. + + +.. attribute:: TarInfo.uid + + User ID of the user who originally stored this member. + + +.. attribute:: TarInfo.gid + + Group ID of the user who originally stored this member. + + +.. attribute:: TarInfo.uname + + User name. + + +.. attribute:: TarInfo.gname + + Group name. + + +.. attribute:: TarInfo.pax_headers + + A dictionary containing key-value pairs of an associated pax extended header. + + +A :class:`TarInfo` object also provides some convenient query methods: + + +.. method:: TarInfo.isfile() + + Return :const:`True` if the :class:`Tarinfo` object is a regular file. + + +.. method:: TarInfo.isreg() + + Same as :meth:`isfile`. + + +.. method:: TarInfo.isdir() + + Return :const:`True` if it is a directory. + + +.. method:: TarInfo.issym() + + Return :const:`True` if it is a symbolic link. + + +.. method:: TarInfo.islnk() + + Return :const:`True` if it is a hard link. + + +.. method:: TarInfo.ischr() + + Return :const:`True` if it is a character device. + + +.. method:: TarInfo.isblk() + + Return :const:`True` if it is a block device. + + +.. method:: TarInfo.isfifo() + + Return :const:`True` if it is a FIFO. + + +.. method:: TarInfo.isdev() + + Return :const:`True` if it is one of character device, block device or FIFO. + + +.. _tarfile-commandline: +.. program:: tarfile + +Command-Line Interface +---------------------- + +.. versionadded:: 3.4 + +The :mod:`tarfile` module provides a simple command-line interface to interact +with tar archives. + +If you want to create a new tar archive, specify its name after the :option:`-c` +option and then list the filename(s) that should be included: + +.. code-block:: shell-session + + $ python -m tarfile -c monty.tar spam.txt eggs.txt + +Passing a directory is also acceptable: + +.. code-block:: shell-session + + $ python -m tarfile -c monty.tar life-of-brian_1979/ + +If you want to extract a tar archive into the current directory, use +the :option:`-e` option: + +.. code-block:: shell-session + + $ python -m tarfile -e monty.tar + +You can also extract a tar archive into a different directory by passing the +directory's name: + +.. code-block:: shell-session + + $ python -m tarfile -e monty.tar other-dir/ + +For a list of the files in a tar archive, use the :option:`-l` option: + +.. code-block:: shell-session + + $ python -m tarfile -l monty.tar + + +Command-line options +~~~~~~~~~~~~~~~~~~~~ + +.. cmdoption:: -l + --list + + List files in a tarfile. + +.. cmdoption:: -c ... + --create ... + + Create tarfile from source files. + +.. cmdoption:: -e [] + --extract [] + + Extract tarfile into the current directory if *output_dir* is not specified. + +.. cmdoption:: -t + --test + + Test whether the tarfile is valid or not. + +.. cmdoption:: -v, --verbose + + Verbose output. + +.. _tar-examples: + +Examples +-------- + +How to extract an entire tar archive to the current working directory:: + + import tarfile + tar = tarfile.open("sample.tar.gz") + tar.extractall() + tar.close() + +How to extract a subset of a tar archive with :meth:`TarFile.extractall` using +a generator function instead of a list:: + + import os + import tarfile + + def py_files(members): + for tarinfo in members: + if os.path.splitext(tarinfo.name)[1] == ".py": + yield tarinfo + + tar = tarfile.open("sample.tar.gz") + tar.extractall(members=py_files(tar)) + tar.close() + +How to create an uncompressed tar archive from a list of filenames:: + + import tarfile + tar = tarfile.open("sample.tar", "w") + for name in ["foo", "bar", "quux"]: + tar.add(name) + tar.close() + +The same example using the :keyword:`with` statement:: + + import tarfile + with tarfile.open("sample.tar", "w") as tar: + for name in ["foo", "bar", "quux"]: + tar.add(name) + +How to read a gzip compressed tar archive and display some member information:: + + import tarfile + tar = tarfile.open("sample.tar.gz", "r:gz") + for tarinfo in tar: + print(tarinfo.name, "is", tarinfo.size, "bytes in size and is", end="") + if tarinfo.isreg(): + print("a regular file.") + elif tarinfo.isdir(): + print("a directory.") + else: + print("something else.") + tar.close() + +How to create an archive and reset the user information using the *filter* +parameter in :meth:`TarFile.add`:: + + import tarfile + def reset(tarinfo): + tarinfo.uid = tarinfo.gid = 0 + tarinfo.uname = tarinfo.gname = "root" + return tarinfo + tar = tarfile.open("sample.tar.gz", "w:gz") + tar.add("foo", filter=reset) + tar.close() + + +.. _tar-formats: + +Supported tar formats +--------------------- + +There are three tar formats that can be created with the :mod:`tarfile` module: + +* The POSIX.1-1988 ustar format (:const:`USTAR_FORMAT`). It supports filenames + up to a length of at best 256 characters and linknames up to 100 characters. + The maximum file size is 8 GiB. This is an old and limited but widely + supported format. + +* The GNU tar format (:const:`GNU_FORMAT`). It supports long filenames and + linknames, files bigger than 8 GiB and sparse files. It is the de facto + standard on GNU/Linux systems. :mod:`tarfile` fully supports the GNU tar + extensions for long names, sparse file support is read-only. + +* The POSIX.1-2001 pax format (:const:`PAX_FORMAT`). It is the most flexible + format with virtually no limits. It supports long filenames and linknames, large + files and stores pathnames in a portable way. Modern tar implementations, + including GNU tar, bsdtar/libarchive and star, fully support extended *pax* + features; some old or unmaintained libraries may not, but should treat + *pax* archives as if they were in the universally-supported *ustar* format. + It is the current default format for new archives. + + It extends the existing *ustar* format with extra headers for information + that cannot be stored otherwise. There are two flavours of pax headers: + Extended headers only affect the subsequent file header, global + headers are valid for the complete archive and affect all following files. + All the data in a pax header is encoded in *UTF-8* for portability reasons. + +There are some more variants of the tar format which can be read, but not +created: + +* The ancient V7 format. This is the first tar format from Unix Seventh Edition, + storing only regular files and directories. Names must not be longer than 100 + characters, there is no user/group name information. Some archives have + miscalculated header checksums in case of fields with non-ASCII characters. + +* The SunOS tar extended format. This format is a variant of the POSIX.1-2001 + pax format, but is not compatible. + +.. _tar-unicode: + +Unicode issues +-------------- + +The tar format was originally conceived to make backups on tape drives with the +main focus on preserving file system information. Nowadays tar archives are +commonly used for file distribution and exchanging archives over networks. One +problem of the original format (which is the basis of all other formats) is +that there is no concept of supporting different character encodings. For +example, an ordinary tar archive created on a *UTF-8* system cannot be read +correctly on a *Latin-1* system if it contains non-*ASCII* characters. Textual +metadata (like filenames, linknames, user/group names) will appear damaged. +Unfortunately, there is no way to autodetect the encoding of an archive. The +pax format was designed to solve this problem. It stores non-ASCII metadata +using the universal character encoding *UTF-8*. + +The details of character conversion in :mod:`tarfile` are controlled by the +*encoding* and *errors* keyword arguments of the :class:`TarFile` class. + +*encoding* defines the character encoding to use for the metadata in the +archive. The default value is :func:`sys.getfilesystemencoding` or ``'ascii'`` +as a fallback. Depending on whether the archive is read or written, the +metadata must be either decoded or encoded. If *encoding* is not set +appropriately, this conversion may fail. + +The *errors* argument defines how characters are treated that cannot be +converted. Possible values are listed in section :ref:`error-handlers`. +The default scheme is ``'surrogateescape'`` which Python also uses for its +file system calls, see :ref:`os-filenames`. + +For :const:`PAX_FORMAT` archives (the default), *encoding* is generally not needed +because all the metadata is stored using *UTF-8*. *encoding* is only used in +the rare cases when binary pax headers are decoded or when strings with +surrogate characters are stored. diff --git a/cpython_2/environment/repo/Doc/library/telnetlib.rst b/cpython_2/environment/repo/Doc/library/telnetlib.rst new file mode 100644 index 0000000000000000000000000000000000000000..48a9aea50dddd1aecdfc102ca99c9fad131aa03b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/telnetlib.rst @@ -0,0 +1,256 @@ +:mod:`telnetlib` --- Telnet client +================================== + +.. module:: telnetlib + :synopsis: Telnet client class. + +.. sectionauthor:: Skip Montanaro + +**Source code:** :source:`Lib/telnetlib.py` + +.. index:: single: protocol; Telnet + +-------------- + +The :mod:`telnetlib` module provides a :class:`Telnet` class that implements the +Telnet protocol. See :rfc:`854` for details about the protocol. In addition, it +provides symbolic constants for the protocol characters (see below), and for the +telnet options. The symbolic names of the telnet options follow the definitions +in ``arpa/telnet.h``, with the leading ``TELOPT_`` removed. For symbolic names +of options which are traditionally not included in ``arpa/telnet.h``, see the +module source itself. + +The symbolic constants for the telnet commands are: IAC, DONT, DO, WONT, WILL, +SE (Subnegotiation End), NOP (No Operation), DM (Data Mark), BRK (Break), IP +(Interrupt process), AO (Abort output), AYT (Are You There), EC (Erase +Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin). + + +.. class:: Telnet(host=None, port=0[, timeout]) + + :class:`Telnet` represents a connection to a Telnet server. The instance is + initially not connected by default; the :meth:`~Telnet.open` method must be used to + establish a connection. Alternatively, the host name and optional port + number can be passed to the constructor too, in which case the connection to + the server will be established before the constructor returns. The optional + *timeout* parameter specifies a timeout in seconds for blocking operations + like the connection attempt (if not specified, the global default timeout + setting will be used). + + Do not reopen an already connected instance. + + This class has many :meth:`read_\*` methods. Note that some of them raise + :exc:`EOFError` when the end of the connection is read, because they can return + an empty string for other reasons. See the individual descriptions below. + + A :class:`Telnet` object is a context manager and can be used in a + :keyword:`with` statement. When the :keyword:`!with` block ends, the + :meth:`close` method is called:: + + >>> from telnetlib import Telnet + >>> with Telnet('localhost', 23) as tn: + ... tn.interact() + ... + + .. versionchanged:: 3.6 Context manager support added + + +.. seealso:: + + :rfc:`854` - Telnet Protocol Specification + Definition of the Telnet protocol. + + +.. _telnet-objects: + +Telnet Objects +-------------- + +:class:`Telnet` instances have the following methods: + + +.. method:: Telnet.read_until(expected, timeout=None) + + Read until a given byte string, *expected*, is encountered or until *timeout* + seconds have passed. + + When no match is found, return whatever is available instead, possibly empty + bytes. Raise :exc:`EOFError` if the connection is closed and no cooked data + is available. + + +.. method:: Telnet.read_all() + + Read all data until EOF as bytes; block until connection closed. + + +.. method:: Telnet.read_some() + + Read at least one byte of cooked data unless EOF is hit. Return ``b''`` if + EOF is hit. Block if no data is immediately available. + + +.. method:: Telnet.read_very_eager() + + Read everything that can be without blocking in I/O (eager). + + Raise :exc:`EOFError` if connection closed and no cooked data available. + Return ``b''`` if no cooked data available otherwise. Do not block unless in + the midst of an IAC sequence. + + +.. method:: Telnet.read_eager() + + Read readily available data. + + Raise :exc:`EOFError` if connection closed and no cooked data available. + Return ``b''`` if no cooked data available otherwise. Do not block unless in + the midst of an IAC sequence. + + +.. method:: Telnet.read_lazy() + + Process and return data already in the queues (lazy). + + Raise :exc:`EOFError` if connection closed and no data available. Return + ``b''`` if no cooked data available otherwise. Do not block unless in the + midst of an IAC sequence. + + +.. method:: Telnet.read_very_lazy() + + Return any data available in the cooked queue (very lazy). + + Raise :exc:`EOFError` if connection closed and no data available. Return + ``b''`` if no cooked data available otherwise. This method never blocks. + + +.. method:: Telnet.read_sb_data() + + Return the data collected between a SB/SE pair (suboption begin/end). The + callback should access these data when it was invoked with a ``SE`` command. + This method never blocks. + + +.. method:: Telnet.open(host, port=0[, timeout]) + + Connect to a host. The optional second argument is the port number, which + defaults to the standard Telnet port (23). The optional *timeout* parameter + specifies a timeout in seconds for blocking operations like the connection + attempt (if not specified, the global default timeout setting will be used). + + Do not try to reopen an already connected instance. + + .. audit-event:: telnetlib.Telnet.open self,host,port telnetlib.Telnet.open + + +.. method:: Telnet.msg(msg, *args) + + Print a debug message when the debug level is ``>`` 0. If extra arguments are + present, they are substituted in the message using the standard string + formatting operator. + + +.. method:: Telnet.set_debuglevel(debuglevel) + + Set the debug level. The higher the value of *debuglevel*, the more debug + output you get (on ``sys.stdout``). + + +.. method:: Telnet.close() + + Close the connection. + + +.. method:: Telnet.get_socket() + + Return the socket object used internally. + + +.. method:: Telnet.fileno() + + Return the file descriptor of the socket object used internally. + + +.. method:: Telnet.write(buffer) + + Write a byte string to the socket, doubling any IAC characters. This can + block if the connection is blocked. May raise :exc:`OSError` if the + connection is closed. + + .. audit-event:: telnetlib.Telnet.write self,buffer telnetlib.Telnet.write + + .. versionchanged:: 3.3 + This method used to raise :exc:`socket.error`, which is now an alias + of :exc:`OSError`. + + +.. method:: Telnet.interact() + + Interaction function, emulates a very dumb Telnet client. + + +.. method:: Telnet.mt_interact() + + Multithreaded version of :meth:`interact`. + + +.. method:: Telnet.expect(list, timeout=None) + + Read until one from a list of a regular expressions matches. + + The first argument is a list of regular expressions, either compiled + (:ref:`regex objects `) or uncompiled (byte strings). The + optional second argument is a timeout, in seconds; the default is to block + indefinitely. + + Return a tuple of three items: the index in the list of the first regular + expression that matches; the match object returned; and the bytes read up + till and including the match. + + If end of file is found and no bytes were read, raise :exc:`EOFError`. + Otherwise, when nothing matches, return ``(-1, None, data)`` where *data* is + the bytes received so far (may be empty bytes if a timeout happened). + + If a regular expression ends with a greedy match (such as ``.*``) or if more + than one expression can match the same input, the results are + non-deterministic, and may depend on the I/O timing. + + +.. method:: Telnet.set_option_negotiation_callback(callback) + + Each time a telnet option is read on the input flow, this *callback* (if set) is + called with the following parameters: callback(telnet socket, command + (DO/DONT/WILL/WONT), option). No other action is done afterwards by telnetlib. + + +.. _telnet-example: + +Telnet Example +-------------- + +.. sectionauthor:: Peter Funk + + +A simple example illustrating typical use:: + + import getpass + import telnetlib + + HOST = "localhost" + user = input("Enter your remote account: ") + password = getpass.getpass() + + tn = telnetlib.Telnet(HOST) + + tn.read_until(b"login: ") + tn.write(user.encode('ascii') + b"\n") + if password: + tn.read_until(b"Password: ") + tn.write(password.encode('ascii') + b"\n") + + tn.write(b"ls\n") + tn.write(b"exit\n") + + print(tn.read_all().decode('ascii')) + diff --git a/cpython_2/environment/repo/Doc/library/tempfile.rst b/cpython_2/environment/repo/Doc/library/tempfile.rst new file mode 100644 index 0000000000000000000000000000000000000000..a59817c1039210913ebf5848ddc2cb6447e1d9dc --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tempfile.rst @@ -0,0 +1,358 @@ +:mod:`tempfile` --- Generate temporary files and directories +============================================================ + +.. module:: tempfile + :synopsis: Generate temporary files and directories. + +.. sectionauthor:: Zack Weinberg + +**Source code:** :source:`Lib/tempfile.py` + +.. index:: + pair: temporary; file name + pair: temporary; file + +-------------- + +This module creates temporary files and directories. It works on all +supported platforms. :class:`TemporaryFile`, :class:`NamedTemporaryFile`, +:class:`TemporaryDirectory`, and :class:`SpooledTemporaryFile` are high-level +interfaces which provide automatic cleanup and can be used as +context managers. :func:`mkstemp` and +:func:`mkdtemp` are lower-level functions which require manual cleanup. + +All the user-callable functions and constructors take additional arguments which +allow direct control over the location and name of temporary files and +directories. Files names used by this module include a string of +random characters which allows those files to be securely created in +shared temporary directories. +To maintain backward compatibility, the argument order is somewhat odd; it +is recommended to use keyword arguments for clarity. + +The module defines the following user-callable items: + +.. function:: TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None) + + Return a :term:`file-like object` that can be used as a temporary storage area. + The file is created securely, using the same rules as :func:`mkstemp`. It will be destroyed as soon + as it is closed (including an implicit close when the object is garbage + collected). Under Unix, the directory entry for the file is either not created at all or is removed + immediately after the file is created. Other platforms do not support + this; your code should not rely on a temporary file created using this + function having or not having a visible name in the file system. + + The resulting object can be used as a context manager (see + :ref:`tempfile-examples`). On completion of the context or + destruction of the file object the temporary file will be removed + from the filesystem. + + The *mode* parameter defaults to ``'w+b'`` so that the file created can + be read and written without being closed. Binary mode is used so that it + behaves consistently on all platforms without regard for the data that is + stored. *buffering*, *encoding*, *errors* and *newline* are interpreted as for + :func:`open`. + + The *dir*, *prefix* and *suffix* parameters have the same meaning and + defaults as with :func:`mkstemp`. + + The returned object is a true file object on POSIX platforms. On other + platforms, it is a file-like object whose :attr:`!file` attribute is the + underlying true file object. + + The :py:data:`os.O_TMPFILE` flag is used if it is available and works + (Linux-specific, requires Linux kernel 3.11 or later). + + .. audit-event:: tempfile.mkstemp fullpath tempfile.TemporaryFile + + .. versionchanged:: 3.5 + + The :py:data:`os.O_TMPFILE` flag is now used if available. + + .. versionchanged:: 3.8 + Added *errors* parameter. + + +.. function:: NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None) + + This function operates exactly as :func:`TemporaryFile` does, except that + the file is guaranteed to have a visible name in the file system (on + Unix, the directory entry is not unlinked). That name can be retrieved + from the :attr:`name` attribute of the returned + file-like object. Whether the name can be + used to open the file a second time, while the named temporary file is + still open, varies across platforms (it can be so used on Unix; it cannot + on Windows NT or later). If *delete* is true (the default), the file is + deleted as soon as it is closed. + The returned object is always a file-like object whose :attr:`!file` + attribute is the underlying true file object. This file-like object can + be used in a :keyword:`with` statement, just like a normal file. + + .. audit-event:: tempfile.mkstemp fullpath tempfile.NamedTemporaryFile + + .. versionchanged:: 3.8 + Added *errors* parameter. + + +.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None) + + This function operates exactly as :func:`TemporaryFile` does, except that + data is spooled in memory until the file size exceeds *max_size*, or + until the file's :func:`fileno` method is called, at which point the + contents are written to disk and operation proceeds as with + :func:`TemporaryFile`. + + The resulting file has one additional method, :func:`rollover`, which + causes the file to roll over to an on-disk file regardless of its size. + + The returned object is a file-like object whose :attr:`_file` attribute + is either an :class:`io.BytesIO` or :class:`io.TextIOWrapper` object + (depending on whether binary or text *mode* was specified) or a true file + object, depending on whether :func:`rollover` has been called. This + file-like object can be used in a :keyword:`with` statement, just like + a normal file. + + .. versionchanged:: 3.3 + the truncate method now accepts a ``size`` argument. + + .. versionchanged:: 3.8 + Added *errors* parameter. + + +.. function:: TemporaryDirectory(suffix=None, prefix=None, dir=None) + + This function securely creates a temporary directory using the same rules as :func:`mkdtemp`. + The resulting object can be used as a context manager (see + :ref:`tempfile-examples`). On completion of the context or destruction + of the temporary directory object the newly created temporary directory + and all its contents are removed from the filesystem. + + The directory name can be retrieved from the :attr:`name` attribute of the + returned object. When the returned object is used as a context manager, the + :attr:`name` will be assigned to the target of the :keyword:`!as` clause in + the :keyword:`with` statement, if there is one. + + The directory can be explicitly cleaned up by calling the + :func:`cleanup` method. + + .. audit-event:: tempfile.mkdtemp fullpath tempfile.TemporaryDirectory + + .. versionadded:: 3.2 + + +.. function:: mkstemp(suffix=None, prefix=None, dir=None, text=False) + + Creates a temporary file in the most secure manner possible. There are + no race conditions in the file's creation, assuming that the platform + properly implements the :const:`os.O_EXCL` flag for :func:`os.open`. The + file is readable and writable only by the creating user ID. If the + platform uses permission bits to indicate whether a file is executable, + the file is executable by no one. The file descriptor is not inherited + by child processes. + + Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible + for deleting the temporary file when done with it. + + If *suffix* is not ``None``, the file name will end with that suffix, + otherwise there will be no suffix. :func:`mkstemp` does not put a dot + between the file name and the suffix; if you need one, put it at the + beginning of *suffix*. + + If *prefix* is not ``None``, the file name will begin with that prefix; + otherwise, a default prefix is used. The default is the return value of + :func:`gettempprefix` or :func:`gettempprefixb`, as appropriate. + + If *dir* is not ``None``, the file will be created in that directory; + otherwise, a default directory is used. The default directory is chosen + from a platform-dependent list, but the user of the application can + control the directory location by setting the *TMPDIR*, *TEMP* or *TMP* + environment variables. There is thus no guarantee that the generated + filename will have any nice properties, such as not requiring quoting + when passed to external commands via ``os.popen()``. + + If any of *suffix*, *prefix*, and *dir* are not + ``None``, they must be the same type. + If they are bytes, the returned name will be bytes instead of str. + If you want to force a bytes return value with otherwise default behavior, + pass ``suffix=b''``. + + If *text* is specified, it indicates whether to open the file in binary + mode (the default) or text mode. On some platforms, this makes no + difference. + + :func:`mkstemp` returns a tuple containing an OS-level handle to an open + file (as would be returned by :func:`os.open`) and the absolute pathname + of that file, in that order. + + .. audit-event:: tempfile.mkstemp fullpath tempfile.mkstemp + + .. versionchanged:: 3.5 + *suffix*, *prefix*, and *dir* may now be supplied in bytes in order to + obtain a bytes return value. Prior to this, only str was allowed. + *suffix* and *prefix* now accept and default to ``None`` to cause + an appropriate default value to be used. + + .. versionchanged:: 3.6 + The *dir* parameter now accepts a :term:`path-like object`. + + +.. function:: mkdtemp(suffix=None, prefix=None, dir=None) + + Creates a temporary directory in the most secure manner possible. There + are no race conditions in the directory's creation. The directory is + readable, writable, and searchable only by the creating user ID. + + The user of :func:`mkdtemp` is responsible for deleting the temporary + directory and its contents when done with it. + + The *prefix*, *suffix*, and *dir* arguments are the same as for + :func:`mkstemp`. + + :func:`mkdtemp` returns the absolute pathname of the new directory. + + .. audit-event:: tempfile.mkdtemp fullpath tempfile.mkdtemp + + .. versionchanged:: 3.5 + *suffix*, *prefix*, and *dir* may now be supplied in bytes in order to + obtain a bytes return value. Prior to this, only str was allowed. + *suffix* and *prefix* now accept and default to ``None`` to cause + an appropriate default value to be used. + + .. versionchanged:: 3.6 + The *dir* parameter now accepts a :term:`path-like object`. + + +.. function:: gettempdir() + + Return the name of the directory used for temporary files. This + defines the default value for the *dir* argument to all functions + in this module. + + Python searches a standard list of directories to find one which + the calling user can create files in. The list is: + + #. The directory named by the :envvar:`TMPDIR` environment variable. + + #. The directory named by the :envvar:`TEMP` environment variable. + + #. The directory named by the :envvar:`TMP` environment variable. + + #. A platform-specific location: + + * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`, + :file:`\\TEMP`, and :file:`\\TMP`, in that order. + + * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and + :file:`/usr/tmp`, in that order. + + #. As a last resort, the current working directory. + + The result of this search is cached, see the description of + :data:`tempdir` below. + +.. function:: gettempdirb() + + Same as :func:`gettempdir` but the return value is in bytes. + + .. versionadded:: 3.5 + +.. function:: gettempprefix() + + Return the filename prefix used to create temporary files. This does not + contain the directory component. + +.. function:: gettempprefixb() + + Same as :func:`gettempprefix` but the return value is in bytes. + + .. versionadded:: 3.5 + +The module uses a global variable to store the name of the directory +used for temporary files returned by :func:`gettempdir`. It can be +set directly to override the selection process, but this is discouraged. +All functions in this module take a *dir* argument which can be used +to specify the directory and this is the recommended approach. + +.. data:: tempdir + + When set to a value other than ``None``, this variable defines the + default value for the *dir* argument to the functions defined in this + module. + + If ``tempdir`` is ``None`` (the default) at any call to any of the above + functions except :func:`gettempprefix` it is initialized following the + algorithm described in :func:`gettempdir`. + +.. _tempfile-examples: + +Examples +-------- + +Here are some examples of typical usage of the :mod:`tempfile` module:: + + >>> import tempfile + + # create a temporary file and write some data to it + >>> fp = tempfile.TemporaryFile() + >>> fp.write(b'Hello world!') + # read data from file + >>> fp.seek(0) + >>> fp.read() + b'Hello world!' + # close the file, it will be removed + >>> fp.close() + + # create a temporary file using a context manager + >>> with tempfile.TemporaryFile() as fp: + ... fp.write(b'Hello world!') + ... fp.seek(0) + ... fp.read() + b'Hello world!' + >>> + # file is now closed and removed + + # create a temporary directory using the context manager + >>> with tempfile.TemporaryDirectory() as tmpdirname: + ... print('created temporary directory', tmpdirname) + >>> + # directory and contents have been removed + + +Deprecated functions and variables +---------------------------------- + +A historical way to create temporary files was to first generate a +file name with the :func:`mktemp` function and then create a file +using this name. Unfortunately this is not secure, because a different +process may create a file with this name in the time between the call +to :func:`mktemp` and the subsequent attempt to create the file by the +first process. The solution is to combine the two steps and create the +file immediately. This approach is used by :func:`mkstemp` and the +other functions described above. + +.. function:: mktemp(suffix='', prefix='tmp', dir=None) + + .. deprecated:: 2.3 + Use :func:`mkstemp` instead. + + Return an absolute pathname of a file that did not exist at the time the + call is made. The *prefix*, *suffix*, and *dir* arguments are similar + to those of :func:`mkstemp`, except that bytes file names, ``suffix=None`` + and ``prefix=None`` are not supported. + + .. warning:: + + Use of this function may introduce a security hole in your program. By + the time you get around to doing anything with the file name it returns, + someone else may have beaten you to the punch. :func:`mktemp` usage can + be replaced easily with :func:`NamedTemporaryFile`, passing it the + ``delete=False`` parameter:: + + >>> f = NamedTemporaryFile(delete=False) + >>> f.name + '/tmp/tmptjujjt' + >>> f.write(b"Hello World!\n") + 13 + >>> f.close() + >>> os.unlink(f.name) + >>> os.path.exists(f.name) + False diff --git a/cpython_2/environment/repo/Doc/library/termios.rst b/cpython_2/environment/repo/Doc/library/termios.rst new file mode 100644 index 0000000000000000000000000000000000000000..d75a87c55a46ec34c2f458ecd8b26645cef7c36b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/termios.rst @@ -0,0 +1,105 @@ +:mod:`termios` --- POSIX style tty control +========================================== + +.. module:: termios + :platform: Unix + :synopsis: POSIX style tty control. + +.. index:: + pair: POSIX; I/O control + pair: tty; I/O control + +-------------- + +This module provides an interface to the POSIX calls for tty I/O control. For a +complete description of these calls, see :manpage:`termios(3)` Unix manual +page. It is only available for those Unix versions that support POSIX +*termios* style tty I/O control configured during installation. + +All functions in this module take a file descriptor *fd* as their first +argument. This can be an integer file descriptor, such as returned by +``sys.stdin.fileno()``, or a :term:`file object`, such as ``sys.stdin`` itself. + +This module also defines all the constants needed to work with the functions +provided here; these have the same name as their counterparts in C. Please +refer to your system documentation for more information on using these terminal +control interfaces. + +The module defines the following functions: + + +.. function:: tcgetattr(fd) + + Return a list containing the tty attributes for file descriptor *fd*, as + follows: ``[iflag, oflag, cflag, lflag, ispeed, ospeed, cc]`` where *cc* is a + list of the tty special characters (each a string of length 1, except the + items with indices :const:`VMIN` and :const:`VTIME`, which are integers when + these fields are defined). The interpretation of the flags and the speeds as + well as the indexing in the *cc* array must be done using the symbolic + constants defined in the :mod:`termios` module. + + +.. function:: tcsetattr(fd, when, attributes) + + Set the tty attributes for file descriptor *fd* from the *attributes*, which is + a list like the one returned by :func:`tcgetattr`. The *when* argument + determines when the attributes are changed: :const:`TCSANOW` to change + immediately, :const:`TCSADRAIN` to change after transmitting all queued output, + or :const:`TCSAFLUSH` to change after transmitting all queued output and + discarding all queued input. + + +.. function:: tcsendbreak(fd, duration) + + Send a break on file descriptor *fd*. A zero *duration* sends a break for + 0.25--0.5 seconds; a nonzero *duration* has a system dependent meaning. + + +.. function:: tcdrain(fd) + + Wait until all output written to file descriptor *fd* has been transmitted. + + +.. function:: tcflush(fd, queue) + + Discard queued data on file descriptor *fd*. The *queue* selector specifies + which queue: :const:`TCIFLUSH` for the input queue, :const:`TCOFLUSH` for the + output queue, or :const:`TCIOFLUSH` for both queues. + + +.. function:: tcflow(fd, action) + + Suspend or resume input or output on file descriptor *fd*. The *action* + argument can be :const:`TCOOFF` to suspend output, :const:`TCOON` to restart + output, :const:`TCIOFF` to suspend input, or :const:`TCION` to restart input. + + +.. seealso:: + + Module :mod:`tty` + Convenience functions for common terminal control operations. + + +.. _termios-example: + +Example +------- + +Here's a function that prompts for a password with echoing turned off. Note the +technique using a separate :func:`tcgetattr` call and a :keyword:`try` ... +:keyword:`finally` statement to ensure that the old tty attributes are restored +exactly no matter what happens:: + + def getpass(prompt="Password: "): + import termios, sys + fd = sys.stdin.fileno() + old = termios.tcgetattr(fd) + new = termios.tcgetattr(fd) + new[3] = new[3] & ~termios.ECHO # lflags + try: + termios.tcsetattr(fd, termios.TCSADRAIN, new) + passwd = input(prompt) + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old) + return passwd + diff --git a/cpython_2/environment/repo/Doc/library/test.rst b/cpython_2/environment/repo/Doc/library/test.rst new file mode 100644 index 0000000000000000000000000000000000000000..f7e6eba0181614d7ef6a3125360195f5267b3b80 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/test.rst @@ -0,0 +1,1630 @@ +:mod:`test` --- Regression tests package for Python +=================================================== + +.. module:: test + :synopsis: Regression tests package containing the testing suite for Python. + +.. sectionauthor:: Brett Cannon + +.. note:: + The :mod:`test` package is meant for internal use by Python only. It is + documented for the benefit of the core developers of Python. Any use of + this package outside of Python's standard library is discouraged as code + mentioned here can change or be removed without notice between releases of + Python. + +-------------- + +The :mod:`test` package contains all regression tests for Python as well as the +modules :mod:`test.support` and :mod:`test.regrtest`. +:mod:`test.support` is used to enhance your tests while +:mod:`test.regrtest` drives the testing suite. + +Each module in the :mod:`test` package whose name starts with ``test_`` is a +testing suite for a specific module or feature. All new tests should be written +using the :mod:`unittest` or :mod:`doctest` module. Some older tests are +written using a "traditional" testing style that compares output printed to +``sys.stdout``; this style of test is considered deprecated. + + +.. seealso:: + + Module :mod:`unittest` + Writing PyUnit regression tests. + + Module :mod:`doctest` + Tests embedded in documentation strings. + + +.. _writing-tests: + +Writing Unit Tests for the :mod:`test` package +---------------------------------------------- + +It is preferred that tests that use the :mod:`unittest` module follow a few +guidelines. One is to name the test module by starting it with ``test_`` and end +it with the name of the module being tested. The test methods in the test module +should start with ``test_`` and end with a description of what the method is +testing. This is needed so that the methods are recognized by the test driver as +test methods. Also, no documentation string for the method should be included. A +comment (such as ``# Tests function returns only True or False``) should be used +to provide documentation for test methods. This is done because documentation +strings get printed out if they exist and thus what test is being run is not +stated. + +A basic boilerplate is often used:: + + import unittest + from test import support + + class MyTestCase1(unittest.TestCase): + + # Only use setUp() and tearDown() if necessary + + def setUp(self): + ... code to execute in preparation for tests ... + + def tearDown(self): + ... code to execute to clean up after tests ... + + def test_feature_one(self): + # Test feature one. + ... testing code ... + + def test_feature_two(self): + # Test feature two. + ... testing code ... + + ... more test methods ... + + class MyTestCase2(unittest.TestCase): + ... same structure as MyTestCase1 ... + + ... more test classes ... + + if __name__ == '__main__': + unittest.main() + +This code pattern allows the testing suite to be run by :mod:`test.regrtest`, +on its own as a script that supports the :mod:`unittest` CLI, or via the +``python -m unittest`` CLI. + +The goal for regression testing is to try to break code. This leads to a few +guidelines to be followed: + +* The testing suite should exercise all classes, functions, and constants. This + includes not just the external API that is to be presented to the outside + world but also "private" code. + +* Whitebox testing (examining the code being tested when the tests are being + written) is preferred. Blackbox testing (testing only the published user + interface) is not complete enough to make sure all boundary and edge cases + are tested. + +* Make sure all possible values are tested including invalid ones. This makes + sure that not only all valid values are acceptable but also that improper + values are handled correctly. + +* Exhaust as many code paths as possible. Test where branching occurs and thus + tailor input to make sure as many different paths through the code are taken. + +* Add an explicit test for any bugs discovered for the tested code. This will + make sure that the error does not crop up again if the code is changed in the + future. + +* Make sure to clean up after your tests (such as close and remove all temporary + files). + +* If a test is dependent on a specific condition of the operating system then + verify the condition already exists before attempting the test. + +* Import as few modules as possible and do it as soon as possible. This + minimizes external dependencies of tests and also minimizes possible anomalous + behavior from side-effects of importing a module. + +* Try to maximize code reuse. On occasion, tests will vary by something as small + as what type of input is used. Minimize code duplication by subclassing a + basic test class with a class that specifies the input:: + + class TestFuncAcceptsSequencesMixin: + + func = mySuperWhammyFunction + + def test_func(self): + self.func(self.arg) + + class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase): + arg = [1, 2, 3] + + class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase): + arg = 'abc' + + class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase): + arg = (1, 2, 3) + + When using this pattern, remember that all classes that inherit from + :class:`unittest.TestCase` are run as tests. The :class:`Mixin` class in the example above + does not have any data and so can't be run by itself, thus it does not + inherit from :class:`unittest.TestCase`. + + +.. seealso:: + + Test Driven Development + A book by Kent Beck on writing tests before code. + + +.. _regrtest: + +Running tests using the command-line interface +---------------------------------------------- + +The :mod:`test` package can be run as a script to drive Python's regression +test suite, thanks to the :option:`-m` option: :program:`python -m test`. Under +the hood, it uses :mod:`test.regrtest`; the call :program:`python -m +test.regrtest` used in previous Python versions still works. Running the +script by itself automatically starts running all regression tests in the +:mod:`test` package. It does this by finding all modules in the package whose +name starts with ``test_``, importing them, and executing the function +:func:`test_main` if present or loading the tests via +unittest.TestLoader.loadTestsFromModule if ``test_main`` does not exist. The +names of tests to execute may also be passed to the script. Specifying a single +regression test (:program:`python -m test test_spam`) will minimize output and +only print whether the test passed or failed. + +Running :mod:`test` directly allows what resources are available for +tests to use to be set. You do this by using the ``-u`` command-line +option. Specifying ``all`` as the value for the ``-u`` option enables all +possible resources: :program:`python -m test -uall`. +If all but one resource is desired (a more common case), a +comma-separated list of resources that are not desired may be listed after +``all``. The command :program:`python -m test -uall,-audio,-largefile` +will run :mod:`test` with all resources except the ``audio`` and +``largefile`` resources. For a list of all resources and more command-line +options, run :program:`python -m test -h`. + +Some other ways to execute the regression tests depend on what platform the +tests are being executed on. On Unix, you can run :program:`make test` at the +top-level directory where Python was built. On Windows, +executing :program:`rt.bat` from your :file:`PCbuild` directory will run all +regression tests. + + +:mod:`test.support` --- Utilities for the Python test suite +=========================================================== + +.. module:: test.support + :synopsis: Support for Python's regression test suite. + + +The :mod:`test.support` module provides support for Python's regression +test suite. + +.. note:: + + :mod:`test.support` is not a public module. It is documented here to help + Python developers write tests. The API of this module is subject to change + without backwards compatibility concerns between releases. + + +This module defines the following exceptions: + +.. exception:: TestFailed + + Exception to be raised when a test fails. This is deprecated in favor of + :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion + methods. + + +.. exception:: ResourceDenied + + Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a + network connection) is not available. Raised by the :func:`requires` + function. + + +The :mod:`test.support` module defines the following constants: + +.. data:: verbose + + ``True`` when verbose output is enabled. Should be checked when more + detailed information is desired about a running test. *verbose* is set by + :mod:`test.regrtest`. + + +.. data:: is_jython + + ``True`` if the running interpreter is Jython. + + +.. data:: is_android + + ``True`` if the system is Android. + + +.. data:: unix_shell + + Path for shell if not on Windows; otherwise ``None``. + + +.. data:: FS_NONASCII + + A non-ASCII character encodable by :func:`os.fsencode`. + + +.. data:: TESTFN + + Set to a name that is safe to use as the name of a temporary file. Any + temporary file that is created should be closed and unlinked (removed). + + +.. data:: TESTFN_UNICODE + + Set to a non-ASCII name for a temporary file. + + +.. data:: TESTFN_ENCODING + + Set to :func:`sys.getfilesystemencoding`. + + +.. data:: TESTFN_UNENCODABLE + + Set to a filename (str type) that should not be able to be encoded by file + system encoding in strict mode. It may be ``None`` if it's not possible to + generate such a filename. + + +.. data:: TESTFN_UNDECODABLE + + Set to a filename (bytes type) that should not be able to be decoded by + file system encoding in strict mode. It may be ``None`` if it's not + possible to generate such a filename. + + +.. data:: TESTFN_NONASCII + + Set to a filename containing the :data:`FS_NONASCII` character. + + +.. data:: LOOPBACK_TIMEOUT + + Timeout in seconds for tests using a network server listening on the network + local loopback interface like ``127.0.0.1``. + + The timeout is long enough to prevent test failure: it takes into account + that the client and the server can run in different threads or even + different processes. + + The timeout should be long enough for :meth:`~socket.socket.connect`, + :meth:`~socket.socket.recv` and :meth:`~socket.socket.send` methods of + :class:`socket.socket`. + + Its default value is 5 seconds. + + See also :data:`INTERNET_TIMEOUT`. + + +.. data:: INTERNET_TIMEOUT + + Timeout in seconds for network requests going to the Internet. + + The timeout is short enough to prevent a test to wait for too long if the + Internet request is blocked for whatever reason. + + Usually, a timeout using :data:`INTERNET_TIMEOUT` should not mark a test as + failed, but skip the test instead: see + :func:`~test.support.socket_helper.transient_internet`. + + Its default value is 1 minute. + + See also :data:`LOOPBACK_TIMEOUT`. + + +.. data:: SHORT_TIMEOUT + + Timeout in seconds to mark a test as failed if the test takes "too long". + + The timeout value depends on the regrtest ``--timeout`` command line option. + + If a test using :data:`SHORT_TIMEOUT` starts to fail randomly on slow + buildbots, use :data:`LONG_TIMEOUT` instead. + + Its default value is 30 seconds. + + +.. data:: LONG_TIMEOUT + + Timeout in seconds to detect when a test hangs. + + It is long enough to reduce the risk of test failure on the slowest Python + buildbots. It should not be used to mark a test as failed if the test takes + "too long". The timeout value depends on the regrtest ``--timeout`` command + line option. + + Its default value is 5 minutes. + + See also :data:`LOOPBACK_TIMEOUT`, :data:`INTERNET_TIMEOUT` and + :data:`SHORT_TIMEOUT`. + + +.. data:: SAVEDCWD + + Set to :func:`os.getcwd`. + + +.. data:: PGO + + Set when tests can be skipped when they are not useful for PGO. + + +.. data:: PIPE_MAX_SIZE + + A constant that is likely larger than the underlying OS pipe buffer size, + to make writes blocking. + + +.. data:: SOCK_MAX_SIZE + + A constant that is likely larger than the underlying OS socket buffer size, + to make writes blocking. + + +.. data:: TEST_SUPPORT_DIR + + Set to the top level directory that contains :mod:`test.support`. + + +.. data:: TEST_HOME_DIR + + Set to the top level directory for the test package. + + +.. data:: TEST_DATA_DIR + + Set to the ``data`` directory within the test package. + + +.. data:: MAX_Py_ssize_t + + Set to :data:`sys.maxsize` for big memory tests. + + +.. data:: max_memuse + + Set by :func:`set_memlimit` as the memory limit for big memory tests. + Limited by :data:`MAX_Py_ssize_t`. + + +.. data:: real_max_memuse + + Set by :func:`set_memlimit` as the memory limit for big memory tests. Not + limited by :data:`MAX_Py_ssize_t`. + + +.. data:: MISSING_C_DOCSTRINGS + + Return ``True`` if running on CPython, not on Windows, and configuration + not set with ``WITH_DOC_STRINGS``. + + +.. data:: HAVE_DOCSTRINGS + + Check for presence of docstrings. + + +.. data:: TEST_HTTP_URL + + Define the URL of a dedicated HTTP server for the network tests. + + +.. data:: ALWAYS_EQ + + Object that is equal to anything. Used to test mixed type comparison. + + +.. data:: NEVER_EQ + + Object that is not equal to anything (even to :data:`ALWAYS_EQ`). + Used to test mixed type comparison. + + +.. data:: LARGEST + + Object that is greater than anything (except itself). + Used to test mixed type comparison. + + +.. data:: SMALLEST + + Object that is less than anything (except itself). + Used to test mixed type comparison. + + +The :mod:`test.support` module defines the following functions: + +.. function:: forget(module_name) + + Remove the module named *module_name* from ``sys.modules`` and delete any + byte-compiled files of the module. + + +.. function:: unload(name) + + Delete *name* from ``sys.modules``. + + +.. function:: unlink(filename) + + Call :func:`os.unlink` on *filename*. On Windows platforms, this is + wrapped with a wait loop that checks for the existence fo the file. + + +.. function:: rmdir(filename) + + Call :func:`os.rmdir` on *filename*. On Windows platforms, this is + wrapped with a wait loop that checks for the existence of the file. + + +.. function:: rmtree(path) + + Call :func:`shutil.rmtree` on *path* or call :func:`os.lstat` and + :func:`os.rmdir` to remove a path and its contents. On Windows platforms, + this is wrapped with a wait loop that checks for the existence of the files. + + +.. function:: make_legacy_pyc(source) + + Move a :pep:`3147`/:pep:`488` pyc file to its legacy pyc location and return the file + system path to the legacy pyc file. The *source* value is the file system + path to the source file. It does not need to exist, however the PEP + 3147/488 pyc file must exist. + + +.. function:: is_resource_enabled(resource) + + Return ``True`` if *resource* is enabled and available. The list of + available resources is only set when :mod:`test.regrtest` is executing the + tests. + + +.. function:: python_is_optimized() + + Return ``True`` if Python was not built with ``-O0`` or ``-Og``. + + +.. function:: with_pymalloc() + + Return :data:`_testcapi.WITH_PYMALLOC`. + + +.. function:: requires(resource, msg=None) + + Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the + argument to :exc:`ResourceDenied` if it is raised. Always returns + ``True`` if called by a function whose ``__name__`` is ``'__main__'``. + Used when tests are executed by :mod:`test.regrtest`. + + +.. function:: system_must_validate_cert(f) + + Raise :exc:`unittest.SkipTest` on TLS certification validation failures. + + +.. function:: sortdict(dict) + + Return a repr of *dict* with keys sorted. + + +.. function:: findfile(filename, subdir=None) + + Return the path to the file named *filename*. If no match is found + *filename* is returned. This does not equal a failure since it could be the + path to the file. + + Setting *subdir* indicates a relative path to use to find the file + rather than looking directly in the path directories. + + +.. function:: create_empty_file(filename) + + Create an empty file with *filename*. If it already exists, truncate it. + + +.. function:: fd_count() + + Count the number of open file descriptors. + + +.. function:: match_test(test) + + Match *test* to patterns set in :func:`set_match_tests`. + + +.. function:: set_match_tests(patterns) + + Define match test with regular expression *patterns*. + + +.. function:: run_unittest(\*classes) + + Execute :class:`unittest.TestCase` subclasses passed to the function. The + function scans the classes for methods starting with the prefix ``test_`` + and executes the tests individually. + + It is also legal to pass strings as parameters; these should be keys in + ``sys.modules``. Each associated module will be scanned by + ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the + following :func:`test_main` function:: + + def test_main(): + support.run_unittest(__name__) + + This will run all tests defined in the named module. + + +.. function:: run_doctest(module, verbosity=None, optionflags=0) + + Run :func:`doctest.testmod` on the given *module*. Return + ``(failure_count, test_count)``. + + If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity + set to :data:`verbose`. Otherwise, it is run with verbosity set to + ``None``. *optionflags* is passed as ``optionflags`` to + :func:`doctest.testmod`. + + +.. function:: setswitchinterval(interval) + + Set the :func:`sys.setswitchinterval` to the given *interval*. Defines + a minimum interval for Android systems to prevent the system from hanging. + + +.. function:: check_impl_detail(**guards) + + Use this check to guard CPython's implementation-specific tests or to + run them only on the implementations guarded by the arguments:: + + check_impl_detail() # Only on CPython (default). + check_impl_detail(jython=True) # Only on Jython. + check_impl_detail(cpython=False) # Everywhere except CPython. + + +.. function:: check_warnings(\*filters, quiet=True) + + A convenience wrapper for :func:`warnings.catch_warnings()` that makes it + easier to test that a warning was correctly raised. It is approximately + equivalent to calling ``warnings.catch_warnings(record=True)`` with + :meth:`warnings.simplefilter` set to ``always`` and with the option to + automatically validate the results that are recorded. + + ``check_warnings`` accepts 2-tuples of the form ``("message regexp", + WarningCategory)`` as positional arguments. If one or more *filters* are + provided, or if the optional keyword argument *quiet* is ``False``, + it checks to make sure the warnings are as expected: each specified filter + must match at least one of the warnings raised by the enclosed code or the + test fails, and if any warnings are raised that do not match any of the + specified filters the test fails. To disable the first of these checks, + set *quiet* to ``True``. + + If no arguments are specified, it defaults to:: + + check_warnings(("", Warning), quiet=True) + + In this case all warnings are caught and no errors are raised. + + On entry to the context manager, a :class:`WarningRecorder` instance is + returned. The underlying warnings list from + :func:`~warnings.catch_warnings` is available via the recorder object's + :attr:`warnings` attribute. As a convenience, the attributes of the object + representing the most recent warning can also be accessed directly through + the recorder object (see example below). If no warning has been raised, + then any of the attributes that would otherwise be expected on an object + representing a warning will return ``None``. + + The recorder object also has a :meth:`reset` method, which clears the + warnings list. + + The context manager is designed to be used like this:: + + with check_warnings(("assertion is always true", SyntaxWarning), + ("", UserWarning)): + exec('assert(False, "Hey!")') + warnings.warn(UserWarning("Hide me!")) + + In this case if either warning was not raised, or some other warning was + raised, :func:`check_warnings` would raise an error. + + When a test needs to look more deeply into the warnings, rather than + just checking whether or not they occurred, code like this can be used:: + + with check_warnings(quiet=True) as w: + warnings.warn("foo") + assert str(w.args[0]) == "foo" + warnings.warn("bar") + assert str(w.args[0]) == "bar" + assert str(w.warnings[0].args[0]) == "foo" + assert str(w.warnings[1].args[0]) == "bar" + w.reset() + assert len(w.warnings) == 0 + + + Here all warnings will be caught, and the test code tests the captured + warnings directly. + + .. versionchanged:: 3.2 + New optional arguments *filters* and *quiet*. + + +.. function:: check_no_resource_warning(testcase) + + Context manager to check that no :exc:`ResourceWarning` was raised. You + must remove the object which may emit :exc:`ResourceWarning` before the + end of the context manager. + + +.. function:: set_memlimit(limit) + + Set the values for :data:`max_memuse` and :data:`real_max_memuse` for big + memory tests. + + +.. function:: record_original_stdout(stdout) + + Store the value from *stdout*. It is meant to hold the stdout at the + time the regrtest began. + + +.. function:: get_original_stdout + + Return the original stdout set by :func:`record_original_stdout` or + ``sys.stdout`` if it's not set. + + +.. function:: args_from_interpreter_flags() + + Return a list of command line arguments reproducing the current settings + in ``sys.flags`` and ``sys.warnoptions``. + + +.. function:: optim_args_from_interpreter_flags() + + Return a list of command line arguments reproducing the current + optimization settings in ``sys.flags``. + + +.. function:: captured_stdin() + captured_stdout() + captured_stderr() + + A context managers that temporarily replaces the named stream with + :class:`io.StringIO` object. + + Example use with output streams:: + + with captured_stdout() as stdout, captured_stderr() as stderr: + print("hello") + print("error", file=sys.stderr) + assert stdout.getvalue() == "hello\n" + assert stderr.getvalue() == "error\n" + + Example use with input stream:: + + with captured_stdin() as stdin: + stdin.write('hello\n') + stdin.seek(0) + # call test code that consumes from sys.stdin + captured = input() + self.assertEqual(captured, "hello") + + +.. function:: temp_dir(path=None, quiet=False) + + A context manager that creates a temporary directory at *path* and + yields the directory. + + If *path* is ``None``, the temporary directory is created using + :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager + raises an exception on error. Otherwise, if *path* is specified and + cannot be created, only a warning is issued. + + +.. function:: change_cwd(path, quiet=False) + + A context manager that temporarily changes the current working + directory to *path* and yields the directory. + + If *quiet* is ``False``, the context manager raises an exception + on error. Otherwise, it issues only a warning and keeps the current + working directory the same. + + +.. function:: temp_cwd(name='tempcwd', quiet=False) + + A context manager that temporarily creates a new directory and + changes the current working directory (CWD). + + The context manager creates a temporary directory in the current + directory with name *name* before temporarily changing the current + working directory. If *name* is ``None``, the temporary directory is + created using :func:`tempfile.mkdtemp`. + + If *quiet* is ``False`` and it is not possible to create or change + the CWD, an error is raised. Otherwise, only a warning is raised + and the original CWD is used. + + +.. function:: temp_umask(umask) + + A context manager that temporarily sets the process umask. + + +.. function:: disable_faulthandler() + + A context manager that replaces ``sys.stderr`` with ``sys.__stderr__``. + + +.. function:: gc_collect() + + Force as many objects as possible to be collected. This is needed because + timely deallocation is not guaranteed by the garbage collector. This means + that ``__del__`` methods may be called later than expected and weakrefs + may remain alive for longer than expected. + + +.. function:: disable_gc() + + A context manager that disables the garbage collector upon entry and + reenables it upon exit. + + +.. function:: swap_attr(obj, attr, new_val) + + Context manager to swap out an attribute with a new object. + + Usage:: + + with swap_attr(obj, "attr", 5): + ... + + This will set ``obj.attr`` to 5 for the duration of the ``with`` block, + restoring the old value at the end of the block. If ``attr`` doesn't + exist on ``obj``, it will be created and then deleted at the end of the + block. + + The old value (or ``None`` if it doesn't exist) will be assigned to the + target of the "as" clause, if there is one. + + +.. function:: swap_item(obj, attr, new_val) + + Context manager to swap out an item with a new object. + + Usage:: + + with swap_item(obj, "item", 5): + ... + + This will set ``obj["item"]`` to 5 for the duration of the ``with`` block, + restoring the old value at the end of the block. If ``item`` doesn't + exist on ``obj``, it will be created and then deleted at the end of the + block. + + The old value (or ``None`` if it doesn't exist) will be assigned to the + target of the "as" clause, if there is one. + + +.. function:: print_warning(msg) + + Print a warning into :data:`sys.__stderr__`. Format the message as: + ``f"Warning -- {msg}"``. If *msg* is made of multiple lines, add + ``"Warning -- "`` prefix to each line. + + .. versionadded:: 3.9 + + +.. function:: wait_process(pid, *, exitcode, timeout=None) + + Wait until process *pid* completes and check that the process exit code is + *exitcode*. + + Raise an :exc:`AssertionError` if the process exit code is not equal to + *exitcode*. + + If the process runs longer than *timeout* seconds (:data:`SHORT_TIMEOUT` by + default), kill the process and raise an :exc:`AssertionError`. The timeout + feature is not available on Windows. + + .. versionadded:: 3.9 + + +.. function:: wait_threads_exit(timeout=60.0) + + Context manager to wait until all threads created in the ``with`` statement + exit. + + +.. function:: start_threads(threads, unlock=None) + + Context manager to start *threads*. It attempts to join the threads upon + exit. + + +.. function:: calcobjsize(fmt) + + Return :func:`struct.calcsize` for ``nP{fmt}0n`` or, if ``gettotalrefcount`` + exists, ``2PnP{fmt}0P``. + + +.. function:: calcvobjsize(fmt) + + Return :func:`struct.calcsize` for ``nPn{fmt}0n`` or, if ``gettotalrefcount`` + exists, ``2PnPn{fmt}0P``. + + +.. function:: checksizeof(test, o, size) + + For testcase *test*, assert that the ``sys.getsizeof`` for *o* plus the GC + header size equals *size*. + + +.. function:: can_symlink() + + Return ``True`` if the OS supports symbolic links, ``False`` + otherwise. + + +.. function:: can_xattr() + + Return ``True`` if the OS supports xattr, ``False`` + otherwise. + + +.. decorator:: skip_unless_symlink + + A decorator for running tests that require support for symbolic links. + + +.. decorator:: skip_unless_xattr + + A decorator for running tests that require support for xattr. + + +.. decorator:: anticipate_failure(condition) + + A decorator to conditionally mark tests with + :func:`unittest.expectedFailure`. Any use of this decorator should + have an associated comment identifying the relevant tracker issue. + + +.. decorator:: run_with_locale(catstr, *locales) + + A decorator for running a function in a different locale, correctly + resetting it after it has finished. *catstr* is the locale category as + a string (for example ``"LC_ALL"``). The *locales* passed will be tried + sequentially, and the first valid locale will be used. + + +.. decorator:: run_with_tz(tz) + + A decorator for running a function in a specific timezone, correctly + resetting it after it has finished. + + +.. decorator:: requires_freebsd_version(*min_version) + + Decorator for the minimum version when running test on FreeBSD. If the + FreeBSD version is less than the minimum, raise :exc:`unittest.SkipTest`. + + +.. decorator:: requires_linux_version(*min_version) + + Decorator for the minimum version when running test on Linux. If the + Linux version is less than the minimum, raise :exc:`unittest.SkipTest`. + + +.. decorator:: requires_mac_version(*min_version) + + Decorator for the minimum version when running test on Mac OS X. If the + MAC OS X version is less than the minimum, raise :exc:`unittest.SkipTest`. + + +.. decorator:: requires_IEEE_754 + + Decorator for skipping tests on non-IEEE 754 platforms. + + +.. decorator:: requires_zlib + + Decorator for skipping tests if :mod:`zlib` doesn't exist. + + +.. decorator:: requires_gzip + + Decorator for skipping tests if :mod:`gzip` doesn't exist. + + +.. decorator:: requires_bz2 + + Decorator for skipping tests if :mod:`bz2` doesn't exist. + + +.. decorator:: requires_lzma + + Decorator for skipping tests if :mod:`lzma` doesn't exist. + + +.. decorator:: requires_resource(resource) + + Decorator for skipping tests if *resource* is not available. + + +.. decorator:: requires_docstrings + + Decorator for only running the test if :data:`HAVE_DOCSTRINGS`. + + +.. decorator:: cpython_only(test) + + Decorator for tests only applicable to CPython. + + +.. decorator:: impl_detail(msg=None, **guards) + + Decorator for invoking :func:`check_impl_detail` on *guards*. If that + returns ``False``, then uses *msg* as the reason for skipping the test. + + +.. decorator:: no_tracing(func) + + Decorator to temporarily turn off tracing for the duration of the test. + + +.. decorator:: refcount_test(test) + + Decorator for tests which involve reference counting. The decorator does + not run the test if it is not run by CPython. Any trace function is unset + for the duration of the test to prevent unexpected refcounts caused by + the trace function. + + +.. decorator:: reap_threads(func) + + Decorator to ensure the threads are cleaned up even if the test fails. + + +.. decorator:: bigmemtest(size, memuse, dry_run=True) + + Decorator for bigmem tests. + + *size* is a requested size for the test (in arbitrary, test-interpreted + units.) *memuse* is the number of bytes per unit for the test, or a good + estimate of it. For example, a test that needs two byte buffers, of 4 GiB + each, could be decorated with ``@bigmemtest(size=_4G, memuse=2)``. + + The *size* argument is normally passed to the decorated test method as an + extra argument. If *dry_run* is ``True``, the value passed to the test + method may be less than the requested value. If *dry_run* is ``False``, it + means the test doesn't support dummy runs when ``-M`` is not specified. + + +.. decorator:: bigaddrspacetest(f) + + Decorator for tests that fill the address space. *f* is the function to + wrap. + + +.. function:: make_bad_fd() + + Create an invalid file descriptor by opening and closing a temporary file, + and returning its descriptor. + + +.. function:: check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None) + + Test for syntax errors in *statement* by attempting to compile *statement*. + *testcase* is the :mod:`unittest` instance for the test. *errtext* is the + regular expression which should match the string representation of the + raised :exc:`SyntaxError`. If *lineno* is not ``None``, compares to + the line of the exception. If *offset* is not ``None``, compares to + the offset of the exception. + + +.. function:: check_syntax_warning(testcase, statement, errtext='', *, lineno=1, offset=None) + + Test for syntax warning in *statement* by attempting to compile *statement*. + Test also that the :exc:`SyntaxWarning` is emitted only once, and that it + will be converted to a :exc:`SyntaxError` when turned into error. + *testcase* is the :mod:`unittest` instance for the test. *errtext* is the + regular expression which should match the string representation of the + emitted :exc:`SyntaxWarning` and raised :exc:`SyntaxError`. If *lineno* + is not ``None``, compares to the line of the warning and exception. + If *offset* is not ``None``, compares to the offset of the exception. + + .. versionadded:: 3.8 + + +.. function:: open_urlresource(url, *args, **kw) + + Open *url*. If open fails, raises :exc:`TestFailed`. + + +.. function:: import_module(name, deprecated=False, *, required_on()) + + This function imports and returns the named module. Unlike a normal + import, this function raises :exc:`unittest.SkipTest` if the module + cannot be imported. + + Module and package deprecation messages are suppressed during this import + if *deprecated* is ``True``. If a module is required on a platform but + optional for others, set *required_on* to an iterable of platform prefixes + which will be compared against :data:`sys.platform`. + + .. versionadded:: 3.1 + + +.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False) + + This function imports and returns a fresh copy of the named Python module + by removing the named module from ``sys.modules`` before doing the import. + Note that unlike :func:`reload`, the original module is not affected by + this operation. + + *fresh* is an iterable of additional module names that are also removed + from the ``sys.modules`` cache before doing the import. + + *blocked* is an iterable of module names that are replaced with ``None`` + in the module cache during the import to ensure that attempts to import + them raise :exc:`ImportError`. + + The named module and any modules named in the *fresh* and *blocked* + parameters are saved before starting the import and then reinserted into + ``sys.modules`` when the fresh import is complete. + + Module and package deprecation messages are suppressed during this import + if *deprecated* is ``True``. + + This function will raise :exc:`ImportError` if the named module cannot be + imported. + + Example use:: + + # Get copies of the warnings module for testing without affecting the + # version being used by the rest of the test suite. One copy uses the + # C implementation, the other is forced to use the pure Python fallback + # implementation + py_warnings = import_fresh_module('warnings', blocked=['_warnings']) + c_warnings = import_fresh_module('warnings', fresh=['_warnings']) + + .. versionadded:: 3.1 + + +.. function:: modules_setup() + + Return a copy of :data:`sys.modules`. + + +.. function:: modules_cleanup(oldmodules) + + Remove modules except for *oldmodules* and ``encodings`` in order to + preserve internal cache. + + +.. function:: threading_setup() + + Return current thread count and copy of dangling threads. + + +.. function:: threading_cleanup(*original_values) + + Cleanup up threads not specified in *original_values*. Designed to emit + a warning if a test leaves running threads in the background. + + +.. function:: join_thread(thread, timeout=30.0) + + Join a *thread* within *timeout*. Raise an :exc:`AssertionError` if thread + is still alive after *timeout* seconds. + + +.. function:: reap_children() + + Use this at the end of ``test_main`` whenever sub-processes are started. + This will help ensure that no extra children (zombies) stick around to + hog resources and create problems when looking for refleaks. + + +.. function:: get_attribute(obj, name) + + Get an attribute, raising :exc:`unittest.SkipTest` if :exc:`AttributeError` + is raised. + + +.. function:: catch_threading_exception() + + Context manager catching :class:`threading.Thread` exception using + :func:`threading.excepthook`. + + Attributes set when an exception is catched: + + * ``exc_type`` + * ``exc_value`` + * ``exc_traceback`` + * ``thread`` + + See :func:`threading.excepthook` documentation. + + These attributes are deleted at the context manager exit. + + Usage:: + + with support.catch_threading_exception() as cm: + # code spawning a thread which raises an exception + ... + + # check the thread exception, use cm attributes: + # exc_type, exc_value, exc_traceback, thread + ... + + # exc_type, exc_value, exc_traceback, thread attributes of cm no longer + # exists at this point + # (to avoid reference cycles) + + .. versionadded:: 3.8 + + +.. function:: catch_unraisable_exception() + + Context manager catching unraisable exception using + :func:`sys.unraisablehook`. + + Storing the exception value (``cm.unraisable.exc_value``) creates a + reference cycle. The reference cycle is broken explicitly when the context + manager exits. + + Storing the object (``cm.unraisable.object``) can resurrect it if it is set + to an object which is being finalized. Exiting the context manager clears + the stored object. + + Usage:: + + with support.catch_unraisable_exception() as cm: + # code creating an "unraisable exception" + ... + + # check the unraisable exception: use cm.unraisable + ... + + # cm.unraisable attribute no longer exists at this point + # (to break a reference cycle) + + .. versionadded:: 3.8 + + +.. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern) + + Generic implementation of the :mod:`unittest` ``load_tests`` protocol for + use in test packages. *pkg_dir* is the root directory of the package; + *loader*, *standard_tests*, and *pattern* are the arguments expected by + ``load_tests``. In simple cases, the test package's ``__init__.py`` + can be the following:: + + import os + from test.support import load_package_tests + + def load_tests(*args): + return load_package_tests(os.path.dirname(__file__), *args) + + +.. function:: fs_is_case_insensitive(directory) + + Return ``True`` if the file system for *directory* is case-insensitive. + + +.. function:: detect_api_mismatch(ref_api, other_api, *, ignore=()) + + Returns the set of attributes, functions or methods of *ref_api* not + found on *other_api*, except for a defined list of items to be + ignored in this check specified in *ignore*. + + By default this skips private attributes beginning with '_' but + includes all magic methods, i.e. those starting and ending in '__'. + + .. versionadded:: 3.5 + + +.. function:: patch(test_instance, object_to_patch, attr_name, new_value) + + Override *object_to_patch.attr_name* with *new_value*. Also add + cleanup procedure to *test_instance* to restore *object_to_patch* for + *attr_name*. The *attr_name* should be a valid attribute for + *object_to_patch*. + + +.. function:: run_in_subinterp(code) + + Run *code* in subinterpreter. Raise :exc:`unittest.SkipTest` if + :mod:`tracemalloc` is enabled. + + +.. function:: check_free_after_iterating(test, iter, cls, args=()) + + Assert that *iter* is deallocated after iterating. + + +.. function:: missing_compiler_executable(cmd_names=[]) + + Check for the existence of the compiler executables whose names are listed + in *cmd_names* or all the compiler executables when *cmd_names* is empty + and return the first missing executable or ``None`` when none is found + missing. + + +.. function:: check__all__(test_case, module, name_of_module=None, extra=(), blacklist=()) + + Assert that the ``__all__`` variable of *module* contains all public names. + + The module's public names (its API) are detected automatically + based on whether they match the public name convention and were defined in + *module*. + + The *name_of_module* argument can specify (as a string or tuple thereof) what + module(s) an API could be defined in order to be detected as a public + API. One case for this is when *module* imports part of its public API from + other modules, possibly a C backend (like ``csv`` and its ``_csv``). + + The *extra* argument can be a set of names that wouldn't otherwise be automatically + detected as "public", like objects without a proper ``__module__`` + attribute. If provided, it will be added to the automatically detected ones. + + The *blacklist* argument can be a set of names that must not be treated as part of + the public API even though their names indicate otherwise. + + Example use:: + + import bar + import foo + import unittest + from test import support + + class MiscTestCase(unittest.TestCase): + def test__all__(self): + support.check__all__(self, foo) + + class OtherTestCase(unittest.TestCase): + def test__all__(self): + extra = {'BAR_CONST', 'FOO_CONST'} + blacklist = {'baz'} # Undocumented name. + # bar imports part of its API from _bar. + support.check__all__(self, bar, ('bar', '_bar'), + extra=extra, blacklist=blacklist) + + .. versionadded:: 3.6 + + +The :mod:`test.support` module defines the following classes: + +.. class:: TransientResource(exc, **kwargs) + + Instances are a context manager that raises :exc:`ResourceDenied` if the + specified exception type is raised. Any keyword arguments are treated as + attribute/value pairs to be compared against any exception raised within the + :keyword:`with` statement. Only if all pairs match properly against + attributes on the exception is :exc:`ResourceDenied` raised. + + +.. class:: EnvironmentVarGuard() + + Class used to temporarily set or unset environment variables. Instances can + be used as a context manager and have a complete dictionary interface for + querying/modifying the underlying ``os.environ``. After exit from the + context manager all changes to environment variables done through this + instance will be rolled back. + + .. versionchanged:: 3.1 + Added dictionary interface. + +.. method:: EnvironmentVarGuard.set(envvar, value) + + Temporarily set the environment variable ``envvar`` to the value of + ``value``. + + +.. method:: EnvironmentVarGuard.unset(envvar) + + Temporarily unset the environment variable ``envvar``. + + +.. class:: SuppressCrashReport() + + A context manager used to try to prevent crash dialog popups on tests that + are expected to crash a subprocess. + + On Windows, it disables Windows Error Reporting dialogs using + `SetErrorMode `_. + + On UNIX, :func:`resource.setrlimit` is used to set + :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file + creation. + + On both platforms, the old value is restored by :meth:`__exit__`. + + +.. class:: CleanImport(*module_names) + + A context manager to force import to return a new module reference. This + is useful for testing module-level behaviors, such as the emission of a + DeprecationWarning on import. Example usage:: + + with CleanImport('foo'): + importlib.import_module('foo') # New reference. + + +.. class:: DirsOnSysPath(*paths) + + A context manager to temporarily add directories to sys.path. + + This makes a copy of :data:`sys.path`, appends any directories given + as positional arguments, then reverts :data:`sys.path` to the copied + settings when the context ends. + + Note that *all* :data:`sys.path` modifications in the body of the + context manager, including replacement of the object, + will be reverted at the end of the block. + + +.. class:: SaveSignals() + + Class to save and restore signal handlers registered by the Python signal + handler. + + +.. class:: Matcher() + + .. method:: matches(self, d, **kwargs) + + Try to match a single dict with the supplied arguments. + + + .. method:: match_value(self, k, dv, v) + + Try to match a single stored value (*dv*) with a supplied value (*v*). + + +.. class:: WarningsRecorder() + + Class used to record warnings for unit tests. See documentation of + :func:`check_warnings` above for more details. + + +.. class:: BasicTestRunner() + + .. method:: run(test) + + Run *test* and return the result. + + +.. class:: FakePath(path) + + Simple :term:`path-like object`. It implements the :meth:`__fspath__` + method which just returns the *path* argument. If *path* is an exception, + it will be raised in :meth:`!__fspath__`. + + +:mod:`test.support.socket_helper` --- Utilities for socket tests +================================================================ + +.. module:: test.support.socket_helper + :synopsis: Support for socket tests. + + +The :mod:`test.support.socket_helper` module provides support for socket tests. + +.. versionadded:: 3.9 + + +.. data:: IPV6_ENABLED + + Set to ``True`` if IPv6 is enabled on this host, ``False`` otherwise. + + +.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM) + + Returns an unused port that should be suitable for binding. This is + achieved by creating a temporary socket with the same family and type as + the ``sock`` parameter (default is :const:`~socket.AF_INET`, + :const:`~socket.SOCK_STREAM`), + and binding it to the specified host address (defaults to ``0.0.0.0``) + with the port set to 0, eliciting an unused ephemeral port from the OS. + The temporary socket is then closed and deleted, and the ephemeral port is + returned. + + Either this method or :func:`bind_port` should be used for any tests + where a server socket needs to be bound to a particular port for the + duration of the test. + Which one to use depends on whether the calling code is creating a Python + socket, or if an unused port needs to be provided in a constructor + or passed to an external program (i.e. the ``-accept`` argument to + openssl's s_server mode). Always prefer :func:`bind_port` over + :func:`find_unused_port` where possible. Using a hard coded port is + discouraged since it can make multiple instances of the test impossible to + run simultaneously, which is a problem for buildbots. + + +.. function:: bind_port(sock, host=HOST) + + Bind the socket to a free port and return the port number. Relies on + ephemeral ports in order to ensure we are using an unbound port. This is + important as many tests may be running simultaneously, especially in a + buildbot environment. This method raises an exception if the + ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is + :const:`~socket.SOCK_STREAM`, and the socket has + :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it. + Tests should never set these socket options for TCP/IP sockets. + The only case for setting these options is testing multicasting via + multiple UDP sockets. + + Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is + available (i.e. on Windows), it will be set on the socket. This will + prevent anyone else from binding to our host/port for the duration of the + test. + + +.. function:: bind_unix_socket(sock, addr) + + Bind a unix socket, raising :exc:`unittest.SkipTest` if + :exc:`PermissionError` is raised. + + +.. decorator:: skip_unless_bind_unix_socket + + A decorator for running tests that require a functional ``bind()`` for Unix + sockets. + + +.. function:: transient_internet(resource_name, *, timeout=30.0, errnos=()) + + A context manager that raises :exc:`~test.support.ResourceDenied` when + various issues with the internet connection manifest themselves as + exceptions. + + +:mod:`test.support.script_helper` --- Utilities for the Python execution tests +============================================================================== + +.. module:: test.support.script_helper + :synopsis: Support for Python's script execution tests. + + +The :mod:`test.support.script_helper` module provides support for Python's +script execution tests. + +.. function:: interpreter_requires_environment() + + Return ``True`` if ``sys.executable interpreter`` requires environment + variables in order to be able to run at all. + + This is designed to be used with ``@unittest.skipIf()`` to annotate tests + that need to use an ``assert_python*()`` function to launch an isolated + mode (``-I``) or no environment mode (``-E``) sub-interpreter process. + + A normal build & test does not run into this situation but it can happen + when trying to run the standard library test suite from an interpreter that + doesn't have an obvious home with Python's current home finding logic. + + Setting :envvar:`PYTHONHOME` is one way to get most of the testsuite to run + in that situation. :envvar:`PYTHONPATH` or :envvar:`PYTHONUSERSITE` are + other common environment variables that might impact whether or not the + interpreter can start. + + +.. function:: run_python_until_end(*args, **env_vars) + + Set up the environment based on *env_vars* for running the interpreter + in a subprocess. The values can include ``__isolated``, ``__cleanenv``, + ``__cwd``, and ``TERM``. + + .. versionchanged:: 3.9 + The function no longer strips whitespaces from *stderr*. + + +.. function:: assert_python_ok(*args, **env_vars) + + Assert that running the interpreter with *args* and optional environment + variables *env_vars* succeeds (``rc == 0``) and return a ``(return code, + stdout, stderr)`` tuple. + + If the ``__cleanenv`` keyword is set, *env_vars* is used as a fresh + environment. + + Python is started in isolated mode (command line option ``-I``), + except if the ``__isolated`` keyword is set to ``False``. + + .. versionchanged:: 3.9 + The function no longer strips whitespaces from *stderr*. + + +.. function:: assert_python_failure(*args, **env_vars) + + Assert that running the interpreter with *args* and optional environment + variables *env_vars* fails (``rc != 0``) and return a ``(return code, + stdout, stderr)`` tuple. + + See :func:`assert_python_ok` for more options. + + .. versionchanged:: 3.9 + The function no longer strips whitespaces from *stderr*. + + +.. function:: spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw) + + Run a Python subprocess with the given arguments. + + *kw* is extra keyword args to pass to :func:`subprocess.Popen`. Returns a + :class:`subprocess.Popen` object. + + +.. function:: kill_python(p) + + Run the given :class:`subprocess.Popen` process until completion and return + stdout. + + +.. function:: make_script(script_dir, script_basename, source, omit_suffix=False) + + Create script containing *source* in path *script_dir* and *script_basename*. + If *omit_suffix* is ``False``, append ``.py`` to the name. Return the full + script path. + + +.. function:: make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None) + + Create zip file at *zip_dir* and *zip_basename* with extension ``zip`` which + contains the files in *script_name*. *name_in_zip* is the archive name. + Return a tuple containing ``(full path, full path of archive name)``. + + +.. function:: make_pkg(pkg_dir, init_source='') + + Create a directory named *pkg_dir* containing an ``__init__`` file with + *init_source* as its contents. + + +.. function:: make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, \ + source, depth=1, compiled=False) + + Create a zip package directory with a path of *zip_dir* and *zip_basename* + containing an empty ``__init__`` file and a file *script_basename* + containing the *source*. If *compiled* is ``True``, both source files will + be compiled and added to the zip package. Return a tuple of the full zip + path and the archive name for the zip file. + + +:mod:`test.support.bytecode_helper` --- Support tools for testing correct bytecode generation +============================================================================================= + +.. module:: test.support.bytecode_helper + :synopsis: Support tools for testing correct bytecode generation. + +The :mod:`test.support.bytecode_helper` module provides support for testing +and inspecting bytecode generation. + +The module defines the following class: + +.. class:: BytecodeTestCase(unittest.TestCase) + + This class has custom assertion methods for inspecting bytecode. + +.. method:: BytecodeTestCase.get_disassembly_as_string(co) + + Return the disassembly of *co* as string. + + +.. method:: BytecodeTestCase.assertInBytecode(x, opname, argval=_UNSPECIFIED) + + Return instr if *opname* is found, otherwise throws :exc:`AssertionError`. + + +.. method:: BytecodeTestCase.assertNotInBytecode(x, opname, argval=_UNSPECIFIED) + + Throws :exc:`AssertionError` if *opname* is found. diff --git a/cpython_2/environment/repo/Doc/library/text.rst b/cpython_2/environment/repo/Doc/library/text.rst new file mode 100644 index 0000000000000000000000000000000000000000..47b678434fc899c6bd39bf4726217b3a8c783b6b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/text.rst @@ -0,0 +1,26 @@ +.. _stringservices: +.. _textservices: + +************************ +Text Processing Services +************************ + +The modules described in this chapter provide a wide range of string +manipulation operations and other text processing services. + +The :mod:`codecs` module described under :ref:`binaryservices` is also +highly relevant to text processing. In addition, see the documentation for +Python's built-in string type in :ref:`textseq`. + + +.. toctree:: + + string.rst + re.rst + difflib.rst + textwrap.rst + unicodedata.rst + stringprep.rst + readline.rst + rlcompleter.rst + diff --git a/cpython_2/environment/repo/Doc/library/textwrap.rst b/cpython_2/environment/repo/Doc/library/textwrap.rst new file mode 100644 index 0000000000000000000000000000000000000000..16837104b6cebcde285fbfad8c3289617de36443 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/textwrap.rst @@ -0,0 +1,299 @@ +:mod:`textwrap` --- Text wrapping and filling +============================================= + +.. module:: textwrap + :synopsis: Text wrapping and filling + +.. moduleauthor:: Greg Ward +.. sectionauthor:: Greg Ward + +**Source code:** :source:`Lib/textwrap.py` + +-------------- + +The :mod:`textwrap` module provides some convenience functions, +as well as :class:`TextWrapper`, the class that does all the work. +If you're just wrapping or filling one or two text strings, the convenience +functions should be good enough; otherwise, you should use an instance of +:class:`TextWrapper` for efficiency. + +.. function:: wrap(text, width=70, **kwargs) + + Wraps the single paragraph in *text* (a string) so every line is at most + *width* characters long. Returns a list of output lines, without final + newlines. + + Optional keyword arguments correspond to the instance attributes of + :class:`TextWrapper`, documented below. *width* defaults to ``70``. + + See the :meth:`TextWrapper.wrap` method for additional details on how + :func:`wrap` behaves. + + +.. function:: fill(text, width=70, **kwargs) + + Wraps the single paragraph in *text*, and returns a single string containing the + wrapped paragraph. :func:`fill` is shorthand for :: + + "\n".join(wrap(text, ...)) + + In particular, :func:`fill` accepts exactly the same keyword arguments as + :func:`wrap`. + + +.. function:: shorten(text, width, **kwargs) + + Collapse and truncate the given *text* to fit in the given *width*. + + First the whitespace in *text* is collapsed (all whitespace is replaced by + single spaces). If the result fits in the *width*, it is returned. + Otherwise, enough words are dropped from the end so that the remaining words + plus the :attr:`placeholder` fit within :attr:`width`:: + + >>> textwrap.shorten("Hello world!", width=12) + 'Hello world!' + >>> textwrap.shorten("Hello world!", width=11) + 'Hello [...]' + >>> textwrap.shorten("Hello world", width=10, placeholder="...") + 'Hello...' + + Optional keyword arguments correspond to the instance attributes of + :class:`TextWrapper`, documented below. Note that the whitespace is + collapsed before the text is passed to the :class:`TextWrapper` :meth:`fill` + function, so changing the value of :attr:`.tabsize`, :attr:`.expand_tabs`, + :attr:`.drop_whitespace`, and :attr:`.replace_whitespace` will have no effect. + + .. versionadded:: 3.4 + + +.. function:: dedent(text) + + Remove any common leading whitespace from every line in *text*. + + This can be used to make triple-quoted strings line up with the left edge of the + display, while still presenting them in the source code in indented form. + + Note that tabs and spaces are both treated as whitespace, but they are not + equal: the lines ``" hello"`` and ``"\thello"`` are considered to have no + common leading whitespace. + + Lines containing only whitespace are ignored in the input and normalized to a + single newline character in the output. + + For example:: + + def test(): + # end first line with \ to avoid the empty line! + s = '''\ + hello + world + ''' + print(repr(s)) # prints ' hello\n world\n ' + print(repr(dedent(s))) # prints 'hello\n world\n' + + +.. function:: indent(text, prefix, predicate=None) + + Add *prefix* to the beginning of selected lines in *text*. + + Lines are separated by calling ``text.splitlines(True)``. + + By default, *prefix* is added to all lines that do not consist + solely of whitespace (including any line endings). + + For example:: + + >>> s = 'hello\n\n \nworld' + >>> indent(s, ' ') + ' hello\n\n \n world' + + The optional *predicate* argument can be used to control which lines + are indented. For example, it is easy to add *prefix* to even empty + and whitespace-only lines:: + + >>> print(indent(s, '+ ', lambda line: True)) + + hello + + + + + + world + + .. versionadded:: 3.3 + + +:func:`wrap`, :func:`fill` and :func:`shorten` work by creating a +:class:`TextWrapper` instance and calling a single method on it. That +instance is not reused, so for applications that process many text +strings using :func:`wrap` and/or :func:`fill`, it may be more efficient to +create your own :class:`TextWrapper` object. + +Text is preferably wrapped on whitespaces and right after the hyphens in +hyphenated words; only then will long words be broken if necessary, unless +:attr:`TextWrapper.break_long_words` is set to false. + +.. class:: TextWrapper(**kwargs) + + The :class:`TextWrapper` constructor accepts a number of optional keyword + arguments. Each keyword argument corresponds to an instance attribute, so + for example :: + + wrapper = TextWrapper(initial_indent="* ") + + is the same as :: + + wrapper = TextWrapper() + wrapper.initial_indent = "* " + + You can re-use the same :class:`TextWrapper` object many times, and you can + change any of its options through direct assignment to instance attributes + between uses. + + The :class:`TextWrapper` instance attributes (and keyword arguments to the + constructor) are as follows: + + + .. attribute:: width + + (default: ``70``) The maximum length of wrapped lines. As long as there + are no individual words in the input text longer than :attr:`width`, + :class:`TextWrapper` guarantees that no output line will be longer than + :attr:`width` characters. + + + .. attribute:: expand_tabs + + (default: ``True``) If true, then all tab characters in *text* will be + expanded to spaces using the :meth:`expandtabs` method of *text*. + + + .. attribute:: tabsize + + (default: ``8``) If :attr:`expand_tabs` is true, then all tab characters + in *text* will be expanded to zero or more spaces, depending on the + current column and the given tab size. + + .. versionadded:: 3.3 + + + .. attribute:: replace_whitespace + + (default: ``True``) If true, after tab expansion but before wrapping, + the :meth:`wrap` method will replace each whitespace character + with a single space. The whitespace characters replaced are + as follows: tab, newline, vertical tab, formfeed, and carriage + return (``'\t\n\v\f\r'``). + + .. note:: + + If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true, + each tab character will be replaced by a single space, which is *not* + the same as tab expansion. + + .. note:: + + If :attr:`replace_whitespace` is false, newlines may appear in the + middle of a line and cause strange output. For this reason, text should + be split into paragraphs (using :meth:`str.splitlines` or similar) + which are wrapped separately. + + + .. attribute:: drop_whitespace + + (default: ``True``) If true, whitespace at the beginning and ending of + every line (after wrapping but before indenting) is dropped. + Whitespace at the beginning of the paragraph, however, is not dropped + if non-whitespace follows it. If whitespace being dropped takes up an + entire line, the whole line is dropped. + + + .. attribute:: initial_indent + + (default: ``''``) String that will be prepended to the first line of + wrapped output. Counts towards the length of the first line. The empty + string is not indented. + + + .. attribute:: subsequent_indent + + (default: ``''``) String that will be prepended to all lines of wrapped + output except the first. Counts towards the length of each line except + the first. + + + .. attribute:: fix_sentence_endings + + (default: ``False``) If true, :class:`TextWrapper` attempts to detect + sentence endings and ensure that sentences are always separated by exactly + two spaces. This is generally desired for text in a monospaced font. + However, the sentence detection algorithm is imperfect: it assumes that a + sentence ending consists of a lowercase letter followed by one of ``'.'``, + ``'!'``, or ``'?'``, possibly followed by one of ``'"'`` or ``"'"``, + followed by a space. One problem with this is algorithm is that it is + unable to detect the difference between "Dr." in :: + + [...] Dr. Frankenstein's monster [...] + + and "Spot." in :: + + [...] See Spot. See Spot run [...] + + :attr:`fix_sentence_endings` is false by default. + + Since the sentence detection algorithm relies on ``string.lowercase`` for + the definition of "lowercase letter", and a convention of using two spaces + after a period to separate sentences on the same line, it is specific to + English-language texts. + + + .. attribute:: break_long_words + + (default: ``True``) If true, then words longer than :attr:`width` will be + broken in order to ensure that no lines are longer than :attr:`width`. If + it is false, long words will not be broken, and some lines may be longer + than :attr:`width`. (Long words will be put on a line by themselves, in + order to minimize the amount by which :attr:`width` is exceeded.) + + + .. attribute:: break_on_hyphens + + (default: ``True``) If true, wrapping will occur preferably on whitespaces + and right after hyphens in compound words, as it is customary in English. + If false, only whitespaces will be considered as potentially good places + for line breaks, but you need to set :attr:`break_long_words` to false if + you want truly insecable words. Default behaviour in previous versions + was to always allow breaking hyphenated words. + + + .. attribute:: max_lines + + (default: ``None``) If not ``None``, then the output will contain at most + *max_lines* lines, with *placeholder* appearing at the end of the output. + + .. versionadded:: 3.4 + + + .. index:: single: ...; placeholder + + .. attribute:: placeholder + + (default: ``' [...]'``) String that will appear at the end of the output + text if it has been truncated. + + .. versionadded:: 3.4 + + + :class:`TextWrapper` also provides some public methods, analogous to the + module-level convenience functions: + + .. method:: wrap(text) + + Wraps the single paragraph in *text* (a string) so every line is at most + :attr:`width` characters long. All wrapping options are taken from + instance attributes of the :class:`TextWrapper` instance. Returns a list + of output lines, without final newlines. If the wrapped output has no + content, the returned list is empty. + + + .. method:: fill(text) + + Wraps the single paragraph in *text*, and returns a single string + containing the wrapped paragraph. diff --git a/cpython_2/environment/repo/Doc/library/threading.rst b/cpython_2/environment/repo/Doc/library/threading.rst new file mode 100644 index 0000000000000000000000000000000000000000..3a446adfac8c5a046376294998741c27f9bb0599 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/threading.rst @@ -0,0 +1,1076 @@ +:mod:`threading` --- Thread-based parallelism +============================================= + +.. module:: threading + :synopsis: Thread-based parallelism. + +**Source code:** :source:`Lib/threading.py` + +-------------- + +This module constructs higher-level threading interfaces on top of the lower +level :mod:`_thread` module. See also the :mod:`queue` module. + +.. versionchanged:: 3.7 + This module used to be optional, it is now always available. + +.. note:: + + While they are not listed below, the ``camelCase`` names used for some + methods and functions in this module in the Python 2.x series are still + supported by this module. + + +This module defines the following functions: + + +.. function:: active_count() + + Return the number of :class:`Thread` objects currently alive. The returned + count is equal to the length of the list returned by :func:`.enumerate`. + + +.. function:: current_thread() + + Return the current :class:`Thread` object, corresponding to the caller's thread + of control. If the caller's thread of control was not created through the + :mod:`threading` module, a dummy thread object with limited functionality is + returned. + + +.. function:: excepthook(args, /) + + Handle uncaught exception raised by :func:`Thread.run`. + + The *args* argument has the following attributes: + + * *exc_type*: Exception type. + * *exc_value*: Exception value, can be ``None``. + * *exc_traceback*: Exception traceback, can be ``None``. + * *thread*: Thread which raised the exception, can be ``None``. + + If *exc_type* is :exc:`SystemExit`, the exception is silently ignored. + Otherwise, the exception is printed out on :data:`sys.stderr`. + + If this function raises an exception, :func:`sys.excepthook` is called to + handle it. + + :func:`threading.excepthook` can be overridden to control how uncaught + exceptions raised by :func:`Thread.run` are handled. + + Storing *exc_value* using a custom hook can create a reference cycle. It + should be cleared explicitly to break the reference cycle when the + exception is no longer needed. + + Storing *thread* using a custom hook can resurrect it if it is set to an + object which is being finalized. Avoid storing *thread* after the custom + hook completes to avoid resurrecting objects. + + .. seealso:: + :func:`sys.excepthook` handles uncaught exceptions. + + .. versionadded:: 3.8 + + +.. function:: get_ident() + + Return the 'thread identifier' of the current thread. This is a nonzero + integer. Its value has no direct meaning; it is intended as a magic cookie + to be used e.g. to index a dictionary of thread-specific data. Thread + identifiers may be recycled when a thread exits and another thread is + created. + + .. versionadded:: 3.3 + + +.. function:: get_native_id() + + Return the native integral Thread ID of the current thread assigned by the kernel. + This is a non-negative integer. + Its value may be used to uniquely identify this particular thread system-wide + (until the thread terminates, after which the value may be recycled by the OS). + + .. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX. + + .. versionadded:: 3.8 + + +.. function:: enumerate() + + Return a list of all :class:`Thread` objects currently alive. The list + includes daemonic threads, dummy thread objects created by + :func:`current_thread`, and the main thread. It excludes terminated threads + and threads that have not yet been started. + + +.. function:: main_thread() + + Return the main :class:`Thread` object. In normal conditions, the + main thread is the thread from which the Python interpreter was + started. + + .. versionadded:: 3.4 + + +.. function:: settrace(func) + + .. index:: single: trace function + + Set a trace function for all threads started from the :mod:`threading` module. + The *func* will be passed to :func:`sys.settrace` for each thread, before its + :meth:`~Thread.run` method is called. + + +.. function:: setprofile(func) + + .. index:: single: profile function + + Set a profile function for all threads started from the :mod:`threading` module. + The *func* will be passed to :func:`sys.setprofile` for each thread, before its + :meth:`~Thread.run` method is called. + + +.. function:: stack_size([size]) + + Return the thread stack size used when creating new threads. The optional + *size* argument specifies the stack size to be used for subsequently created + threads, and must be 0 (use platform or configured default) or a positive + integer value of at least 32,768 (32 KiB). If *size* is not specified, + 0 is used. If changing the thread stack size is + unsupported, a :exc:`RuntimeError` is raised. If the specified stack size is + invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32 KiB + is currently the minimum supported stack size value to guarantee sufficient + stack space for the interpreter itself. Note that some platforms may have + particular restrictions on values for the stack size, such as requiring a + minimum stack size > 32 KiB or requiring allocation in multiples of the system + memory page size - platform documentation should be referred to for more + information (4 KiB pages are common; using multiples of 4096 for the stack size is + the suggested approach in the absence of more specific information). + + .. availability:: Windows, systems with POSIX threads. + + +This module also defines the following constant: + +.. data:: TIMEOUT_MAX + + The maximum value allowed for the *timeout* parameter of blocking functions + (:meth:`Lock.acquire`, :meth:`RLock.acquire`, :meth:`Condition.wait`, etc.). + Specifying a timeout greater than this value will raise an + :exc:`OverflowError`. + + .. versionadded:: 3.2 + + +This module defines a number of classes, which are detailed in the sections +below. + +The design of this module is loosely based on Java's threading model. However, +where Java makes locks and condition variables basic behavior of every object, +they are separate objects in Python. Python's :class:`Thread` class supports a +subset of the behavior of Java's Thread class; currently, there are no +priorities, no thread groups, and threads cannot be destroyed, stopped, +suspended, resumed, or interrupted. The static methods of Java's Thread class, +when implemented, are mapped to module-level functions. + +All of the methods described below are executed atomically. + + +Thread-Local Data +----------------- + +Thread-local data is data whose values are thread specific. To manage +thread-local data, just create an instance of :class:`local` (or a +subclass) and store attributes on it:: + + mydata = threading.local() + mydata.x = 1 + +The instance's values will be different for separate threads. + + +.. class:: local() + + A class that represents thread-local data. + + For more details and extensive examples, see the documentation string of the + :mod:`_threading_local` module. + + +.. _thread-objects: + +Thread Objects +-------------- + +The :class:`Thread` class represents an activity that is run in a separate +thread of control. There are two ways to specify the activity: by passing a +callable object to the constructor, or by overriding the :meth:`~Thread.run` +method in a subclass. No other methods (except for the constructor) should be +overridden in a subclass. In other words, *only* override the +:meth:`~Thread.__init__` and :meth:`~Thread.run` methods of this class. + +Once a thread object is created, its activity must be started by calling the +thread's :meth:`~Thread.start` method. This invokes the :meth:`~Thread.run` +method in a separate thread of control. + +Once the thread's activity is started, the thread is considered 'alive'. It +stops being alive when its :meth:`~Thread.run` method terminates -- either +normally, or by raising an unhandled exception. The :meth:`~Thread.is_alive` +method tests whether the thread is alive. + +Other threads can call a thread's :meth:`~Thread.join` method. This blocks +the calling thread until the thread whose :meth:`~Thread.join` method is +called is terminated. + +A thread has a name. The name can be passed to the constructor, and read or +changed through the :attr:`~Thread.name` attribute. + +If the :meth:`~Thread.run` method raises an exception, +:func:`threading.excepthook` is called to handle it. By default, +:func:`threading.excepthook` ignores silently :exc:`SystemExit`. + +A thread can be flagged as a "daemon thread". The significance of this flag is +that the entire Python program exits when only daemon threads are left. The +initial value is inherited from the creating thread. The flag can be set +through the :attr:`~Thread.daemon` property or the *daemon* constructor +argument. + +.. note:: + Daemon threads are abruptly stopped at shutdown. Their resources (such + as open files, database transactions, etc.) may not be released properly. + If you want your threads to stop gracefully, make them non-daemonic and + use a suitable signalling mechanism such as an :class:`Event`. + +There is a "main thread" object; this corresponds to the initial thread of +control in the Python program. It is not a daemon thread. + +There is the possibility that "dummy thread objects" are created. These are +thread objects corresponding to "alien threads", which are threads of control +started outside the threading module, such as directly from C code. Dummy +thread objects have limited functionality; they are always considered alive and +daemonic, and cannot be :meth:`~Thread.join`\ ed. They are never deleted, +since it is impossible to detect the termination of alien threads. + + +.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={}, *, \ + daemon=None) + + This constructor should always be called with keyword arguments. Arguments + are: + + *group* should be ``None``; reserved for future extension when a + :class:`ThreadGroup` class is implemented. + + *target* is the callable object to be invoked by the :meth:`run` method. + Defaults to ``None``, meaning nothing is called. + + *name* is the thread name. By default, a unique name is constructed of the + form "Thread-*N*" where *N* is a small decimal number. + + *args* is the argument tuple for the target invocation. Defaults to ``()``. + + *kwargs* is a dictionary of keyword arguments for the target invocation. + Defaults to ``{}``. + + If not ``None``, *daemon* explicitly sets whether the thread is daemonic. + If ``None`` (the default), the daemonic property is inherited from the + current thread. + + If the subclass overrides the constructor, it must make sure to invoke the + base class constructor (``Thread.__init__()``) before doing anything else to + the thread. + + .. versionchanged:: 3.3 + Added the *daemon* argument. + + .. method:: start() + + Start the thread's activity. + + It must be called at most once per thread object. It arranges for the + object's :meth:`~Thread.run` method to be invoked in a separate thread + of control. + + This method will raise a :exc:`RuntimeError` if called more than once + on the same thread object. + + .. method:: run() + + Method representing the thread's activity. + + You may override this method in a subclass. The standard :meth:`run` + method invokes the callable object passed to the object's constructor as + the *target* argument, if any, with positional and keyword arguments taken + from the *args* and *kwargs* arguments, respectively. + + .. method:: join(timeout=None) + + Wait until the thread terminates. This blocks the calling thread until + the thread whose :meth:`~Thread.join` method is called terminates -- either + normally or through an unhandled exception -- or until the optional + timeout occurs. + + When the *timeout* argument is present and not ``None``, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). As :meth:`~Thread.join` always returns ``None``, + you must call :meth:`~Thread.is_alive` after :meth:`~Thread.join` to + decide whether a timeout happened -- if the thread is still alive, the + :meth:`~Thread.join` call timed out. + + When the *timeout* argument is not present or ``None``, the operation will + block until the thread terminates. + + A thread can be :meth:`~Thread.join`\ ed many times. + + :meth:`~Thread.join` raises a :exc:`RuntimeError` if an attempt is made + to join the current thread as that would cause a deadlock. It is also + an error to :meth:`~Thread.join` a thread before it has been started + and attempts to do so raise the same exception. + + .. attribute:: name + + A string used for identification purposes only. It has no semantics. + Multiple threads may be given the same name. The initial name is set by + the constructor. + + .. method:: getName() + setName() + + Old getter/setter API for :attr:`~Thread.name`; use it directly as a + property instead. + + .. attribute:: ident + + The 'thread identifier' of this thread or ``None`` if the thread has not + been started. This is a nonzero integer. See the :func:`get_ident` + function. Thread identifiers may be recycled when a thread exits and + another thread is created. The identifier is available even after the + thread has exited. + + .. attribute:: native_id + + The native integral thread ID of this thread. + This is a non-negative integer, or ``None`` if the thread has not + been started. See the :func:`get_native_id` function. + This represents the Thread ID (``TID``) as assigned to the + thread by the OS (kernel). Its value may be used to uniquely identify + this particular thread system-wide (until the thread terminates, + after which the value may be recycled by the OS). + + .. note:: + + Similar to Process IDs, Thread IDs are only valid (guaranteed unique + system-wide) from the time the thread is created until the thread + has been terminated. + + .. availability:: Requires :func:`get_native_id` function. + + .. versionadded:: 3.8 + + .. method:: is_alive() + + Return whether the thread is alive. + + This method returns ``True`` just before the :meth:`~Thread.run` method + starts until just after the :meth:`~Thread.run` method terminates. The + module function :func:`.enumerate` returns a list of all alive threads. + + .. attribute:: daemon + + A boolean value indicating whether this thread is a daemon thread (True) + or not (False). This must be set before :meth:`~Thread.start` is called, + otherwise :exc:`RuntimeError` is raised. Its initial value is inherited + from the creating thread; the main thread is not a daemon thread and + therefore all threads created in the main thread default to + :attr:`~Thread.daemon` = ``False``. + + The entire Python program exits when no alive non-daemon threads are left. + + .. method:: isDaemon() + setDaemon() + + Old getter/setter API for :attr:`~Thread.daemon`; use it directly as a + property instead. + + +.. impl-detail:: + + In CPython, due to the :term:`Global Interpreter Lock`, only one thread + can execute Python code at once (even though certain performance-oriented + libraries might overcome this limitation). + If you want your application to make better use of the computational + resources of multi-core machines, you are advised to use + :mod:`multiprocessing` or :class:`concurrent.futures.ProcessPoolExecutor`. + However, threading is still an appropriate model if you want to run + multiple I/O-bound tasks simultaneously. + + +.. _lock-objects: + +Lock Objects +------------ + +A primitive lock is a synchronization primitive that is not owned by a +particular thread when locked. In Python, it is currently the lowest level +synchronization primitive available, implemented directly by the :mod:`_thread` +extension module. + +A primitive lock is in one of two states, "locked" or "unlocked". It is created +in the unlocked state. It has two basic methods, :meth:`~Lock.acquire` and +:meth:`~Lock.release`. When the state is unlocked, :meth:`~Lock.acquire` +changes the state to locked and returns immediately. When the state is locked, +:meth:`~Lock.acquire` blocks until a call to :meth:`~Lock.release` in another +thread changes it to unlocked, then the :meth:`~Lock.acquire` call resets it +to locked and returns. The :meth:`~Lock.release` method should only be +called in the locked state; it changes the state to unlocked and returns +immediately. If an attempt is made to release an unlocked lock, a +:exc:`RuntimeError` will be raised. + +Locks also support the :ref:`context management protocol `. + +When more than one thread is blocked in :meth:`~Lock.acquire` waiting for the +state to turn to unlocked, only one thread proceeds when a :meth:`~Lock.release` +call resets the state to unlocked; which one of the waiting threads proceeds +is not defined, and may vary across implementations. + +All methods are executed atomically. + + +.. class:: Lock() + + The class implementing primitive lock objects. Once a thread has acquired a + lock, subsequent attempts to acquire it block, until it is released; any + thread may release it. + + Note that ``Lock`` is actually a factory function which returns an instance + of the most efficient version of the concrete Lock class that is supported + by the platform. + + + .. method:: acquire(blocking=True, timeout=-1) + + Acquire a lock, blocking or non-blocking. + + When invoked with the *blocking* argument set to ``True`` (the default), + block until the lock is unlocked, then set it to locked and return ``True``. + + When invoked with the *blocking* argument set to ``False``, do not block. + If a call with *blocking* set to ``True`` would block, return ``False`` + immediately; otherwise, set the lock to locked and return ``True``. + + When invoked with the floating-point *timeout* argument set to a positive + value, block for at most the number of seconds specified by *timeout* + and as long as the lock cannot be acquired. A *timeout* argument of ``-1`` + specifies an unbounded wait. It is forbidden to specify a *timeout* + when *blocking* is false. + + The return value is ``True`` if the lock is acquired successfully, + ``False`` if not (for example if the *timeout* expired). + + .. versionchanged:: 3.2 + The *timeout* parameter is new. + + .. versionchanged:: 3.2 + Lock acquisition can now be interrupted by signals on POSIX if the + underlying threading implementation supports it. + + + .. method:: release() + + Release a lock. This can be called from any thread, not only the thread + which has acquired the lock. + + When the lock is locked, reset it to unlocked, and return. If any other threads + are blocked waiting for the lock to become unlocked, allow exactly one of them + to proceed. + + When invoked on an unlocked lock, a :exc:`RuntimeError` is raised. + + There is no return value. + + .. method:: locked() + + Return true if the lock is acquired. + + + +.. _rlock-objects: + +RLock Objects +------------- + +A reentrant lock is a synchronization primitive that may be acquired multiple +times by the same thread. Internally, it uses the concepts of "owning thread" +and "recursion level" in addition to the locked/unlocked state used by primitive +locks. In the locked state, some thread owns the lock; in the unlocked state, +no thread owns it. + +To lock the lock, a thread calls its :meth:`~RLock.acquire` method; this +returns once the thread owns the lock. To unlock the lock, a thread calls +its :meth:`~Lock.release` method. :meth:`~Lock.acquire`/:meth:`~Lock.release` +call pairs may be nested; only the final :meth:`~Lock.release` (the +:meth:`~Lock.release` of the outermost pair) resets the lock to unlocked and +allows another thread blocked in :meth:`~Lock.acquire` to proceed. + +Reentrant locks also support the :ref:`context management protocol `. + + +.. class:: RLock() + + This class implements reentrant lock objects. A reentrant lock must be + released by the thread that acquired it. Once a thread has acquired a + reentrant lock, the same thread may acquire it again without blocking; the + thread must release it once for each time it has acquired it. + + Note that ``RLock`` is actually a factory function which returns an instance + of the most efficient version of the concrete RLock class that is supported + by the platform. + + + .. method:: acquire(blocking=True, timeout=-1) + + Acquire a lock, blocking or non-blocking. + + When invoked without arguments: if this thread already owns the lock, increment + the recursion level by one, and return immediately. Otherwise, if another + thread owns the lock, block until the lock is unlocked. Once the lock is + unlocked (not owned by any thread), then grab ownership, set the recursion level + to one, and return. If more than one thread is blocked waiting until the lock + is unlocked, only one at a time will be able to grab ownership of the lock. + There is no return value in this case. + + When invoked with the *blocking* argument set to true, do the same thing as when + called without arguments, and return ``True``. + + When invoked with the *blocking* argument set to false, do not block. If a call + without an argument would block, return ``False`` immediately; otherwise, do the + same thing as when called without arguments, and return ``True``. + + When invoked with the floating-point *timeout* argument set to a positive + value, block for at most the number of seconds specified by *timeout* + and as long as the lock cannot be acquired. Return ``True`` if the lock has + been acquired, false if the timeout has elapsed. + + .. versionchanged:: 3.2 + The *timeout* parameter is new. + + + .. method:: release() + + Release a lock, decrementing the recursion level. If after the decrement it is + zero, reset the lock to unlocked (not owned by any thread), and if any other + threads are blocked waiting for the lock to become unlocked, allow exactly one + of them to proceed. If after the decrement the recursion level is still + nonzero, the lock remains locked and owned by the calling thread. + + Only call this method when the calling thread owns the lock. A + :exc:`RuntimeError` is raised if this method is called when the lock is + unlocked. + + There is no return value. + + +.. _condition-objects: + +Condition Objects +----------------- + +A condition variable is always associated with some kind of lock; this can be +passed in or one will be created by default. Passing one in is useful when +several condition variables must share the same lock. The lock is part of +the condition object: you don't have to track it separately. + +A condition variable obeys the :ref:`context management protocol `: +using the ``with`` statement acquires the associated lock for the duration of +the enclosed block. The :meth:`~Condition.acquire` and +:meth:`~Condition.release` methods also call the corresponding methods of +the associated lock. + +Other methods must be called with the associated lock held. The +:meth:`~Condition.wait` method releases the lock, and then blocks until +another thread awakens it by calling :meth:`~Condition.notify` or +:meth:`~Condition.notify_all`. Once awakened, :meth:`~Condition.wait` +re-acquires the lock and returns. It is also possible to specify a timeout. + +The :meth:`~Condition.notify` method wakes up one of the threads waiting for +the condition variable, if any are waiting. The :meth:`~Condition.notify_all` +method wakes up all threads waiting for the condition variable. + +Note: the :meth:`~Condition.notify` and :meth:`~Condition.notify_all` methods +don't release the lock; this means that the thread or threads awakened will +not return from their :meth:`~Condition.wait` call immediately, but only when +the thread that called :meth:`~Condition.notify` or :meth:`~Condition.notify_all` +finally relinquishes ownership of the lock. + +The typical programming style using condition variables uses the lock to +synchronize access to some shared state; threads that are interested in a +particular change of state call :meth:`~Condition.wait` repeatedly until they +see the desired state, while threads that modify the state call +:meth:`~Condition.notify` or :meth:`~Condition.notify_all` when they change +the state in such a way that it could possibly be a desired state for one +of the waiters. For example, the following code is a generic +producer-consumer situation with unlimited buffer capacity:: + + # Consume one item + with cv: + while not an_item_is_available(): + cv.wait() + get_an_available_item() + + # Produce one item + with cv: + make_an_item_available() + cv.notify() + +The ``while`` loop checking for the application's condition is necessary +because :meth:`~Condition.wait` can return after an arbitrary long time, +and the condition which prompted the :meth:`~Condition.notify` call may +no longer hold true. This is inherent to multi-threaded programming. The +:meth:`~Condition.wait_for` method can be used to automate the condition +checking, and eases the computation of timeouts:: + + # Consume an item + with cv: + cv.wait_for(an_item_is_available) + get_an_available_item() + +To choose between :meth:`~Condition.notify` and :meth:`~Condition.notify_all`, +consider whether one state change can be interesting for only one or several +waiting threads. E.g. in a typical producer-consumer situation, adding one +item to the buffer only needs to wake up one consumer thread. + + +.. class:: Condition(lock=None) + + This class implements condition variable objects. A condition variable + allows one or more threads to wait until they are notified by another thread. + + If the *lock* argument is given and not ``None``, it must be a :class:`Lock` + or :class:`RLock` object, and it is used as the underlying lock. Otherwise, + a new :class:`RLock` object is created and used as the underlying lock. + + .. versionchanged:: 3.3 + changed from a factory function to a class. + + .. method:: acquire(*args) + + Acquire the underlying lock. This method calls the corresponding method on + the underlying lock; the return value is whatever that method returns. + + .. method:: release() + + Release the underlying lock. This method calls the corresponding method on + the underlying lock; there is no return value. + + .. method:: wait(timeout=None) + + Wait until notified or until a timeout occurs. If the calling thread has + not acquired the lock when this method is called, a :exc:`RuntimeError` is + raised. + + This method releases the underlying lock, and then blocks until it is + awakened by a :meth:`notify` or :meth:`notify_all` call for the same + condition variable in another thread, or until the optional timeout + occurs. Once awakened or timed out, it re-acquires the lock and returns. + + When the *timeout* argument is present and not ``None``, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). + + When the underlying lock is an :class:`RLock`, it is not released using + its :meth:`release` method, since this may not actually unlock the lock + when it was acquired multiple times recursively. Instead, an internal + interface of the :class:`RLock` class is used, which really unlocks it + even when it has been recursively acquired several times. Another internal + interface is then used to restore the recursion level when the lock is + reacquired. + + The return value is ``True`` unless a given *timeout* expired, in which + case it is ``False``. + + .. versionchanged:: 3.2 + Previously, the method always returned ``None``. + + .. method:: wait_for(predicate, timeout=None) + + Wait until a condition evaluates to true. *predicate* should be a + callable which result will be interpreted as a boolean value. + A *timeout* may be provided giving the maximum time to wait. + + This utility method may call :meth:`wait` repeatedly until the predicate + is satisfied, or until a timeout occurs. The return value is + the last return value of the predicate and will evaluate to + ``False`` if the method timed out. + + Ignoring the timeout feature, calling this method is roughly equivalent to + writing:: + + while not predicate(): + cv.wait() + + Therefore, the same rules apply as with :meth:`wait`: The lock must be + held when called and is re-acquired on return. The predicate is evaluated + with the lock held. + + .. versionadded:: 3.2 + + .. method:: notify(n=1) + + By default, wake up one thread waiting on this condition, if any. If the + calling thread has not acquired the lock when this method is called, a + :exc:`RuntimeError` is raised. + + This method wakes up at most *n* of the threads waiting for the condition + variable; it is a no-op if no threads are waiting. + + The current implementation wakes up exactly *n* threads, if at least *n* + threads are waiting. However, it's not safe to rely on this behavior. + A future, optimized implementation may occasionally wake up more than + *n* threads. + + Note: an awakened thread does not actually return from its :meth:`wait` + call until it can reacquire the lock. Since :meth:`notify` does not + release the lock, its caller should. + + .. method:: notify_all() + + Wake up all threads waiting on this condition. This method acts like + :meth:`notify`, but wakes up all waiting threads instead of one. If the + calling thread has not acquired the lock when this method is called, a + :exc:`RuntimeError` is raised. + + +.. _semaphore-objects: + +Semaphore Objects +----------------- + +This is one of the oldest synchronization primitives in the history of computer +science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he +used the names ``P()`` and ``V()`` instead of :meth:`~Semaphore.acquire` and +:meth:`~Semaphore.release`). + +A semaphore manages an internal counter which is decremented by each +:meth:`~Semaphore.acquire` call and incremented by each :meth:`~Semaphore.release` +call. The counter can never go below zero; when :meth:`~Semaphore.acquire` +finds that it is zero, it blocks, waiting until some other thread calls +:meth:`~Semaphore.release`. + +Semaphores also support the :ref:`context management protocol `. + + +.. class:: Semaphore(value=1) + + This class implements semaphore objects. A semaphore manages an atomic + counter representing the number of :meth:`release` calls minus the number of + :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method + blocks if necessary until it can return without making the counter negative. + If not given, *value* defaults to 1. + + The optional argument gives the initial *value* for the internal counter; it + defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is + raised. + + .. versionchanged:: 3.3 + changed from a factory function to a class. + + .. method:: acquire(blocking=True, timeout=None) + + Acquire a semaphore. + + When invoked without arguments: + + * If the internal counter is larger than zero on entry, decrement it by + one and return ``True`` immediately. + * If the internal counter is zero on entry, block until awoken by a call to + :meth:`~Semaphore.release`. Once awoken (and the counter is greater + than 0), decrement the counter by 1 and return ``True``. Exactly one + thread will be awoken by each call to :meth:`~Semaphore.release`. The + order in which threads are awoken should not be relied on. + + When invoked with *blocking* set to false, do not block. If a call + without an argument would block, return ``False`` immediately; otherwise, do + the same thing as when called without arguments, and return ``True``. + + When invoked with a *timeout* other than ``None``, it will block for at + most *timeout* seconds. If acquire does not complete successfully in + that interval, return ``False``. Return ``True`` otherwise. + + .. versionchanged:: 3.2 + The *timeout* parameter is new. + + .. method:: release(n=1) + + Release a semaphore, incrementing the internal counter by *n*. When it + was zero on entry and other threads are waiting for it to become larger + than zero again, wake up *n* of those threads. + + .. versionchanged:: 3.9 + Added the *n* parameter to release multiple waiting threads at once. + + +.. class:: BoundedSemaphore(value=1) + + Class implementing bounded semaphore objects. A bounded semaphore checks to + make sure its current value doesn't exceed its initial value. If it does, + :exc:`ValueError` is raised. In most situations semaphores are used to guard + resources with limited capacity. If the semaphore is released too many times + it's a sign of a bug. If not given, *value* defaults to 1. + + .. versionchanged:: 3.3 + changed from a factory function to a class. + + +.. _semaphore-examples: + +:class:`Semaphore` Example +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Semaphores are often used to guard resources with limited capacity, for example, +a database server. In any situation where the size of the resource is fixed, +you should use a bounded semaphore. Before spawning any worker threads, your +main thread would initialize the semaphore:: + + maxconnections = 5 + # ... + pool_sema = BoundedSemaphore(value=maxconnections) + +Once spawned, worker threads call the semaphore's acquire and release methods +when they need to connect to the server:: + + with pool_sema: + conn = connectdb() + try: + # ... use connection ... + finally: + conn.close() + +The use of a bounded semaphore reduces the chance that a programming error which +causes the semaphore to be released more than it's acquired will go undetected. + + +.. _event-objects: + +Event Objects +------------- + +This is one of the simplest mechanisms for communication between threads: one +thread signals an event and other threads wait for it. + +An event object manages an internal flag that can be set to true with the +:meth:`~Event.set` method and reset to false with the :meth:`~Event.clear` +method. The :meth:`~Event.wait` method blocks until the flag is true. + + +.. class:: Event() + + Class implementing event objects. An event manages a flag that can be set to + true with the :meth:`~Event.set` method and reset to false with the + :meth:`clear` method. The :meth:`wait` method blocks until the flag is true. + The flag is initially false. + + .. versionchanged:: 3.3 + changed from a factory function to a class. + + .. method:: is_set() + + Return ``True`` if and only if the internal flag is true. + + .. method:: set() + + Set the internal flag to true. All threads waiting for it to become true + are awakened. Threads that call :meth:`wait` once the flag is true will + not block at all. + + .. method:: clear() + + Reset the internal flag to false. Subsequently, threads calling + :meth:`wait` will block until :meth:`.set` is called to set the internal + flag to true again. + + .. method:: wait(timeout=None) + + Block until the internal flag is true. If the internal flag is true on + entry, return immediately. Otherwise, block until another thread calls + :meth:`.set` to set the flag to true, or until the optional timeout occurs. + + When the timeout argument is present and not ``None``, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). + + This method returns ``True`` if and only if the internal flag has been set to + true, either before the wait call or after the wait starts, so it will + always return ``True`` except if a timeout is given and the operation + times out. + + .. versionchanged:: 3.1 + Previously, the method always returned ``None``. + + +.. _timer-objects: + +Timer Objects +------------- + +This class represents an action that should be run only after a certain amount +of time has passed --- a timer. :class:`Timer` is a subclass of :class:`Thread` +and as such also functions as an example of creating custom threads. + +Timers are started, as with threads, by calling their :meth:`~Timer.start` +method. The timer can be stopped (before its action has begun) by calling the +:meth:`~Timer.cancel` method. The interval the timer will wait before +executing its action may not be exactly the same as the interval specified by +the user. + +For example:: + + def hello(): + print("hello, world") + + t = Timer(30.0, hello) + t.start() # after 30 seconds, "hello, world" will be printed + + +.. class:: Timer(interval, function, args=None, kwargs=None) + + Create a timer that will run *function* with arguments *args* and keyword + arguments *kwargs*, after *interval* seconds have passed. + If *args* is ``None`` (the default) then an empty list will be used. + If *kwargs* is ``None`` (the default) then an empty dict will be used. + + .. versionchanged:: 3.3 + changed from a factory function to a class. + + .. method:: cancel() + + Stop the timer, and cancel the execution of the timer's action. This will + only work if the timer is still in its waiting stage. + + +Barrier Objects +--------------- + +.. versionadded:: 3.2 + +This class provides a simple synchronization primitive for use by a fixed number +of threads that need to wait for each other. Each of the threads tries to pass +the barrier by calling the :meth:`~Barrier.wait` method and will block until +all of the threads have made their :meth:`~Barrier.wait` calls. At this point, +the threads are released simultaneously. + +The barrier can be reused any number of times for the same number of threads. + +As an example, here is a simple way to synchronize a client and server thread:: + + b = Barrier(2, timeout=5) + + def server(): + start_server() + b.wait() + while True: + connection = accept_connection() + process_server_connection(connection) + + def client(): + b.wait() + while True: + connection = make_connection() + process_client_connection(connection) + + +.. class:: Barrier(parties, action=None, timeout=None) + + Create a barrier object for *parties* number of threads. An *action*, when + provided, is a callable to be called by one of the threads when they are + released. *timeout* is the default timeout value if none is specified for + the :meth:`wait` method. + + .. method:: wait(timeout=None) + + Pass the barrier. When all the threads party to the barrier have called + this function, they are all released simultaneously. If a *timeout* is + provided, it is used in preference to any that was supplied to the class + constructor. + + The return value is an integer in the range 0 to *parties* -- 1, different + for each thread. This can be used to select a thread to do some special + housekeeping, e.g.:: + + i = barrier.wait() + if i == 0: + # Only one thread needs to print this + print("passed the barrier") + + If an *action* was provided to the constructor, one of the threads will + have called it prior to being released. Should this call raise an error, + the barrier is put into the broken state. + + If the call times out, the barrier is put into the broken state. + + This method may raise a :class:`BrokenBarrierError` exception if the + barrier is broken or reset while a thread is waiting. + + .. method:: reset() + + Return the barrier to the default, empty state. Any threads waiting on it + will receive the :class:`BrokenBarrierError` exception. + + Note that using this function may require some external + synchronization if there are other threads whose state is unknown. If a + barrier is broken it may be better to just leave it and create a new one. + + .. method:: abort() + + Put the barrier into a broken state. This causes any active or future + calls to :meth:`wait` to fail with the :class:`BrokenBarrierError`. Use + this for example if one of the threads needs to abort, to avoid deadlocking the + application. + + It may be preferable to simply create the barrier with a sensible + *timeout* value to automatically guard against one of the threads going + awry. + + .. attribute:: parties + + The number of threads required to pass the barrier. + + .. attribute:: n_waiting + + The number of threads currently waiting in the barrier. + + .. attribute:: broken + + A boolean that is ``True`` if the barrier is in the broken state. + + +.. exception:: BrokenBarrierError + + This exception, a subclass of :exc:`RuntimeError`, is raised when the + :class:`Barrier` object is reset or broken. + + +.. _with-locks: + +Using locks, conditions, and semaphores in the :keyword:`!with` statement +------------------------------------------------------------------------- + +All of the objects provided by this module that have :meth:`acquire` and +:meth:`release` methods can be used as context managers for a :keyword:`with` +statement. The :meth:`acquire` method will be called when the block is +entered, and :meth:`release` will be called when the block is exited. Hence, +the following snippet:: + + with some_lock: + # do something... + +is equivalent to:: + + some_lock.acquire() + try: + # do something... + finally: + some_lock.release() + +Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`, +:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as +:keyword:`with` statement context managers. diff --git a/cpython_2/environment/repo/Doc/library/time.rst b/cpython_2/environment/repo/Doc/library/time.rst new file mode 100644 index 0000000000000000000000000000000000000000..cff6320b526db5601d1d3e36bdd16569d6f9b9a2 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/time.rst @@ -0,0 +1,888 @@ +:mod:`time` --- Time access and conversions +=========================================== + +.. module:: time + :synopsis: Time access and conversions. + +-------------- + +This module provides various time-related functions. For related +functionality, see also the :mod:`datetime` and :mod:`calendar` modules. + +Although this module is always available, +not all functions are available on all platforms. Most of the functions +defined in this module call platform C library functions with the same name. It +may sometimes be helpful to consult the platform documentation, because the +semantics of these functions varies among platforms. + +An explanation of some terminology and conventions is in order. + +.. _epoch: + +.. index:: single: epoch + +* The :dfn:`epoch` is the point where the time starts, and is platform + dependent. For Unix, the epoch is January 1, 1970, 00:00:00 (UTC). + To find out what the epoch is on a given platform, look at + ``time.gmtime(0)``. + +.. _leap seconds: https://en.wikipedia.org/wiki/Leap_second + +.. index:: seconds since the epoch + +* The term :dfn:`seconds since the epoch` refers to the total number + of elapsed seconds since the epoch, typically excluding + `leap seconds`_. Leap seconds are excluded from this total on all + POSIX-compliant platforms. + +.. index:: single: Year 2038 + +* The functions in this module may not handle dates and times before the epoch or + far in the future. The cut-off point in the future is determined by the C + library; for 32-bit systems, it is typically in 2038. + +.. index:: + single: 2-digit years + +* Function :func:`strptime` can parse 2-digit years when given ``%y`` format + code. When 2-digit years are parsed, they are converted according to the POSIX + and ISO C standards: values 69--99 are mapped to 1969--1999, and values 0--68 + are mapped to 2000--2068. + +.. index:: + single: UTC + single: Coordinated Universal Time + single: Greenwich Mean Time + +* UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, or + GMT). The acronym UTC is not a mistake but a compromise between English and + French. + +.. index:: single: Daylight Saving Time + +* DST is Daylight Saving Time, an adjustment of the timezone by (usually) one + hour during part of the year. DST rules are magic (determined by local law) and + can change from year to year. The C library has a table containing the local + rules (often it is read from a system file for flexibility) and is the only + source of True Wisdom in this respect. + +* The precision of the various real-time functions may be less than suggested by + the units in which their value or argument is expressed. E.g. on most Unix + systems, the clock "ticks" only 50 or 100 times a second. + +* On the other hand, the precision of :func:`.time` and :func:`sleep` is better + than their Unix equivalents: times are expressed as floating point numbers, + :func:`.time` returns the most accurate time available (using Unix + :c:func:`gettimeofday` where available), and :func:`sleep` will accept a time + with a nonzero fraction (Unix :c:func:`select` is used to implement this, where + available). + +* The time value as returned by :func:`gmtime`, :func:`localtime`, and + :func:`strptime`, and accepted by :func:`asctime`, :func:`mktime` and + :func:`strftime`, is a sequence of 9 integers. The return values of + :func:`gmtime`, :func:`localtime`, and :func:`strptime` also offer attribute + names for individual fields. + + See :class:`struct_time` for a description of these objects. + + .. versionchanged:: 3.3 + The :class:`struct_time` type was extended to provide the :attr:`tm_gmtoff` + and :attr:`tm_zone` attributes when platform supports corresponding + ``struct tm`` members. + + .. versionchanged:: 3.6 + The :class:`struct_time` attributes :attr:`tm_gmtoff` and :attr:`tm_zone` + are now available on all platforms. + +* Use the following functions to convert between time representations: + + +-------------------------+-------------------------+-------------------------+ + | From | To | Use | + +=========================+=========================+=========================+ + | seconds since the epoch | :class:`struct_time` in | :func:`gmtime` | + | | UTC | | + +-------------------------+-------------------------+-------------------------+ + | seconds since the epoch | :class:`struct_time` in | :func:`localtime` | + | | local time | | + +-------------------------+-------------------------+-------------------------+ + | :class:`struct_time` in | seconds since the epoch | :func:`calendar.timegm` | + | UTC | | | + +-------------------------+-------------------------+-------------------------+ + | :class:`struct_time` in | seconds since the epoch | :func:`mktime` | + | local time | | | + +-------------------------+-------------------------+-------------------------+ + + +.. _time-functions: + +Functions +--------- + +.. function:: asctime([t]) + + Convert a tuple or :class:`struct_time` representing a time as returned by + :func:`gmtime` or :func:`localtime` to a string of the following + form: ``'Sun Jun 20 23:21:05 1993'``. The day field is two characters long + and is space padded if the day is a single digit, + e.g.: ``'Wed Jun 9 04:26:40 1993'``. + + If *t* is not provided, the current time as returned by :func:`localtime` + is used. Locale information is not used by :func:`asctime`. + + .. note:: + + Unlike the C function of the same name, :func:`asctime` does not add a + trailing newline. + +.. function:: pthread_getcpuclockid(thread_id) + + Return the *clk_id* of the thread-specific CPU-time clock for the specified *thread_id*. + + Use :func:`threading.get_ident` or the :attr:`~threading.Thread.ident` + attribute of :class:`threading.Thread` objects to get a suitable value + for *thread_id*. + + .. warning:: + Passing an invalid or expired *thread_id* may result in + undefined behavior, such as segmentation fault. + + .. availability:: Unix (see the man page for :manpage:`pthread_getcpuclockid(3)` for + further information). + + .. versionadded:: 3.7 + +.. function:: clock_getres(clk_id) + + Return the resolution (precision) of the specified clock *clk_id*. Refer to + :ref:`time-clock-id-constants` for a list of accepted values for *clk_id*. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: clock_gettime(clk_id) -> float + + Return the time of the specified clock *clk_id*. Refer to + :ref:`time-clock-id-constants` for a list of accepted values for *clk_id*. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: clock_gettime_ns(clk_id) -> int + + Similar to :func:`clock_gettime` but return time as nanoseconds. + + .. availability:: Unix. + + .. versionadded:: 3.7 + + +.. function:: clock_settime(clk_id, time: float) + + Set the time of the specified clock *clk_id*. Currently, + :data:`CLOCK_REALTIME` is the only accepted value for *clk_id*. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. function:: clock_settime_ns(clk_id, time: int) + + Similar to :func:`clock_settime` but set time with nanoseconds. + + .. availability:: Unix. + + .. versionadded:: 3.7 + + +.. function:: ctime([secs]) + + Convert a time expressed in seconds since the epoch to a string of a form: + ``'Sun Jun 20 23:21:05 1993'`` representing local time. The day field + is two characters long and is space padded if the day is a single digit, + e.g.: ``'Wed Jun 9 04:26:40 1993'``. + + If *secs* is not provided or :const:`None`, the current time as + returned by :func:`.time` is used. ``ctime(secs)`` is equivalent to + ``asctime(localtime(secs))``. Locale information is not used by + :func:`ctime`. + + +.. function:: get_clock_info(name) + + Get information on the specified clock as a namespace object. + Supported clock names and the corresponding functions to read their value + are: + + * ``'monotonic'``: :func:`time.monotonic` + * ``'perf_counter'``: :func:`time.perf_counter` + * ``'process_time'``: :func:`time.process_time` + * ``'thread_time'``: :func:`time.thread_time` + * ``'time'``: :func:`time.time` + + The result has the following attributes: + + - *adjustable*: ``True`` if the clock can be changed automatically (e.g. by + a NTP daemon) or manually by the system administrator, ``False`` otherwise + - *implementation*: The name of the underlying C function used to get + the clock value. Refer to :ref:`time-clock-id-constants` for possible values. + - *monotonic*: ``True`` if the clock cannot go backward, + ``False`` otherwise + - *resolution*: The resolution of the clock in seconds (:class:`float`) + + .. versionadded:: 3.3 + + +.. function:: gmtime([secs]) + + Convert a time expressed in seconds since the epoch to a :class:`struct_time` in + UTC in which the dst flag is always zero. If *secs* is not provided or + :const:`None`, the current time as returned by :func:`.time` is used. Fractions + of a second are ignored. See above for a description of the + :class:`struct_time` object. See :func:`calendar.timegm` for the inverse of this + function. + + +.. function:: localtime([secs]) + + Like :func:`gmtime` but converts to local time. If *secs* is not provided or + :const:`None`, the current time as returned by :func:`.time` is used. The dst + flag is set to ``1`` when DST applies to the given time. + + +.. function:: mktime(t) + + This is the inverse function of :func:`localtime`. Its argument is the + :class:`struct_time` or full 9-tuple (since the dst flag is needed; use ``-1`` + as the dst flag if it is unknown) which expresses the time in *local* time, not + UTC. It returns a floating point number, for compatibility with :func:`.time`. + If the input value cannot be represented as a valid time, either + :exc:`OverflowError` or :exc:`ValueError` will be raised (which depends on + whether the invalid value is caught by Python or the underlying C libraries). + The earliest date for which it can generate a time is platform-dependent. + + +.. function:: monotonic() -> float + + Return the value (in fractional seconds) of a monotonic clock, i.e. a clock + that cannot go backwards. The clock is not affected by system clock updates. + The reference point of the returned value is undefined, so that only the + difference between the results of consecutive calls is valid. + + .. versionadded:: 3.3 + .. versionchanged:: 3.5 + The function is now always available and always system-wide. + + +.. function:: monotonic_ns() -> int + + Similar to :func:`monotonic`, but return time as nanoseconds. + + .. versionadded:: 3.7 + +.. function:: perf_counter() -> float + + .. index:: + single: benchmarking + + Return the value (in fractional seconds) of a performance counter, i.e. a + clock with the highest available resolution to measure a short duration. It + does include time elapsed during sleep and is system-wide. The reference + point of the returned value is undefined, so that only the difference between + the results of consecutive calls is valid. + + .. versionadded:: 3.3 + +.. function:: perf_counter_ns() -> int + + Similar to :func:`perf_counter`, but return time as nanoseconds. + + .. versionadded:: 3.7 + + +.. function:: process_time() -> float + + .. index:: + single: CPU time + single: processor time + single: benchmarking + + Return the value (in fractional seconds) of the sum of the system and user + CPU time of the current process. It does not include time elapsed during + sleep. It is process-wide by definition. The reference point of the + returned value is undefined, so that only the difference between the results + of consecutive calls is valid. + + .. versionadded:: 3.3 + +.. function:: process_time_ns() -> int + + Similar to :func:`process_time` but return time as nanoseconds. + + .. versionadded:: 3.7 + +.. function:: sleep(secs) + + Suspend execution of the calling thread for the given number of seconds. + The argument may be a floating point number to indicate a more precise sleep + time. The actual suspension time may be less than that requested because any + caught signal will terminate the :func:`sleep` following execution of that + signal's catching routine. Also, the suspension time may be longer than + requested by an arbitrary amount because of the scheduling of other activity + in the system. + + .. versionchanged:: 3.5 + The function now sleeps at least *secs* even if the sleep is interrupted + by a signal, except if the signal handler raises an exception (see + :pep:`475` for the rationale). + + +.. index:: + single: % (percent); datetime format + +.. function:: strftime(format[, t]) + + Convert a tuple or :class:`struct_time` representing a time as returned by + :func:`gmtime` or :func:`localtime` to a string as specified by the *format* + argument. If *t* is not provided, the current time as returned by + :func:`localtime` is used. *format* must be a string. :exc:`ValueError` is + raised if any field in *t* is outside of the allowed range. + + 0 is a legal argument for any position in the time tuple; if it is normally + illegal the value is forced to a correct one. + + The following directives can be embedded in the *format* string. They are shown + without the optional field width and precision specification, and are replaced + by the indicated characters in the :func:`strftime` result: + + +-----------+------------------------------------------------+-------+ + | Directive | Meaning | Notes | + +===========+================================================+=======+ + | ``%a`` | Locale's abbreviated weekday name. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%A`` | Locale's full weekday name. | | + +-----------+------------------------------------------------+-------+ + | ``%b`` | Locale's abbreviated month name. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%B`` | Locale's full month name. | | + +-----------+------------------------------------------------+-------+ + | ``%c`` | Locale's appropriate date and time | | + | | representation. | | + +-----------+------------------------------------------------+-------+ + | ``%d`` | Day of the month as a decimal number [01,31]. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%H`` | Hour (24-hour clock) as a decimal number | | + | | [00,23]. | | + +-----------+------------------------------------------------+-------+ + | ``%I`` | Hour (12-hour clock) as a decimal number | | + | | [01,12]. | | + +-----------+------------------------------------------------+-------+ + | ``%j`` | Day of the year as a decimal number [001,366]. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%m`` | Month as a decimal number [01,12]. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%M`` | Minute as a decimal number [00,59]. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%p`` | Locale's equivalent of either AM or PM. | \(1) | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%S`` | Second as a decimal number [00,61]. | \(2) | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%U`` | Week number of the year (Sunday as the first | \(3) | + | | day of the week) as a decimal number [00,53]. | | + | | All days in a new year preceding the first | | + | | Sunday are considered to be in week 0. | | + | | | | + | | | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%w`` | Weekday as a decimal number [0(Sunday),6]. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%W`` | Week number of the year (Monday as the first | \(3) | + | | day of the week) as a decimal number [00,53]. | | + | | All days in a new year preceding the first | | + | | Monday are considered to be in week 0. | | + | | | | + | | | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%x`` | Locale's appropriate date representation. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%X`` | Locale's appropriate time representation. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%y`` | Year without century as a decimal number | | + | | [00,99]. | | + +-----------+------------------------------------------------+-------+ + | ``%Y`` | Year with century as a decimal number. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%z`` | Time zone offset indicating a positive or | | + | | negative time difference from UTC/GMT of the | | + | | form +HHMM or -HHMM, where H represents decimal| | + | | hour digits and M represents decimal minute | | + | | digits [-23:59, +23:59]. | | + +-----------+------------------------------------------------+-------+ + | ``%Z`` | Time zone name (no characters if no time zone | | + | | exists). | | + +-----------+------------------------------------------------+-------+ + | ``%%`` | A literal ``'%'`` character. | | + +-----------+------------------------------------------------+-------+ + + Notes: + + (1) + When used with the :func:`strptime` function, the ``%p`` directive only affects + the output hour field if the ``%I`` directive is used to parse the hour. + + (2) + The range really is ``0`` to ``61``; value ``60`` is valid in + timestamps representing `leap seconds`_ and value ``61`` is supported + for historical reasons. + + (3) + When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in + calculations when the day of the week and the year are specified. + + Here is an example, a format for dates compatible with that specified in the + :rfc:`2822` Internet email standard. [#]_ :: + + >>> from time import gmtime, strftime + >>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) + 'Thu, 28 Jun 2001 14:17:15 +0000' + + Additional directives may be supported on certain platforms, but only the + ones listed here have a meaning standardized by ANSI C. To see the full set + of format codes supported on your platform, consult the :manpage:`strftime(3)` + documentation. + + On some platforms, an optional field width and precision specification can + immediately follow the initial ``'%'`` of a directive in the following order; + this is also not portable. The field width is normally 2 except for ``%j`` where + it is 3. + + +.. index:: + single: % (percent); datetime format + +.. function:: strptime(string[, format]) + + Parse a string representing a time according to a format. The return value + is a :class:`struct_time` as returned by :func:`gmtime` or + :func:`localtime`. + + The *format* parameter uses the same directives as those used by + :func:`strftime`; it defaults to ``"%a %b %d %H:%M:%S %Y"`` which matches the + formatting returned by :func:`ctime`. If *string* cannot be parsed according + to *format*, or if it has excess data after parsing, :exc:`ValueError` is + raised. The default values used to fill in any missing data when more + accurate values cannot be inferred are ``(1900, 1, 1, 0, 0, 0, 0, 1, -1)``. + Both *string* and *format* must be strings. + + For example: + + >>> import time + >>> time.strptime("30 Nov 00", "%d %b %y") # doctest: +NORMALIZE_WHITESPACE + time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, + tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1) + + Support for the ``%Z`` directive is based on the values contained in ``tzname`` + and whether ``daylight`` is true. Because of this, it is platform-specific + except for recognizing UTC and GMT which are always known (and are considered to + be non-daylight savings timezones). + + Only the directives specified in the documentation are supported. Because + ``strftime()`` is implemented per platform it can sometimes offer more + directives than those listed. But ``strptime()`` is independent of any platform + and thus does not necessarily support all directives available that are not + documented as supported. + + +.. class:: struct_time + + The type of the time value sequence returned by :func:`gmtime`, + :func:`localtime`, and :func:`strptime`. It is an object with a :term:`named + tuple` interface: values can be accessed by index and by attribute name. The + following values are present: + + +-------+-------------------+---------------------------------+ + | Index | Attribute | Values | + +=======+===================+=================================+ + | 0 | :attr:`tm_year` | (for example, 1993) | + +-------+-------------------+---------------------------------+ + | 1 | :attr:`tm_mon` | range [1, 12] | + +-------+-------------------+---------------------------------+ + | 2 | :attr:`tm_mday` | range [1, 31] | + +-------+-------------------+---------------------------------+ + | 3 | :attr:`tm_hour` | range [0, 23] | + +-------+-------------------+---------------------------------+ + | 4 | :attr:`tm_min` | range [0, 59] | + +-------+-------------------+---------------------------------+ + | 5 | :attr:`tm_sec` | range [0, 61]; see **(2)** in | + | | | :func:`strftime` description | + +-------+-------------------+---------------------------------+ + | 6 | :attr:`tm_wday` | range [0, 6], Monday is 0 | + +-------+-------------------+---------------------------------+ + | 7 | :attr:`tm_yday` | range [1, 366] | + +-------+-------------------+---------------------------------+ + | 8 | :attr:`tm_isdst` | 0, 1 or -1; see below | + +-------+-------------------+---------------------------------+ + | N/A | :attr:`tm_zone` | abbreviation of timezone name | + +-------+-------------------+---------------------------------+ + | N/A | :attr:`tm_gmtoff` | offset east of UTC in seconds | + +-------+-------------------+---------------------------------+ + + Note that unlike the C structure, the month value is a range of [1, 12], not + [0, 11]. + + In calls to :func:`mktime`, :attr:`tm_isdst` may be set to 1 when daylight + savings time is in effect, and 0 when it is not. A value of -1 indicates that + this is not known, and will usually result in the correct state being filled in. + + When a tuple with an incorrect length is passed to a function expecting a + :class:`struct_time`, or having elements of the wrong type, a + :exc:`TypeError` is raised. + +.. function:: time() -> float + + Return the time in seconds since the epoch_ as a floating point + number. The specific date of the epoch and the handling of + `leap seconds`_ is platform dependent. + On Windows and most Unix systems, the epoch is January 1, 1970, + 00:00:00 (UTC) and leap seconds are not counted towards the time + in seconds since the epoch. This is commonly referred to as + `Unix time `_. + To find out what the epoch is on a given platform, look at + ``gmtime(0)``. + + Note that even though the time is always returned as a floating point + number, not all systems provide time with a better precision than 1 second. + While this function normally returns non-decreasing values, it can return a + lower value than a previous call if the system clock has been set back + between the two calls. + + The number returned by :func:`.time` may be converted into a more common + time format (i.e. year, month, day, hour, etc...) in UTC by passing it to + :func:`gmtime` function or in local time by passing it to the + :func:`localtime` function. In both cases a + :class:`struct_time` object is returned, from which the components + of the calendar date may be accessed as attributes. + + +.. function:: thread_time() -> float + + .. index:: + single: CPU time + single: processor time + single: benchmarking + + Return the value (in fractional seconds) of the sum of the system and user + CPU time of the current thread. It does not include time elapsed during + sleep. It is thread-specific by definition. The reference point of the + returned value is undefined, so that only the difference between the results + of consecutive calls in the same thread is valid. + + .. availability:: Windows, Linux, Unix systems supporting + ``CLOCK_THREAD_CPUTIME_ID``. + + .. versionadded:: 3.7 + + +.. function:: thread_time_ns() -> int + + Similar to :func:`thread_time` but return time as nanoseconds. + + .. versionadded:: 3.7 + + +.. function:: time_ns() -> int + + Similar to :func:`~time.time` but returns time as an integer number of nanoseconds + since the epoch_. + + .. versionadded:: 3.7 + +.. function:: tzset() + + Reset the time conversion rules used by the library routines. The environment + variable :envvar:`TZ` specifies how this is done. It will also set the variables + ``tzname`` (from the :envvar:`TZ` environment variable), ``timezone`` (non-DST + seconds West of UTC), ``altzone`` (DST seconds west of UTC) and ``daylight`` + (to 0 if this timezone does not have any daylight saving time rules, or to + nonzero if there is a time, past, present or future when daylight saving time + applies). + + .. availability:: Unix. + + .. note:: + + Although in many cases, changing the :envvar:`TZ` environment variable may + affect the output of functions like :func:`localtime` without calling + :func:`tzset`, this behavior should not be relied on. + + The :envvar:`TZ` environment variable should contain no whitespace. + + The standard format of the :envvar:`TZ` environment variable is (whitespace + added for clarity):: + + std offset [dst [offset [,start[/time], end[/time]]]] + + Where the components are: + + ``std`` and ``dst`` + Three or more alphanumerics giving the timezone abbreviations. These will be + propagated into time.tzname + + ``offset`` + The offset has the form: ``± hh[:mm[:ss]]``. This indicates the value + added the local time to arrive at UTC. If preceded by a '-', the timezone + is east of the Prime Meridian; otherwise, it is west. If no offset follows + dst, summer time is assumed to be one hour ahead of standard time. + + ``start[/time], end[/time]`` + Indicates when to change to and back from DST. The format of the + start and end dates are one of the following: + + :samp:`J{n}` + The Julian day *n* (1 <= *n* <= 365). Leap days are not counted, so in + all years February 28 is day 59 and March 1 is day 60. + + :samp:`{n}` + The zero-based Julian day (0 <= *n* <= 365). Leap days are counted, and + it is possible to refer to February 29. + + :samp:`M{m}.{n}.{d}` + The *d*'th day (0 <= *d* <= 6) of week *n* of month *m* of the year (1 + <= *n* <= 5, 1 <= *m* <= 12, where week 5 means "the last *d* day in + month *m*" which may occur in either the fourth or the fifth + week). Week 1 is the first week in which the *d*'th day occurs. Day + zero is a Sunday. + + ``time`` has the same format as ``offset`` except that no leading sign + ('-' or '+') is allowed. The default, if time is not given, is 02:00:00. + + :: + + >>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0' + >>> time.tzset() + >>> time.strftime('%X %x %Z') + '02:07:36 05/08/03 EDT' + >>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0' + >>> time.tzset() + >>> time.strftime('%X %x %Z') + '16:08:12 05/08/03 AEST' + + On many Unix systems (including \*BSD, Linux, Solaris, and Darwin), it is more + convenient to use the system's zoneinfo (:manpage:`tzfile(5)`) database to + specify the timezone rules. To do this, set the :envvar:`TZ` environment + variable to the path of the required timezone datafile, relative to the root of + the systems 'zoneinfo' timezone database, usually located at + :file:`/usr/share/zoneinfo`. For example, ``'US/Eastern'``, + ``'Australia/Melbourne'``, ``'Egypt'`` or ``'Europe/Amsterdam'``. :: + + >>> os.environ['TZ'] = 'US/Eastern' + >>> time.tzset() + >>> time.tzname + ('EST', 'EDT') + >>> os.environ['TZ'] = 'Egypt' + >>> time.tzset() + >>> time.tzname + ('EET', 'EEST') + + +.. _time-clock-id-constants: + +Clock ID Constants +------------------ + +These constants are used as parameters for :func:`clock_getres` and +:func:`clock_gettime`. + +.. data:: CLOCK_BOOTTIME + + Identical to :data:`CLOCK_MONOTONIC`, except it also includes any time that + the system is suspended. + + This allows applications to get a suspend-aware monotonic clock without + having to deal with the complications of :data:`CLOCK_REALTIME`, which may + have discontinuities if the time is changed using ``settimeofday()`` or + similar. + + .. availability:: Linux 2.6.39 or later. + + .. versionadded:: 3.7 + + +.. data:: CLOCK_HIGHRES + + The Solaris OS has a ``CLOCK_HIGHRES`` timer that attempts to use an optimal + hardware source, and may give close to nanosecond resolution. + ``CLOCK_HIGHRES`` is the nonadjustable, high-resolution clock. + + .. availability:: Solaris. + + .. versionadded:: 3.3 + + +.. data:: CLOCK_MONOTONIC + + Clock that cannot be set and represents monotonic time since some unspecified + starting point. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. data:: CLOCK_MONOTONIC_RAW + + Similar to :data:`CLOCK_MONOTONIC`, but provides access to a raw + hardware-based time that is not subject to NTP adjustments. + + .. availability:: Linux 2.6.28 and newer, macOS 10.12 and newer. + + .. versionadded:: 3.3 + + +.. data:: CLOCK_PROCESS_CPUTIME_ID + + High-resolution per-process timer from the CPU. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. data:: CLOCK_PROF + + High-resolution per-process timer from the CPU. + + .. availability:: FreeBSD, NetBSD 7 or later, OpenBSD. + + .. versionadded:: 3.7 + +.. data:: CLOCK_TAI + + `International Atomic Time `_ + + The system must have a current leap second table in order for this to give + the correct answer. PTP or NTP software can maintain a leap second table. + + .. availability:: Linux. + + .. versionadded:: 3.9 + +.. data:: CLOCK_THREAD_CPUTIME_ID + + Thread-specific CPU-time clock. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. data:: CLOCK_UPTIME + + Time whose absolute value is the time the system has been running and not + suspended, providing accurate uptime measurement, both absolute and + interval. + + .. availability:: FreeBSD, OpenBSD 5.5 or later. + + .. versionadded:: 3.7 + + +.. data:: CLOCK_UPTIME_RAW + + Clock that increments monotonically, tracking the time since an arbitrary + point, unaffected by frequency or time adjustments and not incremented while + the system is asleep. + + .. availability:: macOS 10.12 and newer. + + .. versionadded:: 3.8 + +The following constant is the only parameter that can be sent to +:func:`clock_settime`. + + +.. data:: CLOCK_REALTIME + + System-wide real-time clock. Setting this clock requires appropriate + privileges. + + .. availability:: Unix. + + .. versionadded:: 3.3 + + +.. _time-timezone-constants: + +Timezone Constants +------------------- + +.. data:: altzone + + The offset of the local DST timezone, in seconds west of UTC, if one is defined. + This is negative if the local DST timezone is east of UTC (as in Western Europe, + including the UK). Only use this if ``daylight`` is nonzero. See note below. + +.. data:: daylight + + Nonzero if a DST timezone is defined. See note below. + +.. data:: timezone + + The offset of the local (non-DST) timezone, in seconds west of UTC (negative in + most of Western Europe, positive in the US, zero in the UK). See note below. + +.. data:: tzname + + A tuple of two strings: the first is the name of the local non-DST timezone, the + second is the name of the local DST timezone. If no DST timezone is defined, + the second string should not be used. See note below. + +.. note:: + + For the above Timezone constants (:data:`altzone`, :data:`daylight`, :data:`timezone`, + and :data:`tzname`), the value is determined by the timezone rules in effect + at module load time or the last time :func:`tzset` is called and may be incorrect + for times in the past. It is recommended to use the :attr:`tm_gmtoff` and + :attr:`tm_zone` results from :func:`localtime` to obtain timezone information. + + +.. seealso:: + + Module :mod:`datetime` + More object-oriented interface to dates and times. + + Module :mod:`locale` + Internationalization services. The locale setting affects the interpretation + of many format specifiers in :func:`strftime` and :func:`strptime`. + + Module :mod:`calendar` + General calendar-related functions. :func:`~calendar.timegm` is the + inverse of :func:`gmtime` from this module. + +.. rubric:: Footnotes + +.. [#] The use of ``%Z`` is now deprecated, but the ``%z`` escape that expands to the + preferred hour/minute offset is not supported by all ANSI C libraries. Also, a + strict reading of the original 1982 :rfc:`822` standard calls for a two-digit + year (%y rather than %Y), but practice moved to 4-digit years long before the + year 2000. After that, :rfc:`822` became obsolete and the 4-digit year has + been first recommended by :rfc:`1123` and then mandated by :rfc:`2822`. + diff --git a/cpython_2/environment/repo/Doc/library/timeit.rst b/cpython_2/environment/repo/Doc/library/timeit.rst new file mode 100644 index 0000000000000000000000000000000000000000..46fa62c15fc2ef0001b114ea018f333c6706db06 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/timeit.rst @@ -0,0 +1,372 @@ +:mod:`timeit` --- Measure execution time of small code snippets +=============================================================== + +.. module:: timeit + :synopsis: Measure the execution time of small code snippets. + +**Source code:** :source:`Lib/timeit.py` + +.. index:: + single: Benchmarking + single: Performance + +-------------- + +This module provides a simple way to time small bits of Python code. It has both +a :ref:`timeit-command-line-interface` as well as a :ref:`callable ` +one. It avoids a number of common traps for measuring execution times. +See also Tim Peters' introduction to the "Algorithms" chapter in the *Python +Cookbook*, published by O'Reilly. + + +Basic Examples +-------------- + +The following example shows how the :ref:`timeit-command-line-interface` +can be used to compare three different expressions: + +.. code-block:: shell-session + + $ python3 -m timeit '"-".join(str(n) for n in range(100))' + 10000 loops, best of 5: 30.2 usec per loop + $ python3 -m timeit '"-".join([str(n) for n in range(100)])' + 10000 loops, best of 5: 27.5 usec per loop + $ python3 -m timeit '"-".join(map(str, range(100)))' + 10000 loops, best of 5: 23.2 usec per loop + +This can be achieved from the :ref:`python-interface` with:: + + >>> import timeit + >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) + 0.3018611848820001 + >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000) + 0.2727368790656328 + >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000) + 0.23702679807320237 + +A callable can also be passed from the :ref:`python-interface`:: + + >>> timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000) + 0.19665591977536678 + +Note however that :func:`.timeit` will automatically determine the number of +repetitions only when the command-line interface is used. In the +:ref:`timeit-examples` section you can find more advanced examples. + + +.. _python-interface: + +Python Interface +---------------- + +The module defines three convenience functions and a public class: + + +.. function:: timeit(stmt='pass', setup='pass', timer=, number=1000000, globals=None) + + Create a :class:`Timer` instance with the given statement, *setup* code and + *timer* function and run its :meth:`.timeit` method with *number* executions. + The optional *globals* argument specifies a namespace in which to execute the + code. + + .. versionchanged:: 3.5 + The optional *globals* parameter was added. + + +.. function:: repeat(stmt='pass', setup='pass', timer=, repeat=5, number=1000000, globals=None) + + Create a :class:`Timer` instance with the given statement, *setup* code and + *timer* function and run its :meth:`.repeat` method with the given *repeat* + count and *number* executions. The optional *globals* argument specifies a + namespace in which to execute the code. + + .. versionchanged:: 3.5 + The optional *globals* parameter was added. + + .. versionchanged:: 3.7 + Default value of *repeat* changed from 3 to 5. + +.. function:: default_timer() + + The default timer, which is always :func:`time.perf_counter`. + + .. versionchanged:: 3.3 + :func:`time.perf_counter` is now the default timer. + + +.. class:: Timer(stmt='pass', setup='pass', timer=, globals=None) + + Class for timing execution speed of small code snippets. + + The constructor takes a statement to be timed, an additional statement used + for setup, and a timer function. Both statements default to ``'pass'``; + the timer function is platform-dependent (see the module doc string). + *stmt* and *setup* may also contain multiple statements separated by ``;`` + or newlines, as long as they don't contain multi-line string literals. The + statement will by default be executed within timeit's namespace; this behavior + can be controlled by passing a namespace to *globals*. + + To measure the execution time of the first statement, use the :meth:`.timeit` + method. The :meth:`.repeat` and :meth:`.autorange` methods are convenience + methods to call :meth:`.timeit` multiple times. + + The execution time of *setup* is excluded from the overall timed execution run. + + The *stmt* and *setup* parameters can also take objects that are callable + without arguments. This will embed calls to them in a timer function that + will then be executed by :meth:`.timeit`. Note that the timing overhead is a + little larger in this case because of the extra function calls. + + .. versionchanged:: 3.5 + The optional *globals* parameter was added. + + .. method:: Timer.timeit(number=1000000) + + Time *number* executions of the main statement. This executes the setup + statement once, and then returns the time it takes to execute the main + statement a number of times, measured in seconds as a float. + The argument is the number of times through the loop, defaulting to one + million. The main statement, the setup statement and the timer function + to be used are passed to the constructor. + + .. note:: + + By default, :meth:`.timeit` temporarily turns off :term:`garbage + collection` during the timing. The advantage of this approach is that + it makes independent timings more comparable. The disadvantage is + that GC may be an important component of the performance of the + function being measured. If so, GC can be re-enabled as the first + statement in the *setup* string. For example:: + + timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit() + + + .. method:: Timer.autorange(callback=None) + + Automatically determine how many times to call :meth:`.timeit`. + + This is a convenience function that calls :meth:`.timeit` repeatedly + so that the total time >= 0.2 second, returning the eventual + (number of loops, time taken for that number of loops). It calls + :meth:`.timeit` with increasing numbers from the sequence 1, 2, 5, + 10, 20, 50, ... until the time taken is at least 0.2 second. + + If *callback* is given and is not ``None``, it will be called after + each trial with two arguments: ``callback(number, time_taken)``. + + .. versionadded:: 3.6 + + + .. method:: Timer.repeat(repeat=5, number=1000000) + + Call :meth:`.timeit` a few times. + + This is a convenience function that calls the :meth:`.timeit` repeatedly, + returning a list of results. The first argument specifies how many times + to call :meth:`.timeit`. The second argument specifies the *number* + argument for :meth:`.timeit`. + + .. note:: + + It's tempting to calculate mean and standard deviation from the result + vector and report these. However, this is not very useful. + In a typical case, the lowest value gives a lower bound for how fast + your machine can run the given code snippet; higher values in the + result vector are typically not caused by variability in Python's + speed, but by other processes interfering with your timing accuracy. + So the :func:`min` of the result is probably the only number you + should be interested in. After that, you should look at the entire + vector and apply common sense rather than statistics. + + .. versionchanged:: 3.7 + Default value of *repeat* changed from 3 to 5. + + + .. method:: Timer.print_exc(file=None) + + Helper to print a traceback from the timed code. + + Typical use:: + + t = Timer(...) # outside the try/except + try: + t.timeit(...) # or t.repeat(...) + except Exception: + t.print_exc() + + The advantage over the standard traceback is that source lines in the + compiled template will be displayed. The optional *file* argument directs + where the traceback is sent; it defaults to :data:`sys.stderr`. + + +.. _timeit-command-line-interface: + +Command-Line Interface +---------------------- + +When called as a program from the command line, the following form is used:: + + python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [statement ...] + +Where the following options are understood: + +.. program:: timeit + +.. cmdoption:: -n N, --number=N + + how many times to execute 'statement' + +.. cmdoption:: -r N, --repeat=N + + how many times to repeat the timer (default 5) + +.. cmdoption:: -s S, --setup=S + + statement to be executed once initially (default ``pass``) + +.. cmdoption:: -p, --process + + measure process time, not wallclock time, using :func:`time.process_time` + instead of :func:`time.perf_counter`, which is the default + + .. versionadded:: 3.3 + +.. cmdoption:: -u, --unit=U + + specify a time unit for timer output; can select nsec, usec, msec, or sec + + .. versionadded:: 3.5 + +.. cmdoption:: -v, --verbose + + print raw timing results; repeat for more digits precision + +.. cmdoption:: -h, --help + + print a short usage message and exit + +A multi-line statement may be given by specifying each line as a separate +statement argument; indented lines are possible by enclosing an argument in +quotes and using leading spaces. Multiple :option:`-s` options are treated +similarly. + +If :option:`-n` is not given, a suitable number of loops is calculated by trying +increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the total +time is at least 0.2 seconds. + +:func:`default_timer` measurements can be affected by other programs running on +the same machine, so the best thing to do when accurate timing is necessary is +to repeat the timing a few times and use the best time. The :option:`-r` +option is good for this; the default of 5 repetitions is probably enough in +most cases. You can use :func:`time.process_time` to measure CPU time. + +.. note:: + + There is a certain baseline overhead associated with executing a pass statement. + The code here doesn't try to hide it, but you should be aware of it. The + baseline overhead can be measured by invoking the program without arguments, + and it might differ between Python versions. + + +.. _timeit-examples: + +Examples +-------- + +It is possible to provide a setup statement that is executed only once at the beginning: + +.. code-block:: shell-session + + $ python -m timeit -s 'text = "sample string"; char = "g"' 'char in text' + 5000000 loops, best of 5: 0.0877 usec per loop + $ python -m timeit -s 'text = "sample string"; char = "g"' 'text.find(char)' + 1000000 loops, best of 5: 0.342 usec per loop + +:: + + >>> import timeit + >>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"') + 0.41440500499993504 + >>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"') + 1.7246671520006203 + +The same can be done using the :class:`Timer` class and its methods:: + + >>> import timeit + >>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"') + >>> t.timeit() + 0.3955516149999312 + >>> t.repeat() + [0.40183617287970225, 0.37027556854118704, 0.38344867356679524, 0.3712595970846668, 0.37866875250654886] + + +The following examples show how to time expressions that contain multiple lines. +Here we compare the cost of using :func:`hasattr` vs. :keyword:`try`/:keyword:`except` +to test for missing and present object attributes: + +.. code-block:: shell-session + + $ python -m timeit 'try:' ' str.__bool__' 'except AttributeError:' ' pass' + 20000 loops, best of 5: 15.7 usec per loop + $ python -m timeit 'if hasattr(str, "__bool__"): pass' + 50000 loops, best of 5: 4.26 usec per loop + + $ python -m timeit 'try:' ' int.__bool__' 'except AttributeError:' ' pass' + 200000 loops, best of 5: 1.43 usec per loop + $ python -m timeit 'if hasattr(int, "__bool__"): pass' + 100000 loops, best of 5: 2.23 usec per loop + +:: + + >>> import timeit + >>> # attribute is missing + >>> s = """\ + ... try: + ... str.__bool__ + ... except AttributeError: + ... pass + ... """ + >>> timeit.timeit(stmt=s, number=100000) + 0.9138244460009446 + >>> s = "if hasattr(str, '__bool__'): pass" + >>> timeit.timeit(stmt=s, number=100000) + 0.5829014980008651 + >>> + >>> # attribute is present + >>> s = """\ + ... try: + ... int.__bool__ + ... except AttributeError: + ... pass + ... """ + >>> timeit.timeit(stmt=s, number=100000) + 0.04215312199994514 + >>> s = "if hasattr(int, '__bool__'): pass" + >>> timeit.timeit(stmt=s, number=100000) + 0.08588060699912603 + + +To give the :mod:`timeit` module access to functions you define, you can pass a +*setup* parameter which contains an import statement:: + + def test(): + """Stupid test function""" + L = [i for i in range(100)] + + if __name__ == '__main__': + import timeit + print(timeit.timeit("test()", setup="from __main__ import test")) + +Another option is to pass :func:`globals` to the *globals* parameter, which will cause the code +to be executed within your current global namespace. This can be more convenient +than individually specifying imports:: + + def f(x): + return x**2 + def g(x): + return x**4 + def h(x): + return x**8 + + import timeit + print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals())) diff --git a/cpython_2/environment/repo/Doc/library/tk.rst b/cpython_2/environment/repo/Doc/library/tk.rst new file mode 100644 index 0000000000000000000000000000000000000000..c6c73f057cab165bb4c190d14c003653d3584eb8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tk.rst @@ -0,0 +1,49 @@ +.. _tkinter: + +********************************* +Graphical User Interfaces with Tk +********************************* + +.. index:: + single: GUI + single: Graphical User Interface + single: Tkinter + single: 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` and +the :mod:`tkinter.ttk` modules. + +The :mod:`tkinter` package is a thin object-oriented layer on top of Tcl/Tk. To +use :mod:`tkinter`, you don't need to write Tcl code, but you will need to +consult the Tk documentation, and occasionally the Tcl documentation. +:mod:`tkinter` is a set of wrappers that implement the Tk widgets as Python +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 +alternatives, see the :ref:`other-gui-packages` section. + +.. toctree:: + + tkinter.rst + tkinter.colorchooser.rst + tkinter.font.rst + dialog.rst + tkinter.messagebox.rst + tkinter.scrolledtext.rst + tkinter.dnd.rst + tkinter.ttk.rst + tkinter.tix.rst + idle.rst + othergui.rst + +.. Other sections I have in mind are + Tkinter internals + Freezing Tkinter applications \ No newline at end of file diff --git a/cpython_2/environment/repo/Doc/library/tk_msg.png b/cpython_2/environment/repo/Doc/library/tk_msg.png new file mode 100644 index 0000000000000000000000000000000000000000..7fb6edb6d2e2a7413ef034fc880e1d65a1dd9834 Binary files /dev/null and b/cpython_2/environment/repo/Doc/library/tk_msg.png differ diff --git a/cpython_2/environment/repo/Doc/library/tkinter.colorchooser.rst b/cpython_2/environment/repo/Doc/library/tkinter.colorchooser.rst new file mode 100644 index 0000000000000000000000000000000000000000..60f4d707270d64d6928ca2d32998920b38914a97 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tkinter.colorchooser.rst @@ -0,0 +1,29 @@ +:mod:`tkinter.colorchooser` --- Color choosing dialog +===================================================== + +.. module:: tkinter.colorchooser + :platform: Tk + :synopsis: Color choosing dialog + +**Source code:** :source:`Lib/tkinter/colorchooser.py` + +-------------- + +The :mod:`tkinter.colorchooser` module provides the :class:`Chooser` class +as an interface to the native color picker dialog. ``Chooser`` implements +a modal color choosing dialog window. The ``Chooser`` class inherits from +the :class:`~tkinter.commondialog.Dialog` class. + +.. class:: Chooser(master=None, **options) + +.. function:: askcolor(color=None, **options) + + Create a color choosing dialog. A call to this method will show the window, + wait for the user to make a selection, and return the selected color (or + ``None``) to the caller. + + +.. seealso:: + + Module :mod:`tkinter.commondialog` + Tkinter standard dialog module \ No newline at end of file diff --git a/cpython_2/environment/repo/Doc/library/tkinter.dnd.rst b/cpython_2/environment/repo/Doc/library/tkinter.dnd.rst new file mode 100644 index 0000000000000000000000000000000000000000..6c11c739e1fa111af7957fcd2bf93aadd6e0fbb1 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tkinter.dnd.rst @@ -0,0 +1,64 @@ +:mod:`tkinter.dnd` --- Drag and drop support +============================================ + +.. module:: tkinter.dnd + :platform: Tk + :synopsis: Tkinter drag-and-drop interface + +**Source code:** :source:`Lib/tkinter/dnd.py` + +-------------- + +.. note:: This is experimental and due to be deprecated when it is replaced + with the Tk DND. + +The :mod:`tkinter.dnd` module provides drag-and-drop support for objects within +a single application, within the same window or between windows. To enable an +object to be dragged, you must create an event binding for it that starts the +drag-and-drop process. Typically, you bind a ButtonPress event to a callback +function that you write (see :ref:`Bindings-and-Events`). The function should +call :func:`dnd_start`, where 'source' is the object to be dragged, and 'event' +is the event that invoked the call (the argument to your callback function). + +Selection of a target object occurs as follows: + +#. Top-down search of area under mouse for target widget + + * Target widget should have a callable *dnd_accept* attribute + * If *dnd_accept* is not present or returns None, search moves to parent widget + * If no target widget is found, then the target object is None + +2. Call to *.dnd_leave(source, event)* +#. Call to *.dnd_enter(source, event)* +#. Call to *.dnd_commit(source, event)* to notify of drop +#. Call to *.dnd_end(target, event)* to signal end of drag-and-drop + + +.. class:: DndHandler(source, event) + + The *DndHandler* class handles drag-and-drop events tracking Motion and + ButtonRelease events on the root of the event widget. + + .. method:: cancel(event=None) + + Cancel the drag-and-drop process. + + .. method:: finish(event, commit=0) + + Execute end of drag-and-drop functions. + + .. method:: on_motion(event) + + Inspect area below mouse for target objects while drag is performed. + + .. method:: on_release(event) + + Signal end of drag when the release pattern is triggered. + +.. function:: dnd_start(source, event) + + Factory function for drag-and-drop process. + +.. seealso:: + + :ref:`Bindings-and-Events` \ No newline at end of file diff --git a/cpython_2/environment/repo/Doc/library/tkinter.font.rst b/cpython_2/environment/repo/Doc/library/tkinter.font.rst new file mode 100644 index 0000000000000000000000000000000000000000..30c1e7b5f9eb434a6951b6b089e690f54429035e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tkinter.font.rst @@ -0,0 +1,96 @@ +:mod:`tkinter.font` --- Tkinter font wrapper +============================================ + +.. module:: tkinter.font + :platform: Tk + :synopsis: Tkinter font-wrapping class + +**Source code:** :source:`Lib/tkinter/font.py` + +-------------- + +The :mod:`tkinter.font` module provides the :class:`Font` class for creating +and using named fonts. + +The different font weights and slants are: + +.. data:: NORMAL + BOLD + ITALIC + ROMAN + +.. class:: Font(root=None, font=None, name=None, exists=False, **options) + + The :class:`Font` class represents a named font. *Font* instances are given + unique names and can be specified by their family, size, and style + configuration. Named fonts are Tk's method of creating and identifying + fonts as a single object, rather than specifying a font by its attributes + with each occurrence. + + arguments: + + | *font* - font specifier tuple (family, size, options) + | *name* - unique font name + | *exists* - self points to existing named font if true + + additional keyword options (ignored if *font* is specified): + + | *family* - font family i.e. Courier, Times + | *size* - font size + | If *size* is positive it is interpreted as size in points. + | If *size* is a negative number its absolute value is treated as + as size in pixels. + | *weight* - font emphasis (NORMAL, BOLD) + | *slant* - ROMAN, ITALIC + | *underline* - font underlining (0 - none, 1 - underline) + | *overstrike* - font strikeout (0 - none, 1 - strikeout) + + .. method:: actual(option=None, displayof=None) + + Return the attributes of the font. + + .. method:: cget(option) + + Retrieve an attribute of the font. + + .. method:: config(**options) + + Modify attributes of the font. + + .. method:: copy() + + Return new instance of the current font. + + .. method:: measure(text, displayof=None) + + Return amount of space the text would occupy on the specified display + when formatted in the current font. If no display is specified then the + main application window is assumed. + + .. method:: metrics(*options, **kw) + + Return font-specific data. + Options include: + + *ascent* - distance between baseline and highest point that a + character of the font can occupy + + *descent* - distance between baseline and lowest point that a + character of the font can occupy + + *linespace* - minimum vertical separation necessary between any two + characters of the font that ensures no vertical overlap between lines. + + *fixed* - 1 if font is fixed-width else 0 + +.. function:: families(root=None, displayof=None) + + Return the different font families. + +.. function:: names(root=None) + + Return the names of defined fonts. + +.. function:: nametofont(name) + + Return a :class:`Font` representation of a tk named font. \ No newline at end of file diff --git a/cpython_2/environment/repo/Doc/library/tkinter.messagebox.rst b/cpython_2/environment/repo/Doc/library/tkinter.messagebox.rst new file mode 100644 index 0000000000000000000000000000000000000000..872e72f7a7e2b85e1a09589698050eea8003290d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tkinter.messagebox.rst @@ -0,0 +1,39 @@ +:mod:`tkinter.messagebox` --- Tkinter message prompts +===================================================== + +.. module:: tkinter.messagebox + :platform: Tk + :synopsis: Various types of alert dialogs + +**Source code:** :source:`Lib/tkinter/messagebox.py` + +-------------- + +The :mod:`tkinter.messagebox` module provides a template base class as well as +a variety of convenience methods for commonly used configurations. The message +boxes are modal and will return a subset of (True, False, OK, None, Yes, No) based on +the user's selection. Common message box styles and layouts include but are not +limited to: + +.. figure:: tk_msg.png + +.. class:: Message(master=None, **options) + + Create a default information message box. + +**Information message box** + +.. method:: showinfo(title=None, message=None, **options) + +**Warning message boxes** + +.. method:: showwarning(title=None, message=None, **options) + showerror(title=None, message=None, **options) + +**Question message boxes** + +.. method:: askquestion(title=None, message=None, **options) + askokcancel(title=None, message=None, **options) + askretrycancel(title=None, message=None, **options) + askyesno(title=None, message=None, **options) + askyesnocancel(title=None, message=None, **options) \ No newline at end of file diff --git a/cpython_2/environment/repo/Doc/library/tkinter.rst b/cpython_2/environment/repo/Doc/library/tkinter.rst new file mode 100644 index 0000000000000000000000000000000000000000..2dc44ad36a7f7364497a5dd7b0729d1c314488ae --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tkinter.rst @@ -0,0 +1,864 @@ +:mod:`tkinter` --- Python interface to Tcl/Tk +============================================= + +.. module:: tkinter + :synopsis: Interface to Tcl/Tk for graphical user interfaces + +.. moduleauthor:: Guido van Rossum + +**Source code:** :source:`Lib/tkinter/__init__.py` + +-------------- + +The :mod:`tkinter` package ("Tk interface") is the standard Python interface to +the Tk GUI toolkit. Both Tk and :mod:`tkinter` are available on most Unix +platforms, as well as on Windows systems. (Tk itself is not part of Python; it +is maintained at ActiveState.) + +Running ``python -m tkinter`` from the command line should open a window +demonstrating a simple Tk interface, letting you know that :mod:`tkinter` is +properly installed on your system, and also showing what version of Tcl/Tk is +installed, so you can read the Tcl/Tk documentation specific to that version. + +.. seealso:: + + Tkinter documentation: + + `Python Tkinter Resources `_ + The Python Tkinter Topic Guide provides a great deal of information on using Tk + from Python and links to other sources of information on Tk. + + `TKDocs `_ + Extensive tutorial plus friendlier widget pages for some of the widgets. + + `Tkinter 8.5 reference: a GUI for Python `_ + On-line reference material. + + `Tkinter docs from effbot `_ + Online reference for tkinter supported by effbot.org. + + `Programming Python `_ + Book by Mark Lutz, has excellent coverage of Tkinter. + + `Modern Tkinter for Busy Python Developers `_ + Book by Mark Roseman about building attractive and modern graphical user interfaces with Python and Tkinter. + + `Python and Tkinter Programming `_ + Book by John Grayson (ISBN 1-884777-81-3). + + Tcl/Tk documentation: + + `Tk commands `_ + Most commands are available as :mod:`tkinter` or :mod:`tkinter.ttk` classes. + Change '8.6' to match the version of your Tcl/Tk installation. + + `Tcl/Tk recent man pages `_ + Recent Tcl/Tk manuals on www.tcl.tk. + + `ActiveState Tcl Home Page `_ + The Tk/Tcl development is largely taking place at ActiveState. + + `Tcl and the Tk Toolkit `_ + Book by John Ousterhout, the inventor of Tcl. + + `Practical Programming in Tcl and Tk `_ + Brent Welch's encyclopedic book. + + +Tkinter Modules +--------------- + +Most of the time, :mod:`tkinter` is all you really need, but a number of +additional modules are available as well. The Tk interface is located in a +binary module named :mod:`_tkinter`. This module contains the low-level +interface to Tk, and should never be used directly by application programmers. +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. +Importing :mod:`tkinter` will automatically import :mod:`tkinter.constants`, +so, usually, to use Tkinter all you need is a simple import statement:: + + import tkinter + +Or, more often:: + + from tkinter import * + + +.. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1) + + The :class:`Tk` class is instantiated without arguments. This creates a toplevel + widget of Tk which usually is the main window of an application. Each instance + has its own associated Tcl interpreter. + + .. FIXME: The following keyword arguments are currently recognized: + + +.. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0) + + The :func:`Tcl` function is a factory function which creates an object much like + that created by the :class:`Tk` class, except that it does not initialize the Tk + subsystem. This is most often useful when driving the Tcl interpreter in an + environment where one doesn't want to create extraneous toplevel windows, or + where one cannot (such as Unix/Linux systems without an X server). An object + created by the :func:`Tcl` object can have a Toplevel window created (and the Tk + subsystem initialized) by calling its :meth:`loadtk` method. + + +Other modules that provide Tk support include: + +:mod:`tkinter.colorchooser` + Dialog to let the user choose a color. + +:mod:`tkinter.commondialog` + Base class for the dialogs defined in the other modules listed here. + +:mod:`tkinter.filedialog` + Common dialogs to allow the user to specify a file to open or save. + +:mod:`tkinter.font` + Utilities to help work with fonts. + +:mod:`tkinter.messagebox` + Access to standard Tk dialog boxes. + +:mod:`tkinter.scrolledtext` + Text widget with a vertical scroll bar built in. + +:mod:`tkinter.simpledialog` + Basic dialogs and convenience functions. + +:mod:`tkinter.dnd` + Drag-and-drop support for :mod:`tkinter`. This is experimental and should + become deprecated when it is replaced with the Tk DND. + +:mod:`turtle` + Turtle graphics in a Tk window. + + +Tkinter Life Preserver +---------------------- + +.. sectionauthor:: Matt Conway + + +This section is not designed to be an exhaustive tutorial on either Tk or +Tkinter. Rather, it is intended as a stop gap, providing some introductory +orientation on the system. + +Credits: + +* Tk was written by John Ousterhout while at Berkeley. + +* Tkinter was written by Steen Lumholt and Guido van Rossum. + +* This Life Preserver was written by Matt Conway at the University of Virginia. + +* The HTML rendering, and some liberal editing, was produced from a FrameMaker + version by Ken Manheimer. + +* Fredrik Lundh elaborated and revised the class interface descriptions, to get + them current with Tk 4.2. + +* Mike Clarkson converted the documentation to LaTeX, and compiled the User + Interface chapter of the reference manual. + + +How To Use This Section +^^^^^^^^^^^^^^^^^^^^^^^ + +This section is designed in two parts: the first half (roughly) covers +background material, while the second half can be taken to the keyboard as a +handy reference. + +When trying to answer questions of the form "how do I do blah", it is often best +to find out how to do "blah" in straight Tk, and then convert this back into the +corresponding :mod:`tkinter` call. Python programmers can often guess at the +correct Python command by looking at the Tk documentation. This means that in +order to use Tkinter, you will have to know a little bit about Tk. This document +can't fulfill that role, so the best we can do is point you to the best +documentation that exists. Here are some hints: + +* The authors strongly suggest getting a copy of the Tk man pages. + Specifically, the man pages in the ``manN`` directory are most useful. + The ``man3`` man pages describe the C interface to the Tk library and thus + are not especially helpful for script writers. + +* Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John + Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for + 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 + place to go when nothing else makes sense. + + +A Simple Hello World Program +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + import tkinter as tk + + class Application(tk.Frame): + def __init__(self, master=None): + super().__init__(master) + self.master = master + self.pack() + self.create_widgets() + + def create_widgets(self): + self.hi_there = tk.Button(self) + self.hi_there["text"] = "Hello World\n(click me)" + self.hi_there["command"] = self.say_hi + self.hi_there.pack(side="top") + + self.quit = tk.Button(self, text="QUIT", fg="red", + command=self.master.destroy) + self.quit.pack(side="bottom") + + def say_hi(self): + print("hi there, everyone!") + + root = tk.Tk() + app = Application(master=root) + app.mainloop() + + +A (Very) Quick Look at Tcl/Tk +----------------------------- + +The class hierarchy looks complicated, but in actual practice, application +programmers almost always refer to the classes at the very bottom of the +hierarchy. + +Notes: + +* These classes are provided for the purposes of organizing certain functions + under one namespace. They aren't meant to be instantiated independently. + +* The :class:`Tk` class is meant to be instantiated only once in an application. + Application programmers need not instantiate one explicitly, the system creates + one whenever any of the other classes are instantiated. + +* The :class:`Widget` class is not meant to be instantiated, it is meant only + for subclassing to make "real" widgets (in C++, this is called an 'abstract + class'). + +To make use of this reference material, there will be times when you will need +to know how to read short passages of Tk and how to identify the various parts +of a Tk command. (See section :ref:`tkinter-basic-mapping` for the +:mod:`tkinter` equivalents of what's below.) + +Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists +of tokens separated by spaces. A Tk widget is just its *class*, the *options* +that help configure it, and the *actions* that make it do useful things. + +To make a widget in Tk, the command is always of the form:: + + classCommand newPathname options + +*classCommand* + denotes which kind of widget to make (a button, a label, a menu...) + +.. index:: single: . (dot); in Tkinter + +*newPathname* + is the new name for this widget. All names in Tk must be unique. To help + enforce this, widgets in Tk are named with *pathnames*, just like files in a + file system. The top level widget, the *root*, is called ``.`` (period) and + children are delimited by more periods. For example, + ``.myApp.controlPanel.okButton`` might be the name of a widget. + +*options* + configure the widget's appearance and in some cases, its behavior. The options + come in the form of a list of flags and values. Flags are preceded by a '-', + like Unix shell command flags, and values are put in quotes if they are more + than one word. + +For example:: + + button .fred -fg red -text "hi there" + ^ ^ \______________________/ + | | | + class new options + command widget (-opt val -opt val ...) + +Once created, the pathname to the widget becomes a new command. This new +*widget command* is the programmer's handle for getting the new widget to +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 + +Note that the object name, ``.fred``, starts with a dot. + +As you'd expect, the legal values for *someAction* will depend on the widget's +class: ``.fred disable`` works if fred is a button (fred gets greyed out), but +does not work if fred is a label (disabling of labels is not supported in Tk). + +The legal values of *someOptions* is action dependent. Some actions, like +``disable``, require no arguments, others, like a text-entry box's ``delete`` +command, would need arguments to specify what range of text to delete. + + +.. _tkinter-basic-mapping: + +Mapping Basic Tk into Tkinter +----------------------------- + +Class commands in Tk correspond to class constructors in Tkinter. :: + + button .fred =====> fred = Button() + +The master of an object is implicit in the new name given to it at creation +time. In Tkinter, masters are specified explicitly. :: + + button .panel.fred =====> fred = Button(panel) + +The configuration options in Tk are given in lists of hyphened tags followed by +values. In Tkinter, options are specified as keyword-arguments in the instance +constructor, and keyword-args for configure calls or as instance indices, in +dictionary style, for established instances. See section +:ref:`tkinter-setting-options` on setting options. :: + + button .fred -fg red =====> fred = Button(panel, fg="red") + .fred configure -fg red =====> fred["fg"] = red + OR ==> fred.config(fg="red") + +In Tk, to perform an action on a widget, use the widget name as a command, and +follow it with an action name, possibly with arguments (options). In Tkinter, +you call methods on the class instance to invoke actions on the widget. The +actions (methods) that a given widget can perform are listed in +:file:`tkinter/__init__.py`. :: + + .fred invoke =====> fred.invoke() + +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 +information on the Form geometry manager. :: + + pack .fred -side left =====> fred.pack(side="left") + + +How Tk and Tkinter are Related +------------------------------ + +From the top down: + +Your App Here (Python) + A Python application makes a :mod:`tkinter` call. + +tkinter (Python Package) + This call (say, for example, creating a button widget), is implemented in + the :mod:`tkinter` package, which is written in Python. This Python + function will parse the commands and the arguments and convert them into a + form that makes them look as if they had come from a Tk script instead of + a Python script. + +_tkinter (C) + These commands and their arguments will be passed to a C function in the + :mod:`_tkinter` - note the underscore - extension module. + +Tk Widgets (C and Tcl) + This C function is able to make calls into other C modules, including the C + functions that make up the Tk library. Tk is implemented in C and some Tcl. + The Tcl part of the Tk widgets is used to bind certain default behaviors to + widgets, and is executed once at the point where the Python :mod:`tkinter` + package is imported. (The user never sees this stage). + +Tk (C) + The Tk part of the Tk Widgets implement the final mapping to ... + +Xlib (C) + the Xlib library to draw graphics on the screen. + + +Handy Reference +--------------- + + +.. _tkinter-setting-options: + +Setting Options +^^^^^^^^^^^^^^^ + +Options control things like the color and border width of a widget. Options can +be set in three ways: + +At object creation time, using keyword arguments + :: + + fred = Button(self, fg="red", bg="blue") + +After object creation, treating the option name like a dictionary index + :: + + fred["fg"] = "red" + fred["bg"] = "blue" + +Use the config() method to update multiple attrs subsequent to object creation + :: + + fred.config(fg="red", bg="blue") + +For a complete explanation of a given option and its behavior, see the Tk man +pages for the widget in question. + +Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS" +for each widget. The former is a list of options that are common to many +widgets, the latter are the options that are idiosyncratic to that particular +widget. The Standard Options are documented on the :manpage:`options(3)` man +page. + +No distinction between standard and widget-specific options is made in this +document. Some options don't apply to some kinds of widgets. Whether a given +widget responds to a particular option depends on the class of the widget; +buttons have a ``command`` option, labels do not. + +The options supported by a given widget are listed in that widget's man page, or +can be queried at runtime by calling the :meth:`config` method without +arguments, or by calling the :meth:`keys` method on that widget. The return +value of these calls is a dictionary whose key is the name of the option as a +string (for example, ``'relief'``) and whose values are 5-tuples. + +Some options, like ``bg`` are synonyms for common options with long names +(``bg`` is shorthand for "background"). Passing the ``config()`` method the name +of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed +back will contain the name of the synonym and the "real" option (such as +``('bg', 'background')``). + ++-------+---------------------------------+--------------+ +| Index | Meaning | Example | ++=======+=================================+==============+ +| 0 | option name | ``'relief'`` | ++-------+---------------------------------+--------------+ +| 1 | option name for database lookup | ``'relief'`` | ++-------+---------------------------------+--------------+ +| 2 | option class for database | ``'Relief'`` | +| | lookup | | ++-------+---------------------------------+--------------+ +| 3 | default value | ``'raised'`` | ++-------+---------------------------------+--------------+ +| 4 | current value | ``'groove'`` | ++-------+---------------------------------+--------------+ + +Example:: + + >>> print(fred.config()) + {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')} + +Of course, the dictionary printed will include all the options available and +their values. This is meant only as an example. + + +The Packer +^^^^^^^^^^ + +.. index:: single: packing (widgets) + +The packer is one of Tk's geometry-management mechanisms. Geometry managers +are used to specify the relative positioning of the positioning of widgets +within their container - their mutual *master*. In contrast to the more +cumbersome *placer* (which is used less commonly, and we do not cover here), the +packer takes qualitative relationship specification - *above*, *to the left of*, +*filling*, etc - and works everything out to determine the exact placement +coordinates for you. + +The size of any *master* widget is determined by the size of the "slave widgets" +inside. The packer is used to control where slave widgets appear inside the +master into which they are packed. You can pack widgets into frames, and frames +into other frames, in order to achieve the kind of layout you desire. +Additionally, the arrangement is dynamically adjusted to accommodate incremental +changes to the configuration, once it is packed. + +Note that widgets do not appear until they have had their geometry specified +with a geometry manager. It's a common early mistake to leave out the geometry +specification, and then be surprised when the widget is created but nothing +appears. A widget will appear only after it has had, for example, the packer's +:meth:`pack` method applied to it. + +The pack() method can be called with keyword-option/value pairs that control +where the widget is to appear within its container, and how it is to behave when +the main application window is resized. Here are some examples:: + + fred.pack() # defaults to side = "top" + fred.pack(side="left") + fred.pack(expand=1) + + +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 type. Denotes where the packer is to place each slave in its parcel. + +expand + Boolean, ``0`` or ``1``. + +fill + Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``. + +ipadx and ipady + A distance - designating internal padding on each side of the slave widget. + +padx and pady + A distance - designating external padding on each side of the slave widget. + +side + Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``. + + +Coupling Widget Variables +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The current-value setting of some widgets (like text entry widgets) can be +connected directly to application variables by using special options. These +options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and +``value``. This connection works both ways: if the variable changes for any +reason, the widget it's connected to will be updated to reflect the new value. + +Unfortunately, in the current implementation of :mod:`tkinter` it is not +possible to hand over an arbitrary Python variable to a widget through a +``variable`` or ``textvariable`` option. The only kinds of variables for which +this works are variables that are subclassed from a class called Variable, +defined in :mod:`tkinter`. + +There are many useful subclasses of Variable already defined: +:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and +:class:`BooleanVar`. To read the current value of such a variable, call the +:meth:`get` method on it, and to change its value you call the :meth:`!set` +method. If you follow this protocol, the widget will always track the value of +the variable, with no further intervention on your part. + +For example:: + + class App(Frame): + def __init__(self, master=None): + super().__init__(master) + self.pack() + + self.entrythingy = Entry() + self.entrythingy.pack() + + # here is the application variable + self.contents = StringVar() + # set it to some value + self.contents.set("this is a variable") + # tell the entry widget to watch this variable + self.entrythingy["textvariable"] = self.contents + + # and here we get a callback when the user hits return. + # we will have the program print out the value of the + # application variable when the user hits return + self.entrythingy.bind('', + self.print_contents) + + def print_contents(self, event): + print("hi. contents of entry is now ---->", + self.contents.get()) + + +The Window Manager +^^^^^^^^^^^^^^^^^^ + +.. index:: single: window manager (widgets) + +In Tk, there is a utility command, ``wm``, for interacting with the window +manager. Options to the ``wm`` command allow you to control things like titles, +placement, icon bitmaps, and the like. In :mod:`tkinter`, these commands have +been implemented as methods on the :class:`Wm` class. Toplevel widgets are +subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods +directly. + +To get at the toplevel window that contains a given widget, you can often just +refer to the widget's master. Of course if the widget has been packed inside of +a frame, the master won't represent a toplevel window. To get at the toplevel +window that contains an arbitrary widget, you can call the :meth:`_root` method. +This method begins with an underscore to denote the fact that this function is +part of the implementation, and not an interface to Tk functionality. + +Here are some examples of typical usage:: + + import tkinter as tk + + class App(tk.Frame): + def __init__(self, master=None): + super().__init__(master) + self.pack() + + # create the application + myapp = App() + + # + # here are method calls to the window manager class + # + myapp.master.title("My Do-Nothing Application") + myapp.master.maxsize(1000, 400) + + # start the program + myapp.mainloop() + + +Tk Option Data Types +^^^^^^^^^^^^^^^^^^^^ + +.. index:: single: Tk Option Data Types + +anchor + Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``, + ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``. + +bitmap + There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``, + ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``, + ``'warning'``. To specify an X bitmap filename, give the full path to the file, + preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``. + +boolean + You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``. + +callback + This is any Python function that takes no arguments. For example:: + + def print_it(): + print("hi there") + fred["command"] = print_it + +color + Colors can be given as the names of X colors in the rgb.txt file, or as strings + representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit" + ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here + represent any legal hex digit. See page 160 of Ousterhout's book for details. + +cursor + The standard X cursor names from :file:`cursorfont.h` can be used, without the + ``XC_`` prefix. For example to get a hand cursor (:const:`XC_hand2`), use the + string ``"hand2"``. You can also specify a bitmap and mask file of your own. + See page 179 of Ousterhout's book. + +distance + Screen distances can be specified in either pixels or absolute distances. + Pixels are given as numbers and absolute distances as strings, with the trailing + character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for + millimetres, ``p`` for printer's points. For example, 3.5 inches is expressed + as ``"3.5i"``. + +font + Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with + positive numbers are measured in points; sizes with negative numbers are + measured in pixels. + +geometry + This is a string of the form ``widthxheight``, where width and height are + measured in pixels for most widgets (in characters for widgets displaying text). + For example: ``fred["geometry"] = "200x100"``. + +justify + Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and + ``"fill"``. + +region + This is a string with four space-delimited elements, each of which is a legal + distance (see above). For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and + ``"3c 2c 4c 10.43c"`` are all legal regions. + +relief + Determines what the border style of a widget will be. Legal values are: + ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``. + +scrollcommand + This is almost always the :meth:`!set` method of some scrollbar widget, but can + be any widget method that takes a single argument. + +wrap + Must be one of: ``"none"``, ``"char"``, or ``"word"``. + +.. _Bindings-and-Events: + +Bindings and Events +^^^^^^^^^^^^^^^^^^^ + +.. index:: + single: bind (widgets) + single: events (widgets) + +The bind method from the widget command allows you to watch for certain events +and to have a callback function trigger when that event type occurs. The form +of the bind method is:: + + def bind(self, sequence, func, add=''): + +where: + +sequence + is a string that denotes the target kind of event. (See the bind man page and + page 201 of John Ousterhout's book for details). + +func + is a Python function, taking one argument, to be invoked when the event occurs. + An Event instance will be passed as the argument. (Functions deployed this way + are commonly known as *callbacks*.) + +add + is optional, either ``''`` or ``'+'``. Passing an empty string denotes that + this binding is to replace any other bindings that this event is associated + with. Passing a ``'+'`` means that this function is to be added to the list + of functions bound to this event type. + +For example:: + + def turn_red(self, event): + event.widget["activeforeground"] = "red" + + self.button.bind("", self.turn_red) + +Notice how the widget field of the event is being accessed in the +``turn_red()`` callback. This field contains the widget that caught the X +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 | ++====+=====================+====+=====================+ +| %f | focus | %A | char | ++----+---------------------+----+---------------------+ +| %h | height | %E | send_event | ++----+---------------------+----+---------------------+ +| %k | keycode | %K | keysym | ++----+---------------------+----+---------------------+ +| %s | state | %N | keysym_num | ++----+---------------------+----+---------------------+ +| %t | time | %T | type | ++----+---------------------+----+---------------------+ +| %w | width | %W | widget | ++----+---------------------+----+---------------------+ +| %x | x | %X | x_root | ++----+---------------------+----+---------------------+ +| %y | y | %Y | y_root | ++----+---------------------+----+---------------------+ + + +The index Parameter +^^^^^^^^^^^^^^^^^^^ + +A number of widgets require "index" parameters to be passed. These are used to +point at a specific place in a Text widget, or to particular characters in an +Entry widget, or to particular menu items in a Menu widget. + +Entry widget indexes (index, view index, etc.) + Entry widgets have options that refer to character positions in the text being + displayed. You can use these :mod:`tkinter` functions to access these special + points in text widgets: + +Text widget indexes + The index notation for Text widgets is very rich and is best described in the Tk + man pages. + +Menu indexes (menu.invoke(), menu.entryconfig(), etc.) + Some options and methods for menus manipulate specific menu entries. Anytime a + menu index is needed for an option or a parameter, you may pass in: + + * an integer which refers to the numeric position of the entry in the widget, + counted from the top, starting with 0; + + * the string ``"active"``, which refers to the menu position that is currently + under the cursor; + + * the string ``"last"`` which refers to the last menu item; + + * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted + as a y pixel coordinate in the menu's coordinate system; + + * the string ``"none"``, which indicates no menu entry at all, most often used + with menu.activate() to deactivate all entries, and finally, + + * a text string that is pattern matched against the label of the menu entry, as + scanned from the top of the menu to the bottom. Note that this index type is + considered after all the others, which means that matches for menu items + labelled ``last``, ``active``, or ``none`` may be interpreted as the above + literals, instead. + + +Images +^^^^^^ + +Images of different formats can be created through the corresponding subclass +of :class:`tkinter.Image`: + +* :class:`BitmapImage` for images in XBM format. + +* :class:`PhotoImage` for images in PGM, PPM, GIF and PNG formats. The latter + is supported starting with Tk 8.6. + +Either type of image is created through either the ``file`` or the ``data`` +option (other options are available as well). + +The image object can then be used wherever an ``image`` option is supported by +some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a +reference to the image. When the last Python reference to the image object is +deleted, the image data is deleted as well, and Tk will display an empty box +wherever the image was used. + +.. seealso:: + + The `Pillow `_ package adds support for + formats such as BMP, JPEG, TIFF, and WebP, among others. + +.. _tkinter-file-handlers: + +File Handlers +------------- + +Tk allows you to register and unregister a callback function which will be +called from the Tk mainloop when I/O is possible on a file descriptor. +Only one handler may be registered per file descriptor. Example code:: + + import tkinter + widget = tkinter.Tk() + mask = tkinter.READABLE | tkinter.WRITABLE + widget.tk.createfilehandler(file, mask, callback) + ... + widget.tk.deletefilehandler(file) + +This feature is not available on Windows. + +Since you don't know how many bytes are available for reading, you may not +want to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase` +:meth:`~io.BufferedIOBase.read` or :meth:`~io.IOBase.readline` methods, +since these will insist on reading a predefined number of bytes. +For sockets, the :meth:`~socket.socket.recv` or +:meth:`~socket.socket.recvfrom` methods will work fine; for other files, +use raw reads or ``os.read(file.fileno(), maxbytecount)``. + + +.. method:: Widget.tk.createfilehandler(file, mask, func) + + Registers the file handler callback function *func*. The *file* argument + may either be an object with a :meth:`~io.IOBase.fileno` method (such as + a file or socket object), or an integer file descriptor. The *mask* + argument is an ORed combination of any of the three constants below. + The callback is called as follows:: + + callback(file, mask) + + +.. method:: Widget.tk.deletefilehandler(file) + + Unregisters a file handler. + + +.. data:: READABLE + WRITABLE + EXCEPTION + + Constants used in the *mask* arguments. \ No newline at end of file diff --git a/cpython_2/environment/repo/Doc/library/tkinter.scrolledtext.rst b/cpython_2/environment/repo/Doc/library/tkinter.scrolledtext.rst new file mode 100644 index 0000000000000000000000000000000000000000..d20365baa38690a084a3eaba4a31497f9a01c49d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tkinter.scrolledtext.rst @@ -0,0 +1,37 @@ +:mod:`tkinter.scrolledtext` --- Scrolled Text Widget +==================================================== + +.. module:: tkinter.scrolledtext + :platform: Tk + :synopsis: Text widget with a vertical scroll bar. + +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/tkinter/scrolledtext.py` + +-------------- + +The :mod:`tkinter.scrolledtext` module provides a class of the same name which +implements a basic text widget which has a vertical scroll bar configured to do +the "right thing." Using the :class:`ScrolledText` class is a lot easier than +setting up a text widget and scroll bar directly. + +The text widget and scrollbar are packed together in a :class:`Frame`, and the +methods of the :class:`Grid` and :class:`Pack` geometry managers are acquired +from the :class:`Frame` object. This allows the :class:`ScrolledText` widget to +be used directly to achieve most normal geometry management behavior. + +Should more specific control be necessary, the following attributes are +available: + +.. class:: ScrolledText(master=None, **kw) + + + .. attribute:: frame + + The frame which surrounds the text and scroll bar widgets. + + + .. attribute:: vbar + + The scroll bar widget. diff --git a/cpython_2/environment/repo/Doc/library/tkinter.tix.rst b/cpython_2/environment/repo/Doc/library/tkinter.tix.rst new file mode 100644 index 0000000000000000000000000000000000000000..88b936c47a6d24b7deb86541fc1091e9176bd093 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tkinter.tix.rst @@ -0,0 +1,583 @@ +:mod:`tkinter.tix` --- Extension widgets for Tk +=============================================== + +.. module:: tkinter.tix + :synopsis: Tk Extension Widgets for Tkinter + +.. sectionauthor:: Mike Clarkson + +**Source code:** :source:`Lib/tkinter/tix.py` + +.. index:: single: Tix + +.. deprecated:: 3.6 + This Tk extension is unmaintained and should not be used in new code. Use + :mod:`tkinter.ttk` instead. + +-------------- + +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. +: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. + +With all these new widgets, you can introduce new interaction techniques into +applications, creating more useful and more intuitive user interfaces. You can +design your application by choosing the most appropriate widgets to match the +special needs of your application and users. + +.. seealso:: + + `Tix Homepage `_ + The home page for :mod:`Tix`. This includes links to additional documentation + and downloads. + + `Tix Man Pages `_ + On-line version of the man pages and reference material. + + `Tix Programming Guide `_ + On-line version of the programmer's reference material. + + `Tix Development Applications `_ + Tix applications for development of Tix and Tkinter programs. Tide applications + work under Tk or Tkinter, and include :program:`TixInspect`, an inspector to + remotely modify and debug Tix/Tk/Tkinter applications. + + +Using Tix +--------- + + +.. class:: Tk(screenName=None, baseName=None, className='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 + :class:`tkinter.Tk` with :class:`tix.Tk`:: + + from tkinter import tix + from tkinter.constants import * + root = tix.Tk() + +To use :mod:`tkinter.tix`, you must have the Tix widgets installed, usually +alongside your installation of the Tk widgets. To test your installation, try +the following:: + + from tkinter import tix + root = tix.Tk() + root.tk.eval('package require Tix') + + +Tix Widgets +----------- + +`Tix `_ +introduces over 40 widget classes to the :mod:`tkinter` repertoire. + + +Basic Widgets +^^^^^^^^^^^^^ + + +.. class:: Balloon() + + A `Balloon + `_ that + pops up over a widget to provide help. When the user moves the cursor inside a + widget to which a Balloon widget has been bound, a small pop-up window with a + descriptive message will be shown on the screen. + +.. Python Demo of: +.. \ulink{Balloon}{http://tix.sourceforge.net/dist/current/demos/samples/Balloon.tcl} + + +.. class:: ButtonBox() + + The `ButtonBox + `_ + widget creates a box of buttons, such as is commonly used for ``Ok Cancel``. + +.. Python Demo of: +.. \ulink{ButtonBox}{http://tix.sourceforge.net/dist/current/demos/samples/BtnBox.tcl} + + +.. class:: ComboBox() + + The `ComboBox + `_ + widget is similar to the combo box control in MS Windows. The user can select a + choice by either typing in the entry subwidget or selecting from the listbox + subwidget. + +.. Python Demo of: +.. \ulink{ComboBox}{http://tix.sourceforge.net/dist/current/demos/samples/ComboBox.tcl} + + +.. class:: Control() + + The `Control + `_ + widget is also known as the :class:`SpinBox` widget. The user can adjust the + value by pressing the two arrow buttons or by entering the value directly into + the entry. The new value will be checked against the user-defined upper and + lower limits. + +.. Python Demo of: +.. \ulink{Control}{http://tix.sourceforge.net/dist/current/demos/samples/Control.tcl} + + +.. class:: LabelEntry() + + The `LabelEntry + `_ + widget packages an entry widget and a label into one mega widget. It can + be used to simplify the creation of "entry-form" type of interface. + +.. Python Demo of: +.. \ulink{LabelEntry}{http://tix.sourceforge.net/dist/current/demos/samples/LabEntry.tcl} + + +.. class:: LabelFrame() + + The `LabelFrame + `_ + widget packages a frame widget and a label into one mega widget. To create + widgets inside a LabelFrame widget, one creates the new widgets relative to the + :attr:`frame` subwidget and manage them inside the :attr:`frame` subwidget. + +.. Python Demo of: +.. \ulink{LabelFrame}{http://tix.sourceforge.net/dist/current/demos/samples/LabFrame.tcl} + + +.. class:: Meter() + + The `Meter + `_ widget + can be used to show the progress of a background job which may take a long time + to execute. + +.. Python Demo of: +.. \ulink{Meter}{http://tix.sourceforge.net/dist/current/demos/samples/Meter.tcl} + + +.. class:: OptionMenu() + + The `OptionMenu + `_ + creates a menu button of options. + +.. Python Demo of: +.. \ulink{OptionMenu}{http://tix.sourceforge.net/dist/current/demos/samples/OptMenu.tcl} + + +.. class:: PopupMenu() + + The `PopupMenu + `_ + widget can be used as a replacement of the ``tk_popup`` command. The advantage + of the :mod:`Tix` :class:`PopupMenu` widget is it requires less application code + to manipulate. + +.. Python Demo of: +.. \ulink{PopupMenu}{http://tix.sourceforge.net/dist/current/demos/samples/PopMenu.tcl} + + +.. class:: Select() + + The `Select + `_ widget + is a container of button subwidgets. It can be used to provide radio-box or + check-box style of selection options for the user. + +.. Python Demo of: +.. \ulink{Select}{http://tix.sourceforge.net/dist/current/demos/samples/Select.tcl} + + +.. class:: StdButtonBox() + + The `StdButtonBox + `_ + widget is a group of standard buttons for Motif-like dialog boxes. + +.. Python Demo of: +.. \ulink{StdButtonBox}{http://tix.sourceforge.net/dist/current/demos/samples/StdBBox.tcl} + + +File Selectors +^^^^^^^^^^^^^^ + + +.. class:: DirList() + + The `DirList + `_ + widget displays a list view of a directory, its previous directories and its + sub-directories. The user can choose one of the directories displayed in the + list or change to another directory. + +.. Python Demo of: +.. \ulink{DirList}{http://tix.sourceforge.net/dist/current/demos/samples/DirList.tcl} + + +.. class:: DirTree() + + The `DirTree + `_ + widget displays a tree view of a directory, its previous directories and its + sub-directories. The user can choose one of the directories displayed in the + list or change to another directory. + +.. Python Demo of: +.. \ulink{DirTree}{http://tix.sourceforge.net/dist/current/demos/samples/DirTree.tcl} + + +.. class:: DirSelectDialog() + + The `DirSelectDialog + `_ + widget presents the directories in the file system in a dialog window. The user + can use this dialog window to navigate through the file system to select the + desired directory. + +.. Python Demo of: +.. \ulink{DirSelectDialog}{http://tix.sourceforge.net/dist/current/demos/samples/DirDlg.tcl} + + +.. class:: DirSelectBox() + + The :class:`DirSelectBox` is similar to the standard Motif(TM) + directory-selection box. It is generally used for the user to choose a + directory. DirSelectBox stores the directories mostly recently selected into + a ComboBox widget so that they can be quickly selected again. + + +.. class:: ExFileSelectBox() + + The `ExFileSelectBox + `_ + widget is usually embedded in a tixExFileSelectDialog widget. It provides a + convenient method for the user to select files. The style of the + :class:`ExFileSelectBox` widget is very similar to the standard file dialog on + MS Windows 3.1. + +.. Python Demo of: +.. \ulink{ExFileSelectDialog}{http://tix.sourceforge.net/dist/current/demos/samples/EFileDlg.tcl} + + +.. class:: FileSelectBox() + + The `FileSelectBox + `_ + is similar to the standard Motif(TM) file-selection box. It is generally used + for the user to choose a file. FileSelectBox stores the files mostly recently + selected into a :class:`ComboBox` widget so that they can be quickly selected + again. + +.. Python Demo of: +.. \ulink{FileSelectDialog}{http://tix.sourceforge.net/dist/current/demos/samples/FileDlg.tcl} + + +.. class:: FileEntry() + + The `FileEntry + `_ + widget can be used to input a filename. The user can type in the filename + manually. Alternatively, the user can press the button widget that sits next to + the entry, which will bring up a file selection dialog. + +.. Python Demo of: +.. \ulink{FileEntry}{http://tix.sourceforge.net/dist/current/demos/samples/FileEnt.tcl} + + +Hierarchical ListBox +^^^^^^^^^^^^^^^^^^^^ + + +.. class:: HList() + + The `HList + `_ widget + can be used to display any data that have a hierarchical structure, for example, + file system directory trees. The list entries are indented and connected by + branch lines according to their places in the hierarchy. + +.. Python Demo of: +.. \ulink{HList}{http://tix.sourceforge.net/dist/current/demos/samples/HList1.tcl} + + +.. class:: CheckList() + + The `CheckList + `_ + widget displays a list of items to be selected by the user. CheckList acts + similarly to the Tk checkbutton or radiobutton widgets, except it is capable of + handling many more items than checkbuttons or radiobuttons. + +.. Python Demo of: +.. \ulink{ CheckList}{http://tix.sourceforge.net/dist/current/demos/samples/ChkList.tcl} +.. Python Demo of: +.. \ulink{ScrolledHList (1)}{http://tix.sourceforge.net/dist/current/demos/samples/SHList.tcl} +.. Python Demo of: +.. \ulink{ScrolledHList (2)}{http://tix.sourceforge.net/dist/current/demos/samples/SHList2.tcl} + + +.. class:: Tree() + + The `Tree + `_ widget + can be used to display hierarchical data in a tree form. The user can adjust the + view of the tree by opening or closing parts of the tree. + +.. Python Demo of: +.. \ulink{Tree}{http://tix.sourceforge.net/dist/current/demos/samples/Tree.tcl} +.. Python Demo of: +.. \ulink{Tree (Dynamic)}{http://tix.sourceforge.net/dist/current/demos/samples/DynTree.tcl} + + +Tabular ListBox +^^^^^^^^^^^^^^^ + + +.. class:: TList() + + The `TList + `_ widget + can be used to display data in a tabular format. The list entries of a + :class:`TList` widget are similar to the entries in the Tk listbox widget. The + main differences are (1) the :class:`TList` widget can display the list entries + in a two dimensional format and (2) you can use graphical images as well as + multiple colors and fonts for the list entries. + +.. Python Demo of: +.. \ulink{ScrolledTList (1)}{http://tix.sourceforge.net/dist/current/demos/samples/STList1.tcl} +.. Python Demo of: +.. \ulink{ScrolledTList (2)}{http://tix.sourceforge.net/dist/current/demos/samples/STList2.tcl} +.. Grid has yet to be added to Python +.. \subsubsection{Grid Widget} +.. Python Demo of: +.. \ulink{Simple Grid}{http://tix.sourceforge.net/dist/current/demos/samples/SGrid0.tcl} +.. Python Demo of: +.. \ulink{ScrolledGrid}{http://tix.sourceforge.net/dist/current/demos/samples/SGrid1.tcl} +.. Python Demo of: +.. \ulink{Editable Grid}{http://tix.sourceforge.net/dist/current/demos/samples/EditGrid.tcl} + + +Manager Widgets +^^^^^^^^^^^^^^^ + + +.. class:: PanedWindow() + + The `PanedWindow + `_ + widget allows the user to interactively manipulate the sizes of several panes. + The panes can be arranged either vertically or horizontally. The user changes + the sizes of the panes by dragging the resize handle between two panes. + +.. Python Demo of: +.. \ulink{PanedWindow}{http://tix.sourceforge.net/dist/current/demos/samples/PanedWin.tcl} + + +.. class:: ListNoteBook() + + The `ListNoteBook + `_ + widget is very similar to the :class:`TixNoteBook` widget: it can be used to + display many windows in a limited space using a notebook metaphor. The notebook + is divided into a stack of pages (windows). At one time only one of these pages + can be shown. The user can navigate through these pages by choosing the name of + the desired page in the :attr:`hlist` subwidget. + +.. Python Demo of: +.. \ulink{ListNoteBook}{http://tix.sourceforge.net/dist/current/demos/samples/ListNBK.tcl} + + +.. class:: NoteBook() + + The `NoteBook + `_ + widget can be used to display many windows in a limited space using a notebook + metaphor. The notebook is divided into a stack of pages. At one time only one of + these pages can be shown. The user can navigate through these pages by choosing + the visual "tabs" at the top of the NoteBook widget. + +.. Python Demo of: +.. \ulink{NoteBook}{http://tix.sourceforge.net/dist/current/demos/samples/NoteBook.tcl} + +.. \subsubsection{Scrolled Widgets} +.. Python Demo of: +.. \ulink{ScrolledListBox}{http://tix.sourceforge.net/dist/current/demos/samples/SListBox.tcl} +.. Python Demo of: +.. \ulink{ScrolledText}{http://tix.sourceforge.net/dist/current/demos/samples/SText.tcl} +.. Python Demo of: +.. \ulink{ScrolledWindow}{http://tix.sourceforge.net/dist/current/demos/samples/SWindow.tcl} +.. Python Demo of: +.. \ulink{Canvas Object View}{http://tix.sourceforge.net/dist/current/demos/samples/CObjView.tcl} + + +Image Types +^^^^^^^^^^^ + +The :mod:`tkinter.tix` module adds: + +* `pixmap `_ + capabilities to all :mod:`tkinter.tix` and :mod:`tkinter` widgets to create + color images from XPM files. + + .. Python Demo of: + .. \ulink{XPM Image In Button}{http://tix.sourceforge.net/dist/current/demos/samples/Xpm.tcl} + .. Python Demo of: + .. \ulink{XPM Image In Menu}{http://tix.sourceforge.net/dist/current/demos/samples/Xpm1.tcl} + +* `Compound + `_ image + types can be used to create images that consists of multiple horizontal lines; + each line is composed of a series of items (texts, bitmaps, images or spaces) + arranged from left to right. For example, a compound image can be used to + display a bitmap and a text string simultaneously in a Tk :class:`Button` + widget. + + .. Python Demo of: + .. \ulink{Compound Image In Buttons}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg.tcl} + .. Python Demo of: + .. \ulink{Compound Image In NoteBook}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg2.tcl} + .. Python Demo of: + .. \ulink{Compound Image Notebook Color Tabs}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg4.tcl} + .. Python Demo of: + .. \ulink{Compound Image Icons}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg3.tcl} + + +Miscellaneous Widgets +^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: InputOnly() + + The `InputOnly + `_ + widgets are to accept inputs from the user, which can be done with the ``bind`` + command (Unix only). + + +Form Geometry Manager +^^^^^^^^^^^^^^^^^^^^^ + +In addition, :mod:`tkinter.tix` augments :mod:`tkinter` by providing: + + +.. class:: Form() + + The `Form + `_ geometry + manager based on attachment rules for all Tk widgets. + + +Tix Commands +------------ + + +.. class:: tixCommand() + + The `tix commands + `_ provide + access to miscellaneous elements of :mod:`Tix`'s internal state and the + :mod:`Tix` application context. Most of the information manipulated by these + methods pertains to the application as a whole, or to a screen or display, + rather than to a particular window. + + To view the current settings, the common usage is:: + + from tkinter import tix + root = tix.Tk() + print(root.tix_configure()) + + +.. method:: tixCommand.tix_configure(cnf=None, **kw) + + Query or modify the configuration options of the Tix application context. If no + option is specified, returns a dictionary all of the available options. If + option is specified with no value, then the method returns a list describing the + one named option (this list will be identical to the corresponding sublist of + the value returned if no option is specified). If one or more option-value + pairs are specified, then the method modifies the given option(s) to have the + given value(s); in this case the method returns an empty string. Option may be + any of the configuration options. + + +.. method:: tixCommand.tix_cget(option) + + Returns the current value of the configuration option given by *option*. Option + may be any of the configuration options. + + +.. method:: tixCommand.tix_getbitmap(name) + + Locates a bitmap file of the name ``name.xpm`` or ``name`` in one of the bitmap + directories (see the :meth:`tix_addbitmapdir` method). By using + :meth:`tix_getbitmap`, you can avoid hard coding the pathnames of the bitmap + files in your application. When successful, it returns the complete pathname of + the bitmap file, prefixed with the character ``@``. The returned value can be + used to configure the ``bitmap`` option of the Tk and Tix widgets. + + +.. method:: tixCommand.tix_addbitmapdir(directory) + + Tix maintains a list of directories under which the :meth:`tix_getimage` and + :meth:`tix_getbitmap` methods will search for image files. The standard bitmap + directory is :file:`$TIX_LIBRARY/bitmaps`. The :meth:`tix_addbitmapdir` method + adds *directory* into this list. By using this method, the image files of an + applications can also be located using the :meth:`tix_getimage` or + :meth:`tix_getbitmap` method. + + +.. method:: tixCommand.tix_filedialog([dlgclass]) + + Returns the file selection dialog that may be shared among different calls from + this application. This method will create a file selection dialog widget when + it is called the first time. This dialog will be returned by all subsequent + calls to :meth:`tix_filedialog`. An optional dlgclass parameter can be passed + as a string to specified what type of file selection dialog widget is desired. + Possible options are ``tix``, ``FileSelectDialog`` or ``tixExFileSelectDialog``. + + +.. method:: tixCommand.tix_getimage(self, name) + + Locates an image file of the name :file:`name.xpm`, :file:`name.xbm` or + :file:`name.ppm` in one of the bitmap directories (see the + :meth:`tix_addbitmapdir` method above). If more than one file with the same name + (but different extensions) exist, then the image type is chosen according to the + depth of the X display: xbm images are chosen on monochrome displays and color + images are chosen on color displays. By using :meth:`tix_getimage`, you can + avoid hard coding the pathnames of the image files in your application. When + successful, this method returns the name of the newly created image, which can + be used to configure the ``image`` option of the Tk and Tix widgets. + + +.. method:: tixCommand.tix_option_get(name) + + Gets the options maintained by the Tix scheme mechanism. + + +.. method:: tixCommand.tix_resetoptions(newScheme, newFontSet[, newScmPrio]) + + Resets the scheme and fontset of the Tix application to *newScheme* and + *newFontSet*, respectively. This affects only those widgets created after this + call. Therefore, it is best to call the resetoptions method before the creation + of any widgets in a Tix application. + + The optional parameter *newScmPrio* can be given to reset the priority level of + the Tk options set by the Tix schemes. + + Because of the way Tk handles the X option database, after Tix has been has + imported and inited, it is not possible to reset the color schemes and font sets + using the :meth:`tix_config` method. Instead, the :meth:`tix_resetoptions` + method must be used. diff --git a/cpython_2/environment/repo/Doc/library/tkinter.ttk.rst b/cpython_2/environment/repo/Doc/library/tkinter.ttk.rst new file mode 100644 index 0000000000000000000000000000000000000000..6967d7509657b354cc415ed8a92c16f6f5888ca6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tkinter.ttk.rst @@ -0,0 +1,1527 @@ +:mod:`tkinter.ttk` --- Tk themed widgets +======================================== + +.. module:: tkinter.ttk + :synopsis: Tk themed widget set + +.. sectionauthor:: Guilherme Polo + +**Source code:** :source:`Lib/tkinter/ttk.py` + +.. index:: single: ttk + +-------------- + +The :mod:`tkinter.ttk` module provides access to the Tk themed widget set, +introduced in Tk 8.5. If Python has not been compiled against Tk 8.5, this +module can still be accessed if *Tile* has been installed. The former +method using Tk 8.5 provides additional benefits including anti-aliased font +rendering under X11 and window transparency (requiring a composition +window manager on X11). + +The basic idea for :mod:`tkinter.ttk` is to separate, to the extent possible, +the code implementing a widget's behavior from the code implementing its +appearance. + + +.. seealso:: + + `Tk Widget Styling Support `_ + A document introducing theming support for Tk + + +Using Ttk +--------- + +To start using Ttk, import its module:: + + from tkinter import ttk + +To override the basic Tk widgets, the import should follow the Tk import:: + + from tkinter import * + from tkinter.ttk import * + +That code causes several :mod:`tkinter.ttk` widgets (:class:`Button`, +:class:`Checkbutton`, :class:`Entry`, :class:`Frame`, :class:`Label`, +:class:`LabelFrame`, :class:`Menubutton`, :class:`PanedWindow`, +:class:`Radiobutton`, :class:`Scale` and :class:`Scrollbar`) to +automatically replace the Tk widgets. + +This has the direct benefit of using the new widgets which gives a better +look and feel across platforms; however, the replacement widgets are not +completely compatible. The main difference is that widget options such as +"fg", "bg" and others related to widget styling are no +longer present in Ttk widgets. Instead, use the :class:`ttk.Style` class +for improved styling effects. + + +.. seealso:: + + `Converting existing applications to use Tile widgets `_ + A monograph (using Tcl terminology) about differences typically + encountered when moving applications to use the new widgets. + + +Ttk Widgets +----------- + +Ttk comes with 18 widgets, twelve of which already existed in tkinter: +:class:`Button`, :class:`Checkbutton`, :class:`Entry`, :class:`Frame`, +:class:`Label`, :class:`LabelFrame`, :class:`Menubutton`, :class:`PanedWindow`, +:class:`Radiobutton`, :class:`Scale`, :class:`Scrollbar`, and :class:`Spinbox`. +The other six are new: :class:`Combobox`, :class:`Notebook`, +:class:`Progressbar`, :class:`Separator`, :class:`Sizegrip` and +:class:`Treeview`. And all them are subclasses of :class:`Widget`. + +Using the Ttk widgets gives the application an improved look and feel. +As discussed above, there are differences in how the styling is coded. + +Tk code:: + + l1 = tkinter.Label(text="Test", fg="black", bg="white") + l2 = tkinter.Label(text="Test", fg="black", bg="white") + + +Ttk code:: + + style = ttk.Style() + style.configure("BW.TLabel", foreground="black", background="white") + + l1 = ttk.Label(text="Test", style="BW.TLabel") + l2 = ttk.Label(text="Test", style="BW.TLabel") + +For more information about TtkStyling_, see the :class:`Style` class +documentation. + +Widget +------ + +:class:`ttk.Widget` defines standard options and methods supported by Tk +themed widgets and is not supposed to be directly instantiated. + + +Standard Options +^^^^^^^^^^^^^^^^ + +All the :mod:`ttk` Widgets accepts the following options: + + .. tabularcolumns:: |l|L| + + +-----------+--------------------------------------------------------------+ + | Option | Description | + +===========+==============================================================+ + | class | Specifies the window class. The class is used when querying | + | | the option database for the window's other options, to | + | | determine the default bindtags for the window, and to select | + | | the widget's default layout and style. This option is | + | | read-only, and may only be specified when the window is | + | | created. | + +-----------+--------------------------------------------------------------+ + | cursor | Specifies the mouse cursor to be used for the widget. If set | + | | to the empty string (the default), the cursor is inherited | + | | for the parent widget. | + +-----------+--------------------------------------------------------------+ + | takefocus | Determines whether the window accepts the focus during | + | | keyboard traversal. 0, 1 or an empty string is returned. | + | | If 0 is returned, it means that the window should be skipped | + | | entirely during keyboard traversal. If 1, it means that the | + | | window should receive the input focus as long as it is | + | | viewable. And an empty string means that the traversal | + | | scripts make the decision about whether or not to focus | + | | on the window. | + +-----------+--------------------------------------------------------------+ + | style | May be used to specify a custom widget style. | + +-----------+--------------------------------------------------------------+ + + +Scrollable Widget Options +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following options are supported by widgets that are controlled by a +scrollbar. + + .. tabularcolumns:: |l|L| + + +----------------+---------------------------------------------------------+ + | Option | Description | + +================+=========================================================+ + | xscrollcommand | Used to communicate with horizontal scrollbars. | + | | | + | | When the view in the widget's window change, the widget | + | | will generate a Tcl command based on the scrollcommand. | + | | | + | | Usually this option consists of the method | + | | :meth:`Scrollbar.set` of some scrollbar. This will cause| + | | the scrollbar to be updated whenever the view in the | + | | window changes. | + +----------------+---------------------------------------------------------+ + | yscrollcommand | Used to communicate with vertical scrollbars. | + | | For some more information, see above. | + +----------------+---------------------------------------------------------+ + + +Label Options +^^^^^^^^^^^^^ + +The following options are supported by labels, buttons and other button-like +widgets. + + .. tabularcolumns:: |l|p{0.7\linewidth}| + + +--------------+-----------------------------------------------------------+ + | Option | Description | + +==============+===========================================================+ + | text | Specifies a text string to be displayed inside the widget.| + +--------------+-----------------------------------------------------------+ + | textvariable | Specifies a name whose value will be used in place of the | + | | text option resource. | + +--------------+-----------------------------------------------------------+ + | underline | If set, specifies the index (0-based) of a character to | + | | underline in the text string. The underline character is | + | | used for mnemonic activation. | + +--------------+-----------------------------------------------------------+ + | image | Specifies an image to display. This is a list of 1 or more| + | | elements. The first element is the default image name. The| + | | rest of the list if a sequence of statespec/value pairs as| + | | defined by :meth:`Style.map`, specifying different images | + | | to use when the widget is in a particular state or a | + | | combination of states. All images in the list should have | + | | the same size. | + +--------------+-----------------------------------------------------------+ + | compound | Specifies how to display the image relative to the text, | + | | in the case both text and images options are present. | + | | Valid values are: | + | | | + | | * text: display text only | + | | * image: display image only | + | | * top, bottom, left, right: display image above, below, | + | | left of, or right of the text, respectively. | + | | * none: the default. display the image if present, | + | | otherwise the text. | + +--------------+-----------------------------------------------------------+ + | width | If greater than zero, specifies how much space, in | + | | character widths, to allocate for the text label, if less | + | | than zero, specifies a minimum width. If zero or | + | | unspecified, the natural width of the text label is used. | + +--------------+-----------------------------------------------------------+ + + +Compatibility Options +^^^^^^^^^^^^^^^^^^^^^ + + .. tabularcolumns:: |l|L| + + +--------+----------------------------------------------------------------+ + | Option | Description | + +========+================================================================+ + | state | May be set to "normal" or "disabled" to control the "disabled" | + | | state bit. This is a write-only option: setting it changes the | + | | widget state, but the :meth:`Widget.state` method does not | + | | affect this option. | + +--------+----------------------------------------------------------------+ + +Widget States +^^^^^^^^^^^^^ + +The widget state is a bitmap of independent state flags. + + .. tabularcolumns:: |l|L| + + +------------+-------------------------------------------------------------+ + | Flag | Description | + +============+=============================================================+ + | active | The mouse cursor is over the widget and pressing a mouse | + | | button will cause some action to occur | + +------------+-------------------------------------------------------------+ + | disabled | Widget is disabled under program control | + +------------+-------------------------------------------------------------+ + | focus | Widget has keyboard focus | + +------------+-------------------------------------------------------------+ + | pressed | Widget is being pressed | + +------------+-------------------------------------------------------------+ + | selected | "On", "true", or "current" for things like Checkbuttons and | + | | radiobuttons | + +------------+-------------------------------------------------------------+ + | background | Windows and Mac have a notion of an "active" or foreground | + | | window. The *background* state is set for widgets in a | + | | background window, and cleared for those in the foreground | + | | window | + +------------+-------------------------------------------------------------+ + | readonly | Widget should not allow user modification | + +------------+-------------------------------------------------------------+ + | alternate | A widget-specific alternate display format | + +------------+-------------------------------------------------------------+ + | invalid | The widget's value is invalid | + +------------+-------------------------------------------------------------+ + +A state specification is a sequence of state names, optionally prefixed with +an exclamation point indicating that the bit is off. + + +ttk.Widget +^^^^^^^^^^ + +Besides the methods described below, the :class:`ttk.Widget` supports the +methods :meth:`tkinter.Widget.cget` and :meth:`tkinter.Widget.configure`. + +.. class:: Widget + + .. method:: identify(x, y) + + Returns the name of the element at position *x* *y*, or the empty string + if the point does not lie within any element. + + *x* and *y* are pixel coordinates relative to the widget. + + + .. method:: instate(statespec, callback=None, *args, **kw) + + Test the widget's state. If a callback is not specified, returns ``True`` + if the widget state matches *statespec* and ``False`` otherwise. If callback + is specified then it is called with args if widget state matches + *statespec*. + + + .. method:: state(statespec=None) + + Modify or inquire widget state. If *statespec* is specified, sets the + widget state according to it and return a new *statespec* indicating + which flags were changed. If *statespec* is not specified, returns + the currently-enabled state flags. + + *statespec* will usually be a list or a tuple. + + +Combobox +-------- + +The :class:`ttk.Combobox` widget combines a text field with a pop-down list of +values. This widget is a subclass of :class:`Entry`. + +Besides the methods inherited from :class:`Widget`: :meth:`Widget.cget`, +:meth:`Widget.configure`, :meth:`Widget.identify`, :meth:`Widget.instate` +and :meth:`Widget.state`, and the following inherited from :class:`Entry`: +:meth:`Entry.bbox`, :meth:`Entry.delete`, :meth:`Entry.icursor`, +:meth:`Entry.index`, :meth:`Entry.insert`, :meth:`Entry.selection`, +:meth:`Entry.xview`, it has some other methods, described at +:class:`ttk.Combobox`. + + +Options +^^^^^^^ + +This widget accepts the following specific options: + + .. tabularcolumns:: |l|L| + + +-----------------+--------------------------------------------------------+ + | Option | Description | + +=================+========================================================+ + | exportselection | Boolean value. If set, the widget selection is linked | + | | to the Window Manager selection (which can be returned | + | | by invoking Misc.selection_get, for example). | + +-----------------+--------------------------------------------------------+ + | justify | Specifies how the text is aligned within the widget. | + | | One of "left", "center", or "right". | + +-----------------+--------------------------------------------------------+ + | height | Specifies the height of the pop-down listbox, in rows. | + +-----------------+--------------------------------------------------------+ + | postcommand | A script (possibly registered with Misc.register) that | + | | is called immediately before displaying the values. It | + | | may specify which values to display. | + +-----------------+--------------------------------------------------------+ + | state | One of "normal", "readonly", or "disabled". In the | + | | "readonly" state, the value may not be edited directly,| + | | and the user can only selection of the values from the | + | | dropdown list. In the "normal" state, the text field is| + | | directly editable. In the "disabled" state, no | + | | interaction is possible. | + +-----------------+--------------------------------------------------------+ + | textvariable | Specifies a name whose value is linked to the widget | + | | value. Whenever the value associated with that name | + | | changes, the widget value is updated, and vice versa. | + | | See :class:`tkinter.StringVar`. | + +-----------------+--------------------------------------------------------+ + | values | Specifies the list of values to display in the | + | | drop-down listbox. | + +-----------------+--------------------------------------------------------+ + | width | Specifies an integer value indicating the desired width| + | | of the entry window, in average-size characters of the | + | | widget's font. | + +-----------------+--------------------------------------------------------+ + + +Virtual events +^^^^^^^^^^^^^^ + +The combobox widgets generates a **<>** virtual event +when the user selects an element from the list of values. + + +ttk.Combobox +^^^^^^^^^^^^ + +.. class:: Combobox + + .. method:: current(newindex=None) + + If *newindex* is specified, sets the combobox value to the element + position *newindex*. Otherwise, returns the index of the current value or + -1 if the current value is not in the values list. + + + .. method:: get() + + Returns the current value of the combobox. + + + .. method:: set(value) + + Sets the value of the combobox to *value*. + + +Spinbox +------- +The :class:`ttk.Spinbox` widget is a :class:`ttk.Entry` enhanced with increment +and decrement arrows. It can be used for numbers or lists of string values. +This widget is a subclass of :class:`Entry`. + +Besides the methods inherited from :class:`Widget`: :meth:`Widget.cget`, +:meth:`Widget.configure`, :meth:`Widget.identify`, :meth:`Widget.instate` +and :meth:`Widget.state`, and the following inherited from :class:`Entry`: +:meth:`Entry.bbox`, :meth:`Entry.delete`, :meth:`Entry.icursor`, +:meth:`Entry.index`, :meth:`Entry.insert`, :meth:`Entry.xview`, +it has some other methods, described at :class:`ttk.Spinbox`. + +Options +^^^^^^^ + +This widget accepts the following specific options: + + .. tabularcolumns:: |l|L| + ++----------------------+------------------------------------------------------+ +| Option | Description | ++======================+======================================================+ +| from | Float value. If set, this is the minimum value to | +| | which the decrement button will decrement. Must be | +| | spelled as ``from_`` when used as an argument, since | +| | ``from`` is a Python keyword. | ++----------------------+------------------------------------------------------+ +| to | Float value. If set, this is the maximum value to | +| | which the increment button will increment. | ++----------------------+------------------------------------------------------+ +| increment | Float value. Specifies the amount which the | +| | increment/decrement buttons change the | +| | value. Defaults to 1.0. | ++----------------------+------------------------------------------------------+ +| values | Sequence of string or float values. If specified, | +| | the increment/decrement buttons will cycle through | +| | the items in this sequence rather than incrementing | +| | or decrementing numbers. | +| | | ++----------------------+------------------------------------------------------+ +| wrap | Boolean value. If ``True``, increment and decrement | +| | buttons will cycle from the ``to`` value to the | +| | ``from`` value or the ``from`` value to the ``to`` | +| | value, respectively. | ++----------------------+------------------------------------------------------+ +| format | String value. This specifies the format of numbers | +| | set by the increment/decrement buttons. It must be | +| | in the form "%W.Pf", where W is the padded width of | +| | the value, P is the precision, and '%' and 'f' are | +| | literal. | ++----------------------+------------------------------------------------------+ +| command | Python callable. Will be called with no arguments | +| | whenever either of the increment or decrement buttons| +| | are pressed. | +| | | ++----------------------+------------------------------------------------------+ + + +Virtual events +^^^^^^^^^^^^^^ + +The spinbox widget generates an **<>** virtual event when the +user presses , and a **<>** virtual event when the user +presses . + +ttk.Spinbox +^^^^^^^^^^^^ + +.. class:: Spinbox + + .. method:: get() + + Returns the current value of the spinbox. + + + .. method:: set(value) + + Sets the value of the spinbox to *value*. + + +Notebook +-------- + +Ttk Notebook widget manages a collection of windows and displays a single +one at a time. Each child window is associated with a tab, which the user +may select to change the currently-displayed window. + + +Options +^^^^^^^ + +This widget accepts the following specific options: + + .. tabularcolumns:: |l|L| + + +---------+----------------------------------------------------------------+ + | Option | Description | + +=========+================================================================+ + | height | If present and greater than zero, specifies the desired height | + | | of the pane area (not including internal padding or tabs). | + | | Otherwise, the maximum height of all panes is used. | + +---------+----------------------------------------------------------------+ + | padding | Specifies the amount of extra space to add around the outside | + | | of the notebook. The padding is a list up to four length | + | | specifications left top right bottom. If fewer than four | + | | elements are specified, bottom defaults to top, right defaults | + | | to left, and top defaults to left. | + +---------+----------------------------------------------------------------+ + | width | If present and greater than zero, specified the desired width | + | | of the pane area (not including internal padding). Otherwise, | + | | the maximum width of all panes is used. | + +---------+----------------------------------------------------------------+ + + +Tab Options +^^^^^^^^^^^ + +There are also specific options for tabs: + + .. tabularcolumns:: |l|L| + + +-----------+--------------------------------------------------------------+ + | Option | Description | + +===========+==============================================================+ + | state | Either "normal", "disabled" or "hidden". If "disabled", then | + | | the tab is not selectable. If "hidden", then the tab is not | + | | shown. | + +-----------+--------------------------------------------------------------+ + | sticky | Specifies how the child window is positioned within the pane | + | | area. Value is a string containing zero or more of the | + | | characters "n", "s", "e" or "w". Each letter refers to a | + | | side (north, south, east or west) that the child window will | + | | stick to, as per the :meth:`grid` geometry manager. | + +-----------+--------------------------------------------------------------+ + | padding | Specifies the amount of extra space to add between the | + | | notebook and this pane. Syntax is the same as for the option | + | | padding used by this widget. | + +-----------+--------------------------------------------------------------+ + | text | Specifies a text to be displayed in the tab. | + +-----------+--------------------------------------------------------------+ + | image | Specifies an image to display in the tab. See the option | + | | image described in :class:`Widget`. | + +-----------+--------------------------------------------------------------+ + | compound | Specifies how to display the image relative to the text, in | + | | the case both options text and image are present. See | + | | `Label Options`_ for legal values. | + +-----------+--------------------------------------------------------------+ + | underline | Specifies the index (0-based) of a character to underline in | + | | the text string. The underlined character is used for | + | | mnemonic activation if :meth:`Notebook.enable_traversal` is | + | | called. | + +-----------+--------------------------------------------------------------+ + + +Tab Identifiers +^^^^^^^^^^^^^^^ + +The tab_id present in several methods of :class:`ttk.Notebook` may take any +of the following forms: + +* An integer between zero and the number of tabs +* The name of a child window +* A positional specification of the form "@x,y", which identifies the tab +* The literal string "current", which identifies the currently-selected tab +* The literal string "end", which returns the number of tabs (only valid for + :meth:`Notebook.index`) + + +Virtual Events +^^^^^^^^^^^^^^ + +This widget generates a **<>** virtual event after a new +tab is selected. + + +ttk.Notebook +^^^^^^^^^^^^ + +.. class:: Notebook + + .. method:: add(child, **kw) + + Adds a new tab to the notebook. + + If window is currently managed by the notebook but hidden, it is + restored to its previous position. + + See `Tab Options`_ for the list of available options. + + + .. method:: forget(tab_id) + + Removes the tab specified by *tab_id*, unmaps and unmanages the + associated window. + + + .. method:: hide(tab_id) + + Hides the tab specified by *tab_id*. + + The tab will not be displayed, but the associated window remains + managed by the notebook and its configuration remembered. Hidden tabs + may be restored with the :meth:`add` command. + + + .. method:: identify(x, y) + + Returns the name of the tab element at position *x*, *y*, or the empty + string if none. + + + .. method:: index(tab_id) + + Returns the numeric index of the tab specified by *tab_id*, or the total + number of tabs if *tab_id* is the string "end". + + + .. method:: insert(pos, child, **kw) + + Inserts a pane at the specified position. + + *pos* is either the string "end", an integer index, or the name of a + managed child. If *child* is already managed by the notebook, moves it to + the specified position. + + See `Tab Options`_ for the list of available options. + + + .. method:: select(tab_id=None) + + Selects the specified *tab_id*. + + The associated child window will be displayed, and the + previously-selected window (if different) is unmapped. If *tab_id* is + omitted, returns the widget name of the currently selected pane. + + + .. method:: tab(tab_id, option=None, **kw) + + Query or modify the options of the specific *tab_id*. + + If *kw* is not given, returns a dictionary of the tab option values. If + *option* is specified, returns the value of that *option*. Otherwise, + sets the options to the corresponding values. + + + .. method:: tabs() + + Returns a list of windows managed by the notebook. + + + .. method:: enable_traversal() + + Enable keyboard traversal for a toplevel window containing this notebook. + + This will extend the bindings for the toplevel window containing the + notebook as follows: + + * :kbd:`Control-Tab`: selects the tab following the currently selected one. + * :kbd:`Shift-Control-Tab`: selects the tab preceding the currently selected one. + * :kbd:`Alt-K`: where *K* is the mnemonic (underlined) character of any tab, will + select that tab. + + Multiple notebooks in a single toplevel may be enabled for traversal, + including nested notebooks. However, notebook traversal only works + properly if all panes have the notebook they are in as master. + + +Progressbar +----------- + +The :class:`ttk.Progressbar` widget shows the status of a long-running +operation. It can operate in two modes: 1) the determinate mode which shows the +amount completed relative to the total amount of work to be done and 2) the +indeterminate mode which provides an animated display to let the user know that +work is progressing. + + +Options +^^^^^^^ + +This widget accepts the following specific options: + + .. tabularcolumns:: |l|L| + + +----------+---------------------------------------------------------------+ + | Option | Description | + +==========+===============================================================+ + | orient | One of "horizontal" or "vertical". Specifies the orientation | + | | of the progress bar. | + +----------+---------------------------------------------------------------+ + | length | Specifies the length of the long axis of the progress bar | + | | (width if horizontal, height if vertical). | + +----------+---------------------------------------------------------------+ + | mode | One of "determinate" or "indeterminate". | + +----------+---------------------------------------------------------------+ + | maximum | A number specifying the maximum value. Defaults to 100. | + +----------+---------------------------------------------------------------+ + | value | The current value of the progress bar. In "determinate" mode, | + | | this represents the amount of work completed. In | + | | "indeterminate" mode, it is interpreted as modulo *maximum*; | + | | that is, the progress bar completes one "cycle" when its value| + | | increases by *maximum*. | + +----------+---------------------------------------------------------------+ + | variable | A name which is linked to the option value. If specified, the | + | | value of the progress bar is automatically set to the value of| + | | this name whenever the latter is modified. | + +----------+---------------------------------------------------------------+ + | phase | Read-only option. The widget periodically increments the value| + | | of this option whenever its value is greater than 0 and, in | + | | determinate mode, less than maximum. This option may be used | + | | by the current theme to provide additional animation effects. | + +----------+---------------------------------------------------------------+ + + +ttk.Progressbar +^^^^^^^^^^^^^^^ + +.. class:: Progressbar + + .. method:: start(interval=None) + + Begin autoincrement mode: schedules a recurring timer event that calls + :meth:`Progressbar.step` every *interval* milliseconds. If omitted, + *interval* defaults to 50 milliseconds. + + + .. method:: step(amount=None) + + Increments the progress bar's value by *amount*. + + *amount* defaults to 1.0 if omitted. + + + .. method:: stop() + + Stop autoincrement mode: cancels any recurring timer event initiated by + :meth:`Progressbar.start` for this progress bar. + + +Separator +--------- + +The :class:`ttk.Separator` widget displays a horizontal or vertical separator +bar. + +It has no other methods besides the ones inherited from :class:`ttk.Widget`. + + +Options +^^^^^^^ + +This widget accepts the following specific option: + + .. tabularcolumns:: |l|L| + + +--------+----------------------------------------------------------------+ + | Option | Description | + +========+================================================================+ + | orient | One of "horizontal" or "vertical". Specifies the orientation of| + | | the separator. | + +--------+----------------------------------------------------------------+ + + +Sizegrip +-------- + +The :class:`ttk.Sizegrip` widget (also known as a grow box) allows the user to +resize the containing toplevel window by pressing and dragging the grip. + +This widget has neither specific options nor specific methods, besides the +ones inherited from :class:`ttk.Widget`. + + +Platform-specific notes +^^^^^^^^^^^^^^^^^^^^^^^ + +* On MacOS X, toplevel windows automatically include a built-in size grip + by default. Adding a :class:`Sizegrip` is harmless, since the built-in + grip will just mask the widget. + + +Bugs +^^^^ + +* If the containing toplevel's position was specified relative to the right + or bottom of the screen (e.g. ....), the :class:`Sizegrip` widget will + not resize the window. +* This widget supports only "southeast" resizing. + + +Treeview +-------- + +The :class:`ttk.Treeview` widget displays a hierarchical collection of items. +Each item has a textual label, an optional image, and an optional list of data +values. The data values are displayed in successive columns after the tree +label. + +The order in which data values are displayed may be controlled by setting +the widget option ``displaycolumns``. The tree widget can also display column +headings. Columns may be accessed by number or symbolic names listed in the +widget option columns. See `Column Identifiers`_. + +Each item is identified by a unique name. The widget will generate item IDs +if they are not supplied by the caller. There is a distinguished root item, +named ``{}``. The root item itself is not displayed; its children appear at the +top level of the hierarchy. + +Each item also has a list of tags, which can be used to associate event bindings +with individual items and control the appearance of the item. + +The Treeview widget supports horizontal and vertical scrolling, according to +the options described in `Scrollable Widget Options`_ and the methods +:meth:`Treeview.xview` and :meth:`Treeview.yview`. + + +Options +^^^^^^^ + +This widget accepts the following specific options: + + .. tabularcolumns:: |l|p{0.7\linewidth}| + + +----------------+--------------------------------------------------------+ + | Option | Description | + +================+========================================================+ + | columns | A list of column identifiers, specifying the number of | + | | columns and their names. | + +----------------+--------------------------------------------------------+ + | displaycolumns | A list of column identifiers (either symbolic or | + | | integer indices) specifying which data columns are | + | | displayed and the order in which they appear, or the | + | | string "#all". | + +----------------+--------------------------------------------------------+ + | height | Specifies the number of rows which should be visible. | + | | Note: the requested width is determined from the sum | + | | of the column widths. | + +----------------+--------------------------------------------------------+ + | padding | Specifies the internal padding for the widget. The | + | | padding is a list of up to four length specifications. | + +----------------+--------------------------------------------------------+ + | selectmode | Controls how the built-in class bindings manage the | + | | selection. One of "extended", "browse" or "none". | + | | If set to "extended" (the default), multiple items may | + | | be selected. If "browse", only a single item will be | + | | selected at a time. If "none", the selection will not | + | | be changed. | + | | | + | | Note that the application code and tag bindings can set| + | | the selection however they wish, regardless of the | + | | value of this option. | + +----------------+--------------------------------------------------------+ + | show | A list containing zero or more of the following values,| + | | specifying which elements of the tree to display. | + | | | + | | * tree: display tree labels in column #0. | + | | * headings: display the heading row. | + | | | + | | The default is "tree headings", i.e., show all | + | | elements. | + | | | + | | **Note**: Column #0 always refers to the tree column, | + | | even if show="tree" is not specified. | + +----------------+--------------------------------------------------------+ + + +Item Options +^^^^^^^^^^^^ + +The following item options may be specified for items in the insert and item +widget commands. + + .. tabularcolumns:: |l|L| + + +--------+---------------------------------------------------------------+ + | Option | Description | + +========+===============================================================+ + | text | The textual label to display for the item. | + +--------+---------------------------------------------------------------+ + | image | A Tk Image, displayed to the left of the label. | + +--------+---------------------------------------------------------------+ + | values | The list of values associated with the item. | + | | | + | | Each item should have the same number of values as the widget | + | | option columns. If there are fewer values than columns, the | + | | remaining values are assumed empty. If there are more values | + | | than columns, the extra values are ignored. | + +--------+---------------------------------------------------------------+ + | open | ``True``/``False`` value indicating whether the item's | + | | children should be displayed or hidden. | + +--------+---------------------------------------------------------------+ + | tags | A list of tags associated with this item. | + +--------+---------------------------------------------------------------+ + + +Tag Options +^^^^^^^^^^^ + +The following options may be specified on tags: + + .. tabularcolumns:: |l|L| + + +------------+-----------------------------------------------------------+ + | Option | Description | + +============+===========================================================+ + | foreground | Specifies the text foreground color. | + +------------+-----------------------------------------------------------+ + | background | Specifies the cell or item background color. | + +------------+-----------------------------------------------------------+ + | font | Specifies the font to use when drawing text. | + +------------+-----------------------------------------------------------+ + | image | Specifies the item image, in case the item's image option | + | | is empty. | + +------------+-----------------------------------------------------------+ + + +Column Identifiers +^^^^^^^^^^^^^^^^^^ + +Column identifiers take any of the following forms: + +* A symbolic name from the list of columns option. +* An integer n, specifying the nth data column. +* A string of the form #n, where n is an integer, specifying the nth display + column. + +Notes: + +* Item's option values may be displayed in a different order than the order + in which they are stored. +* Column #0 always refers to the tree column, even if show="tree" is not + specified. + +A data column number is an index into an item's option values list; a display +column number is the column number in the tree where the values are displayed. +Tree labels are displayed in column #0. If option displaycolumns is not set, +then data column n is displayed in column #n+1. Again, **column #0 always +refers to the tree column**. + + +Virtual Events +^^^^^^^^^^^^^^ + +The Treeview widget generates the following virtual events. + + .. tabularcolumns:: |l|L| + + +--------------------+--------------------------------------------------+ + | Event | Description | + +====================+==================================================+ + | <> | Generated whenever the selection changes. | + +--------------------+--------------------------------------------------+ + | <> | Generated just before settings the focus item to | + | | open=True. | + +--------------------+--------------------------------------------------+ + | <> | Generated just after setting the focus item to | + | | open=False. | + +--------------------+--------------------------------------------------+ + +The :meth:`Treeview.focus` and :meth:`Treeview.selection` methods can be used +to determine the affected item or items. + + +ttk.Treeview +^^^^^^^^^^^^ + +.. class:: Treeview + + .. method:: bbox(item, column=None) + + Returns the bounding box (relative to the treeview widget's window) of + the specified *item* in the form (x, y, width, height). + + If *column* is specified, returns the bounding box of that cell. If the + *item* is not visible (i.e., if it is a descendant of a closed item or is + scrolled offscreen), returns an empty string. + + + .. method:: get_children(item=None) + + Returns the list of children belonging to *item*. + + If *item* is not specified, returns root children. + + + .. method:: set_children(item, *newchildren) + + Replaces *item*'s child with *newchildren*. + + Children present in *item* that are not present in *newchildren* are + detached from the tree. No items in *newchildren* may be an ancestor of + *item*. Note that not specifying *newchildren* results in detaching + *item*'s children. + + + .. method:: column(column, option=None, **kw) + + Query or modify the options for the specified *column*. + + If *kw* is not given, returns a dict of the column option values. If + *option* is specified then the value for that *option* is returned. + Otherwise, sets the options to the corresponding values. + + The valid options/values are: + + * id + Returns the column name. This is a read-only option. + * anchor: One of the standard Tk anchor values. + Specifies how the text in this column should be aligned with respect + to the cell. + * minwidth: width + The minimum width of the column in pixels. The treeview widget will + not make the column any smaller than specified by this option when + the widget is resized or the user drags a column. + * stretch: ``True``/``False`` + Specifies whether the column's width should be adjusted when + the widget is resized. + * width: width + The width of the column in pixels. + + To configure the tree column, call this with column = "#0" + + .. method:: delete(*items) + + Delete all specified *items* and all their descendants. + + The root item may not be deleted. + + + .. method:: detach(*items) + + Unlinks all of the specified *items* from the tree. + + The items and all of their descendants are still present, and may be + reinserted at another point in the tree, but will not be displayed. + + The root item may not be detached. + + + .. method:: exists(item) + + Returns ``True`` if the specified *item* is present in the tree. + + + .. method:: focus(item=None) + + If *item* is specified, sets the focus item to *item*. Otherwise, returns + the current focus item, or '' if there is none. + + + .. method:: heading(column, option=None, **kw) + + Query or modify the heading options for the specified *column*. + + If *kw* is not given, returns a dict of the heading option values. If + *option* is specified then the value for that *option* is returned. + Otherwise, sets the options to the corresponding values. + + The valid options/values are: + + * text: text + The text to display in the column heading. + * image: imageName + Specifies an image to display to the right of the column heading. + * anchor: anchor + Specifies how the heading text should be aligned. One of the standard + Tk anchor values. + * command: callback + A callback to be invoked when the heading label is pressed. + + To configure the tree column heading, call this with column = "#0". + + + .. method:: identify(component, x, y) + + Returns a description of the specified *component* under the point given + by *x* and *y*, or the empty string if no such *component* is present at + that position. + + + .. method:: identify_row(y) + + Returns the item ID of the item at position *y*. + + + .. method:: identify_column(x) + + Returns the data column identifier of the cell at position *x*. + + The tree column has ID #0. + + + .. method:: identify_region(x, y) + + Returns one of: + + +-----------+--------------------------------------+ + | region | meaning | + +===========+======================================+ + | heading | Tree heading area. | + +-----------+--------------------------------------+ + | separator | Space between two columns headings. | + +-----------+--------------------------------------+ + | tree | The tree area. | + +-----------+--------------------------------------+ + | cell | A data cell. | + +-----------+--------------------------------------+ + + Availability: Tk 8.6. + + + .. method:: identify_element(x, y) + + Returns the element at position *x*, *y*. + + Availability: Tk 8.6. + + + .. method:: index(item) + + Returns the integer index of *item* within its parent's list of children. + + + .. method:: insert(parent, index, iid=None, **kw) + + Creates a new item and returns the item identifier of the newly created + item. + + *parent* is the item ID of the parent item, or the empty string to create + a new top-level item. *index* is an integer, or the value "end", + specifying where in the list of parent's children to insert the new item. + If *index* is less than or equal to zero, the new node is inserted at + the beginning; if *index* is greater than or equal to the current number + of children, it is inserted at the end. If *iid* is specified, it is used + as the item identifier; *iid* must not already exist in the tree. + Otherwise, a new unique identifier is generated. + + See `Item Options`_ for the list of available points. + + + .. method:: item(item, option=None, **kw) + + Query or modify the options for the specified *item*. + + If no options are given, a dict with options/values for the item is + returned. + If *option* is specified then the value for that option is returned. + Otherwise, sets the options to the corresponding values as given by *kw*. + + + .. method:: move(item, parent, index) + + Moves *item* to position *index* in *parent*'s list of children. + + It is illegal to move an item under one of its descendants. If *index* is + less than or equal to zero, *item* is moved to the beginning; if greater + than or equal to the number of children, it is moved to the end. If *item* + was detached it is reattached. + + + .. method:: next(item) + + Returns the identifier of *item*'s next sibling, or '' if *item* is the + last child of its parent. + + + .. method:: parent(item) + + Returns the ID of the parent of *item*, or '' if *item* is at the top + level of the hierarchy. + + + .. method:: prev(item) + + Returns the identifier of *item*'s previous sibling, or '' if *item* is + the first child of its parent. + + + .. method:: reattach(item, parent, index) + + An alias for :meth:`Treeview.move`. + + + .. method:: see(item) + + Ensure that *item* is visible. + + Sets all of *item*'s ancestors open option to ``True``, and scrolls the + widget if necessary so that *item* is within the visible portion of + the tree. + + + .. method:: selection() + + Returns a tuple of selected items. + + .. versionchanged:: 3.8 + ``selection()`` no longer takes arguments. For changing the selection + state use the following selection methods. + + + .. method:: selection_set(*items) + + *items* becomes the new selection. + + .. versionchanged:: 3.6 + *items* can be passed as separate arguments, not just as a single tuple. + + + .. method:: selection_add(*items) + + Add *items* to the selection. + + .. versionchanged:: 3.6 + *items* can be passed as separate arguments, not just as a single tuple. + + + .. method:: selection_remove(*items) + + Remove *items* from the selection. + + .. versionchanged:: 3.6 + *items* can be passed as separate arguments, not just as a single tuple. + + + .. method:: selection_toggle(*items) + + Toggle the selection state of each item in *items*. + + .. versionchanged:: 3.6 + *items* can be passed as separate arguments, not just as a single tuple. + + + .. method:: set(item, column=None, value=None) + + With one argument, returns a dictionary of column/value pairs for the + specified *item*. With two arguments, returns the current value of the + specified *column*. With three arguments, sets the value of given + *column* in given *item* to the specified *value*. + + + .. method:: tag_bind(tagname, sequence=None, callback=None) + + Bind a callback for the given event *sequence* to the tag *tagname*. + When an event is delivered to an item, the callbacks for each of the + item's tags option are called. + + + .. method:: tag_configure(tagname, option=None, **kw) + + Query or modify the options for the specified *tagname*. + + If *kw* is not given, returns a dict of the option settings for + *tagname*. If *option* is specified, returns the value for that *option* + for the specified *tagname*. Otherwise, sets the options to the + corresponding values for the given *tagname*. + + + .. method:: tag_has(tagname, item=None) + + If *item* is specified, returns 1 or 0 depending on whether the specified + *item* has the given *tagname*. Otherwise, returns a list of all items + that have the specified tag. + + Availability: Tk 8.6 + + + .. method:: xview(*args) + + Query or modify horizontal position of the treeview. + + + .. method:: yview(*args) + + Query or modify vertical position of the treeview. + + +.. _TtkStyling: + +Ttk Styling +----------- + +Each widget in :mod:`ttk` is assigned a style, which specifies the set of +elements making up the widget and how they are arranged, along with dynamic +and default settings for element options. By default the style name is the +same as the widget's class name, but it may be overridden by the widget's style +option. If you don't know the class name of a widget, use the method +:meth:`Misc.winfo_class` (somewidget.winfo_class()). + +.. seealso:: + + `Tcl'2004 conference presentation `_ + This document explains how the theme engine works + + +.. class:: Style + + This class is used to manipulate the style database. + + + .. method:: configure(style, query_opt=None, **kw) + + Query or set the default value of the specified option(s) in *style*. + + Each key in *kw* is an option and each value is a string identifying + the value for that option. + + For example, to change every default button to be a flat button with + some padding and a different background color:: + + from tkinter import ttk + import tkinter + + root = tkinter.Tk() + + ttk.Style().configure("TButton", padding=6, relief="flat", + background="#ccc") + + btn = ttk.Button(text="Sample") + btn.pack() + + root.mainloop() + + + .. method:: map(style, query_opt=None, **kw) + + Query or sets dynamic values of the specified option(s) in *style*. + + Each key in *kw* is an option and each value should be a list or a + tuple (usually) containing statespecs grouped in tuples, lists, or + some other preference. A statespec is a compound of one + or more states and then a value. + + An example may make it more understandable:: + + import tkinter + from tkinter import ttk + + root = tkinter.Tk() + + style = ttk.Style() + style.map("C.TButton", + foreground=[('pressed', 'red'), ('active', 'blue')], + background=[('pressed', '!disabled', 'black'), ('active', 'white')] + ) + + colored_btn = ttk.Button(text="Test", style="C.TButton").pack() + + root.mainloop() + + + Note that the order of the (states, value) sequences for an option does + matter, if the order is changed to ``[('active', 'blue'), ('pressed', + 'red')]`` in the foreground option, for example, the result would be a + blue foreground when the widget were in active or pressed states. + + + .. method:: lookup(style, option, state=None, default=None) + + Returns the value specified for *option* in *style*. + + If *state* is specified, it is expected to be a sequence of one or more + states. If the *default* argument is set, it is used as a fallback value + in case no specification for option is found. + + To check what font a Button uses by default:: + + from tkinter import ttk + + print(ttk.Style().lookup("TButton", "font")) + + + .. method:: layout(style, layoutspec=None) + + Define the widget layout for given *style*. If *layoutspec* is omitted, + return the layout specification for given style. + + *layoutspec*, if specified, is expected to be a list or some other + sequence type (excluding strings), where each item should be a tuple and + the first item is the layout name and the second item should have the + format described in `Layouts`_. + + To understand the format, see the following example (it is not + intended to do anything useful):: + + from tkinter import ttk + import tkinter + + root = tkinter.Tk() + + style = ttk.Style() + style.layout("TMenubutton", [ + ("Menubutton.background", None), + ("Menubutton.button", {"children": + [("Menubutton.focus", {"children": + [("Menubutton.padding", {"children": + [("Menubutton.label", {"side": "left", "expand": 1})] + })] + })] + }), + ]) + + mbtn = ttk.Menubutton(text='Text') + mbtn.pack() + root.mainloop() + + + .. method:: element_create(elementname, etype, *args, **kw) + + Create a new element in the current theme, of the given *etype* which is + expected to be either "image", "from" or "vsapi". The latter is only + available in Tk 8.6a for Windows XP and Vista and is not described here. + + If "image" is used, *args* should contain the default image name followed + by statespec/value pairs (this is the imagespec), and *kw* may have the + following options: + + * border=padding + padding is a list of up to four integers, specifying the left, top, + right, and bottom borders, respectively. + + * height=height + Specifies a minimum height for the element. If less than zero, the + base image's height is used as a default. + + * padding=padding + Specifies the element's interior padding. Defaults to border's value + if not specified. + + * sticky=spec + Specifies how the image is placed within the final parcel. spec + contains zero or more characters "n", "s", "w", or "e". + + * width=width + Specifies a minimum width for the element. If less than zero, the + base image's width is used as a default. + + If "from" is used as the value of *etype*, + :meth:`element_create` will clone an existing + element. *args* is expected to contain a themename, from which + the element will be cloned, and optionally an element to clone from. + If this element to clone from is not specified, an empty element will + be used. *kw* is discarded. + + + .. method:: element_names() + + Returns the list of elements defined in the current theme. + + + .. method:: element_options(elementname) + + Returns the list of *elementname*'s options. + + + .. method:: theme_create(themename, parent=None, settings=None) + + Create a new theme. + + It is an error if *themename* already exists. If *parent* is specified, + the new theme will inherit styles, elements and layouts from the parent + theme. If *settings* are present they are expected to have the same + syntax used for :meth:`theme_settings`. + + + .. method:: theme_settings(themename, settings) + + Temporarily sets the current theme to *themename*, apply specified + *settings* and then restore the previous theme. + + Each key in *settings* is a style and each value may contain the keys + 'configure', 'map', 'layout' and 'element create' and they are expected + to have the same format as specified by the methods + :meth:`Style.configure`, :meth:`Style.map`, :meth:`Style.layout` and + :meth:`Style.element_create` respectively. + + As an example, let's change the Combobox for the default theme a bit:: + + from tkinter import ttk + import tkinter + + root = tkinter.Tk() + + style = ttk.Style() + style.theme_settings("default", { + "TCombobox": { + "configure": {"padding": 5}, + "map": { + "background": [("active", "green2"), + ("!disabled", "green4")], + "fieldbackground": [("!disabled", "green3")], + "foreground": [("focus", "OliveDrab1"), + ("!disabled", "OliveDrab2")] + } + } + }) + + combo = ttk.Combobox().pack() + + root.mainloop() + + + .. method:: theme_names() + + Returns a list of all known themes. + + + .. method:: theme_use(themename=None) + + If *themename* is not given, returns the theme in use. Otherwise, sets + the current theme to *themename*, refreshes all widgets and emits a + <> event. + + +Layouts +^^^^^^^ + +A layout can be just ``None``, if it takes no options, or a dict of +options specifying how to arrange the element. The layout mechanism +uses a simplified version of the pack geometry manager: given an +initial cavity, each element is allocated a parcel. Valid +options/values are: + + * side: whichside + Specifies which side of the cavity to place the element; one of + top, right, bottom or left. If omitted, the element occupies the + entire cavity. + + * sticky: nswe + Specifies where the element is placed inside its allocated parcel. + + * unit: 0 or 1 + If set to 1, causes the element and all of its descendants to be treated as + a single element for the purposes of :meth:`Widget.identify` et al. It's + used for things like scrollbar thumbs with grips. + + * children: [sublayout... ] + Specifies a list of elements to place inside the element. Each + element is a tuple (or other sequence type) where the first item is + the layout name, and the other is a `Layout`_. + +.. _Layout: `Layouts`_ diff --git a/cpython_2/environment/repo/Doc/library/token-list.inc b/cpython_2/environment/repo/Doc/library/token-list.inc new file mode 100644 index 0000000000000000000000000000000000000000..877d39a432ed7008917f94d23968ccc8a76d0bab --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/token-list.inc @@ -0,0 +1,218 @@ +.. Auto-generated by Tools/scripts/generate_token.py +.. data:: ENDMARKER + +.. data:: NAME + +.. data:: NUMBER + +.. data:: STRING + +.. data:: NEWLINE + +.. data:: INDENT + +.. data:: DEDENT + +.. data:: LPAR + + Token value for ``"("``. + +.. data:: RPAR + + Token value for ``")"``. + +.. data:: LSQB + + Token value for ``"["``. + +.. data:: RSQB + + Token value for ``"]"``. + +.. data:: COLON + + Token value for ``":"``. + +.. data:: COMMA + + Token value for ``","``. + +.. data:: SEMI + + Token value for ``";"``. + +.. data:: PLUS + + Token value for ``"+"``. + +.. data:: MINUS + + Token value for ``"-"``. + +.. data:: STAR + + Token value for ``"*"``. + +.. data:: SLASH + + Token value for ``"/"``. + +.. data:: VBAR + + Token value for ``"|"``. + +.. data:: AMPER + + Token value for ``"&"``. + +.. data:: LESS + + Token value for ``"<"``. + +.. data:: GREATER + + Token value for ``">"``. + +.. data:: EQUAL + + Token value for ``"="``. + +.. data:: DOT + + Token value for ``"."``. + +.. data:: PERCENT + + Token value for ``"%"``. + +.. data:: LBRACE + + Token value for ``"{"``. + +.. data:: RBRACE + + Token value for ``"}"``. + +.. data:: EQEQUAL + + Token value for ``"=="``. + +.. data:: NOTEQUAL + + Token value for ``"!="``. + +.. data:: LESSEQUAL + + Token value for ``"<="``. + +.. data:: GREATEREQUAL + + Token value for ``">="``. + +.. data:: TILDE + + Token value for ``"~"``. + +.. data:: CIRCUMFLEX + + Token value for ``"^"``. + +.. data:: LEFTSHIFT + + Token value for ``"<<"``. + +.. data:: RIGHTSHIFT + + Token value for ``">>"``. + +.. data:: DOUBLESTAR + + Token value for ``"**"``. + +.. data:: PLUSEQUAL + + Token value for ``"+="``. + +.. data:: MINEQUAL + + Token value for ``"-="``. + +.. data:: STAREQUAL + + Token value for ``"*="``. + +.. data:: SLASHEQUAL + + Token value for ``"/="``. + +.. data:: PERCENTEQUAL + + Token value for ``"%="``. + +.. data:: AMPEREQUAL + + Token value for ``"&="``. + +.. data:: VBAREQUAL + + Token value for ``"|="``. + +.. data:: CIRCUMFLEXEQUAL + + Token value for ``"^="``. + +.. data:: LEFTSHIFTEQUAL + + Token value for ``"<<="``. + +.. data:: RIGHTSHIFTEQUAL + + Token value for ``">>="``. + +.. data:: DOUBLESTAREQUAL + + Token value for ``"**="``. + +.. data:: DOUBLESLASH + + Token value for ``"//"``. + +.. data:: DOUBLESLASHEQUAL + + Token value for ``"//="``. + +.. data:: AT + + Token value for ``"@"``. + +.. data:: ATEQUAL + + Token value for ``"@="``. + +.. data:: RARROW + + Token value for ``"->"``. + +.. data:: ELLIPSIS + + Token value for ``"..."``. + +.. data:: COLONEQUAL + + Token value for ``":="``. + +.. data:: OP + +.. data:: AWAIT + +.. data:: ASYNC + +.. data:: TYPE_IGNORE + +.. data:: TYPE_COMMENT + +.. data:: ERRORTOKEN + +.. data:: N_TOKENS + +.. data:: NT_OFFSET diff --git a/cpython_2/environment/repo/Doc/library/token.rst b/cpython_2/environment/repo/Doc/library/token.rst new file mode 100644 index 0000000000000000000000000000000000000000..dab8f0fa9b64fcf348dba3044e8bfef498c63b2a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/token.rst @@ -0,0 +1,93 @@ +:mod:`token` --- Constants used with Python parse trees +======================================================= + +.. module:: token + :synopsis: Constants representing terminal nodes of the parse tree. + +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/token.py` + +-------------- + +This module provides constants which represent the numeric values of leaf nodes +of the parse tree (terminal tokens). Refer to the file :file:`Grammar/Grammar` +in the Python distribution for the definitions of the names in the context of +the language grammar. The specific numeric values which the names map to may +change between Python versions. + +The module also provides a mapping from numeric codes to names and some +functions. The functions mirror definitions in the Python C header files. + + +.. data:: tok_name + + Dictionary mapping the numeric values of the constants defined in this module + back to name strings, allowing more human-readable representation of parse trees + to be generated. + + +.. function:: ISTERMINAL(x) + + Return ``True`` for terminal token values. + + +.. function:: ISNONTERMINAL(x) + + Return ``True`` for non-terminal token values. + + +.. function:: ISEOF(x) + + Return ``True`` if *x* is the marker indicating the end of input. + + +The token constants are: + +.. include:: token-list.inc + +The following token type values aren't used by the C tokenizer but are needed for +the :mod:`tokenize` module. + +.. data:: COMMENT + + Token value used to indicate a comment. + + +.. data:: NL + + Token value used to indicate a non-terminating newline. The + :data:`NEWLINE` token 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.tokenize` will + always be an ``ENCODING`` token. + + +.. data:: TYPE_COMMENT + + Token value indicating that a type comment was recognized. Such + tokens are only produced when :func:`ast.parse()` is invoked with + ``type_comments=True``. + + +.. versionchanged:: 3.5 + Added :data:`AWAIT` and :data:`ASYNC` tokens. + +.. versionchanged:: 3.7 + Added :data:`COMMENT`, :data:`NL` and :data:`ENCODING` tokens. + +.. versionchanged:: 3.7 + Removed :data:`AWAIT` and :data:`ASYNC` tokens. "async" and "await" are + now tokenized as :data:`NAME` tokens. + +.. versionchanged:: 3.8 + Added :data:`TYPE_COMMENT`, :data:`TYPE_IGNORE`, :data:`COLONEQUAL`. + Added :data:`AWAIT` and :data:`ASYNC` tokens back (they're needed + to support parsing older Python versions for :func:`ast.parse` with + ``feature_version`` set to 6 or lower). diff --git a/cpython_2/environment/repo/Doc/library/tokenize.rst b/cpython_2/environment/repo/Doc/library/tokenize.rst new file mode 100644 index 0000000000000000000000000000000000000000..11f569df2e7cde774f2d14f120796e373208824f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tokenize.rst @@ -0,0 +1,299 @@ +:mod:`tokenize` --- Tokenizer for Python source +=============================================== + +.. module:: tokenize + :synopsis: Lexical scanner for Python source code. + +.. moduleauthor:: Ka Ping Yee +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/tokenize.py` + +-------------- + +The :mod:`tokenize` module provides a lexical scanner for Python source code, +implemented in Python. The scanner in this module returns comments as tokens +as well, making it useful for implementing "pretty-printers", including +colorizers for on-screen displays. + +To simplify token stream handling, all :ref:`operator ` and +:ref:`delimiter ` tokens and :data:`Ellipsis` are returned using +the generic :data:`~token.OP` token type. The exact +type can be determined by checking the ``exact_type`` property on the +:term:`named tuple` returned from :func:`tokenize.tokenize`. + +Tokenizing Input +---------------- + +The primary entry point is a :term:`generator`: + +.. function:: tokenize(readline) + + The :func:`.tokenize` generator requires one argument, *readline*, which + must be a callable object which provides the same interface as the + :meth:`io.IOBase.readline` method of 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 line on which the token was found. The line passed (the last tuple item) + is the *physical* line. The 5 tuple is returned as a :term:`named tuple` + with the field names: + ``type string start end line``. + + The returned :term:`named tuple` has an additional property named + ``exact_type`` that contains the exact operator type for + :data:`~token.OP` tokens. For all other token types ``exact_type`` + equals the named tuple ``type`` field. + + .. versionchanged:: 3.1 + Added support for named tuples. + + .. versionchanged:: 3.3 + Added support for ``exact_type``. + + :func:`.tokenize` determines the source encoding of the file by looking for a + UTF-8 BOM or encoding cookie, according to :pep:`263`. + +.. function:: generate_tokens(readline) + + Tokenize a source reading unicode strings instead of bytes. + + Like :func:`.tokenize`, the *readline* argument is a callable returning + a single line of input. However, :func:`generate_tokens` expects *readline* + to return a str object rather than bytes. + + The result is an iterator yielding named tuples, exactly like + :func:`.tokenize`. It does not yield an :data:`~token.ENCODING` token. + +All constants from the :mod:`token` module are also exported from +:mod:`tokenize`. + +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. + 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 + positions) may change. + + It returns bytes, encoded using the :data:`~token.ENCODING` token, which + is the first token sequence output by :func:`.tokenize`. If there is no + encoding token in the input, it returns a str instead. + + +:func:`.tokenize` needs to detect the encoding of source files it tokenizes. The +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 argument, + 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:`263`. If both a BOM and a cookie are present, + but disagree, a :exc:`SyntaxError` will be raised. Note that if the BOM is found, + ``'utf-8-sig'`` will be returned as an encoding. + + If no encoding is specified, then the default of ``'utf-8'`` will be + returned. + + Use :func:`.open` to open Python source files: it uses + :func:`detect_encoding` to detect the file encoding. + + +.. function:: open(filename) + + Open a file in read only mode using the encoding detected by + :func:`detect_encoding`. + + .. versionadded:: 3.2 + +.. exception:: TokenError + + Raised when either a docstring or expression that may be split over several + lines is not completed anywhere in the file, for example:: + + """Beginning of + docstring + + or:: + + [1, + 2, + 3 + +Note that unclosed single-quoted strings do not cause an error to be +raised. They are tokenized as :data:`~token.ERRORTOKEN`, followed by the +tokenization of their contents. + + +.. _tokenize-cli: + +Command-Line Usage +------------------ + +.. versionadded:: 3.3 + +The :mod:`tokenize` module can be executed as a script from the command line. +It is as simple as: + +.. code-block:: sh + + python -m tokenize [-e] [filename.py] + +The following options are accepted: + +.. program:: tokenize + +.. cmdoption:: -h, --help + + show this help message and exit + +.. cmdoption:: -e, --exact + + display token names using the exact type + +If :file:`filename.py` is specified its contents are tokenized to stdout. +Otherwise, tokenization is performed on stdin. + +Examples +------------------ + +Example of a script rewriter that transforms float literals into Decimal +objects:: + + from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP + from io import BytesIO + + 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 + """ + result = [] + g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string + for toknum, tokval, _, _, _ in g: + if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens + result.extend([ + (NAME, 'Decimal'), + (OP, '('), + (STRING, repr(tokval)), + (OP, ')') + ]) + else: + result.append((toknum, tokval)) + return untokenize(result).decode('utf-8') + +Example of tokenizing from the command line. The script:: + + def say_hello(): + print("Hello, World!") + + say_hello() + +will be tokenized to the following output where the first column is the range +of the line/column coordinates where the token is found, the second column is +the name of the token, and the final column is the value of the token (if any) + +.. code-block:: shell-session + + $ python -m tokenize hello.py + 0,0-0,0: ENCODING 'utf-8' + 1,0-1,3: NAME 'def' + 1,4-1,13: NAME 'say_hello' + 1,13-1,14: OP '(' + 1,14-1,15: OP ')' + 1,15-1,16: OP ':' + 1,16-1,17: NEWLINE '\n' + 2,0-2,4: INDENT ' ' + 2,4-2,9: NAME 'print' + 2,9-2,10: OP '(' + 2,10-2,25: STRING '"Hello, World!"' + 2,25-2,26: OP ')' + 2,26-2,27: NEWLINE '\n' + 3,0-3,1: NL '\n' + 4,0-4,0: DEDENT '' + 4,0-4,9: NAME 'say_hello' + 4,9-4,10: OP '(' + 4,10-4,11: OP ')' + 4,11-4,12: NEWLINE '\n' + 5,0-5,0: ENDMARKER '' + +The exact token type names can be displayed using the :option:`-e` option: + +.. code-block:: shell-session + + $ python -m tokenize -e hello.py + 0,0-0,0: ENCODING 'utf-8' + 1,0-1,3: NAME 'def' + 1,4-1,13: NAME 'say_hello' + 1,13-1,14: LPAR '(' + 1,14-1,15: RPAR ')' + 1,15-1,16: COLON ':' + 1,16-1,17: NEWLINE '\n' + 2,0-2,4: INDENT ' ' + 2,4-2,9: NAME 'print' + 2,9-2,10: LPAR '(' + 2,10-2,25: STRING '"Hello, World!"' + 2,25-2,26: RPAR ')' + 2,26-2,27: NEWLINE '\n' + 3,0-3,1: NL '\n' + 4,0-4,0: DEDENT '' + 4,0-4,9: NAME 'say_hello' + 4,9-4,10: LPAR '(' + 4,10-4,11: RPAR ')' + 4,11-4,12: NEWLINE '\n' + 5,0-5,0: ENDMARKER '' + +Example of tokenizing a file programmatically, reading unicode +strings instead of bytes with :func:`generate_tokens`:: + + import tokenize + + with tokenize.open('hello.py') as f: + tokens = tokenize.generate_tokens(f.readline) + for token in tokens: + print(token) + +Or reading bytes directly with :func:`.tokenize`:: + + import tokenize + + with open('hello.py', 'rb') as f: + tokens = tokenize.tokenize(f.readline) + for token in tokens: + print(token) diff --git a/cpython_2/environment/repo/Doc/library/trace.rst b/cpython_2/environment/repo/Doc/library/trace.rst new file mode 100644 index 0000000000000000000000000000000000000000..c2732d900bc138a0616c4b49cd6d4a8b9fc50691 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/trace.rst @@ -0,0 +1,216 @@ +:mod:`trace` --- Trace or track Python statement execution +========================================================== + +.. module:: trace + :synopsis: Trace or track Python statement execution. + +**Source code:** :source:`Lib/trace.py` + +-------------- + +The :mod:`trace` module allows you to trace program execution, generate +annotated statement coverage listings, print caller/callee relationships and +list functions executed during a program run. It can be used in another program +or from the command line. + +.. seealso:: + + `Coverage.py `_ + A popular third-party coverage tool that provides HTML + output along with advanced features such as branch coverage. + +.. _trace-cli: + +Command-Line Usage +------------------ + +The :mod:`trace` module can be invoked from the command line. It can be as +simple as :: + + python -m trace --count -C . somefile.py ... + +The above will execute :file:`somefile.py` and generate annotated listings of +all Python modules imported during the execution into the current directory. + +.. program:: trace + +.. cmdoption:: --help + + Display usage and exit. + +.. cmdoption:: --version + + Display the version of the module and exit. + +.. versionadded:: 3.8 + Added ``--module`` option that allows to run an executable module. + +Main options +^^^^^^^^^^^^ + +At least one of the following options must be specified when invoking +:mod:`trace`. The :option:`--listfuncs <-l>` option is mutually exclusive with +the :option:`--trace <-t>` and :option:`--count <-c>` options. When +:option:`--listfuncs <-l>` is provided, neither :option:`--count <-c>` nor +:option:`--trace <-t>` are accepted, and vice versa. + +.. program:: trace + +.. cmdoption:: -c, --count + + Produce a set of annotated listing files upon program completion that shows + how many times each statement was executed. See also + :option:`--coverdir <-C>`, :option:`--file <-f>` and + :option:`--no-report <-R>` below. + +.. cmdoption:: -t, --trace + + Display lines as they are executed. + +.. cmdoption:: -l, --listfuncs + + Display the functions executed by running the program. + +.. cmdoption:: -r, --report + + Produce an annotated list from an earlier program run that used the + :option:`--count <-c>` and :option:`--file <-f>` option. This does not + execute any code. + +.. cmdoption:: -T, --trackcalls + + Display the calling relationships exposed by running the program. + +Modifiers +^^^^^^^^^ + +.. program:: trace + +.. cmdoption:: -f, --file= + + Name of a file to accumulate counts over several tracing runs. Should be + used with the :option:`--count <-c>` option. + +.. cmdoption:: -C, --coverdir= + + Directory where the report files go. The coverage report for + ``package.module`` is written to file :file:`{dir}/{package}/{module}.cover`. + +.. cmdoption:: -m, --missing + + When generating annotated listings, mark lines which were not executed with + ``>>>>>>``. + +.. cmdoption:: -s, --summary + + When using :option:`--count <-c>` or :option:`--report <-r>`, write a brief + summary to stdout for each file processed. + +.. cmdoption:: -R, --no-report + + Do not generate annotated listings. This is useful if you intend to make + several runs with :option:`--count <-c>`, and then produce a single set of + annotated listings at the end. + +.. cmdoption:: -g, --timing + + Prefix each line with the time since the program started. Only used while + tracing. + +Filters +^^^^^^^ + +These options may be repeated multiple times. + +.. program:: trace + +.. cmdoption:: --ignore-module= + + Ignore each of the given module names and its submodules (if it is a + package). The argument can be a list of names separated by a comma. + +.. cmdoption:: --ignore-dir= + + Ignore all modules and packages in the named directory and subdirectories. + The argument can be a list of directories separated by :data:`os.pathsep`. + +.. _trace-api: + +Programmatic Interface +---------------------- + +.. class:: Trace(count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(),\ + ignoredirs=(), infile=None, outfile=None, timing=False) + + Create an object to trace execution of a single statement or expression. All + parameters are optional. *count* enables counting of line numbers. *trace* + enables line execution tracing. *countfuncs* enables listing of the + functions called during the run. *countcallers* enables call relationship + tracking. *ignoremods* is a list of modules or packages to ignore. + *ignoredirs* is a list of directories whose modules or packages should be + ignored. *infile* is the name of the file from which to read stored count + information. *outfile* is the name of the file in which to write updated + count information. *timing* enables a timestamp relative to when tracing was + started to be displayed. + + .. method:: run(cmd) + + Execute the command and gather statistics from the execution with + the current tracing parameters. *cmd* must be a string or code object, + suitable for passing into :func:`exec`. + + .. method:: runctx(cmd, globals=None, locals=None) + + Execute the command and gather statistics from the execution with the + current tracing parameters, in the defined global and local + environments. If not defined, *globals* and *locals* default to empty + dictionaries. + + .. method:: runfunc(func, /, *args, **kwds) + + Call *func* with the given arguments under control of the :class:`Trace` + object with the current tracing parameters. + + .. method:: results() + + Return a :class:`CoverageResults` object that contains the cumulative + results of all previous calls to ``run``, ``runctx`` and ``runfunc`` + for the given :class:`Trace` instance. Does not reset the accumulated + trace results. + +.. class:: CoverageResults + + A container for coverage results, created by :meth:`Trace.results`. Should + not be created directly by the user. + + .. method:: update(other) + + Merge in data from another :class:`CoverageResults` object. + + .. method:: write_results(show_missing=True, summary=False, coverdir=None) + + Write coverage results. Set *show_missing* to show lines that had no + hits. Set *summary* to include in the output the coverage summary per + module. *coverdir* specifies the directory into which the coverage + result files will be output. If ``None``, the results for each source + file are placed in its directory. + +A simple example demonstrating the use of the programmatic interface:: + + import sys + import trace + + # create a Trace object, telling it what to ignore, and whether to + # do tracing or line-counting or both. + tracer = trace.Trace( + ignoredirs=[sys.prefix, sys.exec_prefix], + trace=0, + count=1) + + # run the new command using the given tracer + tracer.run('main()') + + # make a report, placing output in the current directory + r = tracer.results() + r.write_results(show_missing=True, coverdir=".") + diff --git a/cpython_2/environment/repo/Doc/library/traceback.rst b/cpython_2/environment/repo/Doc/library/traceback.rst new file mode 100644 index 0000000000000000000000000000000000000000..462a6a5566e201d346e1e4b395344976ad6057f8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/traceback.rst @@ -0,0 +1,486 @@ +:mod:`traceback` --- Print or retrieve a stack traceback +======================================================== + +.. module:: traceback + :synopsis: Print or retrieve a stack traceback. + +**Source code:** :source:`Lib/traceback.py` + +-------------- + +This module provides a standard interface to extract, format and print stack +traces of Python programs. It exactly mimics the behavior of the Python +interpreter when it prints a stack trace. This is useful when you want to print +stack traces under program control, such as in a "wrapper" around the +interpreter. + +.. index:: object: traceback + +The module uses traceback objects --- this is the object type that is stored in +the :data:`sys.last_traceback` variable and returned as the third item from +:func:`sys.exc_info`. + +The module defines the following functions: + + +.. function:: print_tb(tb, limit=None, file=None) + + Print up to *limit* stack trace entries from traceback object *tb* (starting + from the caller's frame) if *limit* is positive. Otherwise, print the last + ``abs(limit)`` entries. If *limit* is omitted or ``None``, all entries are + printed. If *file* is omitted or ``None``, the output goes to + ``sys.stderr``; otherwise it should be an open file or file-like object to + receive the output. + + .. versionchanged:: 3.5 + Added negative *limit* support. + + +.. function:: print_exception(etype, value, tb, limit=None, file=None, chain=True) + + Print exception information and stack trace entries from traceback object + *tb* to *file*. This differs from :func:`print_tb` in the following + ways: + + * if *tb* is not ``None``, it prints a header ``Traceback (most recent + call last):`` + + * it prints the exception *etype* and *value* after the stack trace + + .. index:: single: ^ (caret); marker + + * if *type(value)* is :exc:`SyntaxError` and *value* has the appropriate + format, it prints the line where the syntax error occurred with a caret + indicating the approximate position of the error. + + The optional *limit* argument has the same meaning as for :func:`print_tb`. + If *chain* is true (the default), then chained exceptions (the + :attr:`__cause__` or :attr:`__context__` attributes of the exception) will be + printed as well, like the interpreter itself does when printing an unhandled + exception. + + .. versionchanged:: 3.5 + The *etype* argument is ignored and inferred from the type of *value*. + + +.. function:: print_exc(limit=None, file=None, chain=True) + + This is a shorthand for ``print_exception(*sys.exc_info(), limit, file, + chain)``. + + +.. function:: print_last(limit=None, file=None, chain=True) + + This is a shorthand for ``print_exception(sys.last_type, sys.last_value, + sys.last_traceback, limit, file, chain)``. In general it will work only + after an exception has reached an interactive prompt (see + :data:`sys.last_type`). + + +.. function:: print_stack(f=None, limit=None, file=None) + + Print up to *limit* stack trace entries (starting from the invocation + point) if *limit* is positive. Otherwise, print the last ``abs(limit)`` + entries. If *limit* is omitted or ``None``, all entries are printed. + The optional *f* argument can be used to specify an alternate stack frame + to start. The optional *file* argument has the same meaning as for + :func:`print_tb`. + + .. versionchanged:: 3.5 + Added negative *limit* support. + + +.. function:: extract_tb(tb, limit=None) + + Return a :class:`StackSummary` object representing a list of "pre-processed" + stack trace entries extracted from the traceback object *tb*. It is useful + for alternate formatting of stack traces. The optional *limit* argument has + the same meaning as for :func:`print_tb`. A "pre-processed" stack trace + entry is a :class:`FrameSummary` object containing attributes + :attr:`~FrameSummary.filename`, :attr:`~FrameSummary.lineno`, + :attr:`~FrameSummary.name`, and :attr:`~FrameSummary.line` representing the + information that is usually printed for a stack trace. The + :attr:`~FrameSummary.line` is a string with leading and trailing + whitespace stripped; if the source is not available it is ``None``. + + +.. function:: extract_stack(f=None, limit=None) + + Extract the raw traceback from the current stack frame. The return value has + the same format as for :func:`extract_tb`. The optional *f* and *limit* + arguments have the same meaning as for :func:`print_stack`. + + +.. function:: format_list(extracted_list) + + Given a list of tuples or :class:`FrameSummary` objects as returned by + :func:`extract_tb` or :func:`extract_stack`, return a list of strings ready + for printing. Each string in the resulting list corresponds to the item with + the same index in the argument list. Each string ends in a newline; the + strings may contain internal newlines as well, for those items whose source + text line is not ``None``. + + +.. function:: format_exception_only(etype, value) + + Format the exception part of a traceback. The arguments are the exception + type and value such as given by ``sys.last_type`` and ``sys.last_value``. + The return value is a list of strings, each ending in a newline. Normally, + the list contains a single string; however, for :exc:`SyntaxError` + exceptions, it contains several lines that (when printed) display detailed + information about where the syntax error occurred. The message indicating + which exception occurred is the always last string in the list. + + +.. function:: format_exception(etype, value, tb, limit=None, chain=True) + + Format a stack trace and the exception information. The arguments have the + same meaning as the corresponding arguments to :func:`print_exception`. The + return value is a list of strings, each ending in a newline and some + containing internal newlines. When these lines are concatenated and printed, + exactly the same text is printed as does :func:`print_exception`. + + .. versionchanged:: 3.5 + The *etype* argument is ignored and inferred from the type of *value*. + + +.. function:: format_exc(limit=None, chain=True) + + This is like ``print_exc(limit)`` but returns a string instead of printing to + a file. + + +.. function:: format_tb(tb, limit=None) + + A shorthand for ``format_list(extract_tb(tb, limit))``. + + +.. function:: format_stack(f=None, limit=None) + + A shorthand for ``format_list(extract_stack(f, limit))``. + +.. function:: clear_frames(tb) + + Clears the local variables of all the stack frames in a traceback *tb* + by calling the :meth:`clear` method of each frame object. + + .. versionadded:: 3.4 + +.. function:: walk_stack(f) + + Walk a stack following ``f.f_back`` from the given frame, yielding the frame + and line number for each frame. If *f* is ``None``, the current stack is + used. This helper is used with :meth:`StackSummary.extract`. + + .. versionadded:: 3.5 + +.. function:: walk_tb(tb) + + Walk a traceback following ``tb_next`` yielding the frame and line number + for each frame. This helper is used with :meth:`StackSummary.extract`. + + .. versionadded:: 3.5 + +The module also defines the following classes: + +:class:`TracebackException` Objects +----------------------------------- + +.. versionadded:: 3.5 + +:class:`TracebackException` objects are created from actual exceptions to +capture data for later printing in a lightweight fashion. + +.. class:: TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False) + + Capture an exception for later rendering. *limit*, *lookup_lines* and + *capture_locals* are as for the :class:`StackSummary` class. + + Note that when locals are captured, they are also shown in the traceback. + + .. attribute:: __cause__ + + A :class:`TracebackException` of the original ``__cause__``. + + .. attribute:: __context__ + + A :class:`TracebackException` of the original ``__context__``. + + .. attribute:: __suppress_context__ + + The ``__suppress_context__`` value from the original exception. + + .. attribute:: stack + + A :class:`StackSummary` representing the traceback. + + .. attribute:: exc_type + + The class of the original traceback. + + .. attribute:: filename + + For syntax errors - the file name where the error occurred. + + .. attribute:: lineno + + For syntax errors - the line number where the error occurred. + + .. attribute:: text + + For syntax errors - the text where the error occurred. + + .. attribute:: offset + + For syntax errors - the offset into the text where the error occurred. + + .. attribute:: msg + + For syntax errors - the compiler error message. + + .. classmethod:: from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False) + + Capture an exception for later rendering. *limit*, *lookup_lines* and + *capture_locals* are as for the :class:`StackSummary` class. + + Note that when locals are captured, they are also shown in the traceback. + + .. method:: format(*, chain=True) + + Format the exception. + + If *chain* is not ``True``, ``__cause__`` and ``__context__`` will not + be formatted. + + The return value is a generator of strings, each ending in a newline and + some containing internal newlines. :func:`~traceback.print_exception` + is a wrapper around this method which just prints the lines to a file. + + The message indicating which exception occurred is always the last + string in the output. + + .. method:: format_exception_only() + + Format the exception part of the traceback. + + The return value is a generator of strings, each ending in a newline. + + Normally, the generator emits a single string; however, for + :exc:`SyntaxError` exceptions, it emits several lines that (when + printed) display detailed information about where the syntax + error occurred. + + The message indicating which exception occurred is always the last + string in the output. + + +:class:`StackSummary` Objects +----------------------------- + +.. versionadded:: 3.5 + +:class:`StackSummary` objects represent a call stack ready for formatting. + +.. class:: StackSummary + + .. classmethod:: extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False) + + Construct a :class:`StackSummary` object from a frame generator (such as + is returned by :func:`~traceback.walk_stack` or + :func:`~traceback.walk_tb`). + + If *limit* is supplied, only this many frames are taken from *frame_gen*. + If *lookup_lines* is ``False``, the returned :class:`FrameSummary` + objects will not have read their lines in yet, making the cost of + creating the :class:`StackSummary` cheaper (which may be valuable if it + may not actually get formatted). If *capture_locals* is ``True`` the + local variables in each :class:`FrameSummary` are captured as object + representations. + + .. classmethod:: from_list(a_list) + + Construct a :class:`StackSummary` object from a supplied list of + :class:`FrameSummary` objects or old-style list of tuples. Each tuple + should be a 4-tuple with filename, lineno, name, line as the elements. + + .. method:: format() + + Returns a list of strings ready for printing. Each string in the + resulting list corresponds to a single frame from the stack. + Each string ends in a newline; the strings may contain internal + newlines as well, for those items with source text lines. + + For long sequences of the same frame and line, the first few + repetitions are shown, followed by a summary line stating the exact + number of further repetitions. + + .. versionchanged:: 3.6 + Long sequences of repeated frames are now abbreviated. + + +:class:`FrameSummary` Objects +----------------------------- + +.. versionadded:: 3.5 + +:class:`FrameSummary` objects represent a single frame in a traceback. + +.. class:: FrameSummary(filename, lineno, name, lookup_line=True, locals=None, line=None) + + Represent a single frame in the traceback or stack that is being formatted + or printed. It may optionally have a stringified version of the frames + locals included in it. If *lookup_line* is ``False``, the source code is not + looked up until the :class:`FrameSummary` has the :attr:`~FrameSummary.line` + attribute accessed (which also happens when casting it to a tuple). + :attr:`~FrameSummary.line` may be directly provided, and will prevent line + lookups happening at all. *locals* is an optional local variable + dictionary, and if supplied the variable representations are stored in the + summary for later display. + +.. _traceback-example: + +Traceback Examples +------------------ + +This simple example implements a basic read-eval-print loop, similar to (but +less useful than) the standard Python interactive interpreter loop. For a more +complete implementation of the interpreter loop, refer to the :mod:`code` +module. :: + + import sys, traceback + + def run_user_code(envdir): + source = input(">>> ") + try: + exec(source, envdir) + except Exception: + print("Exception in user code:") + print("-"*60) + traceback.print_exc(file=sys.stdout) + print("-"*60) + + envdir = {} + while True: + run_user_code(envdir) + + +The following example demonstrates the different ways to print and format the +exception and traceback: + +.. testcode:: + + import sys, traceback + + def lumberjack(): + bright_side_of_death() + + def bright_side_of_death(): + return tuple()[0] + + try: + lumberjack() + except IndexError: + exc_type, exc_value, exc_traceback = sys.exc_info() + print("*** print_tb:") + traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) + print("*** print_exception:") + # exc_type below is ignored on 3.5 and later + traceback.print_exception(exc_type, exc_value, exc_traceback, + limit=2, file=sys.stdout) + print("*** print_exc:") + traceback.print_exc(limit=2, file=sys.stdout) + print("*** format_exc, first and last line:") + formatted_lines = traceback.format_exc().splitlines() + print(formatted_lines[0]) + print(formatted_lines[-1]) + print("*** format_exception:") + # exc_type below is ignored on 3.5 and later + print(repr(traceback.format_exception(exc_type, exc_value, + exc_traceback))) + print("*** extract_tb:") + print(repr(traceback.extract_tb(exc_traceback))) + print("*** format_tb:") + print(repr(traceback.format_tb(exc_traceback))) + print("*** tb_lineno:", exc_traceback.tb_lineno) + +The output for the example would look similar to this: + +.. testoutput:: + :options: +NORMALIZE_WHITESPACE + + *** print_tb: + File "", line 10, in + lumberjack() + *** print_exception: + Traceback (most recent call last): + File "", line 10, in + lumberjack() + File "", line 4, in lumberjack + bright_side_of_death() + IndexError: tuple index out of range + *** print_exc: + Traceback (most recent call last): + File "", line 10, in + lumberjack() + File "", line 4, in lumberjack + bright_side_of_death() + IndexError: tuple index out of range + *** format_exc, first and last line: + Traceback (most recent call last): + IndexError: tuple index out of range + *** format_exception: + ['Traceback (most recent call last):\n', + ' File "", line 10, in \n lumberjack()\n', + ' File "", line 4, in lumberjack\n bright_side_of_death()\n', + ' File "", line 7, in bright_side_of_death\n return tuple()[0]\n', + 'IndexError: tuple index out of range\n'] + *** extract_tb: + [, line 10 in >, + , line 4 in lumberjack>, + , line 7 in bright_side_of_death>] + *** format_tb: + [' File "", line 10, in \n lumberjack()\n', + ' File "", line 4, in lumberjack\n bright_side_of_death()\n', + ' File "", line 7, in bright_side_of_death\n return tuple()[0]\n'] + *** tb_lineno: 10 + + +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 "", line 10, in + another_function() + File "", line 3, in another_function + lumberstack() + File "", line 6, in lumberstack + traceback.print_stack() + [('', 10, '', 'another_function()'), + ('', 3, 'another_function', 'lumberstack()'), + ('', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')] + [' File "", line 10, in \n another_function()\n', + ' File "", line 3, in another_function\n lumberstack()\n', + ' File "", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n'] + + +This last example demonstrates the final few formatting functions: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> import traceback + >>> traceback.format_list([('spam.py', 3, '', 'spam.eggs()'), + ... ('eggs.py', 42, 'eggs', 'return "bacon"')]) + [' File "spam.py", line 3, in \n spam.eggs()\n', + ' File "eggs.py", line 42, in eggs\n return "bacon"\n'] + >>> an_error = IndexError('tuple index out of range') + >>> traceback.format_exception_only(type(an_error), an_error) + ['IndexError: tuple index out of range\n'] diff --git a/cpython_2/environment/repo/Doc/library/tracemalloc.rst b/cpython_2/environment/repo/Doc/library/tracemalloc.rst new file mode 100644 index 0000000000000000000000000000000000000000..3eee9457fb29a8dae35ef1e84a8b12780849cb93 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tracemalloc.rst @@ -0,0 +1,706 @@ +:mod:`tracemalloc` --- Trace memory allocations +=============================================== + +.. module:: tracemalloc + :synopsis: Trace memory allocations. + +.. versionadded:: 3.4 + +**Source code:** :source:`Lib/tracemalloc.py` + +-------------- + +The tracemalloc module is a debug tool to trace memory blocks allocated by +Python. It provides the following information: + +* Traceback where an object was allocated +* Statistics on allocated memory blocks per filename and per line number: + total size, number and average size of allocated memory blocks +* Compute the differences between two snapshots to detect memory leaks + +To trace most memory blocks allocated by Python, the module should be started +as early as possible by setting the :envvar:`PYTHONTRACEMALLOC` environment +variable to ``1``, or by using :option:`-X` ``tracemalloc`` command line +option. The :func:`tracemalloc.start` function can be called at runtime to +start tracing Python memory allocations. + +By default, a trace of an allocated memory block only stores the most recent +frame (1 frame). To store 25 frames at startup: set the +:envvar:`PYTHONTRACEMALLOC` environment variable to ``25``, or use the +:option:`-X` ``tracemalloc=25`` command line option. + + +Examples +-------- + +Display the top 10 +^^^^^^^^^^^^^^^^^^ + +Display the 10 files allocating the most memory:: + + import tracemalloc + + tracemalloc.start() + + # ... run your application ... + + snapshot = tracemalloc.take_snapshot() + top_stats = snapshot.statistics('lineno') + + print("[ Top 10 ]") + for stat in top_stats[:10]: + print(stat) + + +Example of output of the Python test suite:: + + [ Top 10 ] + :716: size=4855 KiB, count=39328, average=126 B + :284: size=521 KiB, count=3199, average=167 B + /usr/lib/python3.4/collections/__init__.py:368: size=244 KiB, count=2315, average=108 B + /usr/lib/python3.4/unittest/case.py:381: size=185 KiB, count=779, average=243 B + /usr/lib/python3.4/unittest/case.py:402: size=154 KiB, count=378, average=416 B + /usr/lib/python3.4/abc.py:133: size=88.7 KiB, count=347, average=262 B + :1446: size=70.4 KiB, count=911, average=79 B + :1454: size=52.0 KiB, count=25, average=2131 B + :5: size=49.7 KiB, count=148, average=344 B + /usr/lib/python3.4/sysconfig.py:411: size=48.0 KiB, count=1, average=48.0 KiB + +We can see that Python loaded ``4855 KiB`` data (bytecode and constants) from +modules and that the :mod:`collections` module allocated ``244 KiB`` to build +:class:`~collections.namedtuple` types. + +See :meth:`Snapshot.statistics` for more options. + + +Compute differences +^^^^^^^^^^^^^^^^^^^ + +Take two snapshots and display the differences:: + + import tracemalloc + tracemalloc.start() + # ... start your application ... + + snapshot1 = tracemalloc.take_snapshot() + # ... call the function leaking memory ... + snapshot2 = tracemalloc.take_snapshot() + + top_stats = snapshot2.compare_to(snapshot1, 'lineno') + + print("[ Top 10 differences ]") + for stat in top_stats[:10]: + print(stat) + +Example of output before/after running some tests of the Python test suite:: + + [ Top 10 differences ] + :716: size=8173 KiB (+4428 KiB), count=71332 (+39369), average=117 B + /usr/lib/python3.4/linecache.py:127: size=940 KiB (+940 KiB), count=8106 (+8106), average=119 B + /usr/lib/python3.4/unittest/case.py:571: size=298 KiB (+298 KiB), count=589 (+589), average=519 B + :284: size=1005 KiB (+166 KiB), count=7423 (+1526), average=139 B + /usr/lib/python3.4/mimetypes.py:217: size=112 KiB (+112 KiB), count=1334 (+1334), average=86 B + /usr/lib/python3.4/http/server.py:848: size=96.0 KiB (+96.0 KiB), count=1 (+1), average=96.0 KiB + /usr/lib/python3.4/inspect.py:1465: size=83.5 KiB (+83.5 KiB), count=109 (+109), average=784 B + /usr/lib/python3.4/unittest/mock.py:491: size=77.7 KiB (+77.7 KiB), count=143 (+143), average=557 B + /usr/lib/python3.4/urllib/parse.py:476: size=71.8 KiB (+71.8 KiB), count=969 (+969), average=76 B + /usr/lib/python3.4/contextlib.py:38: size=67.2 KiB (+67.2 KiB), count=126 (+126), average=546 B + +We can see that Python has loaded ``8173 KiB`` of module data (bytecode and +constants), and that this is ``4428 KiB`` more than had been loaded before the +tests, when the previous snapshot was taken. Similarly, the :mod:`linecache` +module has cached ``940 KiB`` of Python source code to format tracebacks, all +of it since the previous snapshot. + +If the system has little free memory, snapshots can be written on disk using +the :meth:`Snapshot.dump` method to analyze the snapshot offline. Then use the +:meth:`Snapshot.load` method reload the snapshot. + + +Get the traceback of a memory block +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Code to display the traceback of the biggest memory block:: + + import tracemalloc + + # Store 25 frames + tracemalloc.start(25) + + # ... run your application ... + + snapshot = tracemalloc.take_snapshot() + top_stats = snapshot.statistics('traceback') + + # pick the biggest memory block + stat = top_stats[0] + print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024)) + for line in stat.traceback.format(): + print(line) + +Example of output of the Python test suite (traceback limited to 25 frames):: + + 903 memory blocks: 870.1 KiB + File "", line 716 + File "", line 1036 + File "", line 934 + File "", line 1068 + File "", line 619 + File "", line 1581 + File "", line 1614 + File "/usr/lib/python3.4/doctest.py", line 101 + import pdb + File "", line 284 + File "", line 938 + File "", line 1068 + File "", line 619 + File "", line 1581 + File "", line 1614 + File "/usr/lib/python3.4/test/support/__init__.py", line 1728 + import doctest + File "/usr/lib/python3.4/test/test_pickletools.py", line 21 + support.run_doctest(pickletools) + File "/usr/lib/python3.4/test/regrtest.py", line 1276 + test_runner() + File "/usr/lib/python3.4/test/regrtest.py", line 976 + display_failure=not verbose) + File "/usr/lib/python3.4/test/regrtest.py", line 761 + match_tests=ns.match_tests) + File "/usr/lib/python3.4/test/regrtest.py", line 1563 + main() + File "/usr/lib/python3.4/test/__main__.py", line 3 + regrtest.main_in_temp_cwd() + File "/usr/lib/python3.4/runpy.py", line 73 + exec(code, run_globals) + File "/usr/lib/python3.4/runpy.py", line 160 + "__main__", fname, loader, pkg_name) + +We can see that the most memory was allocated in the :mod:`importlib` module to +load data (bytecode and constants) from modules: ``870.1 KiB``. The traceback is +where the :mod:`importlib` loaded data most recently: on the ``import pdb`` +line of the :mod:`doctest` module. The traceback may change if a new module is +loaded. + + +Pretty top +^^^^^^^^^^ + +Code to display the 10 lines allocating the most memory with a pretty output, +ignoring ```` and ```` files:: + + import linecache + import os + import tracemalloc + + def display_top(snapshot, key_type='lineno', limit=10): + snapshot = snapshot.filter_traces(( + tracemalloc.Filter(False, ""), + tracemalloc.Filter(False, ""), + )) + top_stats = snapshot.statistics(key_type) + + print("Top %s lines" % limit) + for index, stat in enumerate(top_stats[:limit], 1): + frame = stat.traceback[0] + print("#%s: %s:%s: %.1f KiB" + % (index, frame.filename, frame.lineno, stat.size / 1024)) + line = linecache.getline(frame.filename, frame.lineno).strip() + if line: + print(' %s' % line) + + other = top_stats[limit:] + if other: + size = sum(stat.size for stat in other) + print("%s other: %.1f KiB" % (len(other), size / 1024)) + total = sum(stat.size for stat in top_stats) + print("Total allocated size: %.1f KiB" % (total / 1024)) + + tracemalloc.start() + + # ... run your application ... + + snapshot = tracemalloc.take_snapshot() + display_top(snapshot) + +Example of output of the Python test suite:: + + Top 10 lines + #1: Lib/base64.py:414: 419.8 KiB + _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars] + #2: Lib/base64.py:306: 419.8 KiB + _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars] + #3: collections/__init__.py:368: 293.6 KiB + exec(class_definition, namespace) + #4: Lib/abc.py:133: 115.2 KiB + cls = super().__new__(mcls, name, bases, namespace) + #5: unittest/case.py:574: 103.1 KiB + testMethod() + #6: Lib/linecache.py:127: 95.4 KiB + lines = fp.readlines() + #7: urllib/parse.py:476: 71.8 KiB + for a in _hexdig for b in _hexdig} + #8: :5: 62.0 KiB + #9: Lib/_weakrefset.py:37: 60.0 KiB + self.data = set() + #10: Lib/base64.py:142: 59.8 KiB + _b32tab2 = [a + b for a in _b32tab for b in _b32tab] + 6220 other: 3602.8 KiB + Total allocated size: 5303.1 KiB + +See :meth:`Snapshot.statistics` for more options. + + +API +--- + +Functions +^^^^^^^^^ + +.. function:: clear_traces() + + Clear traces of memory blocks allocated by Python. + + See also :func:`stop`. + + +.. function:: get_object_traceback(obj) + + Get the traceback where the Python object *obj* was allocated. + Return a :class:`Traceback` instance, or ``None`` if the :mod:`tracemalloc` + module is not tracing memory allocations or did not trace the allocation of + the object. + + See also :func:`gc.get_referrers` and :func:`sys.getsizeof` functions. + + +.. function:: get_traceback_limit() + + Get the maximum number of frames stored in the traceback of a trace. + + The :mod:`tracemalloc` module must be tracing memory allocations to + get the limit, otherwise an exception is raised. + + The limit is set by the :func:`start` function. + + +.. function:: get_traced_memory() + + Get the current size and peak size of memory blocks traced by the + :mod:`tracemalloc` module as a tuple: ``(current: int, peak: int)``. + + +.. function:: get_tracemalloc_memory() + + Get the memory usage in bytes of the :mod:`tracemalloc` module used to store + traces of memory blocks. + Return an :class:`int`. + + +.. function:: is_tracing() + + ``True`` if the :mod:`tracemalloc` module is tracing Python memory + allocations, ``False`` otherwise. + + See also :func:`start` and :func:`stop` functions. + + +.. function:: start(nframe: int=1) + + Start tracing Python memory allocations: install hooks on Python memory + allocators. Collected tracebacks of traces will be limited to *nframe* + frames. By default, a trace of a memory block only stores the most recent + frame: the limit is ``1``. *nframe* must be greater or equal to ``1``. + + You can still read the original number of total frames that composed the + traceback by looking at the :attr:`Traceback.total_nframe` attribute. + + Storing more than ``1`` frame is only useful to compute statistics grouped + by ``'traceback'`` or to compute cumulative statistics: see the + :meth:`Snapshot.compare_to` and :meth:`Snapshot.statistics` methods. + + Storing more frames increases the memory and CPU overhead of the + :mod:`tracemalloc` module. Use the :func:`get_tracemalloc_memory` function + to measure how much memory is used by the :mod:`tracemalloc` module. + + The :envvar:`PYTHONTRACEMALLOC` environment variable + (``PYTHONTRACEMALLOC=NFRAME``) and the :option:`-X` ``tracemalloc=NFRAME`` + command line option can be used to start tracing at startup. + + See also :func:`stop`, :func:`is_tracing` and :func:`get_traceback_limit` + functions. + + +.. function:: stop() + + Stop tracing Python memory allocations: uninstall hooks on Python memory + allocators. Also clears all previously collected traces of memory blocks + allocated by Python. + + Call :func:`take_snapshot` function to take a snapshot of traces before + clearing them. + + See also :func:`start`, :func:`is_tracing` and :func:`clear_traces` + functions. + + +.. function:: take_snapshot() + + Take a snapshot of traces of memory blocks allocated by Python. Return a new + :class:`Snapshot` instance. + + The snapshot does not include memory blocks allocated before the + :mod:`tracemalloc` module started to trace memory allocations. + + Tracebacks of traces are limited to :func:`get_traceback_limit` frames. Use + the *nframe* parameter of the :func:`start` function to store more frames. + + The :mod:`tracemalloc` module must be tracing memory allocations to take a + snapshot, see the :func:`start` function. + + See also the :func:`get_object_traceback` function. + + +DomainFilter +^^^^^^^^^^^^ + +.. class:: DomainFilter(inclusive: bool, domain: int) + + Filter traces of memory blocks by their address space (domain). + + .. versionadded:: 3.6 + + .. attribute:: inclusive + + If *inclusive* is ``True`` (include), match memory blocks allocated + in the address space :attr:`domain`. + + If *inclusive* is ``False`` (exclude), match memory blocks not allocated + in the address space :attr:`domain`. + + .. attribute:: domain + + Address space of a memory block (``int``). Read-only property. + + +Filter +^^^^^^ + +.. class:: Filter(inclusive: bool, filename_pattern: str, lineno: int=None, all_frames: bool=False, domain: int=None) + + Filter on traces of memory blocks. + + See the :func:`fnmatch.fnmatch` function for the syntax of + *filename_pattern*. The ``'.pyc'`` file extension is + replaced with ``'.py'``. + + Examples: + + * ``Filter(True, subprocess.__file__)`` only includes traces of the + :mod:`subprocess` module + * ``Filter(False, tracemalloc.__file__)`` excludes traces of the + :mod:`tracemalloc` module + * ``Filter(False, "")`` excludes empty tracebacks + + + .. versionchanged:: 3.5 + The ``'.pyo'`` file extension is no longer replaced with ``'.py'``. + + .. versionchanged:: 3.6 + Added the :attr:`domain` attribute. + + + .. attribute:: domain + + Address space of a memory block (``int`` or ``None``). + + tracemalloc uses the domain ``0`` to trace memory allocations made by + Python. C extensions can use other domains to trace other resources. + + .. attribute:: inclusive + + If *inclusive* is ``True`` (include), only match memory blocks allocated + in a file with a name matching :attr:`filename_pattern` at line number + :attr:`lineno`. + + If *inclusive* is ``False`` (exclude), ignore memory blocks allocated in + a file with a name matching :attr:`filename_pattern` at line number + :attr:`lineno`. + + .. attribute:: lineno + + Line number (``int``) of the filter. If *lineno* is ``None``, the filter + matches any line number. + + .. attribute:: filename_pattern + + Filename pattern of the filter (``str``). Read-only property. + + .. attribute:: all_frames + + If *all_frames* is ``True``, all frames of the traceback are checked. If + *all_frames* is ``False``, only the most recent frame is checked. + + This attribute has no effect if the traceback limit is ``1``. See the + :func:`get_traceback_limit` function and :attr:`Snapshot.traceback_limit` + attribute. + + +Frame +^^^^^ + +.. class:: Frame + + Frame of a traceback. + + The :class:`Traceback` class is a sequence of :class:`Frame` instances. + + .. attribute:: filename + + Filename (``str``). + + .. attribute:: lineno + + Line number (``int``). + + +Snapshot +^^^^^^^^ + +.. class:: Snapshot + + Snapshot of traces of memory blocks allocated by Python. + + The :func:`take_snapshot` function creates a snapshot instance. + + .. method:: compare_to(old_snapshot: Snapshot, key_type: str, cumulative: bool=False) + + Compute the differences with an old snapshot. Get statistics as a sorted + list of :class:`StatisticDiff` instances grouped by *key_type*. + + See the :meth:`Snapshot.statistics` method for *key_type* and *cumulative* + parameters. + + The result is sorted from the biggest to the smallest by: absolute value + of :attr:`StatisticDiff.size_diff`, :attr:`StatisticDiff.size`, absolute + value of :attr:`StatisticDiff.count_diff`, :attr:`Statistic.count` and + then by :attr:`StatisticDiff.traceback`. + + + .. method:: dump(filename) + + Write the snapshot into a file. + + Use :meth:`load` to reload the snapshot. + + + .. method:: filter_traces(filters) + + Create a new :class:`Snapshot` instance with a filtered :attr:`traces` + sequence, *filters* is a list of :class:`DomainFilter` and + :class:`Filter` instances. If *filters* is an empty list, return a new + :class:`Snapshot` instance with a copy of the traces. + + All inclusive filters are applied at once, a trace is ignored if no + inclusive filters match it. A trace is ignored if at least one exclusive + filter matches it. + + .. versionchanged:: 3.6 + :class:`DomainFilter` instances are now also accepted in *filters*. + + + .. classmethod:: load(filename) + + Load a snapshot from a file. + + See also :meth:`dump`. + + + .. method:: statistics(key_type: str, cumulative: bool=False) + + Get statistics as a sorted list of :class:`Statistic` instances grouped + by *key_type*: + + ===================== ======================== + key_type description + ===================== ======================== + ``'filename'`` filename + ``'lineno'`` filename and line number + ``'traceback'`` traceback + ===================== ======================== + + If *cumulative* is ``True``, cumulate size and count of memory blocks of + all frames of the traceback of a trace, not only the most recent frame. + The cumulative mode can only be used with *key_type* equals to + ``'filename'`` and ``'lineno'``. + + The result is sorted from the biggest to the smallest by: + :attr:`Statistic.size`, :attr:`Statistic.count` and then by + :attr:`Statistic.traceback`. + + + .. attribute:: traceback_limit + + Maximum number of frames stored in the traceback of :attr:`traces`: + result of the :func:`get_traceback_limit` when the snapshot was taken. + + .. attribute:: traces + + Traces of all memory blocks allocated by Python: sequence of + :class:`Trace` instances. + + The sequence has an undefined order. Use the :meth:`Snapshot.statistics` + method to get a sorted list of statistics. + + +Statistic +^^^^^^^^^ + +.. class:: Statistic + + Statistic on memory allocations. + + :func:`Snapshot.statistics` returns a list of :class:`Statistic` instances. + + See also the :class:`StatisticDiff` class. + + .. attribute:: count + + Number of memory blocks (``int``). + + .. attribute:: size + + Total size of memory blocks in bytes (``int``). + + .. attribute:: traceback + + Traceback where the memory block was allocated, :class:`Traceback` + instance. + + +StatisticDiff +^^^^^^^^^^^^^ + +.. class:: StatisticDiff + + Statistic difference on memory allocations between an old and a new + :class:`Snapshot` instance. + + :func:`Snapshot.compare_to` returns a list of :class:`StatisticDiff` + instances. See also the :class:`Statistic` class. + + .. attribute:: count + + Number of memory blocks in the new snapshot (``int``): ``0`` if + the memory blocks have been released in the new snapshot. + + .. attribute:: count_diff + + Difference of number of memory blocks between the old and the new + snapshots (``int``): ``0`` if the memory blocks have been allocated in + the new snapshot. + + .. attribute:: size + + Total size of memory blocks in bytes in the new snapshot (``int``): + ``0`` if the memory blocks have been released in the new snapshot. + + .. attribute:: size_diff + + Difference of total size of memory blocks in bytes between the old and + the new snapshots (``int``): ``0`` if the memory blocks have been + allocated in the new snapshot. + + .. attribute:: traceback + + Traceback where the memory blocks were allocated, :class:`Traceback` + instance. + + +Trace +^^^^^ + +.. class:: Trace + + Trace of a memory block. + + The :attr:`Snapshot.traces` attribute is a sequence of :class:`Trace` + instances. + + .. versionchanged:: 3.6 + Added the :attr:`domain` attribute. + + .. attribute:: domain + + Address space of a memory block (``int``). Read-only property. + + tracemalloc uses the domain ``0`` to trace memory allocations made by + Python. C extensions can use other domains to trace other resources. + + .. attribute:: size + + Size of the memory block in bytes (``int``). + + .. attribute:: traceback + + Traceback where the memory block was allocated, :class:`Traceback` + instance. + + +Traceback +^^^^^^^^^ + +.. class:: Traceback + + Sequence of :class:`Frame` instances sorted from the oldest frame to the + most recent frame. + + A traceback contains at least ``1`` frame. If the ``tracemalloc`` module + failed to get a frame, the filename ``""`` at line number ``0`` is + used. + + When a snapshot is taken, tracebacks of traces are limited to + :func:`get_traceback_limit` frames. See the :func:`take_snapshot` function. + The original number of frames of the traceback is stored in the + :attr:`Traceback.total_nframe` attribute. That allows to know if a traceback + has been truncated by the traceback limit. + + The :attr:`Trace.traceback` attribute is an instance of :class:`Traceback` + instance. + + .. versionchanged:: 3.7 + Frames are now sorted from the oldest to the most recent, instead of most recent to oldest. + + .. attribute:: total_nframe + + Total number of frames that composed the traceback before truncation. + This attribute can be set to ``None`` if the information is not + available. + + .. versionchanged:: 3.9 + The :attr:`Traceback.total_nframe` attribute was added. + + .. method:: format(limit=None, most_recent_first=False) + + Format the traceback as a list of lines with newlines. Use the + :mod:`linecache` module to retrieve lines from the source code. + If *limit* is set, format the *limit* most recent frames if *limit* + is positive. Otherwise, format the ``abs(limit)`` oldest frames. + If *most_recent_first* is ``True``, the order of the formatted frames + is reversed, returning the most recent frame first instead of last. + + Similar to the :func:`traceback.format_tb` function, except that + :meth:`.format` does not include newlines. + + Example:: + + print("Traceback (most recent call first):") + for line in traceback: + print(line) + + Output:: + + Traceback (most recent call first): + File "test.py", line 9 + obj = Object() + File "test.py", line 12 + tb = tracemalloc.get_object_traceback(f()) diff --git a/cpython_2/environment/repo/Doc/library/tty.rst b/cpython_2/environment/repo/Doc/library/tty.rst new file mode 100644 index 0000000000000000000000000000000000000000..b30bc3c7ac42e9d960925ef06dad3682a429124e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/tty.rst @@ -0,0 +1,41 @@ +:mod:`tty` --- Terminal control functions +========================================= + +.. module:: tty + :platform: Unix + :synopsis: Utility functions that perform common terminal control operations. + +.. moduleauthor:: Steen Lumholt +.. sectionauthor:: Moshe Zadka + +**Source code:** :source:`Lib/tty.py` + +-------------- + +The :mod:`tty` module defines functions for putting the tty into cbreak and raw +modes. + +Because it requires the :mod:`termios` module, it will work only on Unix. + +The :mod:`tty` module defines the following functions: + + +.. function:: setraw(fd, when=termios.TCSAFLUSH) + + Change the mode of the file descriptor *fd* to raw. If *when* is omitted, it + defaults to :const:`termios.TCSAFLUSH`, and is passed to + :func:`termios.tcsetattr`. + + +.. function:: setcbreak(fd, when=termios.TCSAFLUSH) + + Change the mode of file descriptor *fd* to cbreak. If *when* is omitted, it + defaults to :const:`termios.TCSAFLUSH`, and is passed to + :func:`termios.tcsetattr`. + + +.. seealso:: + + Module :mod:`termios` + Low-level terminal control interface. + diff --git a/cpython_2/environment/repo/Doc/library/tulip_coro.dia b/cpython_2/environment/repo/Doc/library/tulip_coro.dia new file mode 100644 index 0000000000000000000000000000000000000000..70a33e3c00cf6e45d425e4c56e9a17561fa8c4ce Binary files /dev/null and b/cpython_2/environment/repo/Doc/library/tulip_coro.dia differ diff --git a/cpython_2/environment/repo/Doc/library/tulip_coro.png b/cpython_2/environment/repo/Doc/library/tulip_coro.png new file mode 100644 index 0000000000000000000000000000000000000000..edb26c29faf0d1f97fc68ddf5cc1b7cd23c0e7f7 Binary files /dev/null and b/cpython_2/environment/repo/Doc/library/tulip_coro.png differ diff --git a/cpython_2/environment/repo/Doc/library/turtle-star.pdf b/cpython_2/environment/repo/Doc/library/turtle-star.pdf new file mode 100644 index 0000000000000000000000000000000000000000..e354073dd42f5e6ea48118d7e2363247b190528b Binary files /dev/null and b/cpython_2/environment/repo/Doc/library/turtle-star.pdf differ diff --git a/cpython_2/environment/repo/Doc/library/turtle-star.png b/cpython_2/environment/repo/Doc/library/turtle-star.png new file mode 100644 index 0000000000000000000000000000000000000000..f7d3271c8c8b2a2856e0cc7388bab5908808a786 Binary files /dev/null and b/cpython_2/environment/repo/Doc/library/turtle-star.png differ diff --git a/cpython_2/environment/repo/Doc/library/turtle-star.ps b/cpython_2/environment/repo/Doc/library/turtle-star.ps new file mode 100644 index 0000000000000000000000000000000000000000..46362cb9f7c8f52ae8ee352d81db4bd42bfe26a8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/turtle-star.ps @@ -0,0 +1,447 @@ +%!PS-Adobe-3.0 EPSF-3.0 +%%Creator: Tk Canvas Widget +%%For: Alexander Belopolsky +%%Title: Window .4315905424 +%%CreationDate: Tue Nov 9 12:54:06 2010 +%%XBoundingBox: -172 -52 785 845 +%%BoundingBox: 290 290 520 520 +%%Pages: 1 +%%DocumentData: Clean7Bit +%%Orientation: Portrait +%%EndComments + +%%BeginProlog +/CurrentEncoding [ +/space/space/space/space/space/space/space/space +/space/space/space/space/space/space/space/space +/space/space/space/space/space/space/space/space +/space/space/space/space/space/space/space/space +/space/exclam/quotedbl/numbersign/dollar/percent/ampersand/quotesingle +/parenleft/parenright/asterisk/plus/comma/hyphen/period/slash +/zero/one/two/three/four/five/six/seven +/eight/nine/colon/semicolon/less/equal/greater/question +/at/A/B/C/D/E/F/G +/H/I/J/K/L/M/N/O +/P/Q/R/S/T/U/V/W +/X/Y/Z/bracketleft/backslash/bracketright/asciicircum/underscore +/grave/a/b/c/d/e/f/g +/h/i/j/k/l/m/n/o +/p/q/r/s/t/u/v/w +/x/y/z/braceleft/bar/braceright/asciitilde/space +/space/space/space/space/space/space/space/space +/space/space/space/space/space/space/space/space +/space/space/space/space/space/space/space/space +/space/space/space/space/space/space/space/space +/space/exclamdown/cent/sterling/currency/yen/brokenbar/section +/dieresis/copyright/ordfeminine/guillemotleft/logicalnot/hyphen/registered/macron +/degree/plusminus/twosuperior/threesuperior/acute/mu/paragraph/periodcentered +/cedilla/onesuperior/ordmasculine/guillemotright/onequarter/onehalf/threequarters/questiondown +/Agrave/Aacute/Acircumflex/Atilde/Adieresis/Aring/AE/Ccedilla +/Egrave/Eacute/Ecircumflex/Edieresis/Igrave/Iacute/Icircumflex/Idieresis +/Eth/Ntilde/Ograve/Oacute/Ocircumflex/Otilde/Odieresis/multiply +/Oslash/Ugrave/Uacute/Ucircumflex/Udieresis/Yacute/Thorn/germandbls +/agrave/aacute/acircumflex/atilde/adieresis/aring/ae/ccedilla +/egrave/eacute/ecircumflex/edieresis/igrave/iacute/icircumflex/idieresis +/eth/ntilde/ograve/oacute/ocircumflex/otilde/odieresis/divide +/oslash/ugrave/uacute/ucircumflex/udieresis/yacute/thorn/ydieresis +] def + +50 dict begin +% This is a standard prolog for Postscript generated by Tk's canvas +% widget. +% RCS: @(#) $Id$ + +% The definitions below just define all of the variables used in +% any of the procedures here. This is needed for obscure reasons +% explained on p. 716 of the Postscript manual (Section H.2.7, +% "Initializing Variables," in the section on Encapsulated Postscript). + +/baseline 0 def +/stipimage 0 def +/height 0 def +/justify 0 def +/lineLength 0 def +/spacing 0 def +/stipple 0 def +/strings 0 def +/xoffset 0 def +/yoffset 0 def +/tmpstip null def + + +/cstringshow { + { + dup type /stringtype eq + { show } { glyphshow } + ifelse + } + forall +} bind def + + + +/cstringwidth { + 0 exch 0 exch + { + dup type /stringtype eq + { stringwidth } { + currentfont /Encoding get exch 1 exch put (\001) stringwidth + } + ifelse + exch 3 1 roll add 3 1 roll add exch + } + forall +} bind def + +% font ISOEncode font +% This procedure changes the encoding of a font from the default +% Postscript encoding to current system encoding. It's typically invoked just +% before invoking "setfont". The body of this procedure comes from +% Section 5.6.1 of the Postscript book. + +/ISOEncode { + dup length dict begin + {1 index /FID ne {def} {pop pop} ifelse} forall + /Encoding CurrentEncoding def + currentdict + end + + % I'm not sure why it's necessary to use "definefont" on this new + % font, but it seems to be important; just use the name "Temporary" + % for the font. + + /Temporary exch definefont +} bind def + +% StrokeClip +% +% This procedure converts the current path into a clip area under +% the assumption of stroking. It's a bit tricky because some Postscript +% interpreters get errors during strokepath for dashed lines. If +% this happens then turn off dashes and try again. + +/StrokeClip { + {strokepath} stopped { + (This Postscript printer gets limitcheck overflows when) = + (stippling dashed lines; lines will be printed solid instead.) = + [] 0 setdash strokepath} if + clip +} bind def + +% desiredSize EvenPixels closestSize +% +% The procedure below is used for stippling. Given the optimal size +% of a dot in a stipple pattern in the current user coordinate system, +% compute the closest size that is an exact multiple of the device's +% pixel size. This allows stipple patterns to be displayed without +% aliasing effects. + +/EvenPixels { + % Compute exact number of device pixels per stipple dot. + dup 0 matrix currentmatrix dtransform + dup mul exch dup mul add sqrt + + % Round to an integer, make sure the number is at least 1, and compute + % user coord distance corresponding to this. + dup round dup 1 lt {pop 1} if + exch div mul +} bind def + +% width height string StippleFill -- +% +% Given a path already set up and a clipping region generated from +% it, this procedure will fill the clipping region with a stipple +% pattern. "String" contains a proper image description of the +% stipple pattern and "width" and "height" give its dimensions. Each +% stipple dot is assumed to be about one unit across in the current +% user coordinate system. This procedure trashes the graphics state. + +/StippleFill { + % The following code is needed to work around a NeWSprint bug. + + /tmpstip 1 index def + + % Change the scaling so that one user unit in user coordinates + % corresponds to the size of one stipple dot. + 1 EvenPixels dup scale + + % Compute the bounding box occupied by the path (which is now + % the clipping region), and round the lower coordinates down + % to the nearest starting point for the stipple pattern. Be + % careful about negative numbers, since the rounding works + % differently on them. + + pathbbox + 4 2 roll + 5 index div dup 0 lt {1 sub} if cvi 5 index mul 4 1 roll + 6 index div dup 0 lt {1 sub} if cvi 6 index mul 3 2 roll + + % Stack now: width height string y1 y2 x1 x2 + % Below is a doubly-nested for loop to iterate across this area + % in units of the stipple pattern size, going up columns then + % across rows, blasting out a stipple-pattern-sized rectangle at + % each position + + 6 index exch { + 2 index 5 index 3 index { + % Stack now: width height string y1 y2 x y + + gsave + 1 index exch translate + 5 index 5 index true matrix tmpstip imagemask + grestore + } for + pop + } for + pop pop pop pop pop +} bind def + +% -- AdjustColor -- +% Given a color value already set for output by the caller, adjusts +% that value to a grayscale or mono value if requested by the CL +% variable. + +/AdjustColor { + CL 2 lt { + currentgray + CL 0 eq { + .5 lt {0} {1} ifelse + } if + setgray + } if +} bind def + +% x y strings spacing xoffset yoffset justify stipple DrawText -- +% This procedure does all of the real work of drawing text. The +% color and font must already have been set by the caller, and the +% following arguments must be on the stack: +% +% x, y - Coordinates at which to draw text. +% strings - An array of strings, one for each line of the text item, +% in order from top to bottom. +% spacing - Spacing between lines. +% xoffset - Horizontal offset for text bbox relative to x and y: 0 for +% nw/w/sw anchor, -0.5 for n/center/s, and -1.0 for ne/e/se. +% yoffset - Vertical offset for text bbox relative to x and y: 0 for +% nw/n/ne anchor, +0.5 for w/center/e, and +1.0 for sw/s/se. +% justify - 0 for left justification, 0.5 for center, 1 for right justify. +% stipple - Boolean value indicating whether or not text is to be +% drawn in stippled fashion. If text is stippled, +% procedure StippleText must have been defined to call +% StippleFill in the right way. +% +% Also, when this procedure is invoked, the color and font must already +% have been set for the text. + +/DrawText { + /stipple exch def + /justify exch def + /yoffset exch def + /xoffset exch def + /spacing exch def + /strings exch def + + % First scan through all of the text to find the widest line. + + /lineLength 0 def + strings { + cstringwidth pop + dup lineLength gt {/lineLength exch def} {pop} ifelse + newpath + } forall + + % Compute the baseline offset and the actual font height. + + 0 0 moveto (TXygqPZ) false charpath + pathbbox dup /baseline exch def + exch pop exch sub /height exch def pop + newpath + + % Translate coordinates first so that the origin is at the upper-left + % corner of the text's bounding box. Remember that x and y for + % positioning are still on the stack. + + translate + lineLength xoffset mul + strings length 1 sub spacing mul height add yoffset mul translate + + % Now use the baseline and justification information to translate so + % that the origin is at the baseline and positioning point for the + % first line of text. + + justify lineLength mul baseline neg translate + + % Iterate over each of the lines to output it. For each line, + % compute its width again so it can be properly justified, then + % display it. + + strings { + dup cstringwidth pop + justify neg mul 0 moveto + stipple { + + + % The text is stippled, so turn it into a path and print + % by calling StippledText, which in turn calls StippleFill. + % Unfortunately, many Postscript interpreters will get + % overflow errors if we try to do the whole string at + % once, so do it a character at a time. + + gsave + /char (X) def + { + dup type /stringtype eq { + % This segment is a string. + { + char 0 3 -1 roll put + currentpoint + gsave + char true charpath clip StippleText + grestore + char stringwidth translate + moveto + } forall + } { + % This segment is glyph name + % Temporary override + currentfont /Encoding get exch 1 exch put + currentpoint + gsave (\001) true charpath clip StippleText + grestore + (\001) stringwidth translate + moveto + } ifelse + } forall + grestore + } {cstringshow} ifelse + 0 spacing neg translate + } forall +} bind def + +%%EndProlog +%%BeginSetup +/CL 2 def +%%EndSetup + +%%Page: 1 1 +save +306.0 396.0 translate +0.9995 0.9995 scale +4 -449 translate +-483 898 moveto 475 898 lineto 475 0 lineto -483 0 lineto closepath clip newpath +gsave +grestore +gsave +0 445 moveto +200 445 lineto +3.03844939755837 479.729635533386 lineto +190.97697355474 411.325606868252 lineto +17.7718927978523 511.325606868252 lineto +170.980781421648 382.768084930944 lineto +42.42325948434 535.97697355474 lineto +142.42325948434 362.771892797852 lineto +74.0192308192062 550.710416955034 lineto +108.748866352592 353.748866352592 lineto +108.748866352592 553.748866352592 lineto +74.0192308192064 356.787315750151 lineto +142.42325948434 544.725839907333 lineto +42.4232594843401 371.520759150445 lineto +170.980781421648 524.72964777424 lineto +17.7718927978524 396.172125836932 lineto +190.97697355474 496.172125836933 lineto +3.03844939755834 427.768097171799 lineto +200 462.497732705185 lineto +-1.13686837721616e-13 462.497732705185 lineto +196.961550602442 427.768097171799 lineto +9.02302644525972 496.172125836932 lineto +182.228107202148 396.172125836933 lineto +29.0192185783518 524.72964777424 lineto +157.57674051566 371.520759150445 lineto +57.5767405156596 544.725839907332 lineto +125.980769180794 356.787315750151 lineto +91.2511336474073 553.748866352592 lineto +91.2511336474079 353.748866352592 lineto +125.980769180793 550.710416955034 lineto +57.5767405156601 362.771892797852 lineto +157.57674051566 535.97697355474 lineto +29.0192185783522 382.768084930944 lineto +182.228107202148 511.325606868253 lineto +9.02302644525994 411.325606868252 lineto +196.961550602442 479.729635533386 lineto +-1.70530256582424e-13 445 lineto +0 445 lineto +1.000 1.000 0.000 setrgbcolor AdjustColor +eofill +grestore +gsave +0 445 moveto +200 445 lineto +3.03844939755837 479.729635533386 lineto +190.97697355474 411.325606868252 lineto +17.7718927978523 511.325606868252 lineto +170.980781421648 382.768084930944 lineto +42.42325948434 535.97697355474 lineto +142.42325948434 362.771892797852 lineto +74.0192308192062 550.710416955034 lineto +108.748866352592 353.748866352592 lineto +108.748866352592 553.748866352592 lineto +74.0192308192064 356.787315750151 lineto +142.42325948434 544.725839907333 lineto +42.4232594843401 371.520759150445 lineto +170.980781421648 524.72964777424 lineto +17.7718927978524 396.172125836932 lineto +190.97697355474 496.172125836933 lineto +3.03844939755834 427.768097171799 lineto +200 462.497732705185 lineto +-1.13686837721616e-13 462.497732705185 lineto +196.961550602442 427.768097171799 lineto +9.02302644525972 496.172125836932 lineto +182.228107202148 396.172125836933 lineto +29.0192185783518 524.72964777424 lineto +157.57674051566 371.520759150445 lineto +57.5767405156596 544.725839907332 lineto +125.980769180794 356.787315750151 lineto +91.2511336474073 553.748866352592 lineto +91.2511336474079 353.748866352592 lineto +125.980769180793 550.710416955034 lineto +57.5767405156601 362.771892797852 lineto +157.57674051566 535.97697355474 lineto +29.0192185783522 382.768084930944 lineto +182.228107202148 511.325606868253 lineto +9.02302644525994 411.325606868252 lineto +196.961550602442 479.729635533386 lineto +-1.70530256582424e-13 445 lineto +1 setlinecap +1 setlinejoin +1 setlinewidth +[] 0 setdash +1.000 0.000 0.000 setrgbcolor AdjustColor +stroke +grestore +gsave +grestore +gsave +-1.70530256582424e-13 445 moveto +-9.00000000000019 450 lineto +-7.00000000000017 445 lineto +-9.00000000000015 440 lineto +-1.70530256582424e-13 445 lineto +1.000 1.000 0.000 setrgbcolor AdjustColor +eofill +-1.70530256582424e-13 445 moveto +-9.00000000000019 450 lineto +-7.00000000000017 445 lineto +-9.00000000000015 440 lineto +-1.70530256582424e-13 445 lineto +1 setlinejoin 1 setlinecap +1 setlinewidth +[] 0 setdash +1.000 0.000 0.000 setrgbcolor AdjustColor +stroke +grestore +restore showpage + +%%Trailer +end +%%EOF + diff --git a/cpython_2/environment/repo/Doc/library/turtle.rst b/cpython_2/environment/repo/Doc/library/turtle.rst new file mode 100644 index 0000000000000000000000000000000000000000..fed85045435b1b614f84d3a917f2102876fef133 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/turtle.rst @@ -0,0 +1,2527 @@ +================================= +:mod:`turtle` --- Turtle graphics +================================= + +.. module:: turtle + :synopsis: An educational framework for simple graphics applications + +.. sectionauthor:: Gregor Lingl + +**Source code:** :source:`Lib/turtle.py` + +.. testsetup:: default + + from turtle import * + turtle = Turtle() + +-------------- + +Introduction +============ + +Turtle graphics is a popular way for introducing programming to kids. It was +part of the original Logo programming language developed by Wally Feurzeig, +Seymour Papert and Cynthia Solomon in 1967. + +Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it the +command ``turtle.forward(15)``, and it moves (on-screen!) 15 pixels in the +direction it is facing, drawing a line as it moves. Give it the command +``turtle.right(25)``, and it rotates in-place 25 degrees clockwise. + +.. sidebar:: Turtle star + + Turtle can draw intricate shapes using programs that repeat simple + moves. + + .. image:: turtle-star.* + :align: center + + .. literalinclude:: ../includes/turtle-star.py + +By combining together these and similar commands, intricate shapes and pictures +can easily be drawn. + +The :mod:`turtle` module is an extended reimplementation of the same-named +module from the Python standard distribution up to version Python 2.5. + +It tries to keep the merits of the old turtle module and to be (nearly) 100% +compatible with it. This means in the first place to enable the learning +programmer to use all the commands, classes and methods interactively when using +the module from within IDLE run with the ``-n`` switch. + +The turtle module provides turtle graphics primitives, in both object-oriented +and procedure-oriented ways. Because it uses :mod:`tkinter` for the underlying +graphics, it needs a version of Python installed with Tk support. + +The object-oriented interface uses essentially two+two classes: + +1. The :class:`TurtleScreen` class defines graphics windows as a playground for + the drawing turtles. Its constructor needs a :class:`tkinter.Canvas` or a + :class:`ScrolledCanvas` as argument. It should be used when :mod:`turtle` is + used as part of some application. + + The function :func:`Screen` returns a singleton object of a + :class:`TurtleScreen` subclass. This function should be used when + :mod:`turtle` is used as a standalone tool for doing graphics. + As a singleton object, inheriting from its class is not possible. + + All methods of TurtleScreen/Screen also exist as functions, i.e. as part of + the procedure-oriented interface. + +2. :class:`RawTurtle` (alias: :class:`RawPen`) defines Turtle objects which draw + on a :class:`TurtleScreen`. Its constructor needs a Canvas, ScrolledCanvas + or TurtleScreen as argument, so the RawTurtle objects know where to draw. + + Derived from RawTurtle is the subclass :class:`Turtle` (alias: :class:`Pen`), + which draws on "the" :class:`Screen` instance which is automatically + created, if not already present. + + All methods of RawTurtle/Turtle also exist as functions, i.e. part of the + procedure-oriented interface. + +The procedural interface provides functions which are derived from the methods +of the classes :class:`Screen` and :class:`Turtle`. They have the same names as +the corresponding methods. A screen object is automatically created whenever a +function derived from a Screen method is called. An (unnamed) turtle object is +automatically created whenever any of the functions derived from a Turtle method +is called. + +To use multiple turtles on a screen one has to use the object-oriented interface. + +.. note:: + In the following documentation the argument list for functions is given. + Methods, of course, have the additional first argument *self* which is + omitted here. + + +Overview of available Turtle and Screen methods +================================================= + +Turtle methods +-------------- + +Turtle motion + Move and draw + | :func:`forward` | :func:`fd` + | :func:`backward` | :func:`bk` | :func:`back` + | :func:`right` | :func:`rt` + | :func:`left` | :func:`lt` + | :func:`goto` | :func:`setpos` | :func:`setposition` + | :func:`setx` + | :func:`sety` + | :func:`setheading` | :func:`seth` + | :func:`home` + | :func:`circle` + | :func:`dot` + | :func:`stamp` + | :func:`clearstamp` + | :func:`clearstamps` + | :func:`undo` + | :func:`speed` + + Tell Turtle's state + | :func:`position` | :func:`pos` + | :func:`towards` + | :func:`xcor` + | :func:`ycor` + | :func:`heading` + | :func:`distance` + + Setting and measurement + | :func:`degrees` + | :func:`radians` + +Pen control + Drawing state + | :func:`pendown` | :func:`pd` | :func:`down` + | :func:`penup` | :func:`pu` | :func:`up` + | :func:`pensize` | :func:`width` + | :func:`pen` + | :func:`isdown` + + Color control + | :func:`color` + | :func:`pencolor` + | :func:`fillcolor` + + Filling + | :func:`filling` + | :func:`begin_fill` + | :func:`end_fill` + + More drawing control + | :func:`reset` + | :func:`clear` + | :func:`write` + +Turtle state + Visibility + | :func:`showturtle` | :func:`st` + | :func:`hideturtle` | :func:`ht` + | :func:`isvisible` + + Appearance + | :func:`shape` + | :func:`resizemode` + | :func:`shapesize` | :func:`turtlesize` + | :func:`shearfactor` + | :func:`settiltangle` + | :func:`tiltangle` + | :func:`tilt` + | :func:`shapetransform` + | :func:`get_shapepoly` + +Using events + | :func:`onclick` + | :func:`onrelease` + | :func:`ondrag` + +Special Turtle methods + | :func:`begin_poly` + | :func:`end_poly` + | :func:`get_poly` + | :func:`clone` + | :func:`getturtle` | :func:`getpen` + | :func:`getscreen` + | :func:`setundobuffer` + | :func:`undobufferentries` + + +Methods of TurtleScreen/Screen +------------------------------ + +Window control + | :func:`bgcolor` + | :func:`bgpic` + | :func:`clear` | :func:`clearscreen` + | :func:`reset` | :func:`resetscreen` + | :func:`screensize` + | :func:`setworldcoordinates` + +Animation control + | :func:`delay` + | :func:`tracer` + | :func:`update` + +Using screen events + | :func:`listen` + | :func:`onkey` | :func:`onkeyrelease` + | :func:`onkeypress` + | :func:`onclick` | :func:`onscreenclick` + | :func:`ontimer` + | :func:`mainloop` | :func:`done` + +Settings and special methods + | :func:`mode` + | :func:`colormode` + | :func:`getcanvas` + | :func:`getshapes` + | :func:`register_shape` | :func:`addshape` + | :func:`turtles` + | :func:`window_height` + | :func:`window_width` + +Input methods + | :func:`textinput` + | :func:`numinput` + +Methods specific to Screen + | :func:`bye` + | :func:`exitonclick` + | :func:`setup` + | :func:`title` + + +Methods of RawTurtle/Turtle and corresponding functions +======================================================= + +Most of the examples in this section refer to a Turtle instance called +``turtle``. + +Turtle motion +------------- + +.. function:: forward(distance) + fd(distance) + + :param distance: a number (integer or float) + + Move the turtle forward by the specified *distance*, in the direction the + turtle is headed. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.position() + (0.00,0.00) + >>> turtle.forward(25) + >>> turtle.position() + (25.00,0.00) + >>> turtle.forward(-75) + >>> turtle.position() + (-50.00,0.00) + + +.. function:: back(distance) + bk(distance) + backward(distance) + + :param distance: a number + + Move the turtle backward by *distance*, opposite to the direction the + turtle is headed. Do not change the turtle's heading. + + .. doctest:: + :hide: + + >>> turtle.goto(0, 0) + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.position() + (0.00,0.00) + >>> turtle.backward(30) + >>> turtle.position() + (-30.00,0.00) + + +.. function:: right(angle) + rt(angle) + + :param angle: a number (integer or float) + + Turn turtle right by *angle* units. (Units are by default degrees, but + can be set via the :func:`degrees` and :func:`radians` functions.) Angle + orientation depends on the turtle mode, see :func:`mode`. + + .. doctest:: + :skipif: _tkinter is None + :hide: + + >>> turtle.setheading(22) + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.heading() + 22.0 + >>> turtle.right(45) + >>> turtle.heading() + 337.0 + + +.. function:: left(angle) + lt(angle) + + :param angle: a number (integer or float) + + Turn turtle left by *angle* units. (Units are by default degrees, but + can be set via the :func:`degrees` and :func:`radians` functions.) Angle + orientation depends on the turtle mode, see :func:`mode`. + + .. doctest:: + :skipif: _tkinter is None + :hide: + + >>> turtle.setheading(22) + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.heading() + 22.0 + >>> turtle.left(45) + >>> turtle.heading() + 67.0 + + +.. function:: goto(x, y=None) + setpos(x, y=None) + setposition(x, y=None) + + :param x: a number or a pair/vector of numbers + :param y: a number or ``None`` + + If *y* is ``None``, *x* must be a pair of coordinates or a :class:`Vec2D` + (e.g. as returned by :func:`pos`). + + Move turtle to an absolute position. If the pen is down, draw line. Do + not change the turtle's orientation. + + .. doctest:: + :skipif: _tkinter is None + :hide: + + >>> turtle.goto(0, 0) + + .. doctest:: + :skipif: _tkinter is None + + >>> tp = turtle.pos() + >>> tp + (0.00,0.00) + >>> turtle.setpos(60,30) + >>> turtle.pos() + (60.00,30.00) + >>> turtle.setpos((20,80)) + >>> turtle.pos() + (20.00,80.00) + >>> turtle.setpos(tp) + >>> turtle.pos() + (0.00,0.00) + + +.. function:: setx(x) + + :param x: a number (integer or float) + + Set the turtle's first coordinate to *x*, leave second coordinate + unchanged. + + .. doctest:: + :skipif: _tkinter is None + :hide: + + >>> turtle.goto(0, 240) + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.position() + (0.00,240.00) + >>> turtle.setx(10) + >>> turtle.position() + (10.00,240.00) + + +.. function:: sety(y) + + :param y: a number (integer or float) + + Set the turtle's second coordinate to *y*, leave first coordinate unchanged. + + .. doctest:: + :skipif: _tkinter is None + :hide: + + >>> turtle.goto(0, 40) + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.position() + (0.00,40.00) + >>> turtle.sety(-10) + >>> turtle.position() + (0.00,-10.00) + + +.. function:: setheading(to_angle) + seth(to_angle) + + :param to_angle: a number (integer or float) + + Set the orientation of the turtle to *to_angle*. Here are some common + directions in degrees: + + =================== ==================== + standard mode logo mode + =================== ==================== + 0 - east 0 - north + 90 - north 90 - east + 180 - west 180 - south + 270 - south 270 - west + =================== ==================== + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.setheading(90) + >>> turtle.heading() + 90.0 + + +.. function:: home() + + Move turtle to the origin -- coordinates (0,0) -- and set its heading to + its start-orientation (which depends on the mode, see :func:`mode`). + + .. doctest:: + :skipif: _tkinter is None + :hide: + + >>> turtle.setheading(90) + >>> turtle.goto(0, -10) + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.heading() + 90.0 + >>> turtle.position() + (0.00,-10.00) + >>> turtle.home() + >>> turtle.position() + (0.00,0.00) + >>> turtle.heading() + 0.0 + + +.. function:: circle(radius, extent=None, steps=None) + + :param radius: a number + :param extent: a number (or ``None``) + :param steps: an integer (or ``None``) + + Draw a circle with given *radius*. The center is *radius* units left of + the turtle; *extent* -- an angle -- determines which part of the circle + is drawn. If *extent* is not given, draw the entire circle. If *extent* + is not a full circle, one endpoint of the arc is the current pen + position. Draw the arc in counterclockwise direction if *radius* is + positive, otherwise in clockwise direction. Finally the direction of the + turtle is changed by the amount of *extent*. + + As the circle is approximated by an inscribed regular polygon, *steps* + determines the number of steps to use. If not given, it will be + calculated automatically. May be used to draw regular polygons. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.home() + >>> turtle.position() + (0.00,0.00) + >>> turtle.heading() + 0.0 + >>> turtle.circle(50) + >>> turtle.position() + (-0.00,0.00) + >>> turtle.heading() + 0.0 + >>> turtle.circle(120, 180) # draw a semicircle + >>> turtle.position() + (0.00,240.00) + >>> turtle.heading() + 180.0 + + +.. function:: dot(size=None, *color) + + :param size: an integer >= 1 (if given) + :param color: a colorstring or a numeric color tuple + + Draw a circular dot with diameter *size*, using *color*. If *size* is + not given, the maximum of pensize+4 and 2*pensize is used. + + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.home() + >>> turtle.dot() + >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50) + >>> turtle.position() + (100.00,-0.00) + >>> turtle.heading() + 0.0 + + +.. function:: stamp() + + Stamp a copy of the turtle shape onto the canvas at the current turtle + position. Return a stamp_id for that stamp, which can be used to delete + it by calling ``clearstamp(stamp_id)``. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.color("blue") + >>> turtle.stamp() + 11 + >>> turtle.fd(50) + + +.. function:: clearstamp(stampid) + + :param stampid: an integer, must be return value of previous + :func:`stamp` call + + Delete stamp with given *stampid*. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.position() + (150.00,-0.00) + >>> turtle.color("blue") + >>> astamp = turtle.stamp() + >>> turtle.fd(50) + >>> turtle.position() + (200.00,-0.00) + >>> turtle.clearstamp(astamp) + >>> turtle.position() + (200.00,-0.00) + + +.. function:: clearstamps(n=None) + + :param n: an integer (or ``None``) + + Delete all or first/last *n* of turtle's stamps. If *n* is ``None``, delete + all stamps, if *n* > 0 delete first *n* stamps, else if *n* < 0 delete + last *n* stamps. + + .. doctest:: + + >>> for i in range(8): + ... turtle.stamp(); turtle.fd(30) + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 + >>> turtle.clearstamps(2) + >>> turtle.clearstamps(-2) + >>> turtle.clearstamps() + + +.. function:: undo() + + Undo (repeatedly) the last turtle action(s). Number of available + undo actions is determined by the size of the undobuffer. + + .. doctest:: + :skipif: _tkinter is None + + >>> for i in range(4): + ... turtle.fd(50); turtle.lt(80) + ... + >>> for i in range(8): + ... turtle.undo() + + +.. function:: speed(speed=None) + + :param speed: an integer in the range 0..10 or a speedstring (see below) + + Set the turtle's speed to an integer value in the range 0..10. If no + argument is given, return current speed. + + If input is a number greater than 10 or smaller than 0.5, speed is set + to 0. Speedstrings are mapped to speedvalues as follows: + + * "fastest": 0 + * "fast": 10 + * "normal": 6 + * "slow": 3 + * "slowest": 1 + + Speeds from 1 to 10 enforce increasingly faster animation of line drawing + and turtle turning. + + Attention: *speed* = 0 means that *no* animation takes + place. forward/back makes turtle jump and likewise left/right make the + turtle turn instantly. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.speed() + 3 + >>> turtle.speed('normal') + >>> turtle.speed() + 6 + >>> turtle.speed(9) + >>> turtle.speed() + 9 + + +Tell Turtle's state +------------------- + +.. function:: position() + pos() + + Return the turtle's current location (x,y) (as a :class:`Vec2D` vector). + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.pos() + (440.00,-0.00) + + +.. function:: towards(x, y=None) + + :param x: a number or a pair/vector of numbers or a turtle instance + :param y: a number if *x* is a number, else ``None`` + + Return the angle between the line from turtle position to position specified + by (x,y), the vector or the other turtle. This depends on the turtle's start + orientation which depends on the mode - "standard"/"world" or "logo"). + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.goto(10, 10) + >>> turtle.towards(0,0) + 225.0 + + +.. function:: xcor() + + Return the turtle's x coordinate. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.home() + >>> turtle.left(50) + >>> turtle.forward(100) + >>> turtle.pos() + (64.28,76.60) + >>> print(round(turtle.xcor(), 5)) + 64.27876 + + +.. function:: ycor() + + Return the turtle's y coordinate. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.home() + >>> turtle.left(60) + >>> turtle.forward(100) + >>> print(turtle.pos()) + (50.00,86.60) + >>> print(round(turtle.ycor(), 5)) + 86.60254 + + +.. function:: heading() + + Return the turtle's current heading (value depends on the turtle mode, see + :func:`mode`). + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.home() + >>> turtle.left(67) + >>> turtle.heading() + 67.0 + + +.. function:: distance(x, y=None) + + :param x: a number or a pair/vector of numbers or a turtle instance + :param y: a number if *x* is a number, else ``None`` + + Return the distance from the turtle to (x,y), the given vector, or the given + other turtle, in turtle step units. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.home() + >>> turtle.distance(30,40) + 50.0 + >>> turtle.distance((30,40)) + 50.0 + >>> joe = Turtle() + >>> joe.forward(77) + >>> turtle.distance(joe) + 77.0 + + +Settings for measurement +------------------------ + +.. function:: degrees(fullcircle=360.0) + + :param fullcircle: a number + + Set angle measurement units, i.e. set number of "degrees" for a full circle. + Default value is 360 degrees. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.home() + >>> turtle.left(90) + >>> turtle.heading() + 90.0 + + Change angle measurement unit to grad (also known as gon, + grade, or gradian and equals 1/100-th of the right angle.) + >>> turtle.degrees(400.0) + >>> turtle.heading() + 100.0 + >>> turtle.degrees(360) + >>> turtle.heading() + 90.0 + + +.. function:: radians() + + Set the angle measurement units to radians. Equivalent to + ``degrees(2*math.pi)``. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.home() + >>> turtle.left(90) + >>> turtle.heading() + 90.0 + >>> turtle.radians() + >>> turtle.heading() + 1.5707963267948966 + + .. doctest:: + :skipif: _tkinter is None + :hide: + + >>> turtle.degrees(360) + + +Pen control +----------- + +Drawing state +~~~~~~~~~~~~~ + +.. function:: pendown() + pd() + down() + + Pull the pen down -- drawing when moving. + + +.. function:: penup() + pu() + up() + + Pull the pen up -- no drawing when moving. + + +.. function:: pensize(width=None) + width(width=None) + + :param width: a positive number + + Set the line thickness to *width* or return it. If resizemode is set to + "auto" and turtleshape is a polygon, that polygon is drawn with the same line + thickness. If no argument is given, the current pensize is returned. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.pensize() + 1 + >>> turtle.pensize(10) # from here on lines of width 10 are drawn + + +.. function:: pen(pen=None, **pendict) + + :param pen: a dictionary with some or all of the below listed keys + :param pendict: one or more keyword-arguments with the below listed keys as keywords + + Return or set the pen's attributes in a "pen-dictionary" with the following + key/value pairs: + + * "shown": True/False + * "pendown": True/False + * "pencolor": color-string or color-tuple + * "fillcolor": color-string or color-tuple + * "pensize": positive number + * "speed": number in range 0..10 + * "resizemode": "auto" or "user" or "noresize" + * "stretchfactor": (positive number, positive number) + * "outline": positive number + * "tilt": number + + This dictionary can be used as argument for a subsequent call to :func:`pen` + to restore the former pen-state. Moreover one or more of these attributes + can be provided as keyword-arguments. This can be used to set several pen + attributes in one statement. + + .. doctest:: + :skipif: _tkinter is None + :options: +NORMALIZE_WHITESPACE + + >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10) + >>> sorted(turtle.pen().items()) + [('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'), + ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'), + ('shearfactor', 0.0), ('shown', True), ('speed', 9), + ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)] + >>> penstate=turtle.pen() + >>> turtle.color("yellow", "") + >>> turtle.penup() + >>> sorted(turtle.pen().items())[:3] + [('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')] + >>> turtle.pen(penstate, fillcolor="green") + >>> sorted(turtle.pen().items())[:3] + [('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')] + +.. function:: isdown() + + Return ``True`` if pen is down, ``False`` if it's up. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.penup() + >>> turtle.isdown() + False + >>> turtle.pendown() + >>> turtle.isdown() + True + + +Color control +~~~~~~~~~~~~~ + +.. function:: pencolor(*args) + + Return or set the pencolor. + + Four input formats are allowed: + + ``pencolor()`` + Return the current pencolor as color specification string or + as a tuple (see example). May be used as input to another + color/pencolor/fillcolor call. + + ``pencolor(colorstring)`` + Set pencolor to *colorstring*, which is a Tk color specification string, + such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``. + + ``pencolor((r, g, b))`` + Set pencolor to the RGB color represented by the tuple of *r*, *g*, and + *b*. Each of *r*, *g*, and *b* must be in the range 0..colormode, where + colormode is either 1.0 or 255 (see :func:`colormode`). + + ``pencolor(r, g, b)`` + Set pencolor to the RGB color represented by *r*, *g*, and *b*. Each of + *r*, *g*, and *b* must be in the range 0..colormode. + + If turtleshape is a polygon, the outline of that polygon is drawn with the + newly set pencolor. + + .. doctest:: + :skipif: _tkinter is None + + >>> colormode() + 1.0 + >>> turtle.pencolor() + 'red' + >>> turtle.pencolor("brown") + >>> turtle.pencolor() + 'brown' + >>> tup = (0.2, 0.8, 0.55) + >>> turtle.pencolor(tup) + >>> turtle.pencolor() + (0.2, 0.8, 0.5490196078431373) + >>> colormode(255) + >>> turtle.pencolor() + (51.0, 204.0, 140.0) + >>> turtle.pencolor('#32c18f') + >>> turtle.pencolor() + (50.0, 193.0, 143.0) + + +.. function:: fillcolor(*args) + + Return or set the fillcolor. + + Four input formats are allowed: + + ``fillcolor()`` + Return the current fillcolor as color specification string, possibly + in tuple format (see example). May be used as input to another + color/pencolor/fillcolor call. + + ``fillcolor(colorstring)`` + Set fillcolor to *colorstring*, which is a Tk color specification string, + such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``. + + ``fillcolor((r, g, b))`` + Set fillcolor to the RGB color represented by the tuple of *r*, *g*, and + *b*. Each of *r*, *g*, and *b* must be in the range 0..colormode, where + colormode is either 1.0 or 255 (see :func:`colormode`). + + ``fillcolor(r, g, b)`` + Set fillcolor to the RGB color represented by *r*, *g*, and *b*. Each of + *r*, *g*, and *b* must be in the range 0..colormode. + + If turtleshape is a polygon, the interior of that polygon is drawn + with the newly set fillcolor. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.fillcolor("violet") + >>> turtle.fillcolor() + 'violet' + >>> turtle.pencolor() + (50.0, 193.0, 143.0) + >>> turtle.fillcolor((50, 193, 143)) # Integers, not floats + >>> turtle.fillcolor() + (50.0, 193.0, 143.0) + >>> turtle.fillcolor('#ffffff') + >>> turtle.fillcolor() + (255.0, 255.0, 255.0) + + +.. function:: color(*args) + + Return or set pencolor and fillcolor. + + Several input formats are allowed. They use 0 to 3 arguments as + follows: + + ``color()`` + Return the current pencolor and the current fillcolor as a pair of color + specification strings or tuples as returned by :func:`pencolor` and + :func:`fillcolor`. + + ``color(colorstring)``, ``color((r,g,b))``, ``color(r,g,b)`` + Inputs as in :func:`pencolor`, set both, fillcolor and pencolor, to the + given value. + + ``color(colorstring1, colorstring2)``, ``color((r1,g1,b1), (r2,g2,b2))`` + Equivalent to ``pencolor(colorstring1)`` and ``fillcolor(colorstring2)`` + and analogously if the other input format is used. + + If turtleshape is a polygon, outline and interior of that polygon is drawn + with the newly set colors. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.color("red", "green") + >>> turtle.color() + ('red', 'green') + >>> color("#285078", "#a0c8f0") + >>> color() + ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0)) + + +See also: Screen method :func:`colormode`. + + +Filling +~~~~~~~ + +.. doctest:: + :skipif: _tkinter is None + :hide: + + >>> turtle.home() + +.. function:: filling() + + Return fillstate (``True`` if filling, ``False`` else). + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.begin_fill() + >>> if turtle.filling(): + ... turtle.pensize(5) + ... else: + ... turtle.pensize(3) + + + +.. function:: begin_fill() + + To be called just before drawing a shape to be filled. + + +.. function:: end_fill() + + Fill the shape drawn after the last call to :func:`begin_fill`. + + Whether or not overlap regions for self-intersecting polygons + or multiple shapes are filled depends on the operating system graphics, + type of overlap, and number of overlaps. For example, the Turtle star + above may be either all yellow or have some white regions. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.color("black", "red") + >>> turtle.begin_fill() + >>> turtle.circle(80) + >>> turtle.end_fill() + + +More drawing control +~~~~~~~~~~~~~~~~~~~~ + +.. function:: reset() + + Delete the turtle's drawings from the screen, re-center the turtle and set + variables to the default values. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.goto(0,-22) + >>> turtle.left(100) + >>> turtle.position() + (0.00,-22.00) + >>> turtle.heading() + 100.0 + >>> turtle.reset() + >>> turtle.position() + (0.00,0.00) + >>> turtle.heading() + 0.0 + + +.. function:: clear() + + Delete the turtle's drawings from the screen. Do not move turtle. State and + position of the turtle as well as drawings of other turtles are not affected. + + +.. function:: write(arg, move=False, align="left", font=("Arial", 8, "normal")) + + :param arg: object to be written to the TurtleScreen + :param move: True/False + :param align: one of the strings "left", "center" or right" + :param font: a triple (fontname, fontsize, fonttype) + + Write text - the string representation of *arg* - at the current turtle + position according to *align* ("left", "center" or right") and with the given + font. If *move* is true, the pen is moved to the bottom-right corner of the + text. By default, *move* is ``False``. + + >>> turtle.write("Home = ", True, align="center") + >>> turtle.write((0,0), True) + + +Turtle state +------------ + +Visibility +~~~~~~~~~~ + +.. function:: hideturtle() + ht() + + Make the turtle invisible. It's a good idea to do this while you're in the + middle of doing some complex drawing, because hiding the turtle speeds up the + drawing observably. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.hideturtle() + + +.. function:: showturtle() + st() + + Make the turtle visible. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.showturtle() + + +.. function:: isvisible() + + Return ``True`` if the Turtle is shown, ``False`` if it's hidden. + + >>> turtle.hideturtle() + >>> turtle.isvisible() + False + >>> turtle.showturtle() + >>> turtle.isvisible() + True + + +Appearance +~~~~~~~~~~ + +.. function:: shape(name=None) + + :param name: a string which is a valid shapename + + Set turtle shape to shape with given *name* or, if name is not given, return + name of current shape. Shape with *name* must exist in the TurtleScreen's + shape dictionary. Initially there are the following polygon shapes: "arrow", + "turtle", "circle", "square", "triangle", "classic". To learn about how to + deal with shapes see Screen method :func:`register_shape`. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.shape() + 'classic' + >>> turtle.shape("turtle") + >>> turtle.shape() + 'turtle' + + +.. function:: resizemode(rmode=None) + + :param rmode: one of the strings "auto", "user", "noresize" + + Set resizemode to one of the values: "auto", "user", "noresize". If *rmode* + is not given, return current resizemode. Different resizemodes have the + following effects: + + - "auto": adapts the appearance of the turtle corresponding to the value of pensize. + - "user": adapts the appearance of the turtle according to the values of + stretchfactor and outlinewidth (outline), which are set by + :func:`shapesize`. + - "noresize": no adaption of the turtle's appearance takes place. + + resizemode("user") is called by :func:`shapesize` when used with arguments. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.resizemode() + 'noresize' + >>> turtle.resizemode("auto") + >>> turtle.resizemode() + 'auto' + + +.. function:: shapesize(stretch_wid=None, stretch_len=None, outline=None) + turtlesize(stretch_wid=None, stretch_len=None, outline=None) + + :param stretch_wid: positive number + :param stretch_len: positive number + :param outline: positive number + + Return or set the pen's attributes x/y-stretchfactors and/or outline. Set + resizemode to "user". If and only if resizemode is set to "user", the turtle + will be displayed stretched according to its stretchfactors: *stretch_wid* is + stretchfactor perpendicular to its orientation, *stretch_len* is + stretchfactor in direction of its orientation, *outline* determines the width + of the shapes's outline. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.shapesize() + (1.0, 1.0, 1) + >>> turtle.resizemode("user") + >>> turtle.shapesize(5, 5, 12) + >>> turtle.shapesize() + (5, 5, 12) + >>> turtle.shapesize(outline=8) + >>> turtle.shapesize() + (5, 5, 8) + + +.. function:: shearfactor(shear=None) + + :param shear: number (optional) + + Set or return the current shearfactor. Shear the turtleshape according to + the given shearfactor shear, which is the tangent of the shear angle. + Do *not* change the turtle's heading (direction of movement). + If shear is not given: return the current shearfactor, i. e. the + tangent of the shear angle, by which lines parallel to the + heading of the turtle are sheared. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.shape("circle") + >>> turtle.shapesize(5,2) + >>> turtle.shearfactor(0.5) + >>> turtle.shearfactor() + 0.5 + + +.. function:: tilt(angle) + + :param angle: a number + + Rotate the turtleshape by *angle* from its current tilt-angle, but do *not* + change the turtle's heading (direction of movement). + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.reset() + >>> turtle.shape("circle") + >>> turtle.shapesize(5,2) + >>> turtle.tilt(30) + >>> turtle.fd(50) + >>> turtle.tilt(30) + >>> turtle.fd(50) + + +.. function:: settiltangle(angle) + + :param angle: a number + + Rotate the turtleshape to point in the direction specified by *angle*, + regardless of its current tilt-angle. *Do not* change the turtle's heading + (direction of movement). + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.reset() + >>> turtle.shape("circle") + >>> turtle.shapesize(5,2) + >>> turtle.settiltangle(45) + >>> turtle.fd(50) + >>> turtle.settiltangle(-45) + >>> turtle.fd(50) + + .. deprecated:: 3.1 + + +.. function:: tiltangle(angle=None) + + :param angle: a number (optional) + + Set or return the current tilt-angle. If angle is given, rotate the + turtleshape to point in the direction specified by angle, + regardless of its current tilt-angle. Do *not* change the turtle's + heading (direction of movement). + If angle is not given: return the current tilt-angle, i. e. the angle + between the orientation of the turtleshape and the heading of the + turtle (its direction of movement). + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.reset() + >>> turtle.shape("circle") + >>> turtle.shapesize(5,2) + >>> turtle.tilt(45) + >>> turtle.tiltangle() + 45.0 + + +.. function:: shapetransform(t11=None, t12=None, t21=None, t22=None) + + :param t11: a number (optional) + :param t12: a number (optional) + :param t21: a number (optional) + :param t12: a number (optional) + + Set or return the current transformation matrix of the turtle shape. + + If none of the matrix elements are given, return the transformation + matrix as a tuple of 4 elements. + Otherwise set the given elements and transform the turtleshape + according to the matrix consisting of first row t11, t12 and + second row t21, 22. The determinant t11 * t22 - t12 * t21 must not be + zero, otherwise an error is raised. + Modify stretchfactor, shearfactor and tiltangle according to the + given matrix. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle = Turtle() + >>> turtle.shape("square") + >>> turtle.shapesize(4,2) + >>> turtle.shearfactor(-0.5) + >>> turtle.shapetransform() + (4.0, -1.0, -0.0, 2.0) + + +.. function:: get_shapepoly() + + Return the current shape polygon as tuple of coordinate pairs. This + can be used to define a new shape or components of a compound shape. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.shape("square") + >>> turtle.shapetransform(4, -1, 0, 2) + >>> turtle.get_shapepoly() + ((50, -20), (30, 20), (-50, 20), (-30, -20)) + + +Using events +------------ + +.. function:: onclick(fun, btn=1, add=None) + + :param fun: a function with two arguments which will be called with the + coordinates of the clicked point on the canvas + :param btn: number of the mouse-button, defaults to 1 (left mouse button) + :param add: ``True`` or ``False`` -- if ``True``, a new binding will be + added, otherwise it will replace a former binding + + Bind *fun* to mouse-click events on this turtle. If *fun* is ``None``, + existing bindings are removed. Example for the anonymous turtle, i.e. the + procedural way: + + .. doctest:: + :skipif: _tkinter is None + + >>> def turn(x, y): + ... left(180) + ... + >>> onclick(turn) # Now clicking into the turtle will turn it. + >>> onclick(None) # event-binding will be removed + + +.. function:: onrelease(fun, btn=1, add=None) + + :param fun: a function with two arguments which will be called with the + coordinates of the clicked point on the canvas + :param btn: number of the mouse-button, defaults to 1 (left mouse button) + :param add: ``True`` or ``False`` -- if ``True``, a new binding will be + added, otherwise it will replace a former binding + + Bind *fun* to mouse-button-release events on this turtle. If *fun* is + ``None``, existing bindings are removed. + + .. doctest:: + :skipif: _tkinter is None + + >>> class MyTurtle(Turtle): + ... def glow(self,x,y): + ... self.fillcolor("red") + ... def unglow(self,x,y): + ... self.fillcolor("") + ... + >>> turtle = MyTurtle() + >>> turtle.onclick(turtle.glow) # clicking on turtle turns fillcolor red, + >>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent. + + +.. function:: ondrag(fun, btn=1, add=None) + + :param fun: a function with two arguments which will be called with the + coordinates of the clicked point on the canvas + :param btn: number of the mouse-button, defaults to 1 (left mouse button) + :param add: ``True`` or ``False`` -- if ``True``, a new binding will be + added, otherwise it will replace a former binding + + Bind *fun* to mouse-move events on this turtle. If *fun* is ``None``, + existing bindings are removed. + + Remark: Every sequence of mouse-move-events on a turtle is preceded by a + mouse-click event on that turtle. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.ondrag(turtle.goto) + + Subsequently, clicking and dragging the Turtle will move it across + the screen thereby producing handdrawings (if pen is down). + + +Special Turtle methods +---------------------- + +.. function:: begin_poly() + + Start recording the vertices of a polygon. Current turtle position is first + vertex of polygon. + + +.. function:: end_poly() + + Stop recording the vertices of a polygon. Current turtle position is last + vertex of polygon. This will be connected with the first vertex. + + +.. function:: get_poly() + + Return the last recorded polygon. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.home() + >>> turtle.begin_poly() + >>> turtle.fd(100) + >>> turtle.left(20) + >>> turtle.fd(30) + >>> turtle.left(60) + >>> turtle.fd(50) + >>> turtle.end_poly() + >>> p = turtle.get_poly() + >>> register_shape("myFavouriteShape", p) + + +.. function:: clone() + + Create and return a clone of the turtle with same position, heading and + turtle properties. + + .. doctest:: + :skipif: _tkinter is None + + >>> mick = Turtle() + >>> joe = mick.clone() + + +.. function:: getturtle() + getpen() + + Return the Turtle object itself. Only reasonable use: as a function to + return the "anonymous turtle": + + .. doctest:: + :skipif: _tkinter is None + + >>> pet = getturtle() + >>> pet.fd(50) + >>> pet + + + +.. function:: getscreen() + + Return the :class:`TurtleScreen` object the turtle is drawing on. + TurtleScreen methods can then be called for that object. + + .. doctest:: + :skipif: _tkinter is None + + >>> ts = turtle.getscreen() + >>> ts + + >>> ts.bgcolor("pink") + + +.. function:: setundobuffer(size) + + :param size: an integer or ``None`` + + Set or disable undobuffer. If *size* is an integer an empty undobuffer of + given size is installed. *size* gives the maximum number of turtle actions + that can be undone by the :func:`undo` method/function. If *size* is + ``None``, the undobuffer is disabled. + + .. doctest:: + :skipif: _tkinter is None + + >>> turtle.setundobuffer(42) + + +.. function:: undobufferentries() + + Return number of entries in the undobuffer. + + .. doctest:: + :skipif: _tkinter is None + + >>> while undobufferentries(): + ... undo() + + + +.. _compoundshapes: + +Compound shapes +--------------- + +To use compound turtle shapes, which consist of several polygons of different +color, you must use the helper class :class:`Shape` explicitly as described +below: + +1. Create an empty Shape object of type "compound". +2. Add as many components to this object as desired, using the + :meth:`addcomponent` method. + + For example: + + .. doctest:: + :skipif: _tkinter is None + + >>> s = Shape("compound") + >>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5)) + >>> s.addcomponent(poly1, "red", "blue") + >>> poly2 = ((0,0),(10,-5),(-10,-5)) + >>> s.addcomponent(poly2, "blue", "red") + +3. Now add the Shape to the Screen's shapelist and use it: + + .. doctest:: + :skipif: _tkinter is None + + >>> register_shape("myshape", s) + >>> shape("myshape") + + +.. note:: + + The :class:`Shape` class is used internally by the :func:`register_shape` + method in different ways. The application programmer has to deal with the + Shape class *only* when using compound shapes like shown above! + + +Methods of TurtleScreen/Screen and corresponding functions +========================================================== + +Most of the examples in this section refer to a TurtleScreen instance called +``screen``. + +.. doctest:: + :skipif: _tkinter is None + :hide: + + >>> screen = Screen() + +Window control +-------------- + +.. function:: bgcolor(*args) + + :param args: a color string or three numbers in the range 0..colormode or a + 3-tuple of such numbers + + + Set or return background color of the TurtleScreen. + + .. doctest:: + :skipif: _tkinter is None + + >>> screen.bgcolor("orange") + >>> screen.bgcolor() + 'orange' + >>> screen.bgcolor("#800080") + >>> screen.bgcolor() + (128.0, 0.0, 128.0) + + +.. function:: bgpic(picname=None) + + :param picname: a string, name of a gif-file or ``"nopic"``, or ``None`` + + Set background image or return name of current backgroundimage. If *picname* + is a filename, set the corresponding image as background. If *picname* is + ``"nopic"``, delete background image, if present. If *picname* is ``None``, + return the filename of the current backgroundimage. :: + + >>> screen.bgpic() + 'nopic' + >>> screen.bgpic("landscape.gif") + >>> screen.bgpic() + "landscape.gif" + + +.. function:: clear() + clearscreen() + + Delete all drawings and all turtles from the TurtleScreen. Reset the now + empty TurtleScreen to its initial state: white background, no background + image, no event bindings and tracing on. + + .. note:: + This TurtleScreen method is available as a global function only under the + name ``clearscreen``. The global function ``clear`` is a different one + derived from the Turtle method ``clear``. + + +.. function:: reset() + resetscreen() + + Reset all Turtles on the Screen to their initial state. + + .. note:: + This TurtleScreen method is available as a global function only under the + name ``resetscreen``. The global function ``reset`` is another one + derived from the Turtle method ``reset``. + + +.. function:: screensize(canvwidth=None, canvheight=None, bg=None) + + :param canvwidth: positive integer, new width of canvas in pixels + :param canvheight: positive integer, new height of canvas in pixels + :param bg: colorstring or color-tuple, new background color + + If no arguments are given, return current (canvaswidth, canvasheight). Else + resize the canvas the turtles are drawing on. Do not alter the drawing + window. To observe hidden parts of the canvas, use the scrollbars. With this + method, one can make visible those parts of a drawing which were outside the + canvas before. + + >>> screen.screensize() + (400, 300) + >>> screen.screensize(2000,1500) + >>> screen.screensize() + (2000, 1500) + + e.g. to search for an erroneously escaped turtle ;-) + + +.. function:: setworldcoordinates(llx, lly, urx, ury) + + :param llx: a number, x-coordinate of lower left corner of canvas + :param lly: a number, y-coordinate of lower left corner of canvas + :param urx: a number, x-coordinate of upper right corner of canvas + :param ury: a number, y-coordinate of upper right corner of canvas + + Set up user-defined coordinate system and switch to mode "world" if + necessary. This performs a ``screen.reset()``. If mode "world" is already + active, all drawings are redrawn according to the new coordinates. + + **ATTENTION**: in user-defined coordinate systems angles may appear + distorted. + + .. doctest:: + :skipif: _tkinter is None + + >>> screen.reset() + >>> screen.setworldcoordinates(-50,-7.5,50,7.5) + >>> for _ in range(72): + ... left(10) + ... + >>> for _ in range(8): + ... left(45); fd(2) # a regular octagon + + .. doctest:: + :skipif: _tkinter is None + :hide: + + >>> screen.reset() + >>> for t in turtles(): + ... t.reset() + + +Animation control +----------------- + +.. function:: delay(delay=None) + + :param delay: positive integer + + Set or return the drawing *delay* in milliseconds. (This is approximately + the time interval between two consecutive canvas updates.) The longer the + drawing delay, the slower the animation. + + Optional argument: + + .. doctest:: + :skipif: _tkinter is None + + >>> screen.delay() + 10 + >>> screen.delay(5) + >>> screen.delay() + 5 + + +.. function:: tracer(n=None, delay=None) + + :param n: nonnegative integer + :param delay: nonnegative integer + + Turn turtle animation on/off and set delay for update drawings. If + *n* is given, only each n-th regular screen update is really + performed. (Can be used to accelerate the drawing of complex + graphics.) When called without arguments, returns the currently + stored value of n. Second argument sets delay value (see + :func:`delay`). + + .. doctest:: + :skipif: _tkinter is None + + >>> screen.tracer(8, 25) + >>> dist = 2 + >>> for i in range(200): + ... fd(dist) + ... rt(90) + ... dist += 2 + + +.. function:: update() + + Perform a TurtleScreen update. To be used when tracer is turned off. + +See also the RawTurtle/Turtle method :func:`speed`. + + +Using screen events +------------------- + +.. function:: listen(xdummy=None, ydummy=None) + + Set focus on TurtleScreen (in order to collect key-events). Dummy arguments + are provided in order to be able to pass :func:`listen` to the onclick method. + + +.. function:: onkey(fun, key) + onkeyrelease(fun, key) + + :param fun: a function with no arguments or ``None`` + :param key: a string: key (e.g. "a") or key-symbol (e.g. "space") + + Bind *fun* to key-release event of key. If *fun* is ``None``, event bindings + are removed. Remark: in order to be able to register key-events, TurtleScreen + must have the focus. (See method :func:`listen`.) + + .. doctest:: + :skipif: _tkinter is None + + >>> def f(): + ... fd(50) + ... lt(60) + ... + >>> screen.onkey(f, "Up") + >>> screen.listen() + + +.. function:: onkeypress(fun, key=None) + + :param fun: a function with no arguments or ``None`` + :param key: a string: key (e.g. "a") or key-symbol (e.g. "space") + + Bind *fun* to key-press event of key if key is given, + or to any key-press-event if no key is given. + Remark: in order to be able to register key-events, TurtleScreen + must have focus. (See method :func:`listen`.) + + .. doctest:: + :skipif: _tkinter is None + + >>> def f(): + ... fd(50) + ... + >>> screen.onkey(f, "Up") + >>> screen.listen() + + +.. function:: onclick(fun, btn=1, add=None) + onscreenclick(fun, btn=1, add=None) + + :param fun: a function with two arguments which will be called with the + coordinates of the clicked point on the canvas + :param btn: number of the mouse-button, defaults to 1 (left mouse button) + :param add: ``True`` or ``False`` -- if ``True``, a new binding will be + added, otherwise it will replace a former binding + + Bind *fun* to mouse-click events on this screen. If *fun* is ``None``, + existing bindings are removed. + + Example for a TurtleScreen instance named ``screen`` and a Turtle instance + named turtle: + + .. doctest:: + :skipif: _tkinter is None + + >>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will + >>> # make the turtle move to the clicked point. + >>> screen.onclick(None) # remove event binding again + + .. note:: + This TurtleScreen method is available as a global function only under the + name ``onscreenclick``. The global function ``onclick`` is another one + derived from the Turtle method ``onclick``. + + +.. function:: ontimer(fun, t=0) + + :param fun: a function with no arguments + :param t: a number >= 0 + + Install a timer that calls *fun* after *t* milliseconds. + + .. doctest:: + :skipif: _tkinter is None + + >>> running = True + >>> def f(): + ... if running: + ... fd(50) + ... lt(60) + ... screen.ontimer(f, 250) + >>> f() ### makes the turtle march around + >>> running = False + + +.. function:: mainloop() + done() + + Starts event loop - calling Tkinter's mainloop function. + Must be the last statement in a turtle graphics program. + Must *not* be used if a script is run from within IDLE in -n mode + (No subprocess) - for interactive use of turtle graphics. :: + + >>> screen.mainloop() + + +Input methods +------------- + +.. function:: textinput(title, prompt) + + :param title: string + :param prompt: string + + Pop up a dialog window for input of a string. Parameter title is + the title of the dialog window, prompt is a text mostly describing + what information to input. + Return the string input. If the dialog is canceled, return ``None``. :: + + >>> screen.textinput("NIM", "Name of first player:") + + +.. function:: numinput(title, prompt, default=None, minval=None, maxval=None) + + :param title: string + :param prompt: string + :param default: number (optional) + :param minval: number (optional) + :param maxval: number (optional) + + Pop up a dialog window for input of a number. title is the title of the + dialog window, prompt is a text mostly describing what numerical information + to input. default: default value, minval: minimum value for input, + maxval: maximum value for input + The number input must be in the range minval .. maxval if these are + given. If not, a hint is issued and the dialog remains open for + correction. + Return the number input. If the dialog is canceled, return ``None``. :: + + >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000) + + +Settings and special methods +---------------------------- + +.. function:: mode(mode=None) + + :param mode: one of the strings "standard", "logo" or "world" + + Set turtle mode ("standard", "logo" or "world") and perform reset. If mode + is not given, current mode is returned. + + Mode "standard" is compatible with old :mod:`turtle`. Mode "logo" is + compatible with most Logo turtle graphics. Mode "world" uses user-defined + "world coordinates". **Attention**: in this mode angles appear distorted if + ``x/y`` unit-ratio doesn't equal 1. + + ============ ========================= =================== + Mode Initial turtle heading positive angles + ============ ========================= =================== + "standard" to the right (east) counterclockwise + "logo" upward (north) clockwise + ============ ========================= =================== + + .. doctest:: + :skipif: _tkinter is None + + >>> mode("logo") # resets turtle heading to north + >>> mode() + 'logo' + + +.. function:: colormode(cmode=None) + + :param cmode: one of the values 1.0 or 255 + + Return the colormode or set it to 1.0 or 255. Subsequently *r*, *g*, *b* + values of color triples have to be in the range 0..\ *cmode*. + + .. doctest:: + :skipif: _tkinter is None + + >>> screen.colormode(1) + >>> turtle.pencolor(240, 160, 80) + Traceback (most recent call last): + ... + TurtleGraphicsError: bad color sequence: (240, 160, 80) + >>> screen.colormode() + 1.0 + >>> screen.colormode(255) + >>> screen.colormode() + 255 + >>> turtle.pencolor(240,160,80) + + +.. function:: getcanvas() + + Return the Canvas of this TurtleScreen. Useful for insiders who know what to + do with a Tkinter Canvas. + + .. doctest:: + :skipif: _tkinter is None + + >>> cv = screen.getcanvas() + >>> cv + + + +.. function:: getshapes() + + Return a list of names of all currently available turtle shapes. + + .. doctest:: + :skipif: _tkinter is None + + >>> screen.getshapes() + ['arrow', 'blank', 'circle', ..., 'turtle'] + + +.. function:: register_shape(name, shape=None) + addshape(name, shape=None) + + There are three different ways to call this function: + + (1) *name* is the name of a gif-file and *shape* is ``None``: Install the + corresponding image shape. :: + + >>> screen.register_shape("turtle.gif") + + .. note:: + Image shapes *do not* rotate when turning the turtle, so they do not + display the heading of the turtle! + + (2) *name* is an arbitrary string and *shape* is a tuple of pairs of + coordinates: Install the corresponding polygon shape. + + .. doctest:: + :skipif: _tkinter is None + + >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3))) + + (3) *name* is an arbitrary string and shape is a (compound) :class:`Shape` + object: Install the corresponding compound shape. + + Add a turtle shape to TurtleScreen's shapelist. Only thusly registered + shapes can be used by issuing the command ``shape(shapename)``. + + +.. function:: turtles() + + Return the list of turtles on the screen. + + .. doctest:: + :skipif: _tkinter is None + + >>> for turtle in screen.turtles(): + ... turtle.color("red") + + +.. function:: window_height() + + Return the height of the turtle window. :: + + >>> screen.window_height() + 480 + + +.. function:: window_width() + + Return the width of the turtle window. :: + + >>> screen.window_width() + 640 + + +.. _screenspecific: + +Methods specific to Screen, not inherited from TurtleScreen +----------------------------------------------------------- + +.. function:: bye() + + Shut the turtlegraphics window. + + +.. function:: exitonclick() + + Bind bye() method to mouse clicks on the Screen. + + + If the value "using_IDLE" in the configuration dictionary is ``False`` + (default value), also enter mainloop. Remark: If IDLE with the ``-n`` switch + (no subprocess) is used, this value should be set to ``True`` in + :file:`turtle.cfg`. In this case IDLE's own mainloop is active also for the + client script. + + +.. function:: setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"]) + + Set the size and position of the main window. Default values of arguments + are stored in the configuration dictionary and can be changed via a + :file:`turtle.cfg` file. + + :param width: if an integer, a size in pixels, if a float, a fraction of the + screen; default is 50% of screen + :param height: if an integer, the height in pixels, if a float, a fraction of + the screen; default is 75% of screen + :param startx: if positive, starting position in pixels from the left + edge of the screen, if negative from the right edge, if ``None``, + center window horizontally + :param starty: if positive, starting position in pixels from the top + edge of the screen, if negative from the bottom edge, if ``None``, + center window vertically + + .. doctest:: + :skipif: _tkinter is None + + >>> screen.setup (width=200, height=200, startx=0, starty=0) + >>> # sets window to 200x200 pixels, in upper left of screen + >>> screen.setup(width=.75, height=0.5, startx=None, starty=None) + >>> # sets window to 75% of screen by 50% of screen and centers + + +.. function:: title(titlestring) + + :param titlestring: a string that is shown in the titlebar of the turtle + graphics window + + Set title of turtle window to *titlestring*. + + .. doctest:: + :skipif: _tkinter is None + + >>> screen.title("Welcome to the turtle zoo!") + + +Public classes +============== + + +.. class:: RawTurtle(canvas) + RawPen(canvas) + + :param canvas: a :class:`tkinter.Canvas`, a :class:`ScrolledCanvas` or a + :class:`TurtleScreen` + + Create a turtle. The turtle has all methods described above as "methods of + Turtle/RawTurtle". + + +.. class:: Turtle() + + Subclass of RawTurtle, has the same interface but draws on a default + :class:`Screen` object created automatically when needed for the first time. + + +.. class:: TurtleScreen(cv) + + :param cv: a :class:`tkinter.Canvas` + + Provides screen oriented methods like :func:`setbg` etc. that are described + above. + +.. class:: Screen() + + Subclass of TurtleScreen, with :ref:`four methods added `. + + +.. class:: ScrolledCanvas(master) + + :param master: some Tkinter widget to contain the ScrolledCanvas, i.e. + a Tkinter-canvas with scrollbars added + + Used by class Screen, which thus automatically provides a ScrolledCanvas as + playground for the turtles. + +.. class:: Shape(type_, data) + + :param type\_: one of the strings "polygon", "image", "compound" + + Data structure modeling shapes. The pair ``(type_, data)`` must follow this + specification: + + + =========== =========== + *type_* *data* + =========== =========== + "polygon" a polygon-tuple, i.e. a tuple of pairs of coordinates + "image" an image (in this form only used internally!) + "compound" ``None`` (a compound 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: + + .. doctest:: + :skipif: _tkinter is None + + >>> poly = ((0,0),(10,-5),(0,10),(-10,-5)) + >>> s = Shape("compound") + >>> s.addcomponent(poly, "red", "blue") + >>> # ... add more components and then use register_shape() + + See :ref:`compoundshapes`. + + +.. class:: Vec2D(x, y) + + A two-dimensional vector class, used as a helper class for implementing + turtle graphics. May be useful for turtle graphics programs too. Derived + from tuple, so a vector is a tuple! + + Provides (for *a*, *b* vectors, *k* number): + + * ``a + b`` vector addition + * ``a - b`` vector subtraction + * ``a * b`` inner product + * ``k * a`` and ``a * k`` multiplication with scalar + * ``abs(a)`` absolute value of a + * ``a.rotate(angle)`` rotation + + +Help and configuration +====================== + +How to use help +--------------- + +The public methods of the Screen and Turtle classes are documented extensively +via docstrings. So these can be used as online-help via the Python help +facilities: + +- When using IDLE, tooltips show the signatures and first lines of the + docstrings of typed in function-/method calls. + +- Calling :func:`help` on methods or functions displays the docstrings:: + + >>> 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 + form:: + + >>> 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() + +These modified docstrings are created automatically together with the function +definitions that are derived from the methods at import time. + + +Translation of docstrings into different languages +-------------------------------------------------- + +There is a utility to create a dictionary the keys of which are the method names +and the values of which are the docstrings of the public methods of the classes +Screen and Turtle. + +.. function:: write_docstringdict(filename="turtle_docstringdict") + + :param filename: a string, used as filename + + Create and write docstring-dictionary to a Python script with the given + filename. This function has to be called explicitly (it is not used by the + turtle graphics classes). The docstring dictionary will be written to the + Python script :file:`{filename}.py`. It is intended to serve as a template + for translation of the docstrings into different languages. + +If you (or your students) want to use :mod:`turtle` with online help in your +native language, you have to translate the docstrings and save the resulting +file as e.g. :file:`turtle_docstringdict_german.py`. + +If you have an appropriate entry in your :file:`turtle.cfg` file this dictionary +will be read in at import time and will replace the original English docstrings. + +At the time of this writing there are docstring dictionaries in German and in +Italian. (Requests please to glingl@aon.at.) + + + +How to configure Screen and Turtles +----------------------------------- + +The built-in default configuration mimics the appearance and behaviour of the +old turtle module in order to retain best possible compatibility with it. + +If you want to use a different configuration which better reflects the features +of this module or which better fits to your needs, e.g. for use in a classroom, +you can prepare a configuration file ``turtle.cfg`` which will be read at import +time and modify the configuration according to its settings. + +The built in configuration would correspond to the following turtle.cfg:: + + width = 0.5 + height = 0.75 + leftright = None + topbottom = None + canvwidth = 400 + canvheight = 300 + mode = standard + colormode = 1.0 + delay = 10 + undobuffersize = 1000 + shape = classic + pencolor = black + fillcolor = black + resizemode = noresize + visible = True + language = english + exampleturtle = turtle + examplescreen = screen + title = Python Turtle Graphics + using_IDLE = False + +Short explanation of selected entries: + +- The first four lines correspond to the arguments of the :meth:`Screen.setup` + method. +- Line 5 and 6 correspond to the arguments of the method + :meth:`Screen.screensize`. +- *shape* can be any of the built-in shapes, e.g: arrow, turtle, etc. For more + info try ``help(shape)``. +- If you want to use no fillcolor (i.e. make the turtle transparent), you have + to write ``fillcolor = ""`` (but all nonempty strings must not have quotes in + the cfg-file). +- If you want to reflect the turtle its state, you have to use ``resizemode = + auto``. +- If you set e.g. ``language = italian`` the docstringdict + :file:`turtle_docstringdict_italian.py` will be loaded at import time (if + present on the import path, e.g. in the same directory as :mod:`turtle`. +- The entries *exampleturtle* and *examplescreen* define the names of these + objects as they occur in the docstrings. The transformation of + method-docstrings to function-docstrings will delete these names from the + docstrings. +- *using_IDLE*: Set this to ``True`` if you regularly work with IDLE and its -n + switch ("no subprocess"). This will prevent :func:`exitonclick` to enter the + mainloop. + +There can be a :file:`turtle.cfg` file in the directory where :mod:`turtle` is +stored and an additional one in the current working directory. The latter will +override the settings of the first one. + +The :file:`Lib/turtledemo` directory contains a :file:`turtle.cfg` file. You can +study it as an example and see its effects when running the demos (preferably +not from within the demo-viewer). + + +:mod:`turtledemo` --- Demo scripts +================================== + +.. module:: turtledemo + :synopsis: A viewer for example turtle scripts + +The :mod:`turtledemo` package includes a set of demo scripts. These +scripts can be run and viewed using the supplied demo viewer as follows:: + + python -m turtledemo + +Alternatively, you can run the demo scripts individually. For example, :: + + python -m turtledemo.bytedesign + +The :mod:`turtledemo` package directory contains: + +- A demo viewer :file:`__main__.py` which can be used to view the sourcecode + of the scripts and run them at the same time. +- Multiple scripts demonstrating different features of the :mod:`turtle` + module. Examples can be accessed via the Examples menu. They can also + be run standalone. +- A :file:`turtle.cfg` file which serves as an example of how to write + and use such files. + +The demo scripts are: + +.. tabularcolumns:: |l|L|L| + ++----------------+------------------------------+-----------------------+ +| Name | Description | Features | ++================+==============================+=======================+ +| bytedesign | complex classical | :func:`tracer`, delay,| +| | turtle graphics pattern | :func:`update` | ++----------------+------------------------------+-----------------------+ +| chaos | graphs Verhulst dynamics, | world coordinates | +| | shows that computer's | | +| | computations can generate | | +| | results sometimes against the| | +| | common sense expectations | | ++----------------+------------------------------+-----------------------+ +| clock | analog clock showing time | turtles as clock's | +| | of your computer | hands, ontimer | ++----------------+------------------------------+-----------------------+ +| colormixer | experiment with r, g, b | :func:`ondrag` | ++----------------+------------------------------+-----------------------+ +| forest | 3 breadth-first trees | randomization | ++----------------+------------------------------+-----------------------+ +| fractalcurves | Hilbert & Koch curves | recursion | ++----------------+------------------------------+-----------------------+ +| lindenmayer | ethnomathematics | L-System | +| | (indian kolams) | | ++----------------+------------------------------+-----------------------+ +| minimal_hanoi | Towers of Hanoi | Rectangular Turtles | +| | | as Hanoi discs | +| | | (shape, shapesize) | ++----------------+------------------------------+-----------------------+ +| nim | play the classical nim game | turtles as nimsticks, | +| | with three heaps of sticks | event driven (mouse, | +| | against the computer. | keyboard) | ++----------------+------------------------------+-----------------------+ +| paint | super minimalistic | :func:`onclick` | +| | drawing program | | ++----------------+------------------------------+-----------------------+ +| peace | elementary | turtle: appearance | +| | | and animation | ++----------------+------------------------------+-----------------------+ +| penrose | aperiodic tiling with | :func:`stamp` | +| | kites and darts | | ++----------------+------------------------------+-----------------------+ +| planet_and_moon| simulation of | compound shapes, | +| | gravitational system | :class:`Vec2D` | ++----------------+------------------------------+-----------------------+ +| round_dance | dancing turtles rotating | compound shapes, clone| +| | pairwise in opposite | shapesize, tilt, | +| | direction | get_shapepoly, update | ++----------------+------------------------------+-----------------------+ +| sorting_animate| visual demonstration of | simple alignment, | +| | different sorting methods | randomization | ++----------------+------------------------------+-----------------------+ +| tree | a (graphical) breadth | :func:`clone` | +| | first tree (using generators)| | ++----------------+------------------------------+-----------------------+ +| two_canvases | simple design | turtles on two | +| | | canvases | ++----------------+------------------------------+-----------------------+ +| wikipedia | a pattern from the wikipedia | :func:`clone`, | +| | article on turtle graphics | :func:`undo` | ++----------------+------------------------------+-----------------------+ +| yinyang | another elementary example | :func:`circle` | ++----------------+------------------------------+-----------------------+ + +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 + 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 + :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 + ``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 + Python 2.6. + +Changes since Python 3.0 +======================== + +- The methods :meth:`Turtle.shearfactor`, :meth:`Turtle.shapetransform` and + :meth:`Turtle.get_shapepoly` have been added. Thus the full range of + regular linear transforms is now available for transforming turtle shapes. + :meth:`Turtle.tiltangle` has been enhanced in functionality: it now can + be used to get or set the tiltangle. :meth:`Turtle.settiltangle` has been + deprecated. + +- The method :meth:`Screen.onkeypress` has been added as a complement to + :meth:`Screen.onkey` which in fact binds actions to the keyrelease event. + Accordingly the latter has got an alias: :meth:`Screen.onkeyrelease`. + +- The method :meth:`Screen.mainloop` has been added. So when working only + with Screen and Turtle objects one must not additionally import + :func:`mainloop` anymore. + +- Two input methods has been added :meth:`Screen.textinput` and + :meth:`Screen.numinput`. These popup input dialogs and return + strings and numbers respectively. + +- Two example scripts :file:`tdemo_nim.py` and :file:`tdemo_round_dance.py` + have been added to the :file:`Lib/turtledemo` directory. + + +.. doctest:: + :skipif: _tkinter is None + :hide: + + >>> for turtle in turtles(): + ... turtle.reset() + >>> turtle.penup() + >>> turtle.goto(-200,25) + >>> turtle.pendown() + >>> turtle.write("No one expects the Spanish Inquisition!", + ... font=("Arial", 20, "normal")) + >>> turtle.penup() + >>> turtle.goto(-100,-50) + >>> turtle.pendown() + >>> turtle.write("Our two chief Turtles are...", + ... font=("Arial", 16, "normal")) + >>> turtle.penup() + >>> turtle.goto(-450,-75) + >>> turtle.write(str(turtles())) diff --git a/cpython_2/environment/repo/Doc/library/types.rst b/cpython_2/environment/repo/Doc/library/types.rst new file mode 100644 index 0000000000000000000000000000000000000000..79acdf4499afd2f09b0f51c47ab26e76674e4e0e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/types.rst @@ -0,0 +1,408 @@ +:mod:`types` --- Dynamic type creation and names for built-in types +=================================================================== + +.. module:: types + :synopsis: Names for built-in types. + +**Source code:** :source:`Lib/types.py` + +-------------- + +This module defines utility functions to assist in dynamic creation of +new types. + +It also defines names for some object types that are used by the standard +Python interpreter, but not exposed as builtins like :class:`int` or +:class:`str` are. + +Finally, it provides some additional type-related utility classes and functions +that are not fundamental enough to be builtins. + + +Dynamic Type Creation +--------------------- + +.. function:: new_class(name, bases=(), kwds=None, exec_body=None) + + Creates a class object dynamically using the appropriate metaclass. + + The first three arguments are the components that make up a class + definition header: the class name, the base classes (in order), the + keyword arguments (such as ``metaclass``). + + The *exec_body* argument is a callback that is used to populate the + freshly created class namespace. It should accept the class namespace + as its sole argument and update the namespace directly with the class + contents. If no callback is provided, it has the same effect as passing + in ``lambda ns: ns``. + + .. versionadded:: 3.3 + +.. function:: prepare_class(name, bases=(), kwds=None) + + Calculates the appropriate metaclass and creates the class namespace. + + The arguments are the components that make up a class definition header: + the class name, the base classes (in order) and the keyword arguments + (such as ``metaclass``). + + The return value is a 3-tuple: ``metaclass, namespace, kwds`` + + *metaclass* is the appropriate metaclass, *namespace* is the + prepared class namespace and *kwds* is an updated copy of the passed + in *kwds* argument with any ``'metaclass'`` entry removed. If no *kwds* + argument is passed in, this will be an empty dict. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.6 + + The default value for the ``namespace`` element of the returned + tuple has changed. Now an insertion-order-preserving mapping is + used when the metaclass does not have a ``__prepare__`` method. + +.. seealso:: + + :ref:`metaclasses` + Full details of the class creation process supported by these functions + + :pep:`3115` - Metaclasses in Python 3000 + Introduced the ``__prepare__`` namespace hook + +.. function:: resolve_bases(bases) + + Resolve MRO entries dynamically as specified by :pep:`560`. + + This function looks for items in *bases* that are not instances of + :class:`type`, and returns a tuple where each such object that has + an ``__mro_entries__`` method is replaced with an unpacked result of + calling this method. If a *bases* item is an instance of :class:`type`, + or it doesn't have an ``__mro_entries__`` method, then it is included in + the return tuple unchanged. + + .. versionadded:: 3.7 + +.. seealso:: + + :pep:`560` - Core support for typing module and generic types + + +Standard Interpreter Types +-------------------------- + +This module provides names for many of the types that are required to +implement a Python interpreter. It deliberately avoids including some of +the types that arise only incidentally during processing such as the +``listiterator`` type. + +Typical use of these names is for :func:`isinstance` or +:func:`issubclass` checks. + + +If you instantiate any of these types, note that signatures may vary between Python versions. + +Standard names are defined for the following types: + +.. data:: FunctionType + LambdaType + + The type of user-defined functions and functions created by + :keyword:`lambda` expressions. + + +.. data:: GeneratorType + + The type of :term:`generator`-iterator objects, created by + generator functions. + + +.. data:: CoroutineType + + The type of :term:`coroutine` objects, created by + :keyword:`async def` functions. + + .. versionadded:: 3.5 + + +.. data:: AsyncGeneratorType + + The type of :term:`asynchronous generator`-iterator objects, created by + asynchronous generator functions. + + .. versionadded:: 3.6 + + +.. class:: CodeType(**kwargs) + + .. index:: builtin: compile + + The type for code objects such as returned by :func:`compile`. + + .. audit-event:: code.__new__ code,filename,name,argcount,posonlyargcount,kwonlyargcount,nlocals,stacksize,flags CodeType + + Note that the audited arguments may not match the names or positions + required by the initializer. + + .. method:: CodeType.replace(**kwargs) + + Return a copy of the code object with new values for the specified fields. + + .. versionadded:: 3.8 + +.. data:: CellType + + The type for cell objects: such objects are used as containers for + a function's free variables. + + .. versionadded:: 3.8 + + +.. data:: MethodType + + The type of methods of user-defined class instances. + + +.. data:: BuiltinFunctionType + BuiltinMethodType + + The type of built-in functions like :func:`len` or :func:`sys.exit`, and + methods of built-in classes. (Here, the term "built-in" means "written in + C".) + + +.. data:: WrapperDescriptorType + + The type of methods of some built-in data types and base classes such as + :meth:`object.__init__` or :meth:`object.__lt__`. + + .. versionadded:: 3.7 + + +.. data:: MethodWrapperType + + The type of *bound* methods of some built-in data types and base classes. + For example it is the type of :code:`object().__str__`. + + .. versionadded:: 3.7 + + +.. data:: MethodDescriptorType + + The type of methods of some built-in data types such as :meth:`str.join`. + + .. versionadded:: 3.7 + + +.. data:: ClassMethodDescriptorType + + The type of *unbound* class methods of some built-in data types such as + ``dict.__dict__['fromkeys']``. + + .. versionadded:: 3.7 + + +.. class:: ModuleType(name, doc=None) + + The type of :term:`modules `. Constructor takes the name of the + module to be created and optionally its :term:`docstring`. + + .. note:: + Use :func:`importlib.util.module_from_spec` to create a new module if you + wish to set the various import-controlled attributes. + + .. attribute:: __doc__ + + The :term:`docstring` of the module. Defaults to ``None``. + + .. attribute:: __loader__ + + The :term:`loader` which loaded the module. Defaults to ``None``. + + .. versionchanged:: 3.4 + Defaults to ``None``. Previously the attribute was optional. + + .. attribute:: __name__ + + The name of the module. + + .. attribute:: __package__ + + Which :term:`package` a module belongs to. If the module is top-level + (i.e. not a part of any specific package) then the attribute should be set + to ``''``, else it should be set to the name of the package (which can be + :attr:`__name__` if the module is a package itself). Defaults to ``None``. + + .. versionchanged:: 3.4 + Defaults to ``None``. Previously the attribute was optional. + + +.. class:: TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno) + + The type of traceback objects such as found in ``sys.exc_info()[2]``. + + See :ref:`the language reference ` for details of the + available attributes and operations, and guidance on creating tracebacks + dynamically. + + +.. data:: FrameType + + The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a + traceback object. + + See :ref:`the language reference ` for details of the + available attributes and operations. + + +.. data:: GetSetDescriptorType + + The type of objects defined in extension modules with ``PyGetSetDef``, such + as ``FrameType.f_locals`` or ``array.array.typecode``. This type is used as + descriptor for object attributes; it has the same purpose as the + :class:`property` type, but for classes defined in extension modules. + + +.. data:: MemberDescriptorType + + The type of objects defined in extension modules with ``PyMemberDef``, such + as ``datetime.timedelta.days``. This type is used as descriptor for simple C + data members which use standard conversion functions; it has the same purpose + as the :class:`property` type, but for classes defined in extension modules. + + .. impl-detail:: + + In other implementations of Python, this type may be identical to + ``GetSetDescriptorType``. + +.. class:: MappingProxyType(mapping) + + Read-only proxy of a mapping. It provides a dynamic view on the mapping's + entries, which means that when the mapping changes, the view reflects these + changes. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.9 + + Updated to support the new union (``|``) operator from :pep:`584`, which + simply delegates to the underlying mapping. + + .. describe:: key in proxy + + Return ``True`` if the underlying mapping has a key *key*, else + ``False``. + + .. describe:: proxy[key] + + Return the item of the underlying mapping with key *key*. Raises a + :exc:`KeyError` if *key* is not in the underlying mapping. + + .. describe:: iter(proxy) + + Return an iterator over the keys of the underlying mapping. This is a + shortcut for ``iter(proxy.keys())``. + + .. describe:: len(proxy) + + Return the number of items in the underlying mapping. + + .. method:: copy() + + Return a shallow copy of the underlying mapping. + + .. method:: get(key[, default]) + + Return the value for *key* if *key* is in the underlying mapping, else + *default*. If *default* is not given, it defaults to ``None``, so that + this method never raises a :exc:`KeyError`. + + .. method:: items() + + Return a new view of the underlying mapping's items (``(key, value)`` + pairs). + + .. method:: keys() + + Return a new view of the underlying mapping's keys. + + .. method:: values() + + Return a new view of the underlying mapping's values. + + .. describe:: reversed(proxy) + + Return a reverse iterator over the keys of the underlying mapping. + + .. versionadded:: 3.9 + + +Additional Utility Classes and Functions +---------------------------------------- + +.. class:: SimpleNamespace + + A simple :class:`object` subclass that provides attribute access to its + namespace, as well as a meaningful repr. + + Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove + attributes. If a ``SimpleNamespace`` object is initialized with keyword + arguments, those are directly added to the underlying namespace. + + The type is roughly equivalent to the following code:: + + class SimpleNamespace: + def __init__(self, /, **kwargs): + self.__dict__.update(kwargs) + + def __repr__(self): + items = (f"{k}={v!r}" for k, v in self.__dict__.items()) + return "{}({})".format(type(self).__name__, ", ".join(items)) + + def __eq__(self, other): + return self.__dict__ == other.__dict__ + + ``SimpleNamespace`` may be useful as a replacement for ``class NS: pass``. + However, for a structured record type use :func:`~collections.namedtuple` + instead. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.9 + Attribute order in the repr changed from alphabetical to insertion (like + ``dict``). + +.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None) + + Route attribute access on a class to __getattr__. + + This is a descriptor, used to define attributes that act differently when + accessed through an instance and through a class. Instance access remains + normal, but access to an attribute through a class will be routed to the + class's __getattr__ method; this is done by raising AttributeError. + + This allows one to have properties active on an instance, and have virtual + attributes on the class with the same name (see :class:`enum.Enum` for an example). + + .. versionadded:: 3.4 + + +Coroutine Utility Functions +--------------------------- + +.. function:: coroutine(gen_func) + + This function transforms a :term:`generator` function into a + :term:`coroutine function` which returns a generator-based coroutine. + The generator-based coroutine is still a :term:`generator iterator`, + but is also considered to be a :term:`coroutine` object and is + :term:`awaitable`. However, it may not necessarily implement + the :meth:`__await__` method. + + If *gen_func* is a generator function, it will be modified in-place. + + If *gen_func* is not a generator function, it will be wrapped. If it + returns an instance of :class:`collections.abc.Generator`, the instance + will be wrapped in an *awaitable* proxy object. All other types + of objects will be returned as is. + + .. versionadded:: 3.5 diff --git a/cpython_2/environment/repo/Doc/library/typing.rst b/cpython_2/environment/repo/Doc/library/typing.rst new file mode 100644 index 0000000000000000000000000000000000000000..fa13c07c44ea3ab246920ee6ea573518d4d4361d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/typing.rst @@ -0,0 +1,1487 @@ +:mod:`typing` --- Support for type hints +======================================== + +.. module:: typing + :synopsis: Support for type hints (see :pep:`484`). + +.. versionadded:: 3.5 + +**Source code:** :source:`Lib/typing.py` + +.. note:: + + The Python runtime does not enforce function and variable type annotations. + They can be used by third party tools such as type checkers, IDEs, linters, + etc. + +-------------- + +This module provides runtime support for type hints as specified by +:pep:`484`, :pep:`526`, :pep:`544`, :pep:`586`, :pep:`589`, and :pep:`591`. +The most fundamental support consists of the types :data:`Any`, :data:`Union`, +:data:`Tuple`, :data:`Callable`, :class:`TypeVar`, and +:class:`Generic`. For full specification please see :pep:`484`. For +a simplified introduction to type hints see :pep:`483`. + + +The function below takes and returns a string and is annotated as follows:: + + def greeting(name: str) -> str: + return 'Hello ' + name + +In the function ``greeting``, the argument ``name`` is expected to be of type +:class:`str` and the return type :class:`str`. Subtypes are accepted as +arguments. + +Type aliases +------------ + +A type alias is defined by assigning the type to the alias. In this example, +``Vector`` and ``List[float]`` will be treated as interchangeable synonyms:: + + from typing import List + Vector = List[float] + + def scale(scalar: float, vector: Vector) -> Vector: + return [scalar * num for num in vector] + + # typechecks; a list of floats qualifies as a Vector. + new_vector = scale(2.0, [1.0, -4.2, 5.4]) + +Type aliases are useful for simplifying complex type signatures. For example:: + + from typing import Dict, Tuple, Sequence + + ConnectionOptions = Dict[str, str] + Address = Tuple[str, int] + Server = Tuple[Address, ConnectionOptions] + + def broadcast_message(message: str, servers: Sequence[Server]) -> None: + ... + + # The static type checker will treat the previous type signature as + # being exactly equivalent to this one. + def broadcast_message( + message: str, + servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None: + ... + +Note that ``None`` as a type hint is a special case and is replaced by +``type(None)``. + +.. _distinct: + +NewType +------- + +Use the :func:`NewType` helper function to create distinct types:: + + from typing import NewType + + UserId = NewType('UserId', int) + some_id = UserId(524313) + +The static type checker will treat the new type as if it were a subclass +of the original type. This is useful in helping catch logical errors:: + + def get_user_name(user_id: UserId) -> str: + ... + + # typechecks + user_a = get_user_name(UserId(42351)) + + # does not typecheck; an int is not a UserId + user_b = get_user_name(-1) + +You may still perform all ``int`` operations on a variable of type ``UserId``, +but the result will always be of type ``int``. This lets you pass in a +``UserId`` wherever an ``int`` might be expected, but will prevent you from +accidentally creating a ``UserId`` in an invalid way:: + + # 'output' is of type 'int', not 'UserId' + output = UserId(23413) + UserId(54341) + +Note that these checks are enforced only by the static type checker. At runtime, +the statement ``Derived = NewType('Derived', Base)`` will make ``Derived`` a +function that immediately returns whatever parameter you pass it. That means +the expression ``Derived(some_value)`` does not create a new class or introduce +any overhead beyond that of a regular function call. + +More precisely, the expression ``some_value is Derived(some_value)`` is always +true at runtime. + +This also means that it is not possible to create a subtype of ``Derived`` +since it is an identity function at runtime, not an actual type:: + + from typing import NewType + + UserId = NewType('UserId', int) + + # Fails at runtime and does not typecheck + class AdminUserId(UserId): pass + +However, it is possible to create a :func:`NewType` based on a 'derived' ``NewType``:: + + from typing import NewType + + UserId = NewType('UserId', int) + + ProUserId = NewType('ProUserId', UserId) + +and typechecking for ``ProUserId`` will work as expected. + +See :pep:`484` for more details. + +.. note:: + + Recall that the use of a type alias declares two types to be *equivalent* to + one another. Doing ``Alias = Original`` will make the static type checker + treat ``Alias`` as being *exactly equivalent* to ``Original`` in all cases. + This is useful when you want to simplify complex type signatures. + + In contrast, ``NewType`` declares one type to be a *subtype* of another. + Doing ``Derived = NewType('Derived', Original)`` will make the static type + checker treat ``Derived`` as a *subclass* of ``Original``, which means a + value of type ``Original`` cannot be used in places where a value of type + ``Derived`` is expected. This is useful when you want to prevent logic + errors with minimal runtime cost. + +.. versionadded:: 3.5.2 + +Callable +-------- + +Frameworks expecting callback functions of specific signatures might be +type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType]``. + +For example:: + + from typing import Callable + + def feeder(get_next_item: Callable[[], str]) -> None: + # Body + + def async_query(on_success: Callable[[int], None], + on_error: Callable[[int, Exception], None]) -> None: + # Body + +It is possible to declare the return type of a callable without specifying +the call signature by substituting a literal ellipsis +for the list of arguments in the type hint: ``Callable[..., ReturnType]``. + +.. _generics: + +Generics +-------- + +Since type information about objects kept in containers cannot be statically +inferred in a generic way, abstract base classes have been extended to support +subscription to denote expected types for container elements. + +:: + + from typing import Mapping, Sequence + + def notify_by_email(employees: Sequence[Employee], + overrides: Mapping[str, str]) -> None: ... + +Generics can be parameterized by using a new factory available in typing +called :class:`TypeVar`. + +:: + + from typing import Sequence, TypeVar + + T = TypeVar('T') # Declare type variable + + def first(l: Sequence[T]) -> T: # Generic function + return l[0] + + +User-defined generic types +-------------------------- + +A user-defined class can be defined as a generic class. + +:: + + from typing import TypeVar, Generic + from logging import Logger + + T = TypeVar('T') + + class LoggedVar(Generic[T]): + def __init__(self, value: T, name: str, logger: Logger) -> None: + self.name = name + self.logger = logger + self.value = value + + def set(self, new: T) -> None: + self.log('Set ' + repr(self.value)) + self.value = new + + def get(self) -> T: + self.log('Get ' + repr(self.value)) + return self.value + + def log(self, message: str) -> None: + self.logger.info('%s: %s', self.name, message) + +``Generic[T]`` as a base class defines that the class ``LoggedVar`` takes a +single type parameter ``T`` . This also makes ``T`` valid as a type within the +class body. + +The :class:`Generic` base class defines :meth:`__class_getitem__` so that +``LoggedVar[t]`` is valid as a type:: + + from typing import Iterable + + def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None: + for var in vars: + var.set(0) + +A generic type can have any number of type variables, and type variables may +be constrained:: + + from typing import TypeVar, Generic + ... + + T = TypeVar('T') + S = TypeVar('S', int, str) + + class StrangePair(Generic[T, S]): + ... + +Each type variable argument to :class:`Generic` must be distinct. +This is thus invalid:: + + from typing import TypeVar, Generic + ... + + T = TypeVar('T') + + class Pair(Generic[T, T]): # INVALID + ... + +You can use multiple inheritance with :class:`Generic`:: + + from typing import TypeVar, Generic, Sized + + T = TypeVar('T') + + class LinkedList(Sized, Generic[T]): + ... + +When inheriting from generic classes, some type variables could be fixed:: + + from typing import TypeVar, Mapping + + T = TypeVar('T') + + class MyDict(Mapping[str, T]): + ... + +In this case ``MyDict`` has a single parameter, ``T``. + +Using a generic class without specifying type parameters assumes +:data:`Any` for each position. In the following example, ``MyIterable`` is +not generic but implicitly inherits from ``Iterable[Any]``:: + + from typing import Iterable + + class MyIterable(Iterable): # Same as Iterable[Any] + +User defined generic type aliases are also supported. Examples:: + + from typing import TypeVar, Iterable, Tuple, Union + S = TypeVar('S') + Response = Union[Iterable[S], int] + + # Return type here is same as Union[Iterable[str], int] + def response(query: str) -> Response[str]: + ... + + T = TypeVar('T', int, float, complex) + Vec = Iterable[Tuple[T, T]] + + def inproduct(v: Vec[T]) -> T: # Same as Iterable[Tuple[T, T]] + return sum(x*y for x, y in v) + +.. versionchanged:: 3.7 + :class:`Generic` no longer has a custom metaclass. + +A user-defined generic class can have ABCs as base classes without a metaclass +conflict. Generic metaclasses are not supported. The outcome of parameterizing +generics is cached, and most types in the typing module are hashable and +comparable for equality. + + +The :data:`Any` type +-------------------- + +A special kind of type is :data:`Any`. A static type checker will treat +every type as being compatible with :data:`Any` and :data:`Any` as being +compatible with every type. + +This means that it is possible to perform any operation or method call on a +value of type on :data:`Any` and assign it to any variable:: + + from typing import Any + + a = None # type: Any + a = [] # OK + a = 2 # OK + + s = '' # type: str + s = a # OK + + def foo(item: Any) -> int: + # Typechecks; 'item' could be any type, + # and that type might have a 'bar' method + item.bar() + ... + +Notice that no typechecking is performed when assigning a value of type +:data:`Any` to a more precise type. For example, the static type checker did +not report an error when assigning ``a`` to ``s`` even though ``s`` was +declared to be of type :class:`str` and receives an :class:`int` value at +runtime! + +Furthermore, all functions without a return type or parameter types will +implicitly default to using :data:`Any`:: + + def legacy_parser(text): + ... + return data + + # A static type checker will treat the above + # as having the same signature as: + def legacy_parser(text: Any) -> Any: + ... + return data + +This behavior allows :data:`Any` to be used as an *escape hatch* when you +need to mix dynamically and statically typed code. + +Contrast the behavior of :data:`Any` with the behavior of :class:`object`. +Similar to :data:`Any`, every type is a subtype of :class:`object`. However, +unlike :data:`Any`, the reverse is not true: :class:`object` is *not* a +subtype of every other type. + +That means when the type of a value is :class:`object`, a type checker will +reject almost all operations on it, and assigning it to a variable (or using +it as a return value) of a more specialized type is a type error. For example:: + + def hash_a(item: object) -> int: + # Fails; an object does not have a 'magic' method. + item.magic() + ... + + def hash_b(item: Any) -> int: + # Typechecks + item.magic() + ... + + # Typechecks, since ints and strs are subclasses of object + hash_a(42) + hash_a("foo") + + # Typechecks, since Any is compatible with all types + hash_b(42) + hash_b("foo") + +Use :class:`object` to indicate that a value could be any type in a typesafe +manner. Use :data:`Any` to indicate that a value is dynamically typed. + + +Nominal vs structural subtyping +------------------------------- + +Initially :pep:`484` defined Python static type system as using +*nominal subtyping*. This means that a class ``A`` is allowed where +a class ``B`` is expected if and only if ``A`` is a subclass of ``B``. + +This requirement previously also applied to abstract base classes, such as +:class:`Iterable`. The problem with this approach is that a class had +to be explicitly marked to support them, which is unpythonic and unlike +what one would normally do in idiomatic dynamically typed Python code. +For example, this conforms to the :pep:`484`:: + + from typing import Sized, Iterable, Iterator + + class Bucket(Sized, Iterable[int]): + ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + +:pep:`544` allows to solve this problem by allowing users to write +the above code without explicit base classes in the class definition, +allowing ``Bucket`` to be implicitly considered a subtype of both ``Sized`` +and ``Iterable[int]`` by static type checkers. This is known as +*structural subtyping* (or static duck-typing):: + + from typing import Iterator, Iterable + + class Bucket: # Note: no base classes + ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + + def collect(items: Iterable[int]) -> int: ... + result = collect(Bucket()) # Passes type check + +Moreover, by subclassing a special class :class:`Protocol`, a user +can define new custom protocols to fully enjoy structural subtyping +(see examples below). + + +Classes, functions, and decorators +---------------------------------- + +The module defines the following classes, functions and decorators: + +.. class:: TypeVar + + Type variable. + + Usage:: + + T = TypeVar('T') # Can be anything + A = TypeVar('A', str, bytes) # Must be str or bytes + + Type variables exist primarily for the benefit of static type + checkers. They serve as the parameters for generic types as well + as for generic function definitions. See class Generic for more + information on generic types. Generic functions work as follows:: + + def repeat(x: T, n: int) -> Sequence[T]: + """Return a list containing n references to x.""" + return [x]*n + + def longest(x: A, y: A) -> A: + """Return the longest of two strings.""" + return x if len(x) >= len(y) else y + + The latter example's signature is essentially the overloading + of ``(str, str) -> str`` and ``(bytes, bytes) -> bytes``. Also note + that if the arguments are instances of some subclass of :class:`str`, + the return type is still plain :class:`str`. + + At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`. In general, + :func:`isinstance` and :func:`issubclass` should not be used with types. + + Type variables may be marked covariant or contravariant by passing + ``covariant=True`` or ``contravariant=True``. See :pep:`484` for more + details. By default type variables are invariant. Alternatively, + a type variable may specify an upper bound using ``bound=``. + This means that an actual type substituted (explicitly or implicitly) + for the type variable must be a subclass of the boundary type, + see :pep:`484`. + +.. class:: Generic + + Abstract base class for generic types. + + A generic type is typically declared by inheriting from an + instantiation of this class with one or more type variables. + For example, a generic mapping type might be defined as:: + + class Mapping(Generic[KT, VT]): + def __getitem__(self, key: KT) -> VT: + ... + # Etc. + + This class can then be used as follows:: + + X = TypeVar('X') + Y = TypeVar('Y') + + def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y: + try: + return mapping[key] + except KeyError: + return default + +.. class:: Protocol(Generic) + + Base class for protocol classes. Protocol classes are defined like this:: + + class Proto(Protocol): + def meth(self) -> int: + ... + + Such classes are primarily used with static type checkers that recognize + structural subtyping (static duck-typing), for example:: + + class C: + def meth(self) -> int: + return 0 + + def func(x: Proto) -> int: + return x.meth() + + func(C()) # Passes static type check + + See :pep:`544` for details. Protocol classes decorated with + :func:`runtime_checkable` (described later) act as simple-minded runtime + protocols that check only the presence of given attributes, ignoring their + type signatures. + + Protocol classes can be generic, for example:: + + class GenProto(Protocol[T]): + def meth(self) -> T: + ... + + .. versionadded:: 3.8 + +.. class:: Type(Generic[CT_co]) + + A variable annotated with ``C`` may accept a value of type ``C``. In + contrast, a variable annotated with ``Type[C]`` may accept values that are + classes themselves -- specifically, it will accept the *class object* of + ``C``. For example:: + + a = 3 # Has type 'int' + b = int # Has type 'Type[int]' + c = type(a) # Also has type 'Type[int]' + + Note that ``Type[C]`` is covariant:: + + class User: ... + class BasicUser(User): ... + class ProUser(User): ... + class TeamUser(User): ... + + # Accepts User, BasicUser, ProUser, TeamUser, ... + def make_new_user(user_class: Type[User]) -> User: + # ... + return user_class() + + The fact that ``Type[C]`` is covariant implies that all subclasses of + ``C`` should implement the same constructor signature and class method + signatures as ``C``. The type checker should flag violations of this, + but should also allow constructor calls in subclasses that match the + constructor calls in the indicated base class. How the type checker is + required to handle this particular case may change in future revisions of + :pep:`484`. + + The only legal parameters for :class:`Type` are classes, :data:`Any`, + :ref:`type variables `, and unions of any of these types. + For example:: + + def new_non_team_user(user_class: Type[Union[BaseUser, ProUser]]): ... + + ``Type[Any]`` is equivalent to ``Type`` which in turn is equivalent + to ``type``, which is the root of Python's metaclass hierarchy. + + .. versionadded:: 3.5.2 + +.. class:: Iterable(Generic[T_co]) + + A generic version of :class:`collections.abc.Iterable`. + +.. class:: Iterator(Iterable[T_co]) + + A generic version of :class:`collections.abc.Iterator`. + +.. class:: Reversible(Iterable[T_co]) + + A generic version of :class:`collections.abc.Reversible`. + +.. class:: SupportsInt + + An ABC with one abstract method ``__int__``. + +.. class:: SupportsFloat + + An ABC with one abstract method ``__float__``. + +.. class:: SupportsComplex + + An ABC with one abstract method ``__complex__``. + +.. class:: SupportsBytes + + An ABC with one abstract method ``__bytes__``. + +.. class:: SupportsIndex + + An ABC with one abstract method ``__index__``. + + .. versionadded:: 3.8 + +.. class:: SupportsAbs + + An ABC with one abstract method ``__abs__`` that is covariant + in its return type. + +.. class:: SupportsRound + + An ABC with one abstract method ``__round__`` + that is covariant in its return type. + +.. class:: Container(Generic[T_co]) + + A generic version of :class:`collections.abc.Container`. + +.. class:: Hashable + + An alias to :class:`collections.abc.Hashable` + +.. class:: Sized + + An alias to :class:`collections.abc.Sized` + +.. class:: Collection(Sized, Iterable[T_co], Container[T_co]) + + A generic version of :class:`collections.abc.Collection` + + .. versionadded:: 3.6.0 + +.. class:: AbstractSet(Sized, Collection[T_co]) + + A generic version of :class:`collections.abc.Set`. + +.. class:: MutableSet(AbstractSet[T]) + + A generic version of :class:`collections.abc.MutableSet`. + +.. class:: Mapping(Sized, Collection[KT], Generic[VT_co]) + + A generic version of :class:`collections.abc.Mapping`. + This type can be used as follows:: + + def get_position_in_index(word_list: Mapping[str, int], word: str) -> int: + return word_list[word] + +.. class:: MutableMapping(Mapping[KT, VT]) + + A generic version of :class:`collections.abc.MutableMapping`. + +.. class:: Sequence(Reversible[T_co], Collection[T_co]) + + A generic version of :class:`collections.abc.Sequence`. + +.. class:: MutableSequence(Sequence[T]) + + A generic version of :class:`collections.abc.MutableSequence`. + +.. class:: ByteString(Sequence[int]) + + A generic version of :class:`collections.abc.ByteString`. + + This type represents the types :class:`bytes`, :class:`bytearray`, + and :class:`memoryview`. + + As a shorthand for this type, :class:`bytes` can be used to + annotate arguments of any of the types mentioned above. + +.. class:: Deque(deque, MutableSequence[T]) + + A generic version of :class:`collections.deque`. + + .. versionadded:: 3.5.4 + .. versionadded:: 3.6.1 + +.. class:: List(list, MutableSequence[T]) + + Generic version of :class:`list`. + Useful for annotating return types. To annotate arguments it is preferred + to use an abstract collection type such as :class:`Sequence` or + :class:`Iterable`. + + This type may be used as follows:: + + T = TypeVar('T', int, float) + + def vec2(x: T, y: T) -> List[T]: + return [x, y] + + def keep_positives(vector: Sequence[T]) -> List[T]: + return [item for item in vector if item > 0] + +.. class:: Set(set, MutableSet[T]) + + A generic version of :class:`builtins.set `. + Useful for annotating return types. To annotate arguments it is preferred + to use an abstract collection type such as :class:`AbstractSet`. + +.. class:: FrozenSet(frozenset, AbstractSet[T_co]) + + A generic version of :class:`builtins.frozenset `. + +.. class:: MappingView(Sized, Iterable[T_co]) + + A generic version of :class:`collections.abc.MappingView`. + +.. class:: KeysView(MappingView[KT_co], AbstractSet[KT_co]) + + A generic version of :class:`collections.abc.KeysView`. + +.. class:: ItemsView(MappingView, Generic[KT_co, VT_co]) + + A generic version of :class:`collections.abc.ItemsView`. + +.. class:: ValuesView(MappingView[VT_co]) + + A generic version of :class:`collections.abc.ValuesView`. + +.. class:: Awaitable(Generic[T_co]) + + A generic version of :class:`collections.abc.Awaitable`. + + .. versionadded:: 3.5.2 + +.. class:: Coroutine(Awaitable[V_co], Generic[T_co T_contra, V_co]) + + A generic version of :class:`collections.abc.Coroutine`. + The variance and order of type variables + correspond to those of :class:`Generator`, for example:: + + from typing import List, Coroutine + c = None # type: Coroutine[List[str], str, int] + ... + x = c.send('hi') # type: List[str] + async def bar() -> None: + x = await c # type: int + + .. versionadded:: 3.5.3 + +.. class:: AsyncIterable(Generic[T_co]) + + A generic version of :class:`collections.abc.AsyncIterable`. + + .. versionadded:: 3.5.2 + +.. class:: AsyncIterator(AsyncIterable[T_co]) + + A generic version of :class:`collections.abc.AsyncIterator`. + + .. versionadded:: 3.5.2 + +.. class:: ContextManager(Generic[T_co]) + + A generic version of :class:`contextlib.AbstractContextManager`. + + .. versionadded:: 3.5.4 + .. versionadded:: 3.6.0 + +.. class:: AsyncContextManager(Generic[T_co]) + + A generic version of :class:`contextlib.AbstractAsyncContextManager`. + + .. versionadded:: 3.5.4 + .. versionadded:: 3.6.2 + +.. class:: Dict(dict, MutableMapping[KT, VT]) + + A generic version of :class:`dict`. + Useful for annotating return types. To annotate arguments it is preferred + to use an abstract collection type such as :class:`Mapping`. + + This type can be used as follows:: + + def count_words(text: str) -> Dict[str, int]: + ... + +.. class:: DefaultDict(collections.defaultdict, MutableMapping[KT, VT]) + + A generic version of :class:`collections.defaultdict`. + + .. versionadded:: 3.5.2 + +.. class:: OrderedDict(collections.OrderedDict, MutableMapping[KT, VT]) + + A generic version of :class:`collections.OrderedDict`. + + .. versionadded:: 3.7.2 + +.. class:: Counter(collections.Counter, Dict[T, int]) + + A generic version of :class:`collections.Counter`. + + .. versionadded:: 3.5.4 + .. versionadded:: 3.6.1 + +.. class:: ChainMap(collections.ChainMap, MutableMapping[KT, VT]) + + A generic version of :class:`collections.ChainMap`. + + .. versionadded:: 3.5.4 + .. versionadded:: 3.6.1 + +.. class:: Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]) + + A generator can be annotated by the generic type + ``Generator[YieldType, SendType, ReturnType]``. For example:: + + def echo_round() -> Generator[int, float, str]: + sent = yield 0 + while sent >= 0: + sent = yield round(sent) + return 'Done' + + Note that unlike many other generics in the typing module, the ``SendType`` + of :class:`Generator` behaves contravariantly, not covariantly or + invariantly. + + If your generator will only yield values, set the ``SendType`` and + ``ReturnType`` to ``None``:: + + def infinite_stream(start: int) -> Generator[int, None, None]: + while True: + yield start + start += 1 + + Alternatively, annotate your generator as having a return type of + either ``Iterable[YieldType]`` or ``Iterator[YieldType]``:: + + def infinite_stream(start: int) -> Iterator[int]: + while True: + yield start + start += 1 + +.. class:: AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra]) + + An async generator can be annotated by the generic type + ``AsyncGenerator[YieldType, SendType]``. For example:: + + async def echo_round() -> AsyncGenerator[int, float]: + sent = yield 0 + while sent >= 0.0: + rounded = await round(sent) + sent = yield rounded + + Unlike normal generators, async generators cannot return a value, so there + is no ``ReturnType`` type parameter. As with :class:`Generator`, the + ``SendType`` behaves contravariantly. + + If your generator will only yield values, set the ``SendType`` to + ``None``:: + + async def infinite_stream(start: int) -> AsyncGenerator[int, None]: + while True: + yield start + start = await increment(start) + + Alternatively, annotate your generator as having a return type of + either ``AsyncIterable[YieldType]`` or ``AsyncIterator[YieldType]``:: + + async def infinite_stream(start: int) -> AsyncIterator[int]: + while True: + yield start + start = await increment(start) + + .. versionadded:: 3.6.1 + +.. class:: Text + + ``Text`` is an alias for ``str``. It is provided to supply a forward + compatible path for Python 2 code: in Python 2, ``Text`` is an alias for + ``unicode``. + + Use ``Text`` to indicate that a value must contain a unicode string in + a manner that is compatible with both Python 2 and Python 3:: + + def add_unicode_checkmark(text: Text) -> Text: + return text + u' \u2713' + + .. versionadded:: 3.5.2 + +.. class:: IO + TextIO + BinaryIO + + Generic type ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])`` + and ``BinaryIO(IO[bytes])`` + represent the types of I/O streams such as returned by + :func:`open`. + +.. class:: Pattern + Match + + These type aliases + correspond to the return types from :func:`re.compile` and + :func:`re.match`. These types (and the corresponding functions) + are generic in ``AnyStr`` and can be made specific by writing + ``Pattern[str]``, ``Pattern[bytes]``, ``Match[str]``, or + ``Match[bytes]``. + +.. class:: NamedTuple + + Typed version of :func:`collections.namedtuple`. + + Usage:: + + class Employee(NamedTuple): + name: str + id: int + + This is equivalent to:: + + Employee = collections.namedtuple('Employee', ['name', 'id']) + + To give a field a default value, you can assign to it in the class body:: + + class Employee(NamedTuple): + name: str + id: int = 3 + + employee = Employee('Guido') + assert employee.id == 3 + + Fields with a default value must come after any fields without a default. + + The resulting class has an extra attribute ``__annotations__`` giving a + dict that maps the field names to the field types. (The field names are in + the ``_fields`` attribute and the default values are in the + ``_field_defaults`` attribute both of which are part of the namedtuple + API.) + + ``NamedTuple`` subclasses can also have docstrings and methods:: + + class Employee(NamedTuple): + """Represents an employee.""" + name: str + id: int = 3 + + def __repr__(self) -> str: + return f'' + + Backward-compatible usage:: + + Employee = NamedTuple('Employee', [('name', str), ('id', int)]) + + .. versionchanged:: 3.6 + Added support for :pep:`526` variable annotation syntax. + + .. versionchanged:: 3.6.1 + Added support for default values, methods, and docstrings. + + .. versionchanged:: 3.8 + The ``_field_types`` and ``__annotations__`` attributes are + now regular dictionaries instead of instances of ``OrderedDict``. + + .. versionchanged:: 3.9 + Removed the ``_field_types`` attribute in favor of the more + standard ``__annotations__`` attribute which has the same information. + + +.. class:: TypedDict(dict) + + A simple typed namespace. At runtime it is equivalent to + a plain :class:`dict`. + + ``TypedDict`` creates a dictionary type that expects all of its + instances to have a certain set of keys, where each key is + associated with a value of a consistent type. This expectation + is not checked at runtime but is only enforced by type checkers. + Usage:: + + class Point2D(TypedDict): + x: int + y: int + label: str + + a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + + assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + + The type info for introspection can be accessed via ``Point2D.__annotations__`` + and ``Point2D.__total__``. To allow using this feature with older versions + of Python that do not support :pep:`526`, ``TypedDict`` supports two additional + equivalent syntactic forms:: + + Point2D = TypedDict('Point2D', x=int, y=int, label=str) + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + By default, all keys must be present in a TypedDict. It is possible + to override this by specifying totality. + Usage:: + + class point2D(TypedDict, total=False): + x: int + y: int + + This means that a point2D TypedDict can have any of the keys omitted. A type + checker is only expected to support a literal False or True as the value of + the total argument. True is the default, and makes all items defined in the + class body be required. + + See :pep:`589` for more examples and detailed rules of using ``TypedDict``. + + .. versionadded:: 3.8 + +.. class:: ForwardRef + + A class used for internal typing representation of string forward references. + For example, ``List["SomeClass"]`` is implicitly transformed into + ``List[ForwardRef("SomeClass")]``. This class should not be instantiated by + a user, but may be used by introspection tools. + +.. function:: NewType(typ) + + A helper function to indicate a distinct types to a typechecker, + see :ref:`distinct`. At runtime it returns a function that returns + its argument. Usage:: + + UserId = NewType('UserId', int) + first_user = UserId(1) + + .. versionadded:: 3.5.2 + +.. function:: cast(typ, val) + + Cast a value to a type. + + This returns the value unchanged. To the type checker this + signals that the return value has the designated type, but at + runtime we intentionally don't check anything (we want this + to be as fast as possible). + +.. function:: get_type_hints(obj, globalns=None, localns=None, include_extras=False) + + Return a dictionary containing type hints for a function, method, module + or class object. + + This is often the same as ``obj.__annotations__``. In addition, + forward references encoded as string literals are handled by evaluating + them in ``globals`` and ``locals`` namespaces. If necessary, + ``Optional[t]`` is added for function and method annotations if a default + value equal to ``None`` is set. For a class ``C``, return + a dictionary constructed by merging all the ``__annotations__`` along + ``C.__mro__`` in reverse order. + + The function recursively replaces all ``Annotated[T, ...]`` with ``T``, + unless ``include_extras`` is set to ``True`` (see :class:`Annotated` for + more information). For example:: + + class Student(NamedTuple): + name: Annotated[str, 'some marker'] + + get_type_hints(Student) == {'name': str} + get_type_hints(Student, include_extras=False) == {'name': str} + get_type_hints(Student, include_extras=True) == { + 'name': Annotated[str, 'some marker'] + } + + .. versionchanged:: 3.9 + Added ``include_extras`` parameter as part of :pep:`593`. + +.. function:: get_origin(tp) +.. function:: get_args(tp) + + Provide basic introspection for generic types and special typing forms. + + For a typing object of the form ``X[Y, Z, ...]`` these functions return + ``X`` and ``(Y, Z, ...)``. If ``X`` is a generic alias for a builtin or + :mod:`collections` class, it gets normalized to the original class. + For unsupported objects return ``None`` and ``()`` correspondingly. + Examples:: + + assert get_origin(Dict[str, int]) is dict + assert get_args(Dict[int, str]) == (int, str) + + assert get_origin(Union[int, str]) is Union + assert get_args(Union[int, str]) == (int, str) + + .. versionadded:: 3.8 + +.. decorator:: overload + + The ``@overload`` decorator allows describing functions and methods + that support multiple different combinations of argument types. A series + of ``@overload``-decorated definitions must be followed by exactly one + non-``@overload``-decorated definition (for the same function/method). + The ``@overload``-decorated definitions are for the benefit of the + type checker only, since they will be overwritten by the + non-``@overload``-decorated definition, while the latter is used at + runtime but should be ignored by a type checker. At runtime, calling + a ``@overload``-decorated function directly will raise + :exc:`NotImplementedError`. An example of overload that gives a more + precise type than can be expressed using a union or a type variable:: + + @overload + def process(response: None) -> None: + ... + @overload + def process(response: int) -> Tuple[int, str]: + ... + @overload + def process(response: bytes) -> str: + ... + def process(response): + + + See :pep:`484` for details and comparison with other typing semantics. + +.. decorator:: final + + A decorator to indicate to type checkers that the decorated method + cannot be overridden, and the decorated class cannot be subclassed. + For example:: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. See :pep:`591` for + more details. + + .. versionadded:: 3.8 + +.. decorator:: no_type_check + + Decorator to indicate that annotations are not type hints. + + This works as class or function :term:`decorator`. With a class, it + applies recursively to all methods defined in that class (but not + to methods defined in its superclasses or subclasses). + + This mutates the function(s) in place. + +.. decorator:: no_type_check_decorator + + Decorator to give another decorator the :func:`no_type_check` effect. + + This wraps the decorator with something that wraps the decorated + function in :func:`no_type_check`. + +.. decorator:: type_check_only + + Decorator to mark a class or function to be unavailable at runtime. + + This decorator is itself not available at runtime. It is mainly + intended to mark classes that are defined in type stub files if + an implementation returns an instance of a private class:: + + @type_check_only + class Response: # private or not available at runtime + code: int + def get_header(self, name: str) -> str: ... + + def fetch_response() -> Response: ... + + Note that returning instances of private classes is not recommended. + It is usually preferable to make such classes public. + +.. decorator:: runtime_checkable + + Mark a protocol class as a runtime protocol. + + Such a protocol can be used with :func:`isinstance` and :func:`issubclass`. + This raises :exc:`TypeError` when applied to a non-protocol class. This + allows a simple-minded structural check, very similar to "one trick ponies" + in :mod:`collections.abc` such as :class:`Iterable`. For example:: + + @runtime_checkable + class Closable(Protocol): + def close(self): ... + + assert isinstance(open('/some/file'), Closable) + + **Warning:** this will check only the presence of the required methods, + not their type signatures! + + .. versionadded:: 3.8 + +.. data:: Any + + Special type indicating an unconstrained type. + + * Every type is compatible with :data:`Any`. + * :data:`Any` is compatible with every type. + +.. data:: NoReturn + + Special type indicating that a function never returns. + For example:: + + from typing import NoReturn + + def stop() -> NoReturn: + raise RuntimeError('no way') + + .. versionadded:: 3.5.4 + .. versionadded:: 3.6.2 + +.. data:: Union + + Union type; ``Union[X, Y]`` means either X or Y. + + To define a union, use e.g. ``Union[int, str]``. Details: + + * The arguments must be types and there must be at least one. + + * Unions of unions are flattened, e.g.:: + + Union[Union[int, str], float] == Union[int, str, float] + + * Unions of a single argument vanish, e.g.:: + + Union[int] == int # The constructor actually returns int + + * Redundant arguments are skipped, e.g.:: + + Union[int, str, int] == Union[int, str] + + * When comparing unions, the argument order is ignored, e.g.:: + + Union[int, str] == Union[str, int] + + * You cannot subclass or instantiate a union. + + * You cannot write ``Union[X][Y]``. + + * You can use ``Optional[X]`` as a shorthand for ``Union[X, None]``. + + .. versionchanged:: 3.7 + Don't remove explicit subclasses from unions at runtime. + +.. data:: Optional + + Optional type. + + ``Optional[X]`` is equivalent to ``Union[X, None]``. + + Note that this is not the same concept as an optional argument, + which is one that has a default. An optional argument with a + default does not require the ``Optional`` qualifier on its type + annotation just because it is optional. For example:: + + def foo(arg: int = 0) -> None: + ... + + On the other hand, if an explicit value of ``None`` is allowed, the + use of ``Optional`` is appropriate, whether the argument is optional + or not. For example:: + + def foo(arg: Optional[int] = None) -> None: + ... + +.. data:: Tuple + + Tuple type; ``Tuple[X, Y]`` is the type of a tuple of two items + with the first item of type X and the second of type Y. The type of + the empty tuple can be written as ``Tuple[()]``. + + Example: ``Tuple[T1, T2]`` is a tuple of two elements corresponding + to type variables T1 and T2. ``Tuple[int, float, str]`` is a tuple + of an int, a float and a string. + + To specify a variable-length tuple of homogeneous type, + use literal ellipsis, e.g. ``Tuple[int, ...]``. A plain :data:`Tuple` + is equivalent to ``Tuple[Any, ...]``, and in turn to :class:`tuple`. + +.. data:: Callable + + Callable type; ``Callable[[int], str]`` is a function of (int) -> str. + + The subscription syntax must always be used with exactly two + values: the argument list and the return type. The argument list + must be a list of types or an ellipsis; the return type must be + a single type. + + There is no syntax to indicate optional or keyword arguments; + such function types are rarely used as callback types. + ``Callable[..., ReturnType]`` (literal ellipsis) can be used to + type hint a callable taking any number of arguments and returning + ``ReturnType``. A plain :data:`Callable` is equivalent to + ``Callable[..., Any]``, and in turn to + :class:`collections.abc.Callable`. + +.. data:: Literal + + A type that can be used to indicate to type checkers that the + corresponding variable or function parameter has a value equivalent to + the provided literal (or one of several literals). For example:: + + def validate_simple(data: Any) -> Literal[True]: # always returns True + ... + + MODE = Literal['r', 'rb', 'w', 'wb'] + def open_helper(file: str, mode: MODE) -> str: + ... + + open_helper('/some/path', 'r') # Passes type check + open_helper('/other/path', 'typo') # Error in type checker + + ``Literal[...]`` cannot be subclassed. At runtime, an arbitrary value + is allowed as type argument to ``Literal[...]``, but type checkers may + impose restrictions. See :pep:`586` for more details about literal types. + + .. versionadded:: 3.8 + +.. data:: ClassVar + + Special type construct to mark class variables. + + As introduced in :pep:`526`, a variable annotation wrapped in ClassVar + indicates that a given attribute is intended to be used as a class variable + and should not be set on instances of that class. Usage:: + + class Starship: + stats: ClassVar[Dict[str, int]] = {} # class variable + damage: int = 10 # instance variable + + :data:`ClassVar` accepts only types and cannot be further subscribed. + + :data:`ClassVar` is not a class itself, and should not + be used with :func:`isinstance` or :func:`issubclass`. + :data:`ClassVar` does not change Python runtime behavior, but + it can be used by third-party type checkers. For example, a type checker + might flag the following code as an error:: + + enterprise_d = Starship(3000) + enterprise_d.stats = {} # Error, setting class variable on instance + Starship.stats = {} # This is OK + + .. versionadded:: 3.5.3 + +.. data:: Final + + A special typing construct to indicate to type checkers that a name + cannot be re-assigned or overridden in a subclass. For example:: + + MAX_SIZE: Final = 9000 + MAX_SIZE += 1 # Error reported by type checker + + class Connection: + TIMEOUT: Final[int] = 10 + + class FastConnector(Connection): + TIMEOUT = 1 # Error reported by type checker + + There is no runtime checking of these properties. See :pep:`591` for + more details. + + .. versionadded:: 3.8 + +.. data:: AnyStr + + ``AnyStr`` is a type variable defined as + ``AnyStr = TypeVar('AnyStr', str, bytes)``. + + It is meant to be used for functions that may accept any kind of string + without allowing different kinds of strings to mix. For example:: + + def concat(a: AnyStr, b: AnyStr) -> AnyStr: + return a + b + + concat(u"foo", u"bar") # Ok, output has type 'unicode' + concat(b"foo", b"bar") # Ok, output has type 'bytes' + concat(u"foo", b"bar") # Error, cannot mix unicode and bytes + +.. data:: TYPE_CHECKING + + A special constant that is assumed to be ``True`` by 3rd party static + type checkers. It is ``False`` at runtime. Usage:: + + if TYPE_CHECKING: + import expensive_mod + + def fun(arg: 'expensive_mod.SomeType') -> None: + local_var: expensive_mod.AnotherType = other_fun() + + Note that the first type annotation must be enclosed in quotes, making it a + "forward reference", to hide the ``expensive_mod`` reference from the + interpreter runtime. Type annotations for local variables are not + evaluated, so the second annotation does not need to be enclosed in quotes. + + .. versionadded:: 3.5.2 + +.. data:: Annotated + + A type, introduced in :pep:`593` (``Flexible function and variable + annotations``), to decorate existing types with context-specific metadata + (possibly multiple pieces of it, as ``Annotated`` is variadic). + Specifically, a type ``T`` can be annotated with metadata ``x`` via the + typehint ``Annotated[T, x]``. This metadata can be used for either static + analysis or at runtime. If a library (or tool) encounters a typehint + ``Annotated[T, x]`` and has no special logic for metadata ``x``, it + should ignore it and simply treat the type as ``T``. Unlike the + ``no_type_check`` functionality that currently exists in the ``typing`` + module which completely disables typechecking annotations on a function + or a class, the ``Annotated`` type allows for both static typechecking + of ``T`` (e.g., via mypy or Pyre, which can safely ignore ``x``) + together with runtime access to ``x`` within a specific application. + + Ultimately, the responsibility of how to interpret the annotations (if + at all) is the responsibility of the tool or library encountering the + ``Annotated`` type. A tool or library encountering an ``Annotated`` type + can scan through the annotations to determine if they are of interest + (e.g., using ``isinstance()``). + + When a tool or a library does not support annotations or encounters an + unknown annotation it should just ignore it and treat annotated type as + the underlying type. + + It's up to the tool consuming the annotations to decide whether the + client is allowed to have several annotations on one type and how to + merge those annotations. + + Since the ``Annotated`` type allows you to put several annotations of + the same (or different) type(s) on any node, the tools or libraries + consuming those annotations are in charge of dealing with potential + duplicates. For example, if you are doing value range analysis you might + allow this:: + + T1 = Annotated[int, ValueRange(-10, 5)] + T2 = Annotated[T1, ValueRange(-20, 3)] + + Passing ``include_extras=True`` to :func:`get_type_hints` lets one + access the extra annotations at runtime. + + The details of the syntax: + + * The first argument to ``Annotated`` must be a valid type + + * Multiple type annotations are supported (``Annotated`` supports variadic + arguments):: + + Annotated[int, ValueRange(3, 10), ctype("char")] + + * ``Annotated`` must be called with at least two arguments ( + ``Annotated[int]`` is not valid) + + * The order of the annotations is preserved and matters for equality + checks:: + + Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[ + int, ctype("char"), ValueRange(3, 10) + ] + + * Nested ``Annotated`` types are flattened, with metadata ordered + starting with the innermost annotation:: + + Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[ + int, ValueRange(3, 10), ctype("char") + ] + + * Duplicated annotations are not removed:: + + Annotated[int, ValueRange(3, 10)] != Annotated[ + int, ValueRange(3, 10), ValueRange(3, 10) + ] + + * ``Annotated`` can be used with nested and generic aliases:: + + T = TypeVar('T') + Vec = Annotated[List[Tuple[T, T]], MaxLen(10)] + V = Vec[int] + + V == Annotated[List[Tuple[int, int]], MaxLen(10)] + + .. versionadded:: 3.9 diff --git a/cpython_2/environment/repo/Doc/library/undoc.rst b/cpython_2/environment/repo/Doc/library/undoc.rst new file mode 100644 index 0000000000000000000000000000000000000000..2444080d6b9d90c2eade86f18f93db9166d994f7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/undoc.rst @@ -0,0 +1,26 @@ +.. _undoc: + +******************** +Undocumented Modules +******************** + +Here's a quick listing of modules that are currently undocumented, but that +should be documented. Feel free to contribute documentation for them! (Send +via email to docs@python.org.) + +The idea and original contents for this chapter were taken from a posting by +Fredrik Lundh; the specific contents of this chapter have been substantially +revised. + + +Platform specific modules +========================= + +These modules are used to implement the :mod:`os.path` module, and are not +documented beyond this mention. There's little need to document these. + +:mod:`ntpath` + --- Implementation of :mod:`os.path` on Win32 and Win64 platforms. + +:mod:`posixpath` + --- Implementation of :mod:`os.path` on POSIX. diff --git a/cpython_2/environment/repo/Doc/library/unicodedata.rst b/cpython_2/environment/repo/Doc/library/unicodedata.rst new file mode 100644 index 0000000000000000000000000000000000000000..dade3f265b56a7de7aa09a22a8f36f45e4426292 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/unicodedata.rst @@ -0,0 +1,180 @@ +:mod:`unicodedata` --- Unicode Database +======================================= + +.. module:: unicodedata + :synopsis: Access the Unicode Database. + +.. moduleauthor:: Marc-André Lemburg +.. sectionauthor:: Marc-André Lemburg +.. sectionauthor:: Martin v. Löwis + +.. index:: + single: Unicode + single: character + pair: Unicode; database + +-------------- + +This module provides access to the Unicode Character Database (UCD) which +defines character properties for all Unicode characters. The data contained in +this database is compiled from the `UCD version 13.0.0 +`_. + +The module uses the same names and symbols as defined by Unicode +Standard Annex #44, `"Unicode Character Database" +`_. It defines the +following functions: + + +.. function:: lookup(name) + + Look up character by name. If a character with the given name is found, return + the corresponding character. If not found, :exc:`KeyError` is raised. + + .. versionchanged:: 3.3 + Support for name aliases [#]_ and named sequences [#]_ has been added. + + +.. function:: name(chr[, default]) + + Returns the name assigned to the character *chr* as a string. If no + name is defined, *default* is returned, or, if not given, :exc:`ValueError` is + raised. + + +.. function:: decimal(chr[, default]) + + Returns the decimal value assigned to the character *chr* as integer. + If no such value is defined, *default* is returned, or, if not given, + :exc:`ValueError` is raised. + + +.. function:: digit(chr[, default]) + + Returns the digit value assigned to the character *chr* as integer. + If no such value is defined, *default* is returned, or, if not given, + :exc:`ValueError` is raised. + + +.. function:: numeric(chr[, default]) + + Returns the numeric value assigned to the character *chr* as float. + If no such value is defined, *default* is returned, or, if not given, + :exc:`ValueError` is raised. + + +.. function:: category(chr) + + Returns the general category assigned to the character *chr* as + string. + + +.. function:: bidirectional(chr) + + Returns the bidirectional class assigned to the character *chr* as + string. If no such value is defined, an empty string is returned. + + +.. function:: combining(chr) + + Returns the canonical combining class assigned to the character *chr* + as integer. Returns ``0`` if no combining class is defined. + + +.. function:: east_asian_width(chr) + + Returns the east asian width assigned to the character *chr* as + string. + + +.. function:: mirrored(chr) + + Returns the mirrored property assigned to the character *chr* as + integer. Returns ``1`` if the character has been identified as a "mirrored" + character in bidirectional text, ``0`` otherwise. + + +.. function:: decomposition(chr) + + Returns the character decomposition mapping assigned to the character + *chr* as string. An empty string is returned in case no such mapping is + defined. + + +.. function:: normalize(form, unistr) + + Return the normal form *form* for the Unicode string *unistr*. Valid values for + *form* are 'NFC', 'NFKC', 'NFD', and 'NFKD'. + + The Unicode standard defines various normalization forms of a Unicode string, + based on the definition of canonical equivalence and compatibility equivalence. + In Unicode, several characters can be expressed in various way. For example, the + character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as + the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA). + + For each character, there are two normal forms: normal form C and normal form D. + Normal form D (NFD) is also known as canonical decomposition, and translates + each character into its decomposed form. Normal form C (NFC) first applies a + canonical decomposition, then composes pre-combined characters again. + + In addition to these two forms, there are two additional normal forms based on + compatibility equivalence. In Unicode, certain characters are supported which + normally would be unified with other characters. For example, U+2160 (ROMAN + NUMERAL ONE) is really the same thing as U+0049 (LATIN CAPITAL LETTER I). + However, it is supported in Unicode for compatibility with existing character + sets (e.g. gb2312). + + The normal form KD (NFKD) will apply the compatibility decomposition, i.e. + replace all compatibility characters with their equivalents. The normal form KC + (NFKC) first applies the compatibility decomposition, followed by the canonical + composition. + + Even if two unicode strings are normalized and look the same to + a human reader, if one has combining characters and the other + doesn't, they may not compare equal. + +.. function:: is_normalized(form, unistr) + + Return whether the Unicode string *unistr* is in the normal form *form*. Valid + values for *form* are 'NFC', 'NFKC', 'NFD', and 'NFKD'. + + .. versionadded:: 3.8 + + +In addition, the module exposes the following constant: + +.. data:: unidata_version + + The version of the Unicode database used in this module. + + +.. data:: ucd_3_2_0 + + This is an object that has the same methods as the entire module, but uses the + Unicode database version 3.2 instead, for applications that require this + specific version of the Unicode database (such as IDNA). + +Examples: + + >>> import unicodedata + >>> unicodedata.lookup('LEFT CURLY BRACKET') + '{' + >>> unicodedata.name('/') + 'SOLIDUS' + >>> unicodedata.decimal('9') + 9 + >>> unicodedata.decimal('a') + Traceback (most recent call last): + File "", line 1, in + ValueError: not a decimal + >>> unicodedata.category('A') # 'L'etter, 'u'ppercase + 'Lu' + >>> unicodedata.bidirectional('\u0660') # 'A'rabic, 'N'umber + 'AN' + + +.. rubric:: Footnotes + +.. [#] https://www.unicode.org/Public/13.0.0/ucd/NameAliases.txt + +.. [#] https://www.unicode.org/Public/13.0.0/ucd/NamedSequences.txt diff --git a/cpython_2/environment/repo/Doc/library/unittest.mock-examples.rst b/cpython_2/environment/repo/Doc/library/unittest.mock-examples.rst new file mode 100644 index 0000000000000000000000000000000000000000..e650bb1e23e03ee873b3e53ebec7774cfb37d15a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/unittest.mock-examples.rst @@ -0,0 +1,1321 @@ +:mod:`unittest.mock` --- getting started +======================================== + +.. moduleauthor:: Michael Foord +.. currentmodule:: unittest.mock + +.. versionadded:: 3.3 + + +.. _getting-started: + + +.. testsetup:: + + import asyncio + import unittest + from unittest.mock import Mock, MagicMock, AsyncMock, patch, call, sentinel + + class SomeClass: + attribute = 'this is a doctest' + + @staticmethod + def static_method(): + pass + +Using Mock +---------- + +Mock Patching Methods +~~~~~~~~~~~~~~~~~~~~~ + +Common uses for :class:`Mock` objects include: + +* Patching methods +* Recording method calls on objects + +You might want to replace a method on an object to check that +it is called with the correct arguments by another part of the system: + + >>> real = SomeClass() + >>> real.method = MagicMock(name='method') + >>> real.method(3, 4, 5, key='value') + + +Once our mock has been used (``real.method`` in this example) it has methods +and attributes that allow you to make assertions about how it has been used. + +.. note:: + + In most of these examples the :class:`Mock` and :class:`MagicMock` classes + are interchangeable. As the ``MagicMock`` is the more capable class it makes + a sensible one to use by default. + +Once the mock has been called its :attr:`~Mock.called` attribute is set to +``True``. More importantly we can use the :meth:`~Mock.assert_called_with` or +:meth:`~Mock.assert_called_once_with` method to check that it was called with +the correct arguments. + +This example tests that calling ``ProductionClass().method`` results in a call to +the ``something`` method: + + >>> class ProductionClass: + ... def method(self): + ... self.something(1, 2, 3) + ... def something(self, a, b, c): + ... pass + ... + >>> real = ProductionClass() + >>> real.something = MagicMock() + >>> real.method() + >>> real.something.assert_called_once_with(1, 2, 3) + + + +Mock for Method Calls on an Object +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In the last example we patched a method directly on an object to check that it +was called correctly. Another common use case is to pass an object into a +method (or some part of the system under test) and then check that it is used +in the correct way. + +The simple ``ProductionClass`` below has a ``closer`` method. If it is called with +an object then it calls ``close`` on it. + + >>> class ProductionClass: + ... def closer(self, something): + ... something.close() + ... + +So to test it we need to pass in an object with a ``close`` method and check +that it was called correctly. + + >>> real = ProductionClass() + >>> mock = Mock() + >>> real.closer(mock) + >>> mock.close.assert_called_with() + +We don't have to do any work to provide the 'close' method on our mock. +Accessing close creates it. So, if 'close' hasn't already been called then +accessing it in the test will create it, but :meth:`~Mock.assert_called_with` +will raise a failure exception. + + +Mocking Classes +~~~~~~~~~~~~~~~ + +A common use case is to mock out classes instantiated by your code under test. +When you patch a class, then that class is replaced with a mock. Instances +are created by *calling the class*. This means you access the "mock instance" +by looking at the return value of the mocked class. + +In the example below we have a function ``some_function`` that instantiates ``Foo`` +and calls a method on it. The call to :func:`patch` replaces the class ``Foo`` with a +mock. The ``Foo`` instance is the result of calling the mock, so it is configured +by modifying the mock :attr:`~Mock.return_value`. :: + + >>> def some_function(): + ... instance = module.Foo() + ... return instance.method() + ... + >>> with patch('module.Foo') as mock: + ... instance = mock.return_value + ... instance.method.return_value = 'the result' + ... result = some_function() + ... assert result == 'the result' + + +Naming your mocks +~~~~~~~~~~~~~~~~~ + +It can be useful to give your mocks a name. The name is shown in the repr of +the mock and can be helpful when the mock appears in test failure messages. The +name is also propagated to attributes or methods of the mock: + + >>> mock = MagicMock(name='foo') + >>> mock + + >>> mock.method + + + +Tracking all Calls +~~~~~~~~~~~~~~~~~~ + +Often you want to track more than a single call to a method. The +:attr:`~Mock.mock_calls` attribute records all calls +to child attributes of the mock - and also to their children. + + >>> mock = MagicMock() + >>> mock.method() + + >>> mock.attribute.method(10, x=53) + + >>> mock.mock_calls + [call.method(), call.attribute.method(10, x=53)] + +If you make an assertion about ``mock_calls`` and any unexpected methods +have been called, then the assertion will fail. This is useful because as well +as asserting that the calls you expected have been made, you are also checking +that they were made in the right order and with no additional calls: + +You use the :data:`call` object to construct lists for comparing with +``mock_calls``: + + >>> expected = [call.method(), call.attribute.method(10, x=53)] + >>> mock.mock_calls == expected + True + +However, parameters to calls that return mocks are not recorded, which means it is not +possible to track nested calls where the parameters used to create ancestors are important: + + >>> m = Mock() + >>> m.factory(important=True).deliver() + + >>> m.mock_calls[-1] == call.factory(important=False).deliver() + True + + +Setting Return Values and Attributes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Setting the return values on a mock object is trivially easy: + + >>> mock = Mock() + >>> mock.return_value = 3 + >>> mock() + 3 + +Of course you can do the same for methods on the mock: + + >>> mock = Mock() + >>> mock.method.return_value = 3 + >>> mock.method() + 3 + +The return value can also be set in the constructor: + + >>> mock = Mock(return_value=3) + >>> mock() + 3 + +If you need an attribute setting on your mock, just do it: + + >>> mock = Mock() + >>> mock.x = 3 + >>> mock.x + 3 + +Sometimes you want to mock up a more complex situation, like for example +``mock.connection.cursor().execute("SELECT 1")``. If we wanted this call to +return a list, then we have to configure the result of the nested call. + +We can use :data:`call` to construct the set of calls in a "chained call" like +this for easy assertion afterwards: + + >>> mock = Mock() + >>> cursor = mock.connection.cursor.return_value + >>> cursor.execute.return_value = ['foo'] + >>> mock.connection.cursor().execute("SELECT 1") + ['foo'] + >>> expected = call.connection.cursor().execute("SELECT 1").call_list() + >>> mock.mock_calls + [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')] + >>> mock.mock_calls == expected + True + +It is the call to ``.call_list()`` that turns our call object into a list of +calls representing the chained calls. + + +Raising exceptions with mocks +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A useful attribute is :attr:`~Mock.side_effect`. If you set this to an +exception class or instance then the exception will be raised when the mock +is called. + + >>> mock = Mock(side_effect=Exception('Boom!')) + >>> mock() + Traceback (most recent call last): + ... + Exception: Boom! + + +Side effect functions and iterables +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``side_effect`` can also be set to a function or an iterable. The use case for +``side_effect`` as an iterable is where your mock is going to be called several +times, and you want each call to return a different value. When you set +``side_effect`` to an iterable every call to the mock returns the next value +from the iterable: + + >>> mock = MagicMock(side_effect=[4, 5, 6]) + >>> mock() + 4 + >>> mock() + 5 + >>> mock() + 6 + + +For more advanced use cases, like dynamically varying the return values +depending on what the mock is called with, ``side_effect`` can be a function. +The function will be called with the same arguments as the mock. Whatever the +function returns is what the call returns: + + >>> vals = {(1, 2): 1, (2, 3): 2} + >>> def side_effect(*args): + ... return vals[args] + ... + >>> mock = MagicMock(side_effect=side_effect) + >>> mock(1, 2) + 1 + >>> mock(2, 3) + 2 + + +Mocking asynchronous iterators +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Since Python 3.8, ``AsyncMock`` and ``MagicMock`` have support to mock +:ref:`async-iterators` through ``__aiter__``. The :attr:`~Mock.return_value` +attribute of ``__aiter__`` can be used to set the return values to be used for +iteration. + + >>> mock = MagicMock() # AsyncMock also works here + >>> mock.__aiter__.return_value = [1, 2, 3] + >>> async def main(): + ... return [i async for i in mock] + ... + >>> asyncio.run(main()) + [1, 2, 3] + + +Mocking asynchronous context manager +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Since Python 3.8, ``AsyncMock`` and ``MagicMock`` have support to mock +:ref:`async-context-managers` through ``__aenter__`` and ``__aexit__``. +By default, ``__aenter__`` and ``__aexit__`` are ``AsyncMock`` instances that +return an async function. + + >>> class AsyncContextManager: + ... async def __aenter__(self): + ... return self + ... async def __aexit__(self, exc_type, exc, tb): + ... pass + ... + >>> mock_instance = MagicMock(AsyncContextManager()) # AsyncMock also works here + >>> async def main(): + ... async with mock_instance as result: + ... pass + ... + >>> asyncio.run(main()) + >>> mock_instance.__aenter__.assert_awaited_once() + >>> mock_instance.__aexit__.assert_awaited_once() + + +Creating a Mock from an Existing Object +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +One problem with over use of mocking is that it couples your tests to the +implementation of your mocks rather than your real code. Suppose you have a +class that implements ``some_method``. In a test for another class, you +provide a mock of this object that *also* provides ``some_method``. If later +you refactor the first class, so that it no longer has ``some_method`` - then +your tests will continue to pass even though your code is now broken! + +:class:`Mock` allows you to provide an object as a specification for the mock, +using the *spec* keyword argument. Accessing methods / attributes on the +mock that don't exist on your specification object will immediately raise an +attribute error. If you change the implementation of your specification, then +tests that use that class will start failing immediately without you having to +instantiate the class in those tests. + + >>> mock = Mock(spec=SomeClass) + >>> mock.old_method() + Traceback (most recent call last): + ... + AttributeError: object has no attribute 'old_method' + +Using a specification also enables a smarter matching of calls made to the +mock, regardless of whether some parameters were passed as positional or +named arguments:: + + >>> def f(a, b, c): pass + ... + >>> mock = Mock(spec=f) + >>> mock(1, 2, 3) + + >>> mock.assert_called_with(a=1, b=2, c=3) + +If you want this smarter matching to also work with method calls on the mock, +you can use :ref:`auto-speccing `. + +If you want a stronger form of specification that prevents the setting +of arbitrary attributes as well as the getting of them then you can use +*spec_set* instead of *spec*. + + + +Patch Decorators +---------------- + +.. note:: + + With :func:`patch` it matters that you patch objects in the namespace where + they are looked up. This is normally straightforward, but for a quick guide + read :ref:`where to patch `. + + +A common need in tests is to patch a class attribute or a module attribute, +for example patching a builtin or patching a class in a module to test that it +is instantiated. Modules and classes are effectively global, so patching on +them has to be undone after the test or the patch will persist into other +tests and cause hard to diagnose problems. + +mock provides three convenient decorators for this: :func:`patch`, :func:`patch.object` and +:func:`patch.dict`. ``patch`` takes a single string, of the form +``package.module.Class.attribute`` to specify the attribute you are patching. It +also optionally takes a value that you want the attribute (or class or +whatever) to be replaced with. 'patch.object' takes an object and the name of +the attribute you would like patched, plus optionally the value to patch it +with. + +``patch.object``:: + + >>> original = SomeClass.attribute + >>> @patch.object(SomeClass, 'attribute', sentinel.attribute) + ... def test(): + ... assert SomeClass.attribute == sentinel.attribute + ... + >>> test() + >>> assert SomeClass.attribute == original + + >>> @patch('package.module.attribute', sentinel.attribute) + ... def test(): + ... from package.module import attribute + ... assert attribute is sentinel.attribute + ... + >>> test() + +If you are patching a module (including :mod:`builtins`) then use :func:`patch` +instead of :func:`patch.object`: + + >>> mock = MagicMock(return_value=sentinel.file_handle) + >>> with patch('builtins.open', mock): + ... handle = open('filename', 'r') + ... + >>> mock.assert_called_with('filename', 'r') + >>> assert handle == sentinel.file_handle, "incorrect file handle returned" + +The module name can be 'dotted', in the form ``package.module`` if needed:: + + >>> @patch('package.module.ClassName.attribute', sentinel.attribute) + ... def test(): + ... from package.module import ClassName + ... assert ClassName.attribute == sentinel.attribute + ... + >>> test() + +A nice pattern is to actually decorate test methods themselves: + + >>> class MyTest(unittest.TestCase): + ... @patch.object(SomeClass, 'attribute', sentinel.attribute) + ... def test_something(self): + ... self.assertEqual(SomeClass.attribute, sentinel.attribute) + ... + >>> original = SomeClass.attribute + >>> MyTest('test_something').test_something() + >>> assert SomeClass.attribute == original + +If you want to patch with a Mock, you can use :func:`patch` with only one argument +(or :func:`patch.object` with two arguments). The mock will be created for you and +passed into the test function / method: + + >>> class MyTest(unittest.TestCase): + ... @patch.object(SomeClass, 'static_method') + ... def test_something(self, mock_method): + ... SomeClass.static_method() + ... mock_method.assert_called_with() + ... + >>> MyTest('test_something').test_something() + +You can stack up multiple patch decorators using this pattern:: + + >>> class MyTest(unittest.TestCase): + ... @patch('package.module.ClassName1') + ... @patch('package.module.ClassName2') + ... def test_something(self, MockClass2, MockClass1): + ... self.assertIs(package.module.ClassName1, MockClass1) + ... self.assertIs(package.module.ClassName2, MockClass2) + ... + >>> MyTest('test_something').test_something() + +When you nest patch decorators the mocks are passed in to the decorated +function in the same order they applied (the normal *Python* order that +decorators are applied). This means from the bottom up, so in the example +above the mock for ``test_module.ClassName2`` is passed in first. + +There is also :func:`patch.dict` for setting values in a dictionary just +during a scope and restoring the dictionary to its original state when the test +ends: + + >>> foo = {'key': 'value'} + >>> original = foo.copy() + >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True): + ... assert foo == {'newkey': 'newvalue'} + ... + >>> assert foo == original + +``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers. + +Where you use :func:`patch` to create a mock for you, you can get a reference to the +mock using the "as" form of the with statement: + + >>> class ProductionClass: + ... def method(self): + ... pass + ... + >>> with patch.object(ProductionClass, 'method') as mock_method: + ... mock_method.return_value = None + ... real = ProductionClass() + ... real.method(1, 2, 3) + ... + >>> mock_method.assert_called_with(1, 2, 3) + + +As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as +class decorators. When used in this way it is the same as applying the +decorator individually to every method whose name starts with "test". + + +.. _further-examples: + +Further Examples +---------------- + + +Here are some more examples for some slightly more advanced scenarios. + + +Mocking chained calls +~~~~~~~~~~~~~~~~~~~~~ + +Mocking chained calls is actually straightforward with mock once you +understand the :attr:`~Mock.return_value` attribute. When a mock is called for +the first time, or you fetch its ``return_value`` before it has been called, a +new :class:`Mock` is created. + +This means that you can see how the object returned from a call to a mocked +object has been used by interrogating the ``return_value`` mock: + + >>> mock = Mock() + >>> mock().foo(a=2, b=3) + + >>> mock.return_value.foo.assert_called_with(a=2, b=3) + +From here it is a simple step to configure and then make assertions about +chained calls. Of course another alternative is writing your code in a more +testable way in the first place... + +So, suppose we have some code that looks a little bit like this: + + >>> class Something: + ... def __init__(self): + ... self.backend = BackendProvider() + ... def method(self): + ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call() + ... # more code + +Assuming that ``BackendProvider`` is already well tested, how do we test +``method()``? Specifically, we want to test that the code section ``# more +code`` uses the response object in the correct way. + +As this chain of calls is made from an instance attribute we can monkey patch +the ``backend`` attribute on a ``Something`` instance. In this particular case +we are only interested in the return value from the final call to +``start_call`` so we don't have much configuration to do. Let's assume the +object it returns is 'file-like', so we'll ensure that our response object +uses the builtin :func:`open` as its ``spec``. + +To do this we create a mock instance as our mock backend and create a mock +response object for it. To set the response as the return value for that final +``start_call`` we could do this:: + + mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response + +We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock` +method to directly set the return value for us:: + + >>> something = Something() + >>> mock_response = Mock(spec=open) + >>> mock_backend = Mock() + >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response} + >>> mock_backend.configure_mock(**config) + +With these we monkey patch the "mock backend" in place and can make the real +call:: + + >>> something.backend = mock_backend + >>> something.method() + +Using :attr:`~Mock.mock_calls` we can check the chained call with a single +assert. A chained call is several calls in one line of code, so there will be +several entries in ``mock_calls``. We can use :meth:`call.call_list` to create +this list of calls for us:: + + >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call() + >>> call_list = chained.call_list() + >>> assert mock_backend.mock_calls == call_list + + +Partial mocking +~~~~~~~~~~~~~~~ + +In some tests I wanted to mock out a call to :meth:`datetime.date.today` +to return a known date, but I didn't want to prevent the code under test from +creating new date objects. Unfortunately :class:`datetime.date` is written in C, and +so I couldn't just monkey-patch out the static :meth:`date.today` method. + +I found a simple way of doing this that involved effectively wrapping the date +class with a mock, but passing through calls to the constructor to the real +class (and returning real instances). + +The :func:`patch decorator ` is used here to +mock out the ``date`` class in the module under test. The :attr:`side_effect` +attribute on the mock date class is then set to a lambda function that returns +a real date. When the mock date class is called a real date will be +constructed and returned by ``side_effect``. :: + + >>> from datetime import date + >>> with patch('mymodule.date') as mock_date: + ... mock_date.today.return_value = date(2010, 10, 8) + ... mock_date.side_effect = lambda *args, **kw: date(*args, **kw) + ... + ... assert mymodule.date.today() == date(2010, 10, 8) + ... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8) + +Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the +module that *uses* it. See :ref:`where to patch `. + +When ``date.today()`` is called a known date is returned, but calls to the +``date(...)`` constructor still return normal dates. Without this you can find +yourself having to calculate an expected result using exactly the same +algorithm as the code under test, which is a classic testing anti-pattern. + +Calls to the date constructor are recorded in the ``mock_date`` attributes +(``call_count`` and friends) which may also be useful for your tests. + +An alternative way of dealing with mocking dates, or other builtin classes, +is discussed in `this blog entry +`_. + + +Mocking a Generator Method +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A Python generator is a function or method that uses the :keyword:`yield` statement +to return a series of values when iterated over [#]_. + +A generator method / function is called to return the generator object. It is +the generator object that is then iterated over. The protocol method for +iteration is :meth:`~container.__iter__`, so we can +mock this using a :class:`MagicMock`. + +Here's an example class with an "iter" method implemented as a generator: + + >>> class Foo: + ... def iter(self): + ... for i in [1, 2, 3]: + ... yield i + ... + >>> foo = Foo() + >>> list(foo.iter()) + [1, 2, 3] + + +How would we mock this class, and in particular its "iter" method? + +To configure the values returned from the iteration (implicit in the call to +:class:`list`), we need to configure the object returned by the call to ``foo.iter()``. + + >>> mock_foo = MagicMock() + >>> mock_foo.iter.return_value = iter([1, 2, 3]) + >>> list(mock_foo.iter()) + [1, 2, 3] + +.. [#] There are also generator expressions and more `advanced uses + `_ of generators, but we aren't + concerned about them here. A very good introduction to generators and how + powerful they are is: `Generator Tricks for Systems Programmers + `_. + + +Applying the same patch to every test method +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you want several patches in place for multiple test methods the obvious way +is to apply the patch decorators to every method. This can feel like unnecessary +repetition. For Python 2.6 or more recent you can use :func:`patch` (in all its +various forms) as a class decorator. This applies the patches to all test +methods on the class. A test method is identified by methods whose names start +with ``test``:: + + >>> @patch('mymodule.SomeClass') + ... class MyTest(unittest.TestCase): + ... + ... def test_one(self, MockSomeClass): + ... self.assertIs(mymodule.SomeClass, MockSomeClass) + ... + ... def test_two(self, MockSomeClass): + ... self.assertIs(mymodule.SomeClass, MockSomeClass) + ... + ... def not_a_test(self): + ... return 'something' + ... + >>> MyTest('test_one').test_one() + >>> MyTest('test_two').test_two() + >>> MyTest('test_two').not_a_test() + 'something' + +An alternative way of managing patches is to use the :ref:`start-and-stop`. +These allow you to move the patching into your ``setUp`` and ``tearDown`` methods. +:: + + >>> class MyTest(unittest.TestCase): + ... def setUp(self): + ... self.patcher = patch('mymodule.foo') + ... self.mock_foo = self.patcher.start() + ... + ... def test_foo(self): + ... self.assertIs(mymodule.foo, self.mock_foo) + ... + ... def tearDown(self): + ... self.patcher.stop() + ... + >>> MyTest('test_foo').run() + +If you use this technique you must ensure that the patching is "undone" by +calling ``stop``. This can be fiddlier than you might think, because if an +exception is raised in the setUp then tearDown is not called. +:meth:`unittest.TestCase.addCleanup` makes this easier:: + + >>> class MyTest(unittest.TestCase): + ... def setUp(self): + ... patcher = patch('mymodule.foo') + ... self.addCleanup(patcher.stop) + ... self.mock_foo = patcher.start() + ... + ... def test_foo(self): + ... self.assertIs(mymodule.foo, self.mock_foo) + ... + >>> MyTest('test_foo').run() + + +Mocking Unbound Methods +~~~~~~~~~~~~~~~~~~~~~~~ + +Whilst writing tests today I needed to patch an *unbound method* (patching the +method on the class rather than on the instance). I needed self to be passed +in as the first argument because I want to make asserts about which objects +were calling this particular method. The issue is that you can't patch with a +mock for this, because if you replace an unbound method with a mock it doesn't +become a bound method when fetched from the instance, and so it doesn't get +self passed in. The workaround is to patch the unbound method with a real +function instead. The :func:`patch` decorator makes it so simple to +patch out methods with a mock that having to create a real function becomes a +nuisance. + +If you pass ``autospec=True`` to patch then it does the patching with a +*real* function object. This function object has the same signature as the one +it is replacing, but delegates to a mock under the hood. You still get your +mock auto-created in exactly the same way as before. What it means though, is +that if you use it to patch out an unbound method on a class the mocked +function will be turned into a bound method if it is fetched from an instance. +It will have ``self`` passed in as the first argument, which is exactly what I +wanted: + + >>> class Foo: + ... def foo(self): + ... pass + ... + >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo: + ... mock_foo.return_value = 'foo' + ... foo = Foo() + ... foo.foo() + ... + 'foo' + >>> mock_foo.assert_called_once_with(foo) + +If we don't use ``autospec=True`` then the unbound method is patched out +with a Mock instance instead, and isn't called with ``self``. + + +Checking multiple calls with mock +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +mock has a nice API for making assertions about how your mock objects are used. + + >>> mock = Mock() + >>> mock.foo_bar.return_value = None + >>> mock.foo_bar('baz', spam='eggs') + >>> mock.foo_bar.assert_called_with('baz', spam='eggs') + +If your mock is only being called once you can use the +:meth:`assert_called_once_with` method that also asserts that the +:attr:`call_count` is one. + + >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs') + >>> mock.foo_bar() + >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs') + Traceback (most recent call last): + ... + AssertionError: Expected to be called once. Called 2 times. + +Both ``assert_called_with`` and ``assert_called_once_with`` make assertions about +the *most recent* call. If your mock is going to be called several times, and +you want to make assertions about *all* those calls you can use +:attr:`~Mock.call_args_list`: + + >>> mock = Mock(return_value=None) + >>> mock(1, 2, 3) + >>> mock(4, 5, 6) + >>> mock() + >>> mock.call_args_list + [call(1, 2, 3), call(4, 5, 6), call()] + +The :data:`call` helper makes it easy to make assertions about these calls. You +can build up a list of expected calls and compare it to ``call_args_list``. This +looks remarkably similar to the repr of the ``call_args_list``: + + >>> expected = [call(1, 2, 3), call(4, 5, 6), call()] + >>> mock.call_args_list == expected + True + + +Coping with mutable arguments +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Another situation is rare, but can bite you, is when your mock is called with +mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the +arguments. If the arguments are mutated by the code under test then you can no +longer make assertions about what the values were when the mock was called. + +Here's some example code that shows the problem. Imagine the following functions +defined in 'mymodule':: + + def frob(val): + pass + + def grob(val): + "First frob and then clear val" + frob(val) + val.clear() + +When we try to test that ``grob`` calls ``frob`` with the correct argument look +what happens:: + + >>> with patch('mymodule.frob') as mock_frob: + ... val = {6} + ... mymodule.grob(val) + ... + >>> val + set() + >>> mock_frob.assert_called_with({6}) + Traceback (most recent call last): + ... + AssertionError: Expected: (({6},), {}) + Called with: ((set(),), {}) + +One possibility would be for mock to copy the arguments you pass in. This +could then cause problems if you do assertions that rely on object identity +for equality. + +Here's one solution that uses the :attr:`side_effect` +functionality. If you provide a ``side_effect`` function for a mock then +``side_effect`` will be called with the same args as the mock. This gives us an +opportunity to copy the arguments and store them for later assertions. In this +example I'm using *another* mock to store the arguments so that I can use the +mock methods for doing the assertion. Again a helper function sets this up for +me. :: + + >>> from copy import deepcopy + >>> from unittest.mock import Mock, patch, DEFAULT + >>> def copy_call_args(mock): + ... new_mock = Mock() + ... def side_effect(*args, **kwargs): + ... args = deepcopy(args) + ... kwargs = deepcopy(kwargs) + ... new_mock(*args, **kwargs) + ... return DEFAULT + ... mock.side_effect = side_effect + ... return new_mock + ... + >>> with patch('mymodule.frob') as mock_frob: + ... new_mock = copy_call_args(mock_frob) + ... val = {6} + ... mymodule.grob(val) + ... + >>> new_mock.assert_called_with({6}) + >>> new_mock.call_args + call({6}) + +``copy_call_args`` is called with the mock that will be called. It returns a new +mock that we do the assertion on. The ``side_effect`` function makes a copy of +the args and calls our ``new_mock`` with the copy. + +.. note:: + + If your mock is only going to be used once there is an easier way of + checking arguments at the point they are called. You can simply do the + checking inside a ``side_effect`` function. + + >>> def side_effect(arg): + ... assert arg == {6} + ... + >>> mock = Mock(side_effect=side_effect) + >>> mock({6}) + >>> mock(set()) + Traceback (most recent call last): + ... + AssertionError + +An alternative approach is to create a subclass of :class:`Mock` or +:class:`MagicMock` that copies (using :func:`copy.deepcopy`) the arguments. +Here's an example implementation: + + >>> from copy import deepcopy + >>> class CopyingMock(MagicMock): + ... def __call__(self, /, *args, **kwargs): + ... args = deepcopy(args) + ... kwargs = deepcopy(kwargs) + ... return super(CopyingMock, self).__call__(*args, **kwargs) + ... + >>> c = CopyingMock(return_value=None) + >>> arg = set() + >>> c(arg) + >>> arg.add(1) + >>> c.assert_called_with(set()) + >>> c.assert_called_with(arg) + Traceback (most recent call last): + ... + AssertionError: Expected call: mock({1}) + Actual call: mock(set()) + >>> c.foo + + +When you subclass ``Mock`` or ``MagicMock`` all dynamically created attributes, +and the ``return_value`` will use your subclass automatically. That means all +children of a ``CopyingMock`` will also have the type ``CopyingMock``. + + +Nesting Patches +~~~~~~~~~~~~~~~ + +Using patch as a context manager is nice, but if you do multiple patches you +can end up with nested with statements indenting further and further to the +right:: + + >>> class MyTest(unittest.TestCase): + ... + ... def test_foo(self): + ... with patch('mymodule.Foo') as mock_foo: + ... with patch('mymodule.Bar') as mock_bar: + ... with patch('mymodule.Spam') as mock_spam: + ... assert mymodule.Foo is mock_foo + ... assert mymodule.Bar is mock_bar + ... assert mymodule.Spam is mock_spam + ... + >>> original = mymodule.Foo + >>> MyTest('test_foo').test_foo() + >>> assert mymodule.Foo is original + +With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can +achieve the same effect without the nested indentation. A simple helper +method, ``create_patch``, puts the patch in place and returns the created mock +for us:: + + >>> class MyTest(unittest.TestCase): + ... + ... def create_patch(self, name): + ... patcher = patch(name) + ... thing = patcher.start() + ... self.addCleanup(patcher.stop) + ... return thing + ... + ... def test_foo(self): + ... mock_foo = self.create_patch('mymodule.Foo') + ... mock_bar = self.create_patch('mymodule.Bar') + ... mock_spam = self.create_patch('mymodule.Spam') + ... + ... assert mymodule.Foo is mock_foo + ... assert mymodule.Bar is mock_bar + ... assert mymodule.Spam is mock_spam + ... + >>> original = mymodule.Foo + >>> MyTest('test_foo').run() + >>> assert mymodule.Foo is original + + +Mocking a dictionary with MagicMock +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You may want to mock a dictionary, or other container object, recording all +access to it whilst having it still behave like a dictionary. + +We can do this with :class:`MagicMock`, which will behave like a dictionary, +and using :data:`~Mock.side_effect` to delegate dictionary access to a real +underlying dictionary that is under our control. + +When the :meth:`__getitem__` and :meth:`__setitem__` methods of our ``MagicMock`` are called +(normal dictionary access) then ``side_effect`` is called with the key (and in +the case of ``__setitem__`` the value too). We can also control what is returned. + +After the ``MagicMock`` has been used we can use attributes like +:data:`~Mock.call_args_list` to assert about how the dictionary was used: + + >>> my_dict = {'a': 1, 'b': 2, 'c': 3} + >>> def getitem(name): + ... return my_dict[name] + ... + >>> def setitem(name, val): + ... my_dict[name] = val + ... + >>> mock = MagicMock() + >>> mock.__getitem__.side_effect = getitem + >>> mock.__setitem__.side_effect = setitem + +.. note:: + + An alternative to using ``MagicMock`` is to use ``Mock`` and *only* provide + the magic methods you specifically want: + + >>> mock = Mock() + >>> mock.__getitem__ = Mock(side_effect=getitem) + >>> mock.__setitem__ = Mock(side_effect=setitem) + + A *third* option is to use ``MagicMock`` but passing in ``dict`` as the *spec* + (or *spec_set*) argument so that the ``MagicMock`` created only has + dictionary magic methods available: + + >>> mock = MagicMock(spec_set=dict) + >>> mock.__getitem__.side_effect = getitem + >>> mock.__setitem__.side_effect = setitem + +With these side effect functions in place, the ``mock`` will behave like a normal +dictionary but recording the access. It even raises a :exc:`KeyError` if you try +to access a key that doesn't exist. + + >>> mock['a'] + 1 + >>> mock['c'] + 3 + >>> mock['d'] + Traceback (most recent call last): + ... + KeyError: 'd' + >>> mock['b'] = 'fish' + >>> mock['d'] = 'eggs' + >>> mock['b'] + 'fish' + >>> mock['d'] + 'eggs' + +After it has been used you can make assertions about the access using the normal +mock methods and attributes: + + >>> mock.__getitem__.call_args_list + [call('a'), call('c'), call('d'), call('b'), call('d')] + >>> mock.__setitem__.call_args_list + [call('b', 'fish'), call('d', 'eggs')] + >>> my_dict + {'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'} + + +Mock subclasses and their attributes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There are various reasons why you might want to subclass :class:`Mock`. One +reason might be to add helper methods. Here's a silly example: + + >>> class MyMock(MagicMock): + ... def has_been_called(self): + ... return self.called + ... + >>> mymock = MyMock(return_value=None) + >>> mymock + + >>> mymock.has_been_called() + False + >>> mymock() + >>> mymock.has_been_called() + True + +The standard behaviour for ``Mock`` instances is that attributes and the return +value mocks are of the same type as the mock they are accessed on. This ensures +that ``Mock`` attributes are ``Mocks`` and ``MagicMock`` attributes are ``MagicMocks`` +[#]_. So if you're subclassing to add helper methods then they'll also be +available on the attributes and return value mock of instances of your +subclass. + + >>> mymock.foo + + >>> mymock.foo.has_been_called() + False + >>> mymock.foo() + + >>> mymock.foo.has_been_called() + True + +Sometimes this is inconvenient. For example, `one user +`_ is subclassing mock to +created a `Twisted adaptor +`_. +Having this applied to attributes too actually causes errors. + +``Mock`` (in all its flavours) uses a method called ``_get_child_mock`` to create +these "sub-mocks" for attributes and return values. You can prevent your +subclass being used for attributes by overriding this method. The signature is +that it takes arbitrary keyword arguments (``**kwargs``) which are then passed +onto the mock constructor: + + >>> class Subclass(MagicMock): + ... def _get_child_mock(self, /, **kwargs): + ... return MagicMock(**kwargs) + ... + >>> mymock = Subclass() + >>> mymock.foo + + >>> assert isinstance(mymock, Subclass) + >>> assert not isinstance(mymock.foo, Subclass) + >>> assert not isinstance(mymock(), Subclass) + +.. [#] An exception to this rule are the non-callable mocks. Attributes use the + callable variant because otherwise non-callable mocks couldn't have callable + methods. + + +Mocking imports with patch.dict +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +One situation where mocking can be hard is where you have a local import inside +a function. These are harder to mock because they aren't using an object from +the module namespace that we can patch out. + +Generally local imports are to be avoided. They are sometimes done to prevent +circular dependencies, for which there is *usually* a much better way to solve +the problem (refactor the code) or to prevent "up front costs" by delaying the +import. This can also be solved in better ways than an unconditional local +import (store the module as a class or module attribute and only do the import +on first use). + +That aside there is a way to use ``mock`` to affect the results of an import. +Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it +fetches an *object*, which need not be a module. Importing a module for the +first time results in a module object being put in `sys.modules`, so usually +when you import something you get a module back. This need not be the case +however. + +This means you can use :func:`patch.dict` to *temporarily* put a mock in place +in :data:`sys.modules`. Any imports whilst this patch is active will fetch the mock. +When the patch is complete (the decorated function exits, the with statement +body is complete or ``patcher.stop()`` is called) then whatever was there +previously will be restored safely. + +Here's an example that mocks out the 'fooble' module. + + >>> import sys + >>> mock = Mock() + >>> with patch.dict('sys.modules', {'fooble': mock}): + ... import fooble + ... fooble.blob() + ... + + >>> assert 'fooble' not in sys.modules + >>> mock.blob.assert_called_once_with() + +As you can see the ``import fooble`` succeeds, but on exit there is no 'fooble' +left in :data:`sys.modules`. + +This also works for the ``from module import name`` form: + + >>> mock = Mock() + >>> with patch.dict('sys.modules', {'fooble': mock}): + ... from fooble import blob + ... blob.blip() + ... + + >>> mock.blob.blip.assert_called_once_with() + +With slightly more work you can also mock package imports: + + >>> mock = Mock() + >>> modules = {'package': mock, 'package.module': mock.module} + >>> with patch.dict('sys.modules', modules): + ... from package.module import fooble + ... fooble() + ... + + >>> mock.module.fooble.assert_called_once_with() + + +Tracking order of calls and less verbose call assertions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :class:`Mock` class allows you to track the *order* of method calls on +your mock objects through the :attr:`~Mock.method_calls` attribute. This +doesn't allow you to track the order of calls between separate mock objects, +however we can use :attr:`~Mock.mock_calls` to achieve the same effect. + +Because mocks track calls to child mocks in ``mock_calls``, and accessing an +arbitrary attribute of a mock creates a child mock, we can create our separate +mocks from a parent one. Calls to those child mock will then all be recorded, +in order, in the ``mock_calls`` of the parent: + + >>> manager = Mock() + >>> mock_foo = manager.foo + >>> mock_bar = manager.bar + + >>> mock_foo.something() + + >>> mock_bar.other.thing() + + + >>> manager.mock_calls + [call.foo.something(), call.bar.other.thing()] + +We can then assert about the calls, including the order, by comparing with +the ``mock_calls`` attribute on the manager mock: + + >>> expected_calls = [call.foo.something(), call.bar.other.thing()] + >>> manager.mock_calls == expected_calls + True + +If ``patch`` is creating, and putting in place, your mocks then you can attach +them to a manager mock using the :meth:`~Mock.attach_mock` method. After +attaching calls will be recorded in ``mock_calls`` of the manager. :: + + >>> manager = MagicMock() + >>> with patch('mymodule.Class1') as MockClass1: + ... with patch('mymodule.Class2') as MockClass2: + ... manager.attach_mock(MockClass1, 'MockClass1') + ... manager.attach_mock(MockClass2, 'MockClass2') + ... MockClass1().foo() + ... MockClass2().bar() + + + >>> manager.mock_calls + [call.MockClass1(), + call.MockClass1().foo(), + call.MockClass2(), + call.MockClass2().bar()] + +If many calls have been made, but you're only interested in a particular +sequence of them then an alternative is to use the +:meth:`~Mock.assert_has_calls` method. This takes a list of calls (constructed +with the :data:`call` object). If that sequence of calls are in +:attr:`~Mock.mock_calls` then the assert succeeds. + + >>> m = MagicMock() + >>> m().foo().bar().baz() + + >>> m.one().two().three() + + >>> calls = call.one().two().three().call_list() + >>> m.assert_has_calls(calls) + +Even though the chained call ``m.one().two().three()`` aren't the only calls that +have been made to the mock, the assert still succeeds. + +Sometimes a mock may have several calls made to it, and you are only interested +in asserting about *some* of those calls. You may not even care about the +order. In this case you can pass ``any_order=True`` to ``assert_has_calls``: + + >>> m = MagicMock() + >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50') + (...) + >>> calls = [call.fifty('50'), call(1), call.seven(7)] + >>> m.assert_has_calls(calls, any_order=True) + + +More complex argument matching +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Using the same basic concept as :data:`ANY` we can implement matchers to do more +complex assertions on objects used as arguments to mocks. + +Suppose we expect some object to be passed to a mock that by default +compares equal based on object identity (which is the Python default for user +defined classes). To use :meth:`~Mock.assert_called_with` we would need to pass +in the exact same object. If we are only interested in some of the attributes +of this object then we can create a matcher that will check these attributes +for us. + +You can see in this example how a 'standard' call to ``assert_called_with`` isn't +sufficient: + + >>> class Foo: + ... def __init__(self, a, b): + ... self.a, self.b = a, b + ... + >>> mock = Mock(return_value=None) + >>> mock(Foo(1, 2)) + >>> mock.assert_called_with(Foo(1, 2)) + Traceback (most recent call last): + ... + AssertionError: Expected: call(<__main__.Foo object at 0x...>) + Actual call: call(<__main__.Foo object at 0x...>) + +A comparison function for our ``Foo`` class might look something like this: + + >>> def compare(self, other): + ... if not type(self) == type(other): + ... return False + ... if self.a != other.a: + ... return False + ... if self.b != other.b: + ... return False + ... return True + ... + +And a matcher object that can use comparison functions like this for its +equality operation would look something like this: + + >>> class Matcher: + ... def __init__(self, compare, some_obj): + ... self.compare = compare + ... self.some_obj = some_obj + ... def __eq__(self, other): + ... return self.compare(self.some_obj, other) + ... + +Putting all this together: + + >>> match_foo = Matcher(compare, Foo(1, 2)) + >>> mock.assert_called_with(match_foo) + +The ``Matcher`` is instantiated with our compare function and the ``Foo`` object +we want to compare against. In ``assert_called_with`` the ``Matcher`` equality +method will be called, which compares the object the mock was called with +against the one we created our matcher with. If they match then +``assert_called_with`` passes, and if they don't an :exc:`AssertionError` is raised: + + >>> match_wrong = Matcher(compare, Foo(3, 4)) + >>> mock.assert_called_with(match_wrong) + Traceback (most recent call last): + ... + AssertionError: Expected: ((,), {}) + Called with: ((,), {}) + +With a bit of tweaking you could have the comparison function raise the +:exc:`AssertionError` directly and provide a more useful failure message. + +As of version 1.5, the Python testing library `PyHamcrest +`_ provides similar functionality, +that may be useful here, in the form of its equality matcher +(`hamcrest.library.integration.match_equality +`_). diff --git a/cpython_2/environment/repo/Doc/library/unittest.mock.rst b/cpython_2/environment/repo/Doc/library/unittest.mock.rst new file mode 100644 index 0000000000000000000000000000000000000000..3643d1ad96ed11614291115cbbf7555098251b07 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/unittest.mock.rst @@ -0,0 +1,2767 @@ + +:mod:`unittest.mock` --- mock object library +============================================ + +.. module:: unittest.mock + :synopsis: Mock object library. + +.. moduleauthor:: Michael Foord +.. currentmodule:: unittest.mock + +.. versionadded:: 3.3 + +**Source code:** :source:`Lib/unittest/mock.py` + +-------------- + +:mod:`unittest.mock` is a library for testing in Python. It allows you to +replace parts of your system under test with mock objects and make assertions +about how they have been used. + +:mod:`unittest.mock` provides a core :class:`Mock` class removing the need to +create a host of stubs throughout your test suite. After performing an +action, you can make assertions about which methods / attributes were used +and arguments they were called with. You can also specify return values and +set needed attributes in the normal way. + +Additionally, mock provides a :func:`patch` decorator that handles patching +module and class level attributes within the scope of a test, along with +:const:`sentinel` for creating unique objects. See the `quick guide`_ for +some examples of how to use :class:`Mock`, :class:`MagicMock` and +:func:`patch`. + +Mock is very easy to use and is designed for use with :mod:`unittest`. Mock +is based on the 'action -> assertion' pattern instead of 'record -> replay' +used by many mocking frameworks. + +There is a backport of :mod:`unittest.mock` for earlier versions of Python, +available as `mock on PyPI `_. + + +Quick Guide +----------- + +.. testsetup:: + + class ProductionClass: + def method(self, a, b, c): + pass + + class SomeClass: + @staticmethod + def static_method(args): + return args + + @classmethod + def class_method(cls, args): + return args + + +:class:`Mock` and :class:`MagicMock` objects create all attributes and +methods as you access them and store details of how they have been used. You +can configure them, to specify return values or limit what attributes are +available, and then make assertions about how they have been used: + + >>> from unittest.mock import MagicMock + >>> thing = ProductionClass() + >>> thing.method = MagicMock(return_value=3) + >>> thing.method(3, 4, 5, key='value') + 3 + >>> thing.method.assert_called_with(3, 4, 5, key='value') + +:attr:`side_effect` allows you to perform side effects, including raising an +exception when a mock is called: + + >>> mock = Mock(side_effect=KeyError('foo')) + >>> mock() + Traceback (most recent call last): + ... + KeyError: 'foo' + + >>> values = {'a': 1, 'b': 2, 'c': 3} + >>> def side_effect(arg): + ... return values[arg] + ... + >>> mock.side_effect = side_effect + >>> mock('a'), mock('b'), mock('c') + (1, 2, 3) + >>> mock.side_effect = [5, 4, 3, 2, 1] + >>> mock(), mock(), mock() + (5, 4, 3) + +Mock has many other ways you can configure it and control its behaviour. For +example the *spec* argument configures the mock to take its specification +from another object. Attempting to access attributes or methods on the mock +that don't exist on the spec will fail with an :exc:`AttributeError`. + +The :func:`patch` decorator / context manager makes it easy to mock classes or +objects in a module under test. The object you specify will be replaced with a +mock (or other object) during the test and restored when the test ends:: + + >>> from unittest.mock import patch + >>> @patch('module.ClassName2') + ... @patch('module.ClassName1') + ... def test(MockClass1, MockClass2): + ... module.ClassName1() + ... module.ClassName2() + ... assert MockClass1 is module.ClassName1 + ... assert MockClass2 is module.ClassName2 + ... assert MockClass1.called + ... assert MockClass2.called + ... + >>> test() + +.. note:: + + When you nest patch decorators the mocks are passed in to the decorated + function in the same order they applied (the normal *Python* order that + decorators are applied). This means from the bottom up, so in the example + above the mock for ``module.ClassName1`` is passed in first. + + With :func:`patch` it matters that you patch objects in the namespace where they + are looked up. This is normally straightforward, but for a quick guide + read :ref:`where to patch `. + +As well as a decorator :func:`patch` can be used as a context manager in a with +statement: + + >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method: + ... thing = ProductionClass() + ... thing.method(1, 2, 3) + ... + >>> mock_method.assert_called_once_with(1, 2, 3) + + +There is also :func:`patch.dict` for setting values in a dictionary just +during a scope and restoring the dictionary to its original state when the test +ends: + + >>> foo = {'key': 'value'} + >>> original = foo.copy() + >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True): + ... assert foo == {'newkey': 'newvalue'} + ... + >>> assert foo == original + +Mock supports the mocking of Python :ref:`magic methods `. The +easiest way of using magic methods is with the :class:`MagicMock` class. It +allows you to do things like: + + >>> mock = MagicMock() + >>> mock.__str__.return_value = 'foobarbaz' + >>> str(mock) + 'foobarbaz' + >>> mock.__str__.assert_called_with() + +Mock allows you to assign functions (or other Mock instances) to magic methods +and they will be called appropriately. The :class:`MagicMock` class is just a Mock +variant that has all of the magic methods pre-created for you (well, all the +useful ones anyway). + +The following is an example of using magic methods with the ordinary Mock +class: + + >>> mock = Mock() + >>> mock.__str__ = Mock(return_value='wheeeeee') + >>> str(mock) + 'wheeeeee' + +For ensuring that the mock objects in your tests have the same api as the +objects they are replacing, you can use :ref:`auto-speccing `. +Auto-speccing can be done through the *autospec* argument to patch, or the +:func:`create_autospec` function. Auto-speccing creates mock objects that +have the same attributes and methods as the objects they are replacing, and +any functions and methods (including constructors) have the same call +signature as the real object. + +This ensures that your mocks will fail in the same way as your production +code if they are used incorrectly: + + >>> from unittest.mock import create_autospec + >>> def function(a, b, c): + ... pass + ... + >>> mock_function = create_autospec(function, return_value='fishy') + >>> mock_function(1, 2, 3) + 'fishy' + >>> mock_function.assert_called_once_with(1, 2, 3) + >>> mock_function('wrong arguments') + Traceback (most recent call last): + ... + TypeError: () takes exactly 3 arguments (1 given) + +:func:`create_autospec` can also be used on classes, where it copies the signature of +the ``__init__`` method, and on callable objects where it copies the signature of +the ``__call__`` method. + + + +The Mock Class +-------------- + +.. testsetup:: + + import asyncio + import inspect + import unittest + from unittest.mock import sentinel, DEFAULT, ANY + from unittest.mock import patch, call, Mock, MagicMock, PropertyMock, AsyncMock + from unittest.mock import mock_open + +:class:`Mock` is a flexible mock object intended to replace the use of stubs and +test doubles throughout your code. Mocks are callable and create attributes as +new mocks when you access them [#]_. Accessing the same attribute will always +return the same mock. Mocks record how you use them, allowing you to make +assertions about what your code has done to them. + +:class:`MagicMock` is a subclass of :class:`Mock` with all the magic methods +pre-created and ready to use. There are also non-callable variants, useful +when you are mocking out objects that aren't callable: +:class:`NonCallableMock` and :class:`NonCallableMagicMock` + +The :func:`patch` decorators makes it easy to temporarily replace classes +in a particular module with a :class:`Mock` object. By default :func:`patch` will create +a :class:`MagicMock` for you. You can specify an alternative class of :class:`Mock` using +the *new_callable* argument to :func:`patch`. + + +.. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs) + + Create a new :class:`Mock` object. :class:`Mock` takes several optional arguments + that specify the behaviour of the Mock object: + + * *spec*: This can be either a list of strings or an existing object (a + class or instance) that acts as the specification for the mock object. If + you pass in an object then a list of strings is formed by calling dir on + the object (excluding unsupported magic attributes and methods). + Accessing any attribute not in this list will raise an :exc:`AttributeError`. + + If *spec* is an object (rather than a list of strings) then + :attr:`~instance.__class__` returns the class of the spec object. This + allows mocks to pass :func:`isinstance` tests. + + * *spec_set*: A stricter variant of *spec*. If used, attempting to *set* + or get an attribute on the mock that isn't on the object passed as + *spec_set* will raise an :exc:`AttributeError`. + + * *side_effect*: A function to be called whenever the Mock is called. See + the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or + dynamically changing return values. The function is called with the same + arguments as the mock, and unless it returns :data:`DEFAULT`, the return + value of this function is used as the return value. + + Alternatively *side_effect* can be an exception class or instance. In + this case the exception will be raised when the mock is called. + + If *side_effect* is an iterable then each call to the mock will return + the next value from the iterable. + + A *side_effect* can be cleared by setting it to ``None``. + + * *return_value*: The value returned when the mock is called. By default + this is a new Mock (created on first access). See the + :attr:`return_value` attribute. + + * *unsafe*: By default if any attribute starts with *assert* or + *assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True`` + will allow access to these attributes. + + .. versionadded:: 3.5 + + * *wraps*: Item for the mock object to wrap. If *wraps* is not ``None`` then + calling the Mock will pass the call through to the wrapped object + (returning the real result). Attribute access on the mock will return a + Mock object that wraps the corresponding attribute of the wrapped + object (so attempting to access an attribute that doesn't exist will + raise an :exc:`AttributeError`). + + If the mock has an explicit *return_value* set then calls are not passed + to the wrapped object and the *return_value* is returned instead. + + * *name*: If the mock has a name then it will be used in the repr of the + mock. This can be useful for debugging. The name is propagated to child + mocks. + + Mocks can also be called with arbitrary keyword arguments. These will be + used to set attributes on the mock after it is created. See the + :meth:`configure_mock` method for details. + + .. method:: assert_called() + + Assert that the mock was called at least once. + + >>> mock = Mock() + >>> mock.method() + + >>> mock.method.assert_called() + + .. versionadded:: 3.6 + + .. method:: assert_called_once() + + Assert that the mock was called exactly once. + + >>> mock = Mock() + >>> mock.method() + + >>> mock.method.assert_called_once() + >>> mock.method() + + >>> mock.method.assert_called_once() + Traceback (most recent call last): + ... + AssertionError: Expected 'method' to have been called once. Called 2 times. + + .. versionadded:: 3.6 + + + .. method:: assert_called_with(*args, **kwargs) + + This method is a convenient way of asserting that the last call has been + made in a particular way: + + >>> mock = Mock() + >>> mock.method(1, 2, 3, test='wow') + + >>> mock.method.assert_called_with(1, 2, 3, test='wow') + + .. method:: assert_called_once_with(*args, **kwargs) + + Assert that the mock was called exactly once and that that call was + with the specified arguments. + + >>> mock = Mock(return_value=None) + >>> mock('foo', bar='baz') + >>> mock.assert_called_once_with('foo', bar='baz') + >>> mock('other', bar='values') + >>> mock.assert_called_once_with('other', bar='values') + Traceback (most recent call last): + ... + AssertionError: Expected 'mock' to be called once. Called 2 times. + + + .. method:: assert_any_call(*args, **kwargs) + + assert the mock has been called with the specified arguments. + + The assert passes if the mock has *ever* been called, unlike + :meth:`assert_called_with` and :meth:`assert_called_once_with` that + only pass if the call is the most recent one, and in the case of + :meth:`assert_called_once_with` it must also be the only call. + + >>> mock = Mock(return_value=None) + >>> mock(1, 2, arg='thing') + >>> mock('some', 'thing', 'else') + >>> mock.assert_any_call(1, 2, arg='thing') + + + .. method:: assert_has_calls(calls, any_order=False) + + assert the mock has been called with the specified calls. + The :attr:`mock_calls` list is checked for the calls. + + If *any_order* is false then the calls must be + sequential. There can be extra calls before or after the + specified calls. + + If *any_order* is true then the calls can be in any order, but + they must all appear in :attr:`mock_calls`. + + >>> mock = Mock(return_value=None) + >>> mock(1) + >>> mock(2) + >>> mock(3) + >>> mock(4) + >>> calls = [call(2), call(3)] + >>> mock.assert_has_calls(calls) + >>> calls = [call(4), call(2), call(3)] + >>> mock.assert_has_calls(calls, any_order=True) + + .. method:: assert_not_called() + + Assert the mock was never called. + + >>> m = Mock() + >>> m.hello.assert_not_called() + >>> obj = m.hello() + >>> m.hello.assert_not_called() + Traceback (most recent call last): + ... + AssertionError: Expected 'hello' to not have been called. Called 1 times. + + .. versionadded:: 3.5 + + + .. method:: reset_mock(*, return_value=False, side_effect=False) + + The reset_mock method resets all the call attributes on a mock object: + + >>> mock = Mock(return_value=None) + >>> mock('hello') + >>> mock.called + True + >>> mock.reset_mock() + >>> mock.called + False + + .. versionchanged:: 3.6 + Added two keyword only argument to the reset_mock function. + + This can be useful where you want to make a series of assertions that + reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the + return value, :attr:`side_effect` or any child attributes you have + set using normal assignment by default. In case you want to reset + *return_value* or :attr:`side_effect`, then pass the corresponding + parameter as ``True``. Child mocks and the return value mock + (if any) are reset as well. + + .. note:: *return_value*, and :attr:`side_effect` are keyword only + argument. + + + .. method:: mock_add_spec(spec, spec_set=False) + + Add a spec to a mock. *spec* can either be an object or a + list of strings. Only attributes on the *spec* can be fetched as + attributes from the mock. + + If *spec_set* is true then only attributes on the spec can be set. + + + .. method:: attach_mock(mock, attribute) + + Attach a mock as an attribute of this one, replacing its name and + parent. Calls to the attached mock will be recorded in the + :attr:`method_calls` and :attr:`mock_calls` attributes of this one. + + + .. method:: configure_mock(**kwargs) + + Set attributes on the mock through keyword arguments. + + Attributes plus return values and side effects can be set on child + mocks using standard dot notation and unpacking a dictionary in the + method call: + + >>> mock = Mock() + >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} + >>> mock.configure_mock(**attrs) + >>> mock.method() + 3 + >>> mock.other() + Traceback (most recent call last): + ... + KeyError + + The same thing can be achieved in the constructor call to mocks: + + >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} + >>> mock = Mock(some_attribute='eggs', **attrs) + >>> mock.some_attribute + 'eggs' + >>> mock.method() + 3 + >>> mock.other() + Traceback (most recent call last): + ... + KeyError + + :meth:`configure_mock` exists to make it easier to do configuration + after the mock has been created. + + + .. method:: __dir__() + + :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results. + For mocks with a *spec* this includes all the permitted attributes + for the mock. + + See :data:`FILTER_DIR` for what this filtering does, and how to + switch it off. + + + .. method:: _get_child_mock(**kw) + + Create the child mocks for attributes and return value. + By default child mocks will be the same type as the parent. + Subclasses of Mock may want to override this to customize the way + child mocks are made. + + For non-callable mocks the callable variant will be used (rather than + any custom subclass). + + + .. attribute:: called + + A boolean representing whether or not the mock object has been called: + + >>> mock = Mock(return_value=None) + >>> mock.called + False + >>> mock() + >>> mock.called + True + + .. attribute:: call_count + + An integer telling you how many times the mock object has been called: + + >>> mock = Mock(return_value=None) + >>> mock.call_count + 0 + >>> mock() + >>> mock() + >>> mock.call_count + 2 + + .. attribute:: return_value + + Set this to configure the value returned by calling the mock: + + >>> mock = Mock() + >>> mock.return_value = 'fish' + >>> mock() + 'fish' + + The default return value is a mock object and you can configure it in + the normal way: + + >>> mock = Mock() + >>> mock.return_value.attribute = sentinel.Attribute + >>> mock.return_value() + + >>> mock.return_value.assert_called_with() + + :attr:`return_value` can also be set in the constructor: + + >>> mock = Mock(return_value=3) + >>> mock.return_value + 3 + >>> mock() + 3 + + + .. attribute:: side_effect + + This can either be a function to be called when the mock is called, + an iterable or an exception (class or instance) to be raised. + + If you pass in a function it will be called with same arguments as the + mock and unless the function returns the :data:`DEFAULT` singleton the + call to the mock will then return whatever the function returns. If the + function returns :data:`DEFAULT` then the mock will return its normal + value (from the :attr:`return_value`). + + If you pass in an iterable, it is used to retrieve an iterator which + must yield a value on every call. This value can either be an exception + instance to be raised, or a value to be returned from the call to the + mock (:data:`DEFAULT` handling is identical to the function case). + + An example of a mock that raises an exception (to test exception + handling of an API): + + >>> mock = Mock() + >>> mock.side_effect = Exception('Boom!') + >>> mock() + Traceback (most recent call last): + ... + Exception: Boom! + + Using :attr:`side_effect` to return a sequence of values: + + >>> mock = Mock() + >>> mock.side_effect = [3, 2, 1] + >>> mock(), mock(), mock() + (3, 2, 1) + + Using a callable: + + >>> mock = Mock(return_value=3) + >>> def side_effect(*args, **kwargs): + ... return DEFAULT + ... + >>> mock.side_effect = side_effect + >>> mock() + 3 + + :attr:`side_effect` can be set in the constructor. Here's an example that + adds one to the value the mock is called with and returns it: + + >>> side_effect = lambda value: value + 1 + >>> mock = Mock(side_effect=side_effect) + >>> mock(3) + 4 + >>> mock(-8) + -7 + + Setting :attr:`side_effect` to ``None`` clears it: + + >>> m = Mock(side_effect=KeyError, return_value=3) + >>> m() + Traceback (most recent call last): + ... + KeyError + >>> m.side_effect = None + >>> m() + 3 + + + .. attribute:: call_args + + This is either ``None`` (if the mock hasn't been called), or the + arguments that the mock was last called with. This will be in the + form of a tuple: the first member, which can also be accessed through + the ``args`` property, is any ordered arguments the mock was + called with (or an empty tuple) and the second member, which can + also be accessed through the ``kwargs`` property, is any keyword + arguments (or an empty dictionary). + + >>> mock = Mock(return_value=None) + >>> print(mock.call_args) + None + >>> mock() + >>> mock.call_args + call() + >>> mock.call_args == () + True + >>> mock(3, 4) + >>> mock.call_args + call(3, 4) + >>> mock.call_args == ((3, 4),) + True + >>> mock.call_args.args + (3, 4) + >>> mock.call_args.kwargs + {} + >>> mock(3, 4, 5, key='fish', next='w00t!') + >>> mock.call_args + call(3, 4, 5, key='fish', next='w00t!') + >>> mock.call_args.args + (3, 4, 5) + >>> mock.call_args.kwargs + {'key': 'fish', 'next': 'w00t!'} + + :attr:`call_args`, along with members of the lists :attr:`call_args_list`, + :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects. + These are tuples, so they can be unpacked to get at the individual + arguments and make more complex assertions. See + :ref:`calls as tuples `. + + + .. attribute:: call_args_list + + This is a list of all the calls made to the mock object in sequence + (so the length of the list is the number of times it has been + called). Before any calls have been made it is an empty list. The + :data:`call` object can be used for conveniently constructing lists of + calls to compare with :attr:`call_args_list`. + + >>> mock = Mock(return_value=None) + >>> mock() + >>> mock(3, 4) + >>> mock(key='fish', next='w00t!') + >>> mock.call_args_list + [call(), call(3, 4), call(key='fish', next='w00t!')] + >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)] + >>> mock.call_args_list == expected + True + + Members of :attr:`call_args_list` are :data:`call` objects. These can be + unpacked as tuples to get at the individual arguments. See + :ref:`calls as tuples `. + + + .. attribute:: method_calls + + As well as tracking calls to themselves, mocks also track calls to + methods and attributes, and *their* methods and attributes: + + >>> mock = Mock() + >>> mock.method() + + >>> mock.property.method.attribute() + + >>> mock.method_calls + [call.method(), call.property.method.attribute()] + + Members of :attr:`method_calls` are :data:`call` objects. These can be + unpacked as tuples to get at the individual arguments. See + :ref:`calls as tuples `. + + + .. attribute:: mock_calls + + :attr:`mock_calls` records *all* calls to the mock object, its methods, + magic methods *and* return value mocks. + + >>> mock = MagicMock() + >>> result = mock(1, 2, 3) + >>> mock.first(a=3) + + >>> mock.second() + + >>> int(mock) + 1 + >>> result(1) + + >>> expected = [call(1, 2, 3), call.first(a=3), call.second(), + ... call.__int__(), call()(1)] + >>> mock.mock_calls == expected + True + + Members of :attr:`mock_calls` are :data:`call` objects. These can be + unpacked as tuples to get at the individual arguments. See + :ref:`calls as tuples `. + + .. note:: + + The way :attr:`mock_calls` are recorded means that where nested + calls are made, the parameters of ancestor calls are not recorded + and so will always compare equal: + + >>> mock = MagicMock() + >>> mock.top(a=3).bottom() + + >>> mock.mock_calls + [call.top(a=3), call.top().bottom()] + >>> mock.mock_calls[-1] == call.top(a=-1).bottom() + True + + .. attribute:: __class__ + + Normally the :attr:`__class__` attribute of an object will return its type. + For a mock object with a :attr:`spec`, ``__class__`` returns the spec class + instead. This allows mock objects to pass :func:`isinstance` tests for the + object they are replacing / masquerading as: + + >>> mock = Mock(spec=3) + >>> isinstance(mock, int) + True + + :attr:`__class__` is assignable to, this allows a mock to pass an + :func:`isinstance` check without forcing you to use a spec: + + >>> mock = Mock() + >>> mock.__class__ = dict + >>> isinstance(mock, dict) + True + +.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs) + + A non-callable version of :class:`Mock`. The constructor parameters have the same + meaning of :class:`Mock`, with the exception of *return_value* and *side_effect* + which have no meaning on a non-callable mock. + +Mock objects that use a class or an instance as a :attr:`spec` or +:attr:`spec_set` are able to pass :func:`isinstance` tests: + + >>> mock = Mock(spec=SomeClass) + >>> isinstance(mock, SomeClass) + True + >>> mock = Mock(spec_set=SomeClass()) + >>> isinstance(mock, SomeClass) + True + +The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic +methods ` for the full details. + +The mock classes and the :func:`patch` decorators all take arbitrary keyword +arguments for configuration. For the :func:`patch` decorators the keywords are +passed to the constructor of the mock being created. The keyword arguments +are for configuring attributes of the mock: + + >>> m = MagicMock(attribute=3, other='fish') + >>> m.attribute + 3 + >>> m.other + 'fish' + +The return value and side effect of child mocks can be set in the same way, +using dotted notation. As you can't use dotted names directly in a call you +have to create a dictionary and unpack it using ``**``: + + >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} + >>> mock = Mock(some_attribute='eggs', **attrs) + >>> mock.some_attribute + 'eggs' + >>> mock.method() + 3 + >>> mock.other() + Traceback (most recent call last): + ... + KeyError + +A callable mock which was created with a *spec* (or a *spec_set*) will +introspect the specification object's signature when matching calls to +the mock. Therefore, it can match the actual call's arguments regardless +of whether they were passed positionally or by name:: + + >>> def f(a, b, c): pass + ... + >>> mock = Mock(spec=f) + >>> mock(1, 2, c=3) + + >>> mock.assert_called_with(1, 2, 3) + >>> mock.assert_called_with(a=1, b=2, c=3) + +This applies to :meth:`~Mock.assert_called_with`, +:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and +:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also +apply to method calls on the mock object. + + .. versionchanged:: 3.4 + Added signature introspection on specced and autospecced mock objects. + + +.. class:: PropertyMock(*args, **kwargs) + + A mock intended to be used as a property, or other descriptor, on a class. + :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods + so you can specify a return value when it is fetched. + + Fetching a :class:`PropertyMock` instance from an object calls the mock, with + no args. Setting it calls the mock with the value being set. :: + + >>> class Foo: + ... @property + ... def foo(self): + ... return 'something' + ... @foo.setter + ... def foo(self, value): + ... pass + ... + >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo: + ... mock_foo.return_value = 'mockity-mock' + ... this_foo = Foo() + ... print(this_foo.foo) + ... this_foo.foo = 6 + ... + mockity-mock + >>> mock_foo.mock_calls + [call(), call(6)] + +Because of the way mock attributes are stored you can't directly attach a +:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type +object:: + + >>> m = MagicMock() + >>> p = PropertyMock(return_value=3) + >>> type(m).foo = p + >>> m.foo + 3 + >>> p.assert_called_once_with() + + +.. class:: AsyncMock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs) + + An asynchronous version of :class:`MagicMock`. The :class:`AsyncMock` object will + behave so the object is recognized as an async function, and the result of a + call is an awaitable. + + >>> mock = AsyncMock() + >>> asyncio.iscoroutinefunction(mock) + True + >>> inspect.isawaitable(mock()) # doctest: +SKIP + True + + The result of ``mock()`` is an async function which will have the outcome + of ``side_effect`` or ``return_value`` after it has been awaited: + + - if ``side_effect`` is a function, the async function will return the + result of that function, + - if ``side_effect`` is an exception, the async function will raise the + exception, + - if ``side_effect`` is an iterable, the async function will return the + next value of the iterable, however, if the sequence of result is + exhausted, ``StopAsyncIteration`` is raised immediately, + - if ``side_effect`` is not defined, the async function will return the + value defined by ``return_value``, hence, by default, the async function + returns a new :class:`AsyncMock` object. + + + Setting the *spec* of a :class:`Mock` or :class:`MagicMock` to an async function + will result in a coroutine object being returned after calling. + + >>> async def async_func(): pass + ... + >>> mock = MagicMock(async_func) + >>> mock + + >>> mock() # doctest: +SKIP + + + + Setting the *spec* of a :class:`Mock`, :class:`MagicMock`, or :class:`AsyncMock` + to a class with asynchronous and synchronous functions will automatically + detect the synchronous functions and set them as :class:`MagicMock` (if the + parent mock is :class:`AsyncMock` or :class:`MagicMock`) or :class:`Mock` (if + the parent mock is :class:`Mock`). All asynchronous functions will be + :class:`AsyncMock`. + + >>> class ExampleClass: + ... def sync_foo(): + ... pass + ... async def async_foo(): + ... pass + ... + >>> a_mock = AsyncMock(ExampleClass) + >>> a_mock.sync_foo + + >>> a_mock.async_foo + + >>> mock = Mock(ExampleClass) + >>> mock.sync_foo + + >>> mock.async_foo + + + .. versionadded:: 3.8 + + .. method:: assert_awaited() + + Assert that the mock was awaited at least once. Note that this is separate + from the object having been called, the ``await`` keyword must be used: + + >>> mock = AsyncMock() + >>> async def main(coroutine_mock): + ... await coroutine_mock + ... + >>> coroutine_mock = mock() + >>> mock.called + True + >>> mock.assert_awaited() + Traceback (most recent call last): + ... + AssertionError: Expected mock to have been awaited. + >>> asyncio.run(main(coroutine_mock)) + >>> mock.assert_awaited() + + .. method:: assert_awaited_once() + + Assert that the mock was awaited exactly once. + + >>> mock = AsyncMock() + >>> async def main(): + ... await mock() + ... + >>> asyncio.run(main()) + >>> mock.assert_awaited_once() + >>> asyncio.run(main()) + >>> mock.method.assert_awaited_once() + Traceback (most recent call last): + ... + AssertionError: Expected mock to have been awaited once. Awaited 2 times. + + .. method:: assert_awaited_with(*args, **kwargs) + + Assert that the last await was with the specified arguments. + + >>> mock = AsyncMock() + >>> async def main(*args, **kwargs): + ... await mock(*args, **kwargs) + ... + >>> asyncio.run(main('foo', bar='bar')) + >>> mock.assert_awaited_with('foo', bar='bar') + >>> mock.assert_awaited_with('other') + Traceback (most recent call last): + ... + AssertionError: expected call not found. + Expected: mock('other') + Actual: mock('foo', bar='bar') + + .. method:: assert_awaited_once_with(*args, **kwargs) + + Assert that the mock was awaited exactly once and with the specified + arguments. + + >>> mock = AsyncMock() + >>> async def main(*args, **kwargs): + ... await mock(*args, **kwargs) + ... + >>> asyncio.run(main('foo', bar='bar')) + >>> mock.assert_awaited_once_with('foo', bar='bar') + >>> asyncio.run(main('foo', bar='bar')) + >>> mock.assert_awaited_once_with('foo', bar='bar') + Traceback (most recent call last): + ... + AssertionError: Expected mock to have been awaited once. Awaited 2 times. + + .. method:: assert_any_await(*args, **kwargs) + + Assert the mock has ever been awaited with the specified arguments. + + >>> mock = AsyncMock() + >>> async def main(*args, **kwargs): + ... await mock(*args, **kwargs) + ... + >>> asyncio.run(main('foo', bar='bar')) + >>> asyncio.run(main('hello')) + >>> mock.assert_any_await('foo', bar='bar') + >>> mock.assert_any_await('other') + Traceback (most recent call last): + ... + AssertionError: mock('other') await not found + + .. method:: assert_has_awaits(calls, any_order=False) + + Assert the mock has been awaited with the specified calls. + The :attr:`await_args_list` list is checked for the awaits. + + If *any_order* is false then the awaits must be + sequential. There can be extra calls before or after the + specified awaits. + + If *any_order* is true then the awaits can be in any order, but + they must all appear in :attr:`await_args_list`. + + >>> mock = AsyncMock() + >>> async def main(*args, **kwargs): + ... await mock(*args, **kwargs) + ... + >>> calls = [call("foo"), call("bar")] + >>> mock.assert_has_awaits(calls) + Traceback (most recent call last): + ... + AssertionError: Awaits not found. + Expected: [call('foo'), call('bar')] + Actual: [] + >>> asyncio.run(main('foo')) + >>> asyncio.run(main('bar')) + >>> mock.assert_has_awaits(calls) + + .. method:: assert_not_awaited() + + Assert that the mock was never awaited. + + >>> mock = AsyncMock() + >>> mock.assert_not_awaited() + + .. method:: reset_mock(*args, **kwargs) + + See :func:`Mock.reset_mock`. Also sets :attr:`await_count` to 0, + :attr:`await_args` to None, and clears the :attr:`await_args_list`. + + .. attribute:: await_count + + An integer keeping track of how many times the mock object has been awaited. + + >>> mock = AsyncMock() + >>> async def main(): + ... await mock() + ... + >>> asyncio.run(main()) + >>> mock.await_count + 1 + >>> asyncio.run(main()) + >>> mock.await_count + 2 + + .. attribute:: await_args + + This is either ``None`` (if the mock hasn’t been awaited), or the arguments that + the mock was last awaited with. Functions the same as :attr:`Mock.call_args`. + + >>> mock = AsyncMock() + >>> async def main(*args): + ... await mock(*args) + ... + >>> mock.await_args + >>> asyncio.run(main('foo')) + >>> mock.await_args + call('foo') + >>> asyncio.run(main('bar')) + >>> mock.await_args + call('bar') + + + .. attribute:: await_args_list + + This is a list of all the awaits made to the mock object in sequence (so the + length of the list is the number of times it has been awaited). Before any + awaits have been made it is an empty list. + + >>> mock = AsyncMock() + >>> async def main(*args): + ... await mock(*args) + ... + >>> mock.await_args_list + [] + >>> asyncio.run(main('foo')) + >>> mock.await_args_list + [call('foo')] + >>> asyncio.run(main('bar')) + >>> mock.await_args_list + [call('foo'), call('bar')] + + +Calling +~~~~~~~ + +Mock objects are callable. The call will return the value set as the +:attr:`~Mock.return_value` attribute. The default return value is a new Mock +object; it is created the first time the return value is accessed (either +explicitly or by calling the Mock) - but it is stored and the same one +returned each time. + +Calls made to the object will be recorded in the attributes +like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`. + +If :attr:`~Mock.side_effect` is set then it will be called after the call has +been recorded, so if :attr:`side_effect` raises an exception the call is still +recorded. + +The simplest way to make a mock raise an exception when called is to make +:attr:`~Mock.side_effect` an exception class or instance: + + >>> m = MagicMock(side_effect=IndexError) + >>> m(1, 2, 3) + Traceback (most recent call last): + ... + IndexError + >>> m.mock_calls + [call(1, 2, 3)] + >>> m.side_effect = KeyError('Bang!') + >>> m('two', 'three', 'four') + Traceback (most recent call last): + ... + KeyError: 'Bang!' + >>> m.mock_calls + [call(1, 2, 3), call('two', 'three', 'four')] + +If :attr:`side_effect` is a function then whatever that function returns is what +calls to the mock return. The :attr:`side_effect` function is called with the +same arguments as the mock. This allows you to vary the return value of the +call dynamically, based on the input: + + >>> def side_effect(value): + ... return value + 1 + ... + >>> m = MagicMock(side_effect=side_effect) + >>> m(1) + 2 + >>> m(2) + 3 + >>> m.mock_calls + [call(1), call(2)] + +If you want the mock to still return the default return value (a new mock), or +any set return value, then there are two ways of doing this. Either return +:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`: + + >>> m = MagicMock() + >>> def side_effect(*args, **kwargs): + ... return m.return_value + ... + >>> m.side_effect = side_effect + >>> m.return_value = 3 + >>> m() + 3 + >>> def side_effect(*args, **kwargs): + ... return DEFAULT + ... + >>> m.side_effect = side_effect + >>> m() + 3 + +To remove a :attr:`side_effect`, and return to the default behaviour, set the +:attr:`side_effect` to ``None``: + + >>> m = MagicMock(return_value=6) + >>> def side_effect(*args, **kwargs): + ... return 3 + ... + >>> m.side_effect = side_effect + >>> m() + 3 + >>> m.side_effect = None + >>> m() + 6 + +The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock +will return values from the iterable (until the iterable is exhausted and +a :exc:`StopIteration` is raised): + + >>> m = MagicMock(side_effect=[1, 2, 3]) + >>> m() + 1 + >>> m() + 2 + >>> m() + 3 + >>> m() + Traceback (most recent call last): + ... + StopIteration + +If any members of the iterable are exceptions they will be raised instead of +returned:: + + >>> iterable = (33, ValueError, 66) + >>> m = MagicMock(side_effect=iterable) + >>> m() + 33 + >>> m() + Traceback (most recent call last): + ... + ValueError + >>> m() + 66 + + +.. _deleting-attributes: + +Deleting Attributes +~~~~~~~~~~~~~~~~~~~ + +Mock objects create attributes on demand. This allows them to pretend to be +objects of any type. + +You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an +:exc:`AttributeError` when an attribute is fetched. You can do this by providing +an object as a :attr:`spec` for a mock, but that isn't always convenient. + +You "block" attributes by deleting them. Once deleted, accessing an attribute +will raise an :exc:`AttributeError`. + + >>> mock = MagicMock() + >>> hasattr(mock, 'm') + True + >>> del mock.m + >>> hasattr(mock, 'm') + False + >>> del mock.f + >>> mock.f + Traceback (most recent call last): + ... + AttributeError: f + + +Mock names and the name attribute +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Since "name" is an argument to the :class:`Mock` constructor, if you want your +mock object to have a "name" attribute you can't just pass it in at creation +time. There are two alternatives. One option is to use +:meth:`~Mock.configure_mock`:: + + >>> mock = MagicMock() + >>> mock.configure_mock(name='my_name') + >>> mock.name + 'my_name' + +A simpler option is to simply set the "name" attribute after mock creation:: + + >>> mock = MagicMock() + >>> mock.name = "foo" + + +Attaching Mocks as Attributes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When you attach a mock as an attribute of another mock (or as the return +value) it becomes a "child" of that mock. Calls to the child are recorded in +the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the +parent. This is useful for configuring child mocks and then attaching them to +the parent, or for attaching mocks to a parent that records all calls to the +children and allows you to make assertions about the order of calls between +mocks: + + >>> parent = MagicMock() + >>> child1 = MagicMock(return_value=None) + >>> child2 = MagicMock(return_value=None) + >>> parent.child1 = child1 + >>> parent.child2 = child2 + >>> child1(1) + >>> child2(2) + >>> parent.mock_calls + [call.child1(1), call.child2(2)] + +The exception to this is if the mock has a name. This allows you to prevent +the "parenting" if for some reason you don't want it to happen. + + >>> mock = MagicMock() + >>> not_a_child = MagicMock(name='not-a-child') + >>> mock.attribute = not_a_child + >>> mock.attribute() + + >>> mock.mock_calls + [] + +Mocks created for you by :func:`patch` are automatically given names. To +attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock` +method:: + + >>> thing1 = object() + >>> thing2 = object() + >>> parent = MagicMock() + >>> with patch('__main__.thing1', return_value=None) as child1: + ... with patch('__main__.thing2', return_value=None) as child2: + ... parent.attach_mock(child1, 'child1') + ... parent.attach_mock(child2, 'child2') + ... child1('one') + ... child2('two') + ... + >>> parent.mock_calls + [call.child1('one'), call.child2('two')] + + +.. [#] The only exceptions are magic methods and attributes (those that have + leading and trailing double underscores). Mock doesn't create these but + instead raises an :exc:`AttributeError`. This is because the interpreter + will often implicitly request these methods, and gets *very* confused to + get a new Mock object when it expects a magic method. If you need magic + method support see :ref:`magic methods `. + + +The patchers +------------ + +The patch decorators are used for patching objects only within the scope of +the function they decorate. They automatically handle the unpatching for you, +even if exceptions are raised. All of these functions can also be used in with +statements or as class decorators. + + +patch +~~~~~ + +.. note:: + + The key is to do the patching in the right namespace. See the section `where to patch`_. + +.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) + + :func:`patch` acts as a function decorator, class decorator or a context + manager. Inside the body of the function or with statement, the *target* + is patched with a *new* object. When the function/with statement exits + the patch is undone. + + If *new* is omitted, then the target is replaced with an + :class:`AsyncMock` if the patched object is an async function or + a :class:`MagicMock` otherwise. + If :func:`patch` is used as a decorator and *new* is + omitted, the created mock is passed in as an extra argument to the + decorated function. If :func:`patch` is used as a context manager the created + mock is returned by the context manager. + + *target* should be a string in the form ``'package.module.ClassName'``. The + *target* is imported and the specified object replaced with the *new* + object, so the *target* must be importable from the environment you are + calling :func:`patch` from. The target is imported when the decorated function + is executed, not at decoration time. + + The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock` + if patch is creating one for you. + + In addition you can pass ``spec=True`` or ``spec_set=True``, which causes + patch to pass in the object being mocked as the spec/spec_set object. + + *new_callable* allows you to specify a different class, or callable object, + that will be called to create the *new* object. By default :class:`AsyncMock` + is used for async functions and :class:`MagicMock` for the rest. + + A more powerful form of *spec* is *autospec*. If you set ``autospec=True`` + then the mock will be created with a spec from the object being replaced. + All attributes of the mock will also have the spec of the corresponding + attribute of the object being replaced. Methods and functions being mocked + will have their arguments checked and will raise a :exc:`TypeError` if they are + called with the wrong signature. For mocks + replacing a class, their return value (the 'instance') will have the same + spec as the class. See the :func:`create_autospec` function and + :ref:`auto-speccing`. + + Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an + arbitrary object as the spec instead of the one being replaced. + + By default :func:`patch` will fail to replace attributes that don't exist. + If you pass in ``create=True``, and the attribute doesn't exist, patch will + create the attribute for you when the patched function is called, and delete + it again after the patched function has exited. This is useful for writing + tests against attributes that your production code creates at runtime. It is + off by default because it can be dangerous. With it switched on you can + write passing tests against APIs that don't actually exist! + + .. note:: + + .. versionchanged:: 3.5 + If you are patching builtins in a module then you don't + need to pass ``create=True``, it will be added by default. + + Patch can be used as a :class:`TestCase` class decorator. It works by + decorating each test method in the class. This reduces the boilerplate + code when your test methods share a common patchings set. :func:`patch` finds + tests by looking for method names that start with ``patch.TEST_PREFIX``. + By default this is ``'test'``, which matches the way :mod:`unittest` finds tests. + You can specify an alternative prefix by setting ``patch.TEST_PREFIX``. + + Patch can be used as a context manager, with the with statement. Here the + patching applies to the indented block after the with statement. If you + use "as" then the patched object will be bound to the name after the + "as"; very useful if :func:`patch` is creating a mock object for you. + + :func:`patch` takes arbitrary keyword arguments. These will be passed to + :class:`AsyncMock` if the patched object is asynchronous, to + :class:`MagicMock` otherwise or to *new_callable* if specified. + + ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are + available for alternate use-cases. + +:func:`patch` as function decorator, creating the mock for you and passing it into +the decorated function:: + + >>> @patch('__main__.SomeClass') + ... def function(normal_argument, mock_class): + ... print(mock_class is SomeClass) + ... + >>> function(None) + True + +Patching a class replaces the class with a :class:`MagicMock` *instance*. If the +class is instantiated in the code under test then it will be the +:attr:`~Mock.return_value` of the mock that will be used. + +If the class is instantiated multiple times you could use +:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you +can set the *return_value* to be anything you want. + +To configure return values on methods of *instances* on the patched class +you must do this on the :attr:`return_value`. For example:: + + >>> class Class: + ... def method(self): + ... pass + ... + >>> with patch('__main__.Class') as MockClass: + ... instance = MockClass.return_value + ... instance.method.return_value = 'foo' + ... assert Class() is instance + ... assert Class().method() == 'foo' + ... + +If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the +return value of the created mock will have the same spec. :: + + >>> Original = Class + >>> patcher = patch('__main__.Class', spec=True) + >>> MockClass = patcher.start() + >>> instance = MockClass() + >>> assert isinstance(instance, Original) + >>> patcher.stop() + +The *new_callable* argument is useful where you want to use an alternative +class to the default :class:`MagicMock` for the created mock. For example, if +you wanted a :class:`NonCallableMock` to be used:: + + >>> thing = object() + >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing: + ... assert thing is mock_thing + ... thing() + ... + Traceback (most recent call last): + ... + TypeError: 'NonCallableMock' object is not callable + +Another use case might be to replace an object with an :class:`io.StringIO` instance:: + + >>> from io import StringIO + >>> def foo(): + ... print('Something') + ... + >>> @patch('sys.stdout', new_callable=StringIO) + ... def test(mock_stdout): + ... foo() + ... assert mock_stdout.getvalue() == 'Something\n' + ... + >>> test() + +When :func:`patch` is creating a mock for you, it is common that the first thing +you need to do is to configure the mock. Some of that configuration can be done +in the call to patch. Any arbitrary keywords you pass into the call will be +used to set attributes on the created mock:: + + >>> patcher = patch('__main__.thing', first='one', second='two') + >>> mock_thing = patcher.start() + >>> mock_thing.first + 'one' + >>> mock_thing.second + 'two' + +As well as attributes on the created mock attributes, like the +:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can +also be configured. These aren't syntactically valid to pass in directly as +keyword arguments, but a dictionary with these as keys can still be expanded +into a :func:`patch` call using ``**``:: + + >>> config = {'method.return_value': 3, 'other.side_effect': KeyError} + >>> patcher = patch('__main__.thing', **config) + >>> mock_thing = patcher.start() + >>> mock_thing.method() + 3 + >>> mock_thing.other() + Traceback (most recent call last): + ... + KeyError + +By default, attempting to patch a function in a module (or a method or an +attribute in a class) that does not exist will fail with :exc:`AttributeError`:: + + >>> @patch('sys.non_existing_attribute', 42) + ... def test(): + ... assert sys.non_existing_attribute == 42 + ... + >>> test() + Traceback (most recent call last): + ... + AttributeError: does not have the attribute 'non_existing' + +but adding ``create=True`` in the call to :func:`patch` will make the previous example +work as expected:: + + >>> @patch('sys.non_existing_attribute', 42, create=True) + ... def test(mock_stdout): + ... assert sys.non_existing_attribute == 42 + ... + >>> test() + +.. versionchanged:: 3.8 + + :func:`patch` now returns an :class:`AsyncMock` if the target is an async function. + + +patch.object +~~~~~~~~~~~~ + +.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) + + patch the named member (*attribute*) on an object (*target*) with a mock + object. + + :func:`patch.object` can be used as a decorator, class decorator or a context + manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and + *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`, + :func:`patch.object` takes arbitrary keyword arguments for configuring the mock + object it creates. + + When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX`` + for choosing which methods to wrap. + +You can either call :func:`patch.object` with three arguments or two arguments. The +three argument form takes the object to be patched, the attribute name and the +object to replace the attribute with. + +When calling with the two argument form you omit the replacement object, and a +mock is created for you and passed in as an extra argument to the decorated +function: + + >>> @patch.object(SomeClass, 'class_method') + ... def test(mock_method): + ... SomeClass.class_method(3) + ... mock_method.assert_called_with(3) + ... + >>> test() + +*spec*, *create* and the other arguments to :func:`patch.object` have the same +meaning as they do for :func:`patch`. + + +patch.dict +~~~~~~~~~~ + +.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs) + + Patch a dictionary, or dictionary like object, and restore the dictionary + to its original state after the test. + + *in_dict* can be a dictionary or a mapping like container. If it is a + mapping then it must at least support getting, setting and deleting items + plus iterating over keys. + + *in_dict* can also be a string specifying the name of the dictionary, which + will then be fetched by importing it. + + *values* can be a dictionary of values to set in the dictionary. *values* + can also be an iterable of ``(key, value)`` pairs. + + If *clear* is true then the dictionary will be cleared before the new + values are set. + + :func:`patch.dict` can also be called with arbitrary keyword arguments to set + values in the dictionary. + + .. versionchanged:: 3.8 + + :func:`patch.dict` now returns the patched dictionary when used as a context + manager. + +:func:`patch.dict` can be used as a context manager, decorator or class +decorator: + + >>> foo = {} + >>> @patch.dict(foo, {'newkey': 'newvalue'}) + ... def test(): + ... assert foo == {'newkey': 'newvalue'} + >>> test() + >>> assert foo == {} + +When used as a class decorator :func:`patch.dict` honours +``patch.TEST_PREFIX`` (default to ``'test'``) for choosing which methods to wrap: + + >>> import os + >>> import unittest + >>> from unittest.mock import patch + >>> @patch.dict('os.environ', {'newkey': 'newvalue'}) + ... class TestSample(unittest.TestCase): + ... def test_sample(self): + ... self.assertEqual(os.environ['newkey'], 'newvalue') + +If you want to use a different prefix for your test, you can inform the +patchers of the different prefix by setting ``patch.TEST_PREFIX``. For +more details about how to change the value of see :ref:`test-prefix`. + +:func:`patch.dict` can be used to add members to a dictionary, or simply let a test +change a dictionary, and ensure the dictionary is restored when the test +ends. + + >>> foo = {} + >>> with patch.dict(foo, {'newkey': 'newvalue'}) as patched_foo: + ... assert foo == {'newkey': 'newvalue'} + ... assert patched_foo == {'newkey': 'newvalue'} + ... # You can add, update or delete keys of foo (or patched_foo, it's the same dict) + ... patched_foo['spam'] = 'eggs' + ... + >>> assert foo == {} + >>> assert patched_foo == {} + + >>> import os + >>> with patch.dict('os.environ', {'newkey': 'newvalue'}): + ... print(os.environ['newkey']) + ... + newvalue + >>> assert 'newkey' not in os.environ + +Keywords can be used in the :func:`patch.dict` call to set values in the dictionary: + + >>> mymodule = MagicMock() + >>> mymodule.function.return_value = 'fish' + >>> with patch.dict('sys.modules', mymodule=mymodule): + ... import mymodule + ... mymodule.function('some', 'args') + ... + 'fish' + +:func:`patch.dict` can be used with dictionary like objects that aren't actually +dictionaries. At the very minimum they must support item getting, setting, +deleting and either iteration or membership test. This corresponds to the +magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either +:meth:`__iter__` or :meth:`__contains__`. + + >>> class Container: + ... def __init__(self): + ... self.values = {} + ... def __getitem__(self, name): + ... return self.values[name] + ... def __setitem__(self, name, value): + ... self.values[name] = value + ... def __delitem__(self, name): + ... del self.values[name] + ... def __iter__(self): + ... return iter(self.values) + ... + >>> thing = Container() + >>> thing['one'] = 1 + >>> with patch.dict(thing, one=2, two=3): + ... assert thing['one'] == 2 + ... assert thing['two'] == 3 + ... + >>> assert thing['one'] == 1 + >>> assert list(thing) == ['one'] + + +patch.multiple +~~~~~~~~~~~~~~ + +.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) + + Perform multiple patches in a single call. It takes the object to be + patched (either as an object or a string to fetch the object by importing) + and keyword arguments for the patches:: + + with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): + ... + + Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create + mocks for you. In this case the created mocks are passed into a decorated + function by keyword, and a dictionary is returned when :func:`patch.multiple` is + used as a context manager. + + :func:`patch.multiple` can be used as a decorator, class decorator or a context + manager. The arguments *spec*, *spec_set*, *create*, *autospec* and + *new_callable* have the same meaning as for :func:`patch`. These arguments will + be applied to *all* patches done by :func:`patch.multiple`. + + When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX`` + for choosing which methods to wrap. + +If you want :func:`patch.multiple` to create mocks for you, then you can use +:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator +then the created mocks are passed into the decorated function by keyword. :: + + >>> thing = object() + >>> other = object() + + >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) + ... def test_function(thing, other): + ... assert isinstance(thing, MagicMock) + ... assert isinstance(other, MagicMock) + ... + >>> test_function() + +:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments +passed by keyword *after* any of the standard arguments created by :func:`patch`:: + + >>> @patch('sys.exit') + ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) + ... def test_function(mock_exit, other, thing): + ... assert 'other' in repr(other) + ... assert 'thing' in repr(thing) + ... assert 'exit' in repr(mock_exit) + ... + >>> test_function() + +If :func:`patch.multiple` is used as a context manager, the value returned by the +context manager is a dictionary where created mocks are keyed by name:: + + >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values: + ... assert 'other' in repr(values['other']) + ... assert 'thing' in repr(values['thing']) + ... assert values['thing'] is thing + ... assert values['other'] is other + ... + + +.. _start-and-stop: + +patch methods: start and stop +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do +patching in ``setUp`` methods or where you want to do multiple patches without +nesting decorators or with statements. + +To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as +normal and keep a reference to the returned ``patcher`` object. You can then +call :meth:`start` to put the patch in place and :meth:`stop` to undo it. + +If you are using :func:`patch` to create a mock for you then it will be returned by +the call to ``patcher.start``. :: + + >>> patcher = patch('package.module.ClassName') + >>> from package import module + >>> original = module.ClassName + >>> new_mock = patcher.start() + >>> assert module.ClassName is not original + >>> assert module.ClassName is new_mock + >>> patcher.stop() + >>> assert module.ClassName is original + >>> assert module.ClassName is not new_mock + + +A typical use case for this might be for doing multiple patches in the ``setUp`` +method of a :class:`TestCase`:: + + >>> class MyTest(unittest.TestCase): + ... def setUp(self): + ... self.patcher1 = patch('package.module.Class1') + ... self.patcher2 = patch('package.module.Class2') + ... self.MockClass1 = self.patcher1.start() + ... self.MockClass2 = self.patcher2.start() + ... + ... def tearDown(self): + ... self.patcher1.stop() + ... self.patcher2.stop() + ... + ... def test_something(self): + ... assert package.module.Class1 is self.MockClass1 + ... assert package.module.Class2 is self.MockClass2 + ... + >>> MyTest('test_something').run() + +.. caution:: + + If you use this technique you must ensure that the patching is "undone" by + calling ``stop``. This can be fiddlier than you might think, because if an + exception is raised in the ``setUp`` then ``tearDown`` is not called. + :meth:`unittest.TestCase.addCleanup` makes this easier:: + + >>> class MyTest(unittest.TestCase): + ... def setUp(self): + ... patcher = patch('package.module.Class') + ... self.MockClass = patcher.start() + ... self.addCleanup(patcher.stop) + ... + ... def test_something(self): + ... assert package.module.Class is self.MockClass + ... + + As an added bonus you no longer need to keep a reference to the ``patcher`` + object. + +It is also possible to stop all patches which have been started by using +:func:`patch.stopall`. + +.. function:: patch.stopall + + Stop all active patches. Only stops patches started with ``start``. + + +.. _patch-builtins: + +patch builtins +~~~~~~~~~~~~~~ +You can patch any builtins within a module. The following example patches +builtin :func:`ord`:: + + >>> @patch('__main__.ord') + ... def test(mock_ord): + ... mock_ord.return_value = 101 + ... print(ord('c')) + ... + >>> test() + 101 + + +.. _test-prefix: + +TEST_PREFIX +~~~~~~~~~~~ + +All of the patchers can be used as class decorators. When used in this way +they wrap every test method on the class. The patchers recognise methods that +start with ``'test'`` as being test methods. This is the same way that the +:class:`unittest.TestLoader` finds test methods by default. + +It is possible that you want to use a different prefix for your tests. You can +inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``:: + + >>> patch.TEST_PREFIX = 'foo' + >>> value = 3 + >>> + >>> @patch('__main__.value', 'not three') + ... class Thing: + ... def foo_one(self): + ... print(value) + ... def foo_two(self): + ... print(value) + ... + >>> + >>> Thing().foo_one() + not three + >>> Thing().foo_two() + not three + >>> value + 3 + + +Nesting Patch Decorators +~~~~~~~~~~~~~~~~~~~~~~~~ + +If you want to perform multiple patches then you can simply stack up the +decorators. + +You can stack up multiple patch decorators using this pattern: + + >>> @patch.object(SomeClass, 'class_method') + ... @patch.object(SomeClass, 'static_method') + ... def test(mock1, mock2): + ... assert SomeClass.static_method is mock1 + ... assert SomeClass.class_method is mock2 + ... SomeClass.static_method('foo') + ... SomeClass.class_method('bar') + ... return mock1, mock2 + ... + >>> mock1, mock2 = test() + >>> mock1.assert_called_once_with('foo') + >>> mock2.assert_called_once_with('bar') + + +Note that the decorators are applied from the bottom upwards. This is the +standard way that Python applies decorators. The order of the created mocks +passed into your test function matches this order. + + +.. _where-to-patch: + +Where to patch +~~~~~~~~~~~~~~ + +:func:`patch` works by (temporarily) changing the object that a *name* points to with +another one. There can be many names pointing to any individual object, so +for patching to work you must ensure that you patch the name used by the system +under test. + +The basic principle is that you patch where an object is *looked up*, which +is not necessarily the same place as where it is defined. A couple of +examples will help to clarify this. + +Imagine we have a project that we want to test with the following structure:: + + a.py + -> Defines SomeClass + + b.py + -> from a import SomeClass + -> some_function instantiates SomeClass + +Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using +:func:`patch`. The problem is that when we import module b, which we will have to +do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out +``a.SomeClass`` then it will have no effect on our test; module b already has a +reference to the *real* ``SomeClass`` and it looks like our patching had no +effect. + +The key is to patch out ``SomeClass`` where it is used (or where it is looked up). +In this case ``some_function`` will actually look up ``SomeClass`` in module b, +where we have imported it. The patching should look like:: + + @patch('b.SomeClass') + +However, consider the alternative scenario where instead of ``from a import +SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both +of these import forms are common. In this case the class we want to patch is +being looked up in the module and so we have to patch ``a.SomeClass`` instead:: + + @patch('a.SomeClass') + + +Patching Descriptors and Proxy Objects +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Both patch_ and patch.object_ correctly patch and restore descriptors: class +methods, static methods and properties. You should patch these on the *class* +rather than an instance. They also work with *some* objects +that proxy attribute access, like the `django settings object +`_. + + +MagicMock and magic method support +---------------------------------- + +.. _magic-methods: + +Mocking Magic Methods +~~~~~~~~~~~~~~~~~~~~~ + +:class:`Mock` supports mocking the Python protocol methods, also known as +"magic methods". This allows mock objects to replace containers or other +objects that implement Python protocols. + +Because magic methods are looked up differently from normal methods [#]_, this +support has been specially implemented. This means that only specific magic +methods are supported. The supported list includes *almost* all of them. If +there are any missing that you need please let us know. + +You mock magic methods by setting the method you are interested in to a function +or a mock instance. If you are using a function then it *must* take ``self`` as +the first argument [#]_. + + >>> def __str__(self): + ... return 'fooble' + ... + >>> mock = Mock() + >>> mock.__str__ = __str__ + >>> str(mock) + 'fooble' + + >>> mock = Mock() + >>> mock.__str__ = Mock() + >>> mock.__str__.return_value = 'fooble' + >>> str(mock) + 'fooble' + + >>> mock = Mock() + >>> mock.__iter__ = Mock(return_value=iter([])) + >>> list(mock) + [] + +One use case for this is for mocking objects used as context managers in a +:keyword:`with` statement: + + >>> mock = Mock() + >>> mock.__enter__ = Mock(return_value='foo') + >>> mock.__exit__ = Mock(return_value=False) + >>> with mock as m: + ... assert m == 'foo' + ... + >>> mock.__enter__.assert_called_with() + >>> mock.__exit__.assert_called_with(None, None, None) + +Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they +are recorded in :attr:`~Mock.mock_calls`. + +.. note:: + + If you use the *spec* keyword argument to create a mock then attempting to + set a magic method that isn't in the spec will raise an :exc:`AttributeError`. + +The full list of supported magic methods is: + +* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__`` +* ``__dir__``, ``__format__`` and ``__subclasses__`` +* ``__round__``, ``__floor__``, ``__trunc__`` and ``__ceil__`` +* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``, + ``__eq__`` and ``__ne__`` +* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``, + ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__`` + and ``__missing__`` +* Context manager: ``__enter__``, ``__exit__``, ``__aenter__`` and ``__aexit__`` +* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__`` +* The numeric methods (including right hand and in-place variants): + ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``, + ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``, + ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__`` +* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__`` + and ``__index__`` +* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__`` +* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, + ``__getnewargs__``, ``__getstate__`` and ``__setstate__`` +* File system path representation: ``__fspath__`` +* Asynchronous iteration methods: ``__aiter__`` and ``__anext__`` + +.. versionchanged:: 3.8 + Added support for :func:`os.PathLike.__fspath__`. + +.. versionchanged:: 3.8 + Added support for ``__aenter__``, ``__aexit__``, ``__aiter__`` and ``__anext__``. + + +The following methods exist but are *not* supported as they are either in use +by mock, can't be set dynamically, or can cause problems: + +* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__`` +* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__`` + + + +Magic Mock +~~~~~~~~~~ + +There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`. + + +.. class:: MagicMock(*args, **kw) + + ``MagicMock`` is a subclass of :class:`Mock` with default implementations + of most of the magic methods. You can use ``MagicMock`` without having to + configure the magic methods yourself. + + The constructor parameters have the same meaning as for :class:`Mock`. + + If you use the *spec* or *spec_set* arguments then *only* magic methods + that exist in the spec will be created. + + +.. class:: NonCallableMagicMock(*args, **kw) + + A non-callable version of :class:`MagicMock`. + + The constructor parameters have the same meaning as for + :class:`MagicMock`, with the exception of *return_value* and + *side_effect* which have no meaning on a non-callable mock. + +The magic methods are setup with :class:`MagicMock` objects, so you can configure them +and use them in the usual way: + + >>> mock = MagicMock() + >>> mock[3] = 'fish' + >>> mock.__setitem__.assert_called_with(3, 'fish') + >>> mock.__getitem__.return_value = 'result' + >>> mock[2] + 'result' + +By default many of the protocol methods are required to return objects of a +specific type. These methods are preconfigured with a default return value, so +that they can be used without you having to do anything if you aren't interested +in the return value. You can still *set* the return value manually if you want +to change the default. + +Methods and their defaults: + +* ``__lt__``: ``NotImplemented`` +* ``__gt__``: ``NotImplemented`` +* ``__le__``: ``NotImplemented`` +* ``__ge__``: ``NotImplemented`` +* ``__int__``: ``1`` +* ``__contains__``: ``False`` +* ``__len__``: ``0`` +* ``__iter__``: ``iter([])`` +* ``__exit__``: ``False`` +* ``__aexit__``: ``False`` +* ``__complex__``: ``1j`` +* ``__float__``: ``1.0`` +* ``__bool__``: ``True`` +* ``__index__``: ``1`` +* ``__hash__``: default hash for the mock +* ``__str__``: default str for the mock +* ``__sizeof__``: default sizeof for the mock + +For example: + + >>> mock = MagicMock() + >>> int(mock) + 1 + >>> len(mock) + 0 + >>> list(mock) + [] + >>> object() in mock + False + +The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special. +They do the default equality comparison on identity, using the +:attr:`~Mock.side_effect` attribute, unless you change their return value to +return something else:: + + >>> MagicMock() == 3 + False + >>> MagicMock() != 3 + True + >>> mock = MagicMock() + >>> mock.__eq__.return_value = True + >>> mock == 3 + True + +The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't +required to be an iterator: + + >>> mock = MagicMock() + >>> mock.__iter__.return_value = ['a', 'b', 'c'] + >>> list(mock) + ['a', 'b', 'c'] + >>> list(mock) + ['a', 'b', 'c'] + +If the return value *is* an iterator, then iterating over it once will consume +it and subsequent iterations will result in an empty list: + + >>> mock.__iter__.return_value = iter(['a', 'b', 'c']) + >>> list(mock) + ['a', 'b', 'c'] + >>> list(mock) + [] + +``MagicMock`` has all of the supported magic methods configured except for some +of the obscure and obsolete ones. You can still set these up if you want. + +Magic methods that are supported but not setup by default in ``MagicMock`` are: + +* ``__subclasses__`` +* ``__dir__`` +* ``__format__`` +* ``__get__``, ``__set__`` and ``__delete__`` +* ``__reversed__`` and ``__missing__`` +* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``, + ``__getstate__`` and ``__setstate__`` +* ``__getformat__`` and ``__setformat__`` + + + +.. [#] Magic methods *should* be looked up on the class rather than the + instance. Different versions of Python are inconsistent about applying this + rule. The supported protocol methods should work with all supported versions + of Python. +.. [#] The function is basically hooked up to the class, but each ``Mock`` + instance is kept isolated from the others. + + +Helpers +------- + +sentinel +~~~~~~~~ + +.. data:: sentinel + + The ``sentinel`` object provides a convenient way of providing unique + objects for your tests. + + Attributes are created on demand when you access them by name. Accessing + the same attribute will always return the same object. The objects + returned have a sensible repr so that test failure messages are readable. + + .. versionchanged:: 3.7 + The ``sentinel`` attributes now preserve their identity when they are + :mod:`copied ` or :mod:`pickled `. + +Sometimes when testing you need to test that a specific object is passed as an +argument to another method, or returned. It can be common to create named +sentinel objects to test this. :data:`sentinel` provides a convenient way of +creating and testing the identity of objects like this. + +In this example we monkey patch ``method`` to return ``sentinel.some_object``: + + >>> real = ProductionClass() + >>> real.method = Mock(name="method") + >>> real.method.return_value = sentinel.some_object + >>> result = real.method() + >>> assert result is sentinel.some_object + >>> sentinel.some_object + sentinel.some_object + + +DEFAULT +~~~~~~~ + + +.. data:: DEFAULT + + The :data:`DEFAULT` object is a pre-created sentinel (actually + ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect` + functions to indicate that the normal return value should be used. + + +call +~~~~ + +.. function:: call(*args, **kwargs) + + :func:`call` is a helper object for making simpler assertions, for comparing with + :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`, + :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be + used with :meth:`~Mock.assert_has_calls`. + + >>> m = MagicMock(return_value=None) + >>> m(1, 2, a='foo', b='bar') + >>> m() + >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()] + True + +.. method:: call.call_list() + + For a call object that represents multiple calls, :meth:`call_list` + returns a list of all the intermediate calls as well as the + final call. + +``call_list`` is particularly useful for making assertions on "chained calls". A +chained call is multiple calls on a single line of code. This results in +multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing +the sequence of calls can be tedious. + +:meth:`~call.call_list` can construct the sequence of calls from the same +chained call: + + >>> m = MagicMock() + >>> m(1).method(arg='foo').other('bar')(2.0) + + >>> kall = call(1).method(arg='foo').other('bar')(2.0) + >>> kall.call_list() + [call(1), + call().method(arg='foo'), + call().method().other('bar'), + call().method().other()(2.0)] + >>> m.mock_calls == kall.call_list() + True + +.. _calls-as-tuples: + +A ``call`` object is either a tuple of (positional args, keyword args) or +(name, positional args, keyword args) depending on how it was constructed. When +you construct them yourself this isn't particularly interesting, but the ``call`` +objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and +:attr:`Mock.mock_calls` attributes can be introspected to get at the individual +arguments they contain. + +The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list` +are two-tuples of (positional args, keyword args) whereas the ``call`` objects +in :attr:`Mock.mock_calls`, along with ones you construct yourself, are +three-tuples of (name, positional args, keyword args). + +You can use their "tupleness" to pull out the individual arguments for more +complex introspection and assertions. The positional arguments are a tuple +(an empty tuple if there are no positional arguments) and the keyword +arguments are a dictionary: + + >>> m = MagicMock(return_value=None) + >>> m(1, 2, 3, arg='one', arg2='two') + >>> kall = m.call_args + >>> kall.args + (1, 2, 3) + >>> kall.kwargs + {'arg': 'one', 'arg2': 'two'} + >>> kall.args is kall[0] + True + >>> kall.kwargs is kall[1] + True + + >>> m = MagicMock() + >>> m.foo(4, 5, 6, arg='two', arg2='three') + + >>> kall = m.mock_calls[0] + >>> name, args, kwargs = kall + >>> name + 'foo' + >>> args + (4, 5, 6) + >>> kwargs + {'arg': 'two', 'arg2': 'three'} + >>> name is m.mock_calls[0][0] + True + + +create_autospec +~~~~~~~~~~~~~~~ + +.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs) + + Create a mock object using another object as a spec. Attributes on the + mock will use the corresponding attribute on the *spec* object as their + spec. + + Functions or methods being mocked will have their arguments checked to + ensure that they are called with the correct signature. + + If *spec_set* is ``True`` then attempting to set attributes that don't exist + on the spec object will raise an :exc:`AttributeError`. + + If a class is used as a spec then the return value of the mock (the + instance of the class) will have the same spec. You can use a class as the + spec for an instance object by passing ``instance=True``. The returned mock + will only be callable if instances of the mock are callable. + + :func:`create_autospec` also takes arbitrary keyword arguments that are passed to + the constructor of the created mock. + +See :ref:`auto-speccing` for examples of how to use auto-speccing with +:func:`create_autospec` and the *autospec* argument to :func:`patch`. + + +.. versionchanged:: 3.8 + + :func:`create_autospec` now returns an :class:`AsyncMock` if the target is + an async function. + + +ANY +~~~ + +.. data:: ANY + +Sometimes you may need to make assertions about *some* of the arguments in a +call to mock, but either not care about some of the arguments or want to pull +them individually out of :attr:`~Mock.call_args` and make more complex +assertions on them. + +To ignore certain arguments you can pass in objects that compare equal to +*everything*. Calls to :meth:`~Mock.assert_called_with` and +:meth:`~Mock.assert_called_once_with` will then succeed no matter what was +passed in. + + >>> mock = Mock(return_value=None) + >>> mock('foo', bar=object()) + >>> mock.assert_called_once_with('foo', bar=ANY) + +:data:`ANY` can also be used in comparisons with call lists like +:attr:`~Mock.mock_calls`: + + >>> m = MagicMock(return_value=None) + >>> m(1) + >>> m(1, 2) + >>> m(object()) + >>> m.mock_calls == [call(1), call(1, 2), ANY] + True + + + +FILTER_DIR +~~~~~~~~~~ + +.. data:: FILTER_DIR + +:data:`FILTER_DIR` is a module level variable that controls the way mock objects +respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``, +which uses the filtering described below, to only show useful members. If you +dislike this filtering, or need to switch it off for diagnostic purposes, then +set ``mock.FILTER_DIR = False``. + +With filtering on, ``dir(some_mock)`` shows only useful attributes and will +include any dynamically created attributes that wouldn't normally be shown. +If the mock was created with a *spec* (or *autospec* of course) then all the +attributes from the original are shown, even if they haven't been accessed +yet: + +.. doctest:: + :options: +ELLIPSIS,+NORMALIZE_WHITESPACE + + >>> dir(Mock()) + ['assert_any_call', + 'assert_called', + 'assert_called_once', + 'assert_called_once_with', + 'assert_called_with', + 'assert_has_calls', + 'assert_not_called', + 'attach_mock', + ... + >>> from urllib import request + >>> dir(Mock(spec=request)) + ['AbstractBasicAuthHandler', + 'AbstractDigestAuthHandler', + 'AbstractHTTPHandler', + 'BaseHandler', + ... + +Many of the not-very-useful (private to :class:`Mock` rather than the thing being +mocked) underscore and double underscore prefixed attributes have been +filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this +behaviour you can switch it off by setting the module level switch +:data:`FILTER_DIR`: + +.. doctest:: + :options: +ELLIPSIS,+NORMALIZE_WHITESPACE + + >>> from unittest import mock + >>> mock.FILTER_DIR = False + >>> dir(mock.Mock()) + ['_NonCallableMock__get_return_value', + '_NonCallableMock__get_side_effect', + '_NonCallableMock__return_value_doc', + '_NonCallableMock__set_return_value', + '_NonCallableMock__set_side_effect', + '__call__', + '__class__', + ... + +Alternatively you can just use ``vars(my_mock)`` (instance members) and +``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of +:data:`mock.FILTER_DIR`. + + +mock_open +~~~~~~~~~ + +.. function:: mock_open(mock=None, read_data=None) + + A helper function to create a mock to replace the use of :func:`open`. It works + for :func:`open` called directly or used as a context manager. + + The *mock* argument is the mock object to configure. If ``None`` (the + default) then a :class:`MagicMock` will be created for you, with the API limited + to methods or attributes available on standard file handles. + + *read_data* is a string for the :meth:`~io.IOBase.read`, + :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods + of the file handle to return. Calls to those methods will take data from + *read_data* until it is depleted. The mock of these methods is pretty + simplistic: every time the *mock* is called, the *read_data* is rewound to + the start. If you need more control over the data that you are feeding to + the tested code you will need to customize this mock for yourself. When that + is insufficient, one of the in-memory filesystem packages on `PyPI + `_ can offer a realistic filesystem for testing. + + .. versionchanged:: 3.4 + Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support. + The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather + than returning it on each call. + + .. versionchanged:: 3.5 + *read_data* is now reset on each call to the *mock*. + + .. versionchanged:: 3.8 + Added :meth:`__iter__` to implementation so that iteration (such as in for + loops) correctly consumes *read_data*. + +Using :func:`open` as a context manager is a great way to ensure your file handles +are closed properly and is becoming common:: + + with open('/some/path', 'w') as f: + f.write('something') + +The issue is that even if you mock out the call to :func:`open` it is the +*returned object* that is used as a context manager (and has :meth:`__enter__` and +:meth:`__exit__` called). + +Mocking context managers with a :class:`MagicMock` is common enough and fiddly +enough that a helper function is useful. :: + + >>> m = mock_open() + >>> with patch('__main__.open', m): + ... with open('foo', 'w') as h: + ... h.write('some stuff') + ... + >>> m.mock_calls + [call('foo', 'w'), + call().__enter__(), + call().write('some stuff'), + call().__exit__(None, None, None)] + >>> m.assert_called_once_with('foo', 'w') + >>> handle = m() + >>> handle.write.assert_called_once_with('some stuff') + +And for reading files:: + + >>> with patch('__main__.open', mock_open(read_data='bibble')) as m: + ... with open('foo') as h: + ... result = h.read() + ... + >>> m.assert_called_once_with('foo') + >>> assert result == 'bibble' + + +.. _auto-speccing: + +Autospeccing +~~~~~~~~~~~~ + +Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the +api of mocks to the api of an original object (the spec), but it is recursive +(implemented lazily) so that attributes of mocks only have the same api as +the attributes of the spec. In addition mocked functions / methods have the +same call signature as the original so they raise a :exc:`TypeError` if they are +called incorrectly. + +Before I explain how auto-speccing works, here's why it is needed. + +:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws +when used to mock out objects from a system under test. One of these flaws is +specific to the :class:`Mock` api and the other is a more general problem with using +mock objects. + +First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are +extremely handy: :meth:`~Mock.assert_called_with` and +:meth:`~Mock.assert_called_once_with`. + + >>> mock = Mock(name='Thing', return_value=None) + >>> mock(1, 2, 3) + >>> mock.assert_called_once_with(1, 2, 3) + >>> mock(1, 2, 3) + >>> mock.assert_called_once_with(1, 2, 3) + Traceback (most recent call last): + ... + AssertionError: Expected 'mock' to be called once. Called 2 times. + +Because mocks auto-create attributes on demand, and allow you to call them +with arbitrary arguments, if you misspell one of these assert methods then +your assertion is gone: + +.. code-block:: pycon + + >>> mock = Mock(name='Thing', return_value=None) + >>> mock(1, 2, 3) + >>> mock.assret_called_once_with(4, 5, 6) + +Your tests can pass silently and incorrectly because of the typo. + +The second issue is more general to mocking. If you refactor some of your +code, rename members and so on, any tests for code that is still using the +*old api* but uses mocks instead of the real objects will still pass. This +means your tests can all pass even though your code is broken. + +Note that this is another reason why you need integration tests as well as +unit tests. Testing everything in isolation is all fine and dandy, but if you +don't test how your units are "wired together" there is still lots of room +for bugs that tests might have caught. + +:mod:`mock` already provides a feature to help with this, called speccing. If you +use a class or instance as the :attr:`spec` for a mock then you can only access +attributes on the mock that exist on the real class: + + >>> from urllib import request + >>> mock = Mock(spec=request.Request) + >>> mock.assret_called_with + Traceback (most recent call last): + ... + AttributeError: Mock object has no attribute 'assret_called_with' + +The spec only applies to the mock itself, so we still have the same issue +with any methods on the mock: + +.. code-block:: pycon + + >>> mock.has_data() + + >>> mock.has_data.assret_called_with() + +Auto-speccing solves this problem. You can either pass ``autospec=True`` to +:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a +mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the +object that is being replaced will be used as the spec object. Because the +speccing is done "lazily" (the spec is created as attributes on the mock are +accessed) you can use it with very complex or deeply nested objects (like +modules that import modules that import modules) without a big performance +hit. + +Here's an example of it in use:: + + >>> from urllib import request + >>> patcher = patch('__main__.request', autospec=True) + >>> mock_request = patcher.start() + >>> request is mock_request + True + >>> mock_request.Request + + +You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two +arguments in the constructor (one of which is *self*). Here's what happens if +we try to call it incorrectly:: + + >>> req = request.Request() + Traceback (most recent call last): + ... + TypeError: () takes at least 2 arguments (1 given) + +The spec also applies to instantiated classes (i.e. the return value of +specced mocks):: + + >>> req = request.Request('foo') + >>> req + + +:class:`Request` objects are not callable, so the return value of instantiating our +mocked out :class:`request.Request` is a non-callable mock. With the spec in place +any typos in our asserts will raise the correct error:: + + >>> req.add_header('spam', 'eggs') + + >>> req.add_header.assret_called_with + Traceback (most recent call last): + ... + AttributeError: Mock object has no attribute 'assret_called_with' + >>> req.add_header.assert_called_with('spam', 'eggs') + +In many cases you will just be able to add ``autospec=True`` to your existing +:func:`patch` calls and then be protected against bugs due to typos and api +changes. + +As well as using *autospec* through :func:`patch` there is a +:func:`create_autospec` for creating autospecced mocks directly: + + >>> from urllib import request + >>> mock_request = create_autospec(request) + >>> mock_request.Request('foo', 'bar') + + +This isn't without caveats and limitations however, which is why it is not +the default behaviour. In order to know what attributes are available on the +spec object, autospec has to introspect (access attributes) the spec. As you +traverse attributes on the mock a corresponding traversal of the original +object is happening under the hood. If any of your specced objects have +properties or descriptors that can trigger code execution then you may not be +able to use autospec. On the other hand it is much better to design your +objects so that introspection is safe [#]_. + +A more serious problem is that it is common for instance attributes to be +created in the :meth:`__init__` method and not to exist on the class at all. +*autospec* can't know about any dynamically created attributes and restricts +the api to visible attributes. :: + + >>> class Something: + ... def __init__(self): + ... self.a = 33 + ... + >>> with patch('__main__.Something', autospec=True): + ... thing = Something() + ... thing.a + ... + Traceback (most recent call last): + ... + AttributeError: Mock object has no attribute 'a' + +There are a few different ways of resolving this problem. The easiest, but +not necessarily the least annoying, way is to simply set the required +attributes on the mock after creation. Just because *autospec* doesn't allow +you to fetch attributes that don't exist on the spec it doesn't prevent you +setting them:: + + >>> with patch('__main__.Something', autospec=True): + ... thing = Something() + ... thing.a = 33 + ... + +There is a more aggressive version of both *spec* and *autospec* that *does* +prevent you setting non-existent attributes. This is useful if you want to +ensure your code only *sets* valid attributes too, but obviously it prevents +this particular scenario: + + >>> with patch('__main__.Something', autospec=True, spec_set=True): + ... thing = Something() + ... thing.a = 33 + ... + Traceback (most recent call last): + ... + AttributeError: Mock object has no attribute 'a' + +Probably the best way of solving the problem is to add class attributes as +default values for instance members initialised in :meth:`__init__`. Note that if +you are only setting default attributes in :meth:`__init__` then providing them via +class attributes (shared between instances of course) is faster too. e.g. + +.. code-block:: python + + class Something: + a = 33 + +This brings up another issue. It is relatively common to provide a default +value of ``None`` for members that will later be an object of a different type. +``None`` would be useless as a spec because it wouldn't let you access *any* +attributes or methods on it. As ``None`` is *never* going to be useful as a +spec, and probably indicates a member that will normally of some other type, +autospec doesn't use a spec for members that are set to ``None``. These will +just be ordinary mocks (well - MagicMocks): + + >>> class Something: + ... member = None + ... + >>> mock = create_autospec(Something) + >>> mock.member.foo.bar.baz() + + +If modifying your production classes to add defaults isn't to your liking +then there are more options. One of these is simply to use an instance as the +spec rather than the class. The other is to create a subclass of the +production class and add the defaults to the subclass without affecting the +production class. Both of these require you to use an alternative object as +the spec. Thankfully :func:`patch` supports this - you can simply pass the +alternative object as the *autospec* argument:: + + >>> class Something: + ... def __init__(self): + ... self.a = 33 + ... + >>> class SomethingForTest(Something): + ... a = 33 + ... + >>> p = patch('__main__.Something', autospec=SomethingForTest) + >>> mock = p.start() + >>> mock.a + + + +.. [#] This only applies to classes or already instantiated objects. Calling + a mocked class to create a mock instance *does not* create a real instance. + It is only attribute lookups - along with calls to :func:`dir` - that are done. + +Sealing mocks +~~~~~~~~~~~~~ + + +.. testsetup:: + + from unittest.mock import seal + +.. function:: seal(mock) + + Seal will disable the automatic creation of mocks when accessing an attribute of + the mock being sealed or any of its attributes that are already mocks recursively. + + If a mock instance with a name or a spec is assigned to an attribute + it won't be considered in the sealing chain. This allows one to prevent seal from + fixing part of the mock object. :: + + >>> mock = Mock() + >>> mock.submock.attribute1 = 2 + >>> mock.not_submock = mock.Mock(name="sample_name") + >>> seal(mock) + >>> mock.new_attribute # This will raise AttributeError. + >>> mock.submock.attribute2 # This will raise AttributeError. + >>> mock.not_submock.attribute2 # This won't raise. + + .. versionadded:: 3.7 diff --git a/cpython_2/environment/repo/Doc/library/unittest.rst b/cpython_2/environment/repo/Doc/library/unittest.rst new file mode 100644 index 0000000000000000000000000000000000000000..b2e16cf331e036ceb192421a0931a04970582ff4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/unittest.rst @@ -0,0 +1,2478 @@ +:mod:`unittest` --- Unit testing framework +========================================== + +.. module:: unittest + :synopsis: Unit testing framework for Python. + +.. moduleauthor:: Steve Purcell +.. sectionauthor:: Steve Purcell +.. sectionauthor:: Fred L. Drake, Jr. +.. sectionauthor:: Raymond Hettinger + +**Source code:** :source:`Lib/unittest/__init__.py` + +-------------- + +(If you are already familiar with the basic concepts of testing, you might want +to skip to :ref:`the list of assert methods `.) + +The :mod:`unittest` unit testing framework was originally inspired by JUnit +and has a similar flavor as major unit testing frameworks in other +languages. It supports test automation, sharing of setup and shutdown code +for tests, aggregation of tests into collections, and independence of the +tests from the reporting framework. + +To achieve this, :mod:`unittest` supports some important concepts in an +object-oriented way: + +test fixture + A :dfn:`test fixture` represents the preparation needed to perform one or more + tests, and any associated cleanup actions. This may involve, for example, + creating temporary or proxy databases, directories, or starting a server + process. + +test case + A :dfn:`test case` is the individual unit of testing. It checks for a specific + response to a particular set of inputs. :mod:`unittest` provides a base class, + :class:`TestCase`, which may be used to create new test cases. + +test suite + A :dfn:`test suite` is a collection of test cases, test suites, or both. It is + used to aggregate tests that should be executed together. + +test runner + A :dfn:`test runner` is a component which orchestrates the execution of tests + and provides the outcome to the user. The runner may use a graphical interface, + a textual interface, or return a special value to indicate the results of + executing the tests. + + +.. seealso:: + + Module :mod:`doctest` + Another test-support module with a very different flavor. + + `Simple Smalltalk Testing: With Patterns `_ + Kent Beck's original paper on testing frameworks using the pattern shared + by :mod:`unittest`. + + `pytest `_ + Third-party unittest framework with a lighter-weight syntax for writing + tests. For example, ``assert func(10) == 42``. + + `The Python Testing Tools Taxonomy `_ + An extensive list of Python testing tools including functional testing + frameworks and mock object libraries. + + `Testing in Python Mailing List `_ + A special-interest-group for discussion of testing, and testing tools, + in Python. + + The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is + a GUI tool for test discovery and execution. This is intended largely for ease of use + for those new to unit testing. For production environments it is + recommended that tests be driven by a continuous integration system such as + `Buildbot `_, `Jenkins `_ + or `Hudson `_. + + +.. _unittest-minimal-example: + +Basic example +------------- + +The :mod:`unittest` module provides a rich set of tools for constructing and +running tests. This section demonstrates that a small subset of the tools +suffice to meet the needs of most users. + +Here is a short script to test three string methods:: + + import unittest + + class TestStringMethods(unittest.TestCase): + + def test_upper(self): + self.assertEqual('foo'.upper(), 'FOO') + + def test_isupper(self): + self.assertTrue('FOO'.isupper()) + self.assertFalse('Foo'.isupper()) + + def test_split(self): + s = 'hello world' + self.assertEqual(s.split(), ['hello', 'world']) + # check that s.split fails when the separator is not a string + with self.assertRaises(TypeError): + s.split(2) + + if __name__ == '__main__': + unittest.main() + + +A testcase is created by subclassing :class:`unittest.TestCase`. The three +individual tests are defined with methods whose names start with the letters +``test``. This naming convention informs the test runner about which methods +represent tests. + +The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an +expected result; :meth:`~TestCase.assertTrue` or :meth:`~TestCase.assertFalse` +to verify a condition; or :meth:`~TestCase.assertRaises` to verify that a +specific exception gets raised. These methods are used instead of the +:keyword:`assert` statement so the test runner can accumulate all test results +and produce a report. + +The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you +to define instructions that will be executed before and after each test method. +They are covered in more detail in the section :ref:`organizing-tests`. + +The final block shows a simple way to run the tests. :func:`unittest.main` +provides a command-line interface to the test script. When run from the command +line, the above script produces an output that looks like this:: + + ... + ---------------------------------------------------------------------- + Ran 3 tests in 0.000s + + OK + +Passing the ``-v`` option to your test script will instruct :func:`unittest.main` +to enable a higher level of verbosity, and produce the following output:: + + test_isupper (__main__.TestStringMethods) ... ok + test_split (__main__.TestStringMethods) ... ok + test_upper (__main__.TestStringMethods) ... ok + + ---------------------------------------------------------------------- + Ran 3 tests in 0.001s + + OK + +The above examples show the most commonly used :mod:`unittest` features which +are sufficient to meet many everyday testing needs. The remainder of the +documentation explores the full feature set from first principles. + + +.. _unittest-command-line-interface: + +Command-Line Interface +---------------------- + +The unittest module can be used from the command line to run tests from +modules, classes or even individual test methods:: + + python -m unittest test_module1 test_module2 + python -m unittest test_module.TestClass + python -m unittest test_module.TestClass.test_method + +You can pass in a list with any combination of module names, and fully +qualified class or method names. + +Test modules can be specified by file path as well:: + + python -m unittest tests/test_something.py + +This allows you to use the shell filename completion to specify the test module. +The file specified must still be importable as a module. The path is converted +to a module name by removing the '.py' and converting path separators into '.'. +If you want to execute a test file that isn't importable as a module you should +execute the file directly instead. + +You can run tests with more detail (higher verbosity) by passing in the -v flag:: + + python -m unittest -v test_module + +When executed without arguments :ref:`unittest-test-discovery` is started:: + + python -m unittest + +For a list of all the command-line options:: + + python -m unittest -h + +.. versionchanged:: 3.2 + In earlier versions it was only possible to run individual test methods and + not modules or classes. + + +Command-line options +~~~~~~~~~~~~~~~~~~~~ + +:program:`unittest` supports these command-line options: + +.. program:: unittest + +.. cmdoption:: -b, --buffer + + The standard output and standard error streams are buffered during the test + run. Output during a passing test is discarded. Output is echoed normally + on test fail or error and is added to the failure messages. + +.. cmdoption:: -c, --catch + + :kbd:`Control-C` during the test run waits for the current test to end and then + reports all the results so far. A second :kbd:`Control-C` raises the normal + :exc:`KeyboardInterrupt` exception. + + See `Signal Handling`_ for the functions that provide this functionality. + +.. cmdoption:: -f, --failfast + + Stop the test run on the first error or failure. + +.. cmdoption:: -k + + Only run test methods and classes that match the pattern or substring. + This option may be used multiple times, in which case all test cases that + match of the given patterns are included. + + Patterns that contain a wildcard character (``*``) are matched against the + test name using :meth:`fnmatch.fnmatchcase`; otherwise simple case-sensitive + substring matching is used. + + Patterns are matched against the fully qualified test method name as + imported by the test loader. + + For example, ``-k foo`` matches ``foo_tests.SomeTest.test_something``, + ``bar_tests.SomeTest.test_foo``, but not ``bar_tests.FooTest.test_something``. + +.. cmdoption:: --locals + + Show local variables in tracebacks. + +.. versionadded:: 3.2 + The command-line options ``-b``, ``-c`` and ``-f`` were added. + +.. versionadded:: 3.5 + The command-line option ``--locals``. + +.. versionadded:: 3.7 + The command-line option ``-k``. + +The command line can also be used for test discovery, for running all of the +tests in a project or just a subset. + + +.. _unittest-test-discovery: + +Test Discovery +-------------- + +.. versionadded:: 3.2 + +Unittest supports simple test discovery. In order to be compatible with test +discovery, all of the test files must be :ref:`modules ` or +:ref:`packages ` (including :term:`namespace packages +`) importable from the top-level directory of +the project (this means that their filenames must be valid :ref:`identifiers +`). + +Test discovery is implemented in :meth:`TestLoader.discover`, but can also be +used from the command line. The basic command-line usage is:: + + cd project_directory + python -m unittest discover + +.. note:: + + As a shortcut, ``python -m unittest`` is the equivalent of + ``python -m unittest discover``. If you want to pass arguments to test + discovery the ``discover`` sub-command must be used explicitly. + +The ``discover`` sub-command has the following options: + +.. program:: unittest discover + +.. cmdoption:: -v, --verbose + + Verbose output + +.. cmdoption:: -s, --start-directory directory + + Directory to start discovery (``.`` default) + +.. cmdoption:: -p, --pattern pattern + + Pattern to match test files (``test*.py`` default) + +.. cmdoption:: -t, --top-level-directory directory + + Top level directory of project (defaults to start directory) + +The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in +as positional arguments in that order. The following two command lines +are equivalent:: + + python -m unittest discover -s project_directory -p "*_test.py" + python -m unittest discover project_directory "*_test.py" + +As well as being a path it is possible to pass a package name, for example +``myproject.subpackage.test``, as the start directory. The package name you +supply will then be imported and its location on the filesystem will be used +as the start directory. + +.. caution:: + + Test discovery loads tests by importing them. Once test discovery has found + all the test files from the start directory you specify it turns the paths + into package names to import. For example :file:`foo/bar/baz.py` will be + imported as ``foo.bar.baz``. + + If you have a package installed globally and attempt test discovery on + a different copy of the package then the import *could* happen from the + wrong place. If this happens test discovery will warn you and exit. + + If you supply the start directory as a package name rather than a + path to a directory then discover assumes that whichever location it + imports from is the location you intended, so you will not get the + warning. + +Test modules and packages can customize test loading and discovery by through +the `load_tests protocol`_. + +.. versionchanged:: 3.4 + Test discovery supports :term:`namespace packages `. + + +.. _organizing-tests: + +Organizing test code +-------------------- + +The basic building blocks of unit testing are :dfn:`test cases` --- single +scenarios that must be set up and checked for correctness. In :mod:`unittest`, +test cases are represented by :class:`unittest.TestCase` instances. +To make your own test cases you must write subclasses of +:class:`TestCase` or use :class:`FunctionTestCase`. + +The testing code of a :class:`TestCase` instance should be entirely self +contained, such that it can be run either in isolation or in arbitrary +combination with any number of other test cases. + +The simplest :class:`TestCase` subclass will simply implement a test method +(i.e. a method whose name starts with ``test``) in order to perform specific +testing code:: + + import unittest + + class DefaultWidgetSizeTestCase(unittest.TestCase): + def test_default_widget_size(self): + widget = Widget('The widget') + self.assertEqual(widget.size(), (50, 50)) + +Note that in order to test something, we use one of the :meth:`assert\*` +methods provided by the :class:`TestCase` base class. If the test fails, an +exception will be raised with an explanatory message, and :mod:`unittest` +will identify the test case as a :dfn:`failure`. Any other exceptions will be +treated as :dfn:`errors`. + +Tests can be numerous, and their set-up can be repetitive. Luckily, we +can factor out set-up code by implementing a method called +:meth:`~TestCase.setUp`, which the testing framework will automatically +call for every single test we run:: + + import unittest + + class WidgetTestCase(unittest.TestCase): + def setUp(self): + self.widget = Widget('The widget') + + def test_default_widget_size(self): + self.assertEqual(self.widget.size(), (50,50), + 'incorrect default size') + + def test_widget_resize(self): + self.widget.resize(100,150) + self.assertEqual(self.widget.size(), (100,150), + 'wrong size after resize') + +.. note:: + The order in which the various tests will be run is determined + by sorting the test method names with respect to the built-in + ordering for strings. + +If the :meth:`~TestCase.setUp` method raises an exception while the test is +running, the framework will consider the test to have suffered an error, and +the test method will not be executed. + +Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up +after the test method has been run:: + + import unittest + + class WidgetTestCase(unittest.TestCase): + def setUp(self): + self.widget = Widget('The widget') + + def tearDown(self): + self.widget.dispose() + +If :meth:`~TestCase.setUp` succeeded, :meth:`~TestCase.tearDown` will be +run whether the test method succeeded or not. + +Such a working environment for the testing code is called a +:dfn:`test fixture`. A new TestCase instance is created as a unique +test fixture used to execute each individual test method. Thus +:meth:`~TestCase.setUp`, :meth:`~TestCase.tearDown`, and :meth:`~TestCase.__init__` +will be called once per test. + +It is recommended that you use TestCase implementations to group tests together +according to the features they test. :mod:`unittest` provides a mechanism for +this: the :dfn:`test suite`, represented by :mod:`unittest`'s +:class:`TestSuite` class. In most cases, calling :func:`unittest.main` will do +the right thing and collect all the module's test cases for you and execute +them. + +However, should you want to customize the building of your test suite, +you can do it yourself:: + + def suite(): + suite = unittest.TestSuite() + suite.addTest(WidgetTestCase('test_default_widget_size')) + suite.addTest(WidgetTestCase('test_widget_resize')) + return suite + + if __name__ == '__main__': + runner = unittest.TextTestRunner() + runner.run(suite()) + +You can place the definitions of test cases and test suites in the same modules +as the code they are to test (such as :file:`widget.py`), but there are several +advantages to placing the test code in a separate module, such as +:file:`test_widget.py`: + +* The test module can be run standalone from the command line. + +* The test code can more easily be separated from shipped code. + +* There is less temptation to change test code to fit the code it tests without + a good reason. + +* Test code should be modified much less frequently than the code it tests. + +* Tested code can be refactored more easily. + +* Tests for modules written in C must be in separate modules anyway, so why not + be consistent? + +* If the testing strategy changes, there is no need to change the source code. + + +.. _legacy-unit-tests: + +Re-using old test code +---------------------- + +Some users will find that they have existing test code that they would like to +run from :mod:`unittest`, without converting every old test function to a +:class:`TestCase` subclass. + +For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class. +This subclass of :class:`TestCase` can be used to wrap an existing test +function. Set-up and tear-down functions can also be provided. + +Given the following test function:: + + def testSomething(): + something = makeSomething() + assert something.name is not None + # ... + +one can create an equivalent test case instance as follows, with optional +set-up and tear-down methods:: + + testcase = unittest.FunctionTestCase(testSomething, + setUp=makeSomethingDB, + tearDown=deleteSomethingDB) + +.. note:: + + Even though :class:`FunctionTestCase` can be used to quickly convert an + existing test base over to a :mod:`unittest`\ -based system, this approach is + not recommended. Taking the time to set up proper :class:`TestCase` + subclasses will make future test refactorings infinitely easier. + +In some cases, the existing tests may have been written using the :mod:`doctest` +module. If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can +automatically build :class:`unittest.TestSuite` instances from the existing +:mod:`doctest`\ -based tests. + + +.. _unittest-skipping: + +Skipping tests and expected failures +------------------------------------ + +.. versionadded:: 3.1 + +Unittest supports skipping individual test methods and even whole classes of +tests. In addition, it supports marking a test as an "expected failure," a test +that is broken and will fail, but shouldn't be counted as a failure on a +:class:`TestResult`. + +Skipping a test is simply a matter of using the :func:`skip` :term:`decorator` +or one of its conditional variants, calling :meth:`TestCase.skipTest` within a +:meth:`~TestCase.setUp` or test method, or raising :exc:`SkipTest` directly. + +Basic skipping looks like this:: + + class MyTestCase(unittest.TestCase): + + @unittest.skip("demonstrating skipping") + def test_nothing(self): + self.fail("shouldn't happen") + + @unittest.skipIf(mylib.__version__ < (1, 3), + "not supported in this library version") + def test_format(self): + # Tests that work for only a certain version of the library. + pass + + @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + def test_windows_support(self): + # windows specific testing code + pass + + def test_maybe_skipped(self): + if not external_resource_available(): + self.skipTest("external resource not available") + # test code that depends on the external resource + pass + +This is the output of running the example above in verbose mode:: + + test_format (__main__.MyTestCase) ... skipped 'not supported in this library version' + test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping' + test_maybe_skipped (__main__.MyTestCase) ... skipped 'external resource not available' + test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows' + + ---------------------------------------------------------------------- + Ran 4 tests in 0.005s + + OK (skipped=4) + +Classes can be skipped just like methods:: + + @unittest.skip("showing class skipping") + class MySkippedTestCase(unittest.TestCase): + def test_not_run(self): + pass + +:meth:`TestCase.setUp` can also skip the test. This is useful when a resource +that needs to be set up is not available. + +Expected failures use the :func:`expectedFailure` decorator. :: + + class ExpectedFailureTestCase(unittest.TestCase): + @unittest.expectedFailure + def test_fail(self): + self.assertEqual(1, 0, "broken") + +It's easy to roll your own skipping decorators by making a decorator that calls +:func:`skip` on the test when it wants it to be skipped. This decorator skips +the test unless the passed object has a certain attribute:: + + def skipUnlessHasattr(obj, attr): + if hasattr(obj, attr): + return lambda func: func + return unittest.skip("{!r} doesn't have {!r}".format(obj, attr)) + +The following decorators and exception implement test skipping and expected failures: + +.. decorator:: skip(reason) + + Unconditionally skip the decorated test. *reason* should describe why the + test is being skipped. + +.. decorator:: skipIf(condition, reason) + + Skip the decorated test if *condition* is true. + +.. decorator:: skipUnless(condition, reason) + + Skip the decorated test unless *condition* is true. + +.. decorator:: expectedFailure + + Mark the test as an expected failure. If the test fails it will be + considered a success. If the test passes, it will be considered a failure. + +.. exception:: SkipTest(reason) + + This exception is raised to skip a test. + + Usually you can use :meth:`TestCase.skipTest` or one of the skipping + decorators instead of raising this directly. + +Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them. +Skipped classes will not have :meth:`~TestCase.setUpClass` or :meth:`~TestCase.tearDownClass` run. +Skipped modules will not have :func:`setUpModule` or :func:`tearDownModule` run. + + +.. _subtests: + +Distinguishing test iterations using subtests +--------------------------------------------- + +.. versionadded:: 3.4 + +When there are very small differences among your tests, for +instance some parameters, unittest allows you to distinguish them inside +the body of a test method using the :meth:`~TestCase.subTest` context manager. + +For example, the following test:: + + class NumbersTest(unittest.TestCase): + + def test_even(self): + """ + Test that numbers between 0 and 5 are all even. + """ + for i in range(0, 6): + with self.subTest(i=i): + self.assertEqual(i % 2, 0) + +will produce the following output:: + + ====================================================================== + FAIL: test_even (__main__.NumbersTest) (i=1) + ---------------------------------------------------------------------- + Traceback (most recent call last): + File "subtests.py", line 32, in test_even + self.assertEqual(i % 2, 0) + AssertionError: 1 != 0 + + ====================================================================== + FAIL: test_even (__main__.NumbersTest) (i=3) + ---------------------------------------------------------------------- + Traceback (most recent call last): + File "subtests.py", line 32, in test_even + self.assertEqual(i % 2, 0) + AssertionError: 1 != 0 + + ====================================================================== + FAIL: test_even (__main__.NumbersTest) (i=5) + ---------------------------------------------------------------------- + Traceback (most recent call last): + File "subtests.py", line 32, in test_even + self.assertEqual(i % 2, 0) + AssertionError: 1 != 0 + +Without using a subtest, execution would stop after the first failure, +and the error would be less easy to diagnose because the value of ``i`` +wouldn't be displayed:: + + ====================================================================== + FAIL: test_even (__main__.NumbersTest) + ---------------------------------------------------------------------- + Traceback (most recent call last): + File "subtests.py", line 32, in test_even + self.assertEqual(i % 2, 0) + AssertionError: 1 != 0 + + +.. _unittest-contents: + +Classes and functions +--------------------- + +This section describes in depth the API of :mod:`unittest`. + + +.. _testcase-objects: + +Test cases +~~~~~~~~~~ + +.. class:: TestCase(methodName='runTest') + + Instances of the :class:`TestCase` class represent the logical test units + in the :mod:`unittest` universe. This class is intended to be used as a base + class, with specific tests being implemented by concrete subclasses. This class + implements the interface needed by the test runner to allow it to drive the + tests, and methods that the test code can use to check for and report various + kinds of failure. + + Each instance of :class:`TestCase` will run a single base method: the method + named *methodName*. + In most uses of :class:`TestCase`, you will neither change + the *methodName* nor reimplement the default ``runTest()`` method. + + .. versionchanged:: 3.2 + :class:`TestCase` can be instantiated successfully without providing a + *methodName*. This makes it easier to experiment with :class:`TestCase` + from the interactive interpreter. + + :class:`TestCase` instances provide three groups of methods: one group used + to run the test, another used by the test implementation to check conditions + and report failures, and some inquiry methods allowing information about the + test itself to be gathered. + + Methods in the first group (running the test) are: + + .. method:: setUp() + + Method called to prepare the test fixture. This is called immediately + before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`, + any exception raised by this method will be considered an error rather than + a test failure. The default implementation does nothing. + + + .. method:: tearDown() + + Method called immediately after the test method has been called and the + result recorded. This is called even if the test method raised an + exception, so the implementation in subclasses may need to be particularly + careful about checking internal state. Any exception, other than + :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be + considered an additional error rather than a test failure (thus increasing + the total number of reported errors). This method will only be called if + the :meth:`setUp` succeeds, regardless of the outcome of the test method. + The default implementation does nothing. + + + .. method:: setUpClass() + + A class method called before tests in an individual class are run. + ``setUpClass`` is called with the class as the only argument + and must be decorated as a :func:`classmethod`:: + + @classmethod + def setUpClass(cls): + ... + + See `Class and Module Fixtures`_ for more details. + + .. versionadded:: 3.2 + + + .. method:: tearDownClass() + + A class method called after tests in an individual class have run. + ``tearDownClass`` is called with the class as the only argument + and must be decorated as a :meth:`classmethod`:: + + @classmethod + def tearDownClass(cls): + ... + + See `Class and Module Fixtures`_ for more details. + + .. versionadded:: 3.2 + + + .. method:: run(result=None) + + Run the test, collecting the result into the :class:`TestResult` object + passed as *result*. If *result* is omitted or ``None``, a temporary + result object is created (by calling the :meth:`defaultTestResult` + method) and used. The result object is returned to :meth:`run`'s + caller. + + The same effect may be had by simply calling the :class:`TestCase` + instance. + + .. versionchanged:: 3.3 + Previous versions of ``run`` did not return the result. Neither did + calling an instance. + + .. method:: skipTest(reason) + + Calling this during a test method or :meth:`setUp` skips the current + test. See :ref:`unittest-skipping` for more information. + + .. versionadded:: 3.1 + + + .. method:: subTest(msg=None, **params) + + Return a context manager which executes the enclosed code block as a + subtest. *msg* and *params* are optional, arbitrary values which are + displayed whenever a subtest fails, allowing you to identify them + clearly. + + A test case can contain any number of subtest declarations, and + they can be arbitrarily nested. + + See :ref:`subtests` for more information. + + .. versionadded:: 3.4 + + + .. method:: debug() + + Run the test without collecting the result. This allows exceptions raised + by the test to be propagated to the caller, and can be used to support + running tests under a debugger. + + .. _assert-methods: + + The :class:`TestCase` class provides several assert methods to check for and + report failures. The following table lists the most commonly used methods + (see the tables below for more assert methods): + + +-----------------------------------------+-----------------------------+---------------+ + | Method | Checks that | New in | + +=========================================+=============================+===============+ + | :meth:`assertEqual(a, b) | ``a == b`` | | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertNotEqual(a, b) | ``a != b`` | | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertTrue(x) | ``bool(x) is True`` | | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertFalse(x) | ``bool(x) is False`` | | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertIs(a, b) | ``a is b`` | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertIsNot(a, b) | ``a is not b`` | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertIsNone(x) | ``x is None`` | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertIsNotNone(x) | ``x is not None`` | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertIn(a, b) | ``a in b`` | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertNotIn(a, b) | ``a not in b`` | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertIsInstance(a, b) | ``isinstance(a, b)`` | 3.2 | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + | :meth:`assertNotIsInstance(a, b) | ``not isinstance(a, b)`` | 3.2 | + | ` | | | + +-----------------------------------------+-----------------------------+---------------+ + + All the assert methods accept a *msg* argument that, if specified, is used + as the error message on failure (see also :data:`longMessage`). + Note that the *msg* keyword argument can be passed to :meth:`assertRaises`, + :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex` + only when they are used as a context manager. + + .. method:: assertEqual(first, second, msg=None) + + Test that *first* and *second* are equal. If the values do not + compare equal, the test will fail. + + In addition, if *first* and *second* are the exact same type and one of + list, tuple, dict, set, frozenset or str or any type that a subclass + registers with :meth:`addTypeEqualityFunc` the type-specific equality + function will be called in order to generate a more useful default + error message (see also the :ref:`list of type-specific methods + `). + + .. versionchanged:: 3.1 + Added the automatic calling of type-specific equality function. + + .. versionchanged:: 3.2 + :meth:`assertMultiLineEqual` added as the default type equality + function for comparing strings. + + + .. method:: assertNotEqual(first, second, msg=None) + + Test that *first* and *second* are not equal. If the values do + compare equal, the test will fail. + + .. method:: assertTrue(expr, msg=None) + assertFalse(expr, msg=None) + + Test that *expr* is true (or false). + + Note that this is equivalent to ``bool(expr) is True`` and not to ``expr + is True`` (use ``assertIs(expr, True)`` for the latter). This method + should also be avoided when more specific methods are available (e.g. + ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they + provide a better error message in case of failure. + + + .. method:: assertIs(first, second, msg=None) + assertIsNot(first, second, msg=None) + + Test that *first* and *second* evaluate (or don't evaluate) to the + same object. + + .. versionadded:: 3.1 + + + .. method:: assertIsNone(expr, msg=None) + assertIsNotNone(expr, msg=None) + + Test that *expr* is (or is not) ``None``. + + .. versionadded:: 3.1 + + + .. method:: assertIn(member, container, msg=None) + assertNotIn(member, container, msg=None) + + Test that *member* is (or is not) in *container*. + + .. versionadded:: 3.1 + + + .. method:: assertIsInstance(obj, cls, msg=None) + assertNotIsInstance(obj, cls, msg=None) + + Test that *obj* is (or is not) an instance of *cls* (which can be a + class or a tuple of classes, as supported by :func:`isinstance`). + To check for the exact type, use :func:`assertIs(type(obj), cls) `. + + .. versionadded:: 3.2 + + + + It is also possible to check the production of exceptions, warnings, and + log messages using the following methods: + + +---------------------------------------------------------+--------------------------------------+------------+ + | Method | Checks that | New in | + +=========================================================+======================================+============+ + | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | | + | ` | | | + +---------------------------------------------------------+--------------------------------------+------------+ + | :meth:`assertRaisesRegex(exc, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 | + | ` | and the message matches regex *r* | | + +---------------------------------------------------------+--------------------------------------+------------+ + | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 | + | ` | | | + +---------------------------------------------------------+--------------------------------------+------------+ + | :meth:`assertWarnsRegex(warn, r, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 | + | ` | and the message matches regex *r* | | + +---------------------------------------------------------+--------------------------------------+------------+ + | :meth:`assertLogs(logger, level) | The ``with`` block logs on *logger* | 3.4 | + | ` | with minimum *level* | | + +---------------------------------------------------------+--------------------------------------+------------+ + + .. method:: assertRaises(exception, callable, *args, **kwds) + assertRaises(exception, *, msg=None) + + Test that an exception is raised when *callable* is called with any + positional or keyword arguments that are also passed to + :meth:`assertRaises`. The test passes if *exception* is raised, is an + error if another exception is raised, or fails if no exception is raised. + To catch any of a group of exceptions, a tuple containing the exception + classes may be passed as *exception*. + + If only the *exception* and possibly the *msg* arguments are given, + return a context manager so that the code under test can be written + inline rather than as a function:: + + with self.assertRaises(SomeException): + do_something() + + When used as a context manager, :meth:`assertRaises` accepts the + additional keyword argument *msg*. + + The context manager will store the caught exception object in its + :attr:`exception` attribute. This can be useful if the intention + is to perform additional checks on the exception raised:: + + with self.assertRaises(SomeException) as cm: + do_something() + + the_exception = cm.exception + self.assertEqual(the_exception.error_code, 3) + + .. versionchanged:: 3.1 + Added the ability to use :meth:`assertRaises` as a context manager. + + .. versionchanged:: 3.2 + Added the :attr:`exception` attribute. + + .. versionchanged:: 3.3 + Added the *msg* keyword argument when used as a context manager. + + + .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds) + assertRaisesRegex(exception, regex, *, msg=None) + + Like :meth:`assertRaises` but also tests that *regex* matches + on the string representation of the raised exception. *regex* may be + a regular expression object or a string containing a regular expression + suitable for use by :func:`re.search`. Examples:: + + self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$", + int, 'XYZ') + + or:: + + with self.assertRaisesRegex(ValueError, 'literal'): + int('XYZ') + + .. versionadded:: 3.1 + Added under the name ``assertRaisesRegexp``. + + .. versionchanged:: 3.2 + Renamed to :meth:`assertRaisesRegex`. + + .. versionchanged:: 3.3 + Added the *msg* keyword argument when used as a context manager. + + + .. method:: assertWarns(warning, callable, *args, **kwds) + assertWarns(warning, *, msg=None) + + Test that a warning is triggered when *callable* is called with any + positional or keyword arguments that are also passed to + :meth:`assertWarns`. The test passes if *warning* is triggered and + fails if it isn't. Any exception is an error. + To catch any of a group of warnings, a tuple containing the warning + classes may be passed as *warnings*. + + If only the *warning* and possibly the *msg* arguments are given, + return a context manager so that the code under test can be written + inline rather than as a function:: + + with self.assertWarns(SomeWarning): + do_something() + + When used as a context manager, :meth:`assertWarns` accepts the + additional keyword argument *msg*. + + The context manager will store the caught warning object in its + :attr:`warning` attribute, and the source line which triggered the + warnings in the :attr:`filename` and :attr:`lineno` attributes. + This can be useful if the intention is to perform additional checks + on the warning caught:: + + with self.assertWarns(SomeWarning) as cm: + do_something() + + self.assertIn('myfile.py', cm.filename) + self.assertEqual(320, cm.lineno) + + This method works regardless of the warning filters in place when it + is called. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.3 + Added the *msg* keyword argument when used as a context manager. + + + .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds) + assertWarnsRegex(warning, regex, *, msg=None) + + Like :meth:`assertWarns` but also tests that *regex* matches on the + message of the triggered warning. *regex* may be a regular expression + object or a string containing a regular expression suitable for use + by :func:`re.search`. Example:: + + self.assertWarnsRegex(DeprecationWarning, + r'legacy_function\(\) is deprecated', + legacy_function, 'XYZ') + + or:: + + with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'): + frobnicate('/etc/passwd') + + .. versionadded:: 3.2 + + .. versionchanged:: 3.3 + Added the *msg* keyword argument when used as a context manager. + + .. method:: assertLogs(logger=None, level=None) + + A context manager to test that at least one message is logged on + the *logger* or one of its children, with at least the given + *level*. + + If given, *logger* should be a :class:`logging.Logger` object or a + :class:`str` giving the name of a logger. The default is the root + logger, which will catch all messages. + + If given, *level* should be either a numeric logging level or + its string equivalent (for example either ``"ERROR"`` or + :attr:`logging.ERROR`). The default is :attr:`logging.INFO`. + + The test passes if at least one message emitted inside the ``with`` + block matches the *logger* and *level* conditions, otherwise it fails. + + The object returned by the context manager is a recording helper + which keeps tracks of the matching log messages. It has two + attributes: + + .. attribute:: records + + A list of :class:`logging.LogRecord` objects of the matching + log messages. + + .. attribute:: output + + A list of :class:`str` objects with the formatted output of + matching messages. + + Example:: + + with self.assertLogs('foo', level='INFO') as cm: + logging.getLogger('foo').info('first message') + logging.getLogger('foo.bar').error('second message') + self.assertEqual(cm.output, ['INFO:foo:first message', + 'ERROR:foo.bar:second message']) + + .. versionadded:: 3.4 + + + There are also other methods used to perform more specific checks, such as: + + +---------------------------------------+--------------------------------+--------------+ + | Method | Checks that | New in | + +=======================================+================================+==============+ + | :meth:`assertAlmostEqual(a, b) | ``round(a-b, 7) == 0`` | | + | ` | | | + +---------------------------------------+--------------------------------+--------------+ + | :meth:`assertNotAlmostEqual(a, b) | ``round(a-b, 7) != 0`` | | + | ` | | | + +---------------------------------------+--------------------------------+--------------+ + | :meth:`assertGreater(a, b) | ``a > b`` | 3.1 | + | ` | | | + +---------------------------------------+--------------------------------+--------------+ + | :meth:`assertGreaterEqual(a, b) | ``a >= b`` | 3.1 | + | ` | | | + +---------------------------------------+--------------------------------+--------------+ + | :meth:`assertLess(a, b) | ``a < b`` | 3.1 | + | ` | | | + +---------------------------------------+--------------------------------+--------------+ + | :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 | + | ` | | | + +---------------------------------------+--------------------------------+--------------+ + | :meth:`assertRegex(s, r) | ``r.search(s)`` | 3.1 | + | ` | | | + +---------------------------------------+--------------------------------+--------------+ + | :meth:`assertNotRegex(s, r) | ``not r.search(s)`` | 3.2 | + | ` | | | + +---------------------------------------+--------------------------------+--------------+ + | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 | + | ` | elements in the same number, | | + | | regardless of their order. | | + +---------------------------------------+--------------------------------+--------------+ + + + .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None) + assertNotAlmostEqual(first, second, places=7, msg=None, delta=None) + + Test that *first* and *second* are approximately (or not approximately) + equal by computing the difference, rounding to the given number of + decimal *places* (default 7), and comparing to zero. Note that these + methods round the values to the given number of *decimal places* (i.e. + like the :func:`round` function) and not *significant digits*. + + If *delta* is supplied instead of *places* then the difference + between *first* and *second* must be less or equal to (or greater than) *delta*. + + Supplying both *delta* and *places* raises a :exc:`TypeError`. + + .. versionchanged:: 3.2 + :meth:`assertAlmostEqual` automatically considers almost equal objects + that compare equal. :meth:`assertNotAlmostEqual` automatically fails + if the objects compare equal. Added the *delta* keyword argument. + + + .. method:: assertGreater(first, second, msg=None) + assertGreaterEqual(first, second, msg=None) + assertLess(first, second, msg=None) + assertLessEqual(first, second, msg=None) + + Test that *first* is respectively >, >=, < or <= than *second* depending + on the method name. If not, the test will fail:: + + >>> self.assertGreaterEqual(3, 4) + AssertionError: "3" unexpectedly not greater than or equal to "4" + + .. versionadded:: 3.1 + + + .. method:: assertRegex(text, regex, msg=None) + assertNotRegex(text, regex, msg=None) + + Test that a *regex* search matches (or does not match) *text*. In case + of failure, the error message will include the pattern and the *text* (or + the pattern and the part of *text* that unexpectedly matched). *regex* + may be a regular expression object or a string containing a regular + expression suitable for use by :func:`re.search`. + + .. versionadded:: 3.1 + Added under the name ``assertRegexpMatches``. + .. versionchanged:: 3.2 + The method ``assertRegexpMatches()`` has been renamed to + :meth:`.assertRegex`. + .. versionadded:: 3.2 + :meth:`.assertNotRegex`. + .. versionadded:: 3.5 + The name ``assertNotRegexpMatches`` is a deprecated alias + for :meth:`.assertNotRegex`. + + + .. method:: assertCountEqual(first, second, msg=None) + + Test that sequence *first* contains the same elements as *second*, + regardless of their order. When they don't, an error message listing the + differences between the sequences will be generated. + + Duplicate elements are *not* ignored when comparing *first* and + *second*. It verifies whether each element has the same count in both + sequences. Equivalent to: + ``assertEqual(Counter(list(first)), Counter(list(second)))`` + but works with sequences of unhashable objects as well. + + .. versionadded:: 3.2 + + + .. _type-specific-methods: + + The :meth:`assertEqual` method dispatches the equality check for objects of + the same type to different type-specific methods. These methods are already + implemented for most of the built-in types, but it's also possible to + register new methods using :meth:`addTypeEqualityFunc`: + + .. method:: addTypeEqualityFunc(typeobj, function) + + Registers a type-specific method called by :meth:`assertEqual` to check + if two objects of exactly the same *typeobj* (not subclasses) compare + equal. *function* must take two positional arguments and a third msg=None + keyword argument just as :meth:`assertEqual` does. It must raise + :data:`self.failureException(msg) ` when inequality + between the first two parameters is detected -- possibly providing useful + information and explaining the inequalities in details in the error + message. + + .. versionadded:: 3.1 + + The list of type-specific methods automatically used by + :meth:`~TestCase.assertEqual` are summarized in the following table. Note + that it's usually not necessary to invoke these methods directly. + + +-----------------------------------------+-----------------------------+--------------+ + | Method | Used to compare | New in | + +=========================================+=============================+==============+ + | :meth:`assertMultiLineEqual(a, b) | strings | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+--------------+ + | :meth:`assertSequenceEqual(a, b) | sequences | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+--------------+ + | :meth:`assertListEqual(a, b) | lists | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+--------------+ + | :meth:`assertTupleEqual(a, b) | tuples | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+--------------+ + | :meth:`assertSetEqual(a, b) | sets or frozensets | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+--------------+ + | :meth:`assertDictEqual(a, b) | dicts | 3.1 | + | ` | | | + +-----------------------------------------+-----------------------------+--------------+ + + + + .. method:: assertMultiLineEqual(first, second, msg=None) + + Test that the multiline string *first* is equal to the string *second*. + When not equal a diff of the two strings highlighting the differences + will be included in the error message. This method is used by default + when comparing strings with :meth:`assertEqual`. + + .. versionadded:: 3.1 + + + .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None) + + Tests that two sequences are equal. If a *seq_type* is supplied, both + *first* and *second* must be instances of *seq_type* or a failure will + be raised. If the sequences are different an error message is + constructed that shows the difference between the two. + + This method is not called directly by :meth:`assertEqual`, but + it's used to implement :meth:`assertListEqual` and + :meth:`assertTupleEqual`. + + .. versionadded:: 3.1 + + + .. method:: assertListEqual(first, second, msg=None) + assertTupleEqual(first, second, msg=None) + + Tests that two lists or tuples are equal. If not, an error message is + constructed that shows only the differences between the two. An error + is also raised if either of the parameters are of the wrong type. + These methods are used by default when comparing lists or tuples with + :meth:`assertEqual`. + + .. versionadded:: 3.1 + + + .. method:: assertSetEqual(first, second, msg=None) + + Tests that two sets are equal. If not, an error message is constructed + that lists the differences between the sets. This method is used by + default when comparing sets or frozensets with :meth:`assertEqual`. + + Fails if either of *first* or *second* does not have a :meth:`set.difference` + method. + + .. versionadded:: 3.1 + + + .. method:: assertDictEqual(first, second, msg=None) + + Test that two dictionaries are equal. If not, an error message is + constructed that shows the differences in the dictionaries. This + method will be used by default to compare dictionaries in + calls to :meth:`assertEqual`. + + .. versionadded:: 3.1 + + + + .. _other-methods-and-attrs: + + Finally the :class:`TestCase` provides the following methods and attributes: + + + .. method:: fail(msg=None) + + Signals a test failure unconditionally, with *msg* or ``None`` for + the error message. + + + .. attribute:: failureException + + This class attribute gives the exception raised by the test method. If a + test framework needs to use a specialized exception, possibly to carry + additional information, it must subclass this exception in order to "play + fair" with the framework. The initial value of this attribute is + :exc:`AssertionError`. + + + .. attribute:: longMessage + + This class attribute determines what happens when a custom failure message + is passed as the msg argument to an assertXYY call that fails. + ``True`` is the default value. In this case, the custom message is appended + to the end of the standard failure message. + When set to ``False``, the custom message replaces the standard message. + + The class setting can be overridden in individual test methods by assigning + an instance attribute, self.longMessage, to ``True`` or ``False`` before + calling the assert methods. + + The class setting gets reset before each test call. + + .. versionadded:: 3.1 + + + .. attribute:: maxDiff + + This attribute controls the maximum length of diffs output by assert + methods that report diffs on failure. It defaults to 80*8 characters. + Assert methods affected by this attribute are + :meth:`assertSequenceEqual` (including all the sequence comparison + methods that delegate to it), :meth:`assertDictEqual` and + :meth:`assertMultiLineEqual`. + + Setting ``maxDiff`` to ``None`` means that there is no maximum length of + diffs. + + .. versionadded:: 3.2 + + + Testing frameworks can use the following methods to collect information on + the test: + + + .. method:: countTestCases() + + Return the number of tests represented by this test object. For + :class:`TestCase` instances, this will always be ``1``. + + + .. method:: defaultTestResult() + + Return an instance of the test result class that should be used for this + test case class (if no other result instance is provided to the + :meth:`run` method). + + For :class:`TestCase` instances, this will always be an instance of + :class:`TestResult`; subclasses of :class:`TestCase` should override this + as necessary. + + + .. method:: id() + + Return a string identifying the specific test case. This is usually the + full name of the test method, including the module and class name. + + + .. method:: shortDescription() + + Returns a description of the test, or ``None`` if no description + has been provided. The default implementation of this method + returns the first line of the test method's docstring, if available, + or ``None``. + + .. versionchanged:: 3.1 + In 3.1 this was changed to add the test name to the short description + even in the presence of a docstring. This caused compatibility issues + with unittest extensions and adding the test name was moved to the + :class:`TextTestResult` in Python 3.2. + + + .. method:: addCleanup(function, /, *args, **kwargs) + + Add a function to be called after :meth:`tearDown` to cleanup resources + used during the test. Functions will be called in reverse order to the + order they are added (:abbr:`LIFO (last-in, first-out)`). They + are called with any arguments and keyword arguments passed into + :meth:`addCleanup` when they are added. + + If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called, + then any cleanup functions added will still be called. + + .. versionadded:: 3.1 + + + .. method:: doCleanups() + + This method is called unconditionally after :meth:`tearDown`, or + after :meth:`setUp` if :meth:`setUp` raises an exception. + + It is responsible for calling all the cleanup functions added by + :meth:`addCleanup`. If you need cleanup functions to be called + *prior* to :meth:`tearDown` then you can call :meth:`doCleanups` + yourself. + + :meth:`doCleanups` pops methods off the stack of cleanup + functions one at a time, so it can be called at any time. + + .. versionadded:: 3.1 + + .. classmethod:: addClassCleanup(function, /, *args, **kwargs) + + Add a function to be called after :meth:`tearDownClass` to cleanup + resources used during the test class. Functions will be called in reverse + order to the order they are added (:abbr:`LIFO (last-in, first-out)`). + They are called with any arguments and keyword arguments passed into + :meth:`addClassCleanup` when they are added. + + If :meth:`setUpClass` fails, meaning that :meth:`tearDownClass` is not + called, then any cleanup functions added will still be called. + + .. versionadded:: 3.8 + + + .. classmethod:: doClassCleanups() + + This method is called unconditionally after :meth:`tearDownClass`, or + after :meth:`setUpClass` if :meth:`setUpClass` raises an exception. + + It is responsible for calling all the cleanup functions added by + :meth:`addCleanupClass`. If you need cleanup functions to be called + *prior* to :meth:`tearDownClass` then you can call + :meth:`doCleanupsClass` yourself. + + :meth:`doCleanupsClass` pops methods off the stack of cleanup + functions one at a time, so it can be called at any time. + + .. versionadded:: 3.8 + + +.. class:: IsolatedAsyncioTestCase(methodName='runTest') + + This class provides an API similar to :class:`TestCase` and also accepts + coroutines as test functions. + + .. versionadded:: 3.8 + + .. coroutinemethod:: asyncSetUp() + + Method called to prepare the test fixture. This is called after :meth:`setUp`. + This is called immediately before calling the test method; other than + :exc:`AssertionError` or :exc:`SkipTest`, any exception raised by this method + will be considered an error rather than a test failure. The default implementation + does nothing. + + .. coroutinemethod:: asyncTearDown() + + Method called immediately after the test method has been called and the + result recorded. This is called before :meth:`tearDown`. This is called even if + the test method raised an exception, so the implementation in subclasses may need + to be particularly careful about checking internal state. Any exception, other than + :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be + considered an additional error rather than a test failure (thus increasing + the total number of reported errors). This method will only be called if + the :meth:`asyncSetUp` succeeds, regardless of the outcome of the test method. + The default implementation does nothing. + + .. method:: addAsyncCleanup(function, /, *args, **kwargs) + + This method accepts a coroutine that can be used as a cleanup function. + + .. method:: run(result=None) + + Sets up a new event loop to run the test, collecting the result into + the :class:`TestResult` object passed as *result*. If *result* is + omitted or ``None``, a temporary result object is created (by calling + the :meth:`defaultTestResult` method) and used. The result object is + returned to :meth:`run`'s caller. At the end of the test all the tasks + in the event loop are cancelled. + + + An example illustrating the order:: + + from unittest import IsolatedAsyncioTestCase + + events = [] + + + class Test(IsolatedAsyncioTestCase): + + + def setUp(self): + events.append("setUp") + + async def asyncSetUp(self): + self._async_connection = await AsyncConnection() + events.append("asyncSetUp") + + async def test_response(self): + events.append("test_response") + response = await self._async_connection.get("https://example.com") + self.assertEqual(response.status_code, 200) + self.addAsyncCleanup(self.on_cleanup) + + def tearDown(self): + events.append("tearDown") + + async def asyncTearDown(self): + await self._async_connection.close() + events.append("asyncTearDown") + + async def on_cleanup(self): + events.append("cleanup") + + if __name__ == "__main__": + unittest.main() + + After running the test, ``events`` would contain ``["setUp", "asyncSetUp", "test_response", "asyncTearDown", "tearDown", "cleanup"]``. + + +.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None) + + This class implements the portion of the :class:`TestCase` interface which + allows the test runner to drive the test, but does not provide the methods + which test code can use to check and report errors. This is used to create + test cases using legacy test code, allowing it to be integrated into a + :mod:`unittest`-based test framework. + + +.. _deprecated-aliases: + +Deprecated aliases +################## + +For historical reasons, some of the :class:`TestCase` methods had one or more +aliases that are now deprecated. The following table lists the correct names +along with their deprecated aliases: + + ============================== ====================== ======================= + Method Name Deprecated alias Deprecated alias + ============================== ====================== ======================= + :meth:`.assertEqual` failUnlessEqual assertEquals + :meth:`.assertNotEqual` failIfEqual assertNotEquals + :meth:`.assertTrue` failUnless assert\_ + :meth:`.assertFalse` failIf + :meth:`.assertRaises` failUnlessRaises + :meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals + :meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals + :meth:`.assertRegex` assertRegexpMatches + :meth:`.assertNotRegex` assertNotRegexpMatches + :meth:`.assertRaisesRegex` assertRaisesRegexp + ============================== ====================== ======================= + + .. deprecated:: 3.1 + The fail* aliases listed in the second column have been deprecated. + .. deprecated:: 3.2 + The assert* aliases listed in the third column have been deprecated. + .. deprecated:: 3.2 + ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to + :meth:`.assertRegex` and :meth:`.assertRaisesRegex`. + .. deprecated:: 3.5 + The ``assertNotRegexpMatches`` name is deprecated in favor of :meth:`.assertNotRegex`. + +.. _testsuite-objects: + +Grouping tests +~~~~~~~~~~~~~~ + +.. class:: TestSuite(tests=()) + + This class represents an aggregation of individual test cases and test suites. + The class presents the interface needed by the test runner to allow it to be run + as any other test case. Running a :class:`TestSuite` instance is the same as + iterating over the suite, running each test individually. + + If *tests* is given, it must be an iterable of individual test cases or other + test suites that will be used to build the suite initially. Additional methods + are provided to add test cases and suites to the collection later on. + + :class:`TestSuite` objects behave much like :class:`TestCase` objects, except + they do not actually implement a test. Instead, they are used to aggregate + tests into groups of tests that should be run together. Some additional + methods are available to add tests to :class:`TestSuite` instances: + + + .. method:: TestSuite.addTest(test) + + Add a :class:`TestCase` or :class:`TestSuite` to the suite. + + + .. method:: TestSuite.addTests(tests) + + Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite` + instances to this test suite. + + This is equivalent to iterating over *tests*, calling :meth:`addTest` for + each element. + + :class:`TestSuite` shares the following methods with :class:`TestCase`: + + + .. method:: run(result) + + Run the tests associated with this suite, collecting the result into the + test result object passed as *result*. Note that unlike + :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to + be passed in. + + + .. method:: debug() + + Run the tests associated with this suite without collecting the + result. This allows exceptions raised by the test to be propagated to the + caller and can be used to support running tests under a debugger. + + + .. method:: countTestCases() + + Return the number of tests represented by this test object, including all + individual tests and sub-suites. + + + .. method:: __iter__() + + Tests grouped by a :class:`TestSuite` are always accessed by iteration. + Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note + that this method may be called several times on a single suite (for + example when counting tests or comparing for equality) so the tests + returned by repeated iterations before :meth:`TestSuite.run` must be the + same for each call iteration. After :meth:`TestSuite.run`, callers should + not rely on the tests returned by this method unless the caller uses a + subclass that overrides :meth:`TestSuite._removeTestAtIndex` to preserve + test references. + + .. versionchanged:: 3.2 + In earlier versions the :class:`TestSuite` accessed tests directly rather + than through iteration, so overriding :meth:`__iter__` wasn't sufficient + for providing tests. + + .. versionchanged:: 3.4 + In earlier versions the :class:`TestSuite` held references to each + :class:`TestCase` after :meth:`TestSuite.run`. Subclasses can restore + that behavior by overriding :meth:`TestSuite._removeTestAtIndex`. + + In the typical usage of a :class:`TestSuite` object, the :meth:`run` method + is invoked by a :class:`TestRunner` rather than by the end-user test harness. + + +Loading and running tests +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. class:: TestLoader() + + The :class:`TestLoader` class is used to create test suites from classes and + modules. Normally, there is no need to create an instance of this class; the + :mod:`unittest` module provides an instance that can be shared as + :data:`unittest.defaultTestLoader`. Using a subclass or instance, however, + allows customization of some configurable properties. + + :class:`TestLoader` objects have the following attributes: + + + .. attribute:: errors + + A list of the non-fatal errors encountered while loading tests. Not reset + by the loader at any point. Fatal errors are signalled by the relevant + a method raising an exception to the caller. Non-fatal errors are also + indicated by a synthetic test that will raise the original error when + run. + + .. versionadded:: 3.5 + + + :class:`TestLoader` objects have the following methods: + + + .. method:: loadTestsFromTestCase(testCaseClass) + + Return a suite of all test cases contained in the :class:`TestCase`\ -derived + :class:`testCaseClass`. + + A test case instance is created for each method named by + :meth:`getTestCaseNames`. By default these are the method names + beginning with ``test``. If :meth:`getTestCaseNames` returns no + methods, but the :meth:`runTest` method is implemented, a single test + case is created for that method instead. + + + .. method:: loadTestsFromModule(module, pattern=None) + + Return a suite of all test cases contained in the given module. This + method searches *module* for classes derived from :class:`TestCase` and + creates an instance of the class for each test method defined for the + class. + + .. note:: + + While using a hierarchy of :class:`TestCase`\ -derived classes can be + convenient in sharing fixtures and helper functions, defining test + methods on base classes that are not intended to be instantiated + directly does not play well with this method. Doing so, however, can + be useful when the fixtures are different and defined in subclasses. + + If a module provides a ``load_tests`` function it will be called to + load the tests. This allows modules to customize test loading. + This is the `load_tests protocol`_. The *pattern* argument is passed as + the third argument to ``load_tests``. + + .. versionchanged:: 3.2 + Support for ``load_tests`` added. + + .. versionchanged:: 3.5 + The undocumented and unofficial *use_load_tests* default argument is + deprecated and ignored, although it is still accepted for backward + compatibility. The method also now accepts a keyword-only argument + *pattern* which is passed to ``load_tests`` as the third argument. + + + .. method:: loadTestsFromName(name, module=None) + + Return a suite of all test cases given a string specifier. + + The specifier *name* is a "dotted name" that may resolve either to a + module, a test case class, a test method within a test case class, a + :class:`TestSuite` instance, or a callable object which returns a + :class:`TestCase` or :class:`TestSuite` instance. These checks are + applied in the order listed here; that is, a method on a possible test + case class will be picked up as "a test method within a test case class", + rather than "a callable object". + + For example, if you have a module :mod:`SampleTests` containing a + :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test + methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the + specifier ``'SampleTests.SampleTestCase'`` would cause this method to + return a suite which will run all three test methods. Using the specifier + ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test + suite which will run only the :meth:`test_two` test method. The specifier + can refer to modules and packages which have not been imported; they will + be imported as a side-effect. + + The method optionally resolves *name* relative to the given *module*. + + .. versionchanged:: 3.5 + If an :exc:`ImportError` or :exc:`AttributeError` occurs while traversing + *name* then a synthetic test that raises that error when run will be + returned. These errors are included in the errors accumulated by + self.errors. + + + .. method:: loadTestsFromNames(names, module=None) + + Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather + than a single name. The return value is a test suite which supports all + the tests defined for each name. + + + .. method:: getTestCaseNames(testCaseClass) + + Return a sorted sequence of method names found within *testCaseClass*; + this should be a subclass of :class:`TestCase`. + + + .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None) + + Find all the test modules by recursing into subdirectories from the + specified start directory, and return a TestSuite object containing them. + Only test files that match *pattern* will be loaded. (Using shell style + pattern matching.) Only module names that are importable (i.e. are valid + Python identifiers) will be loaded. + + All test modules must be importable from the top level of the project. If + the start directory is not the top level directory then the top level + directory must be specified separately. + + If importing a module fails, for example due to a syntax error, then + this will be recorded as a single error and discovery will continue. If + the import failure is due to :exc:`SkipTest` being raised, it will be + recorded as a skip instead of an error. + + If a package (a directory containing a file named :file:`__init__.py`) is + found, the package will be checked for a ``load_tests`` function. If this + exists then it will be called + ``package.load_tests(loader, tests, pattern)``. Test discovery takes care + to ensure that a package is only checked for tests once during an + invocation, even if the load_tests function itself calls + ``loader.discover``. + + If ``load_tests`` exists then discovery does *not* recurse into the + package, ``load_tests`` is responsible for loading all tests in the + package. + + The pattern is deliberately not stored as a loader attribute so that + packages can continue discovery themselves. *top_level_dir* is stored so + ``load_tests`` does not need to pass this argument in to + ``loader.discover()``. + + *start_dir* can be a dotted module name as well as a directory. + + .. versionadded:: 3.2 + + .. versionchanged:: 3.4 + Modules that raise :exc:`SkipTest` on import are recorded as skips, + not errors. + Discovery works for :term:`namespace packages `. + Paths are sorted before being imported so that execution order is + the same even if the underlying file system's ordering is not + dependent on file name. + + .. versionchanged:: 3.5 + Found packages are now checked for ``load_tests`` regardless of + whether their path matches *pattern*, because it is impossible for + a package name to match the default pattern. + + + The following attributes of a :class:`TestLoader` can be configured either by + subclassing or assignment on an instance: + + + .. attribute:: testMethodPrefix + + String giving the prefix of method names which will be interpreted as test + methods. The default value is ``'test'``. + + This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` + methods. + + + .. attribute:: sortTestMethodsUsing + + Function to be used to compare method names when sorting them in + :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. + + + .. attribute:: suiteClass + + Callable object that constructs a test suite from a list of tests. No + methods on the resulting object are needed. The default value is the + :class:`TestSuite` class. + + This affects all the :meth:`loadTestsFrom\*` methods. + + .. attribute:: testNamePatterns + + List of Unix shell-style wildcard test name patterns that test methods + have to match to be included in test suites (see ``-v`` option). + + If this attribute is not ``None`` (the default), all test methods to be + included in test suites must match one of the patterns in this list. + Note that matches are always performed using :meth:`fnmatch.fnmatchcase`, + so unlike patterns passed to the ``-v`` option, simple substring patterns + will have to be converted using ``*`` wildcards. + + This affects all the :meth:`loadTestsFrom\*` methods. + + .. versionadded:: 3.7 + + +.. class:: TestResult + + This class is used to compile information about which tests have succeeded + and which have failed. + + A :class:`TestResult` object stores the results of a set of tests. The + :class:`TestCase` and :class:`TestSuite` classes ensure that results are + properly recorded; test authors do not need to worry about recording the + outcome of tests. + + Testing frameworks built on top of :mod:`unittest` may want access to the + :class:`TestResult` object generated by running a set of tests for reporting + purposes; a :class:`TestResult` instance is returned by the + :meth:`TestRunner.run` method for this purpose. + + :class:`TestResult` instances have the following attributes that will be of + interest when inspecting the results of running a set of tests: + + + .. attribute:: errors + + A list containing 2-tuples of :class:`TestCase` instances and strings + holding formatted tracebacks. Each tuple represents a test which raised an + unexpected exception. + + .. attribute:: failures + + A list containing 2-tuples of :class:`TestCase` instances and strings + holding formatted tracebacks. Each tuple represents a test where a failure + was explicitly signalled using the :meth:`TestCase.assert\*` methods. + + .. attribute:: skipped + + A list containing 2-tuples of :class:`TestCase` instances and strings + holding the reason for skipping the test. + + .. versionadded:: 3.1 + + .. attribute:: expectedFailures + + A list containing 2-tuples of :class:`TestCase` instances and strings + holding formatted tracebacks. Each tuple represents an expected failure + of the test case. + + .. attribute:: unexpectedSuccesses + + A list containing :class:`TestCase` instances that were marked as expected + failures, but succeeded. + + .. attribute:: shouldStop + + Set to ``True`` when the execution of tests should stop by :meth:`stop`. + + .. attribute:: testsRun + + The total number of tests run so far. + + .. attribute:: buffer + + If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between + :meth:`startTest` and :meth:`stopTest` being called. Collected output will + only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test + fails or errors. Any output is also attached to the failure / error message. + + .. versionadded:: 3.2 + + .. attribute:: failfast + + If set to true :meth:`stop` will be called on the first failure or error, + halting the test run. + + .. versionadded:: 3.2 + + .. attribute:: tb_locals + + If set to true then local variables will be shown in tracebacks. + + .. versionadded:: 3.5 + + .. method:: wasSuccessful() + + Return ``True`` if all tests run so far have passed, otherwise returns + ``False``. + + .. versionchanged:: 3.4 + Returns ``False`` if there were any :attr:`unexpectedSuccesses` + from tests marked with the :func:`expectedFailure` decorator. + + .. method:: stop() + + This method can be called to signal that the set of tests being run should + be aborted by setting the :attr:`shouldStop` attribute to ``True``. + :class:`TestRunner` objects should respect this flag and return without + running any additional tests. + + For example, this feature is used by the :class:`TextTestRunner` class to + stop the test framework when the user signals an interrupt from the + keyboard. Interactive tools which provide :class:`TestRunner` + implementations can use this in a similar manner. + + The following methods of the :class:`TestResult` class are used to maintain + the internal data structures, and may be extended in subclasses to support + additional reporting requirements. This is particularly useful in building + tools which support interactive reporting while tests are being run. + + + .. method:: startTest(test) + + Called when the test case *test* is about to be run. + + .. method:: stopTest(test) + + Called after the test case *test* has been executed, regardless of the + outcome. + + .. method:: startTestRun() + + Called once before any tests are executed. + + .. versionadded:: 3.1 + + + .. method:: stopTestRun() + + Called once after all tests are executed. + + .. versionadded:: 3.1 + + + .. method:: addError(test, err) + + Called when the test case *test* raises an unexpected exception. *err* is a + tuple of the form returned by :func:`sys.exc_info`: ``(type, value, + traceback)``. + + The default implementation appends a tuple ``(test, formatted_err)`` to + the instance's :attr:`errors` attribute, where *formatted_err* is a + formatted traceback derived from *err*. + + + .. method:: addFailure(test, err) + + Called when the test case *test* signals a failure. *err* is a tuple of + the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``. + + The default implementation appends a tuple ``(test, formatted_err)`` to + the instance's :attr:`failures` attribute, where *formatted_err* is a + formatted traceback derived from *err*. + + + .. method:: addSuccess(test) + + Called when the test case *test* succeeds. + + The default implementation does nothing. + + + .. method:: addSkip(test, reason) + + Called when the test case *test* is skipped. *reason* is the reason the + test gave for skipping. + + The default implementation appends a tuple ``(test, reason)`` to the + instance's :attr:`skipped` attribute. + + + .. method:: addExpectedFailure(test, err) + + Called when the test case *test* fails, but was marked with the + :func:`expectedFailure` decorator. + + The default implementation appends a tuple ``(test, formatted_err)`` to + the instance's :attr:`expectedFailures` attribute, where *formatted_err* + is a formatted traceback derived from *err*. + + + .. method:: addUnexpectedSuccess(test) + + Called when the test case *test* was marked with the + :func:`expectedFailure` decorator, but succeeded. + + The default implementation appends the test to the instance's + :attr:`unexpectedSuccesses` attribute. + + + .. method:: addSubTest(test, subtest, outcome) + + Called when a subtest finishes. *test* is the test case + corresponding to the test method. *subtest* is a custom + :class:`TestCase` instance describing the subtest. + + If *outcome* is :const:`None`, the subtest succeeded. Otherwise, + it failed with an exception where *outcome* is a tuple of the form + returned by :func:`sys.exc_info`: ``(type, value, traceback)``. + + The default implementation does nothing when the outcome is a + success, and records subtest failures as normal failures. + + .. versionadded:: 3.4 + + +.. class:: TextTestResult(stream, descriptions, verbosity) + + A concrete implementation of :class:`TestResult` used by the + :class:`TextTestRunner`. + + .. versionadded:: 3.2 + This class was previously named ``_TextTestResult``. The old name still + exists as an alias but is deprecated. + + +.. data:: defaultTestLoader + + Instance of the :class:`TestLoader` class intended to be shared. If no + customization of the :class:`TestLoader` is needed, this instance can be used + instead of repeatedly creating new instances. + + +.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, \ + buffer=False, resultclass=None, warnings=None, *, tb_locals=False) + + A basic test runner implementation that outputs results to a stream. If *stream* + is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class + has a few configurable parameters, but is essentially very simple. Graphical + applications which run test suites should provide alternate implementations. Such + implementations should accept ``**kwargs`` as the interface to construct runners + changes when features are added to unittest. + + By default this runner shows :exc:`DeprecationWarning`, + :exc:`PendingDeprecationWarning`, :exc:`ResourceWarning` and + :exc:`ImportWarning` even if they are :ref:`ignored by default + `. Deprecation warnings caused by :ref:`deprecated unittest + methods ` are also special-cased and, when the warning + filters are ``'default'`` or ``'always'``, they will appear only once + per-module, in order to avoid too many warning messages. This behavior can + be overridden using Python's :option:`!-Wd` or :option:`!-Wa` options + (see :ref:`Warning control `) and leaving + *warnings* to ``None``. + + .. versionchanged:: 3.2 + Added the ``warnings`` argument. + + .. versionchanged:: 3.2 + The default stream is set to :data:`sys.stderr` at instantiation time rather + than import time. + + .. versionchanged:: 3.5 + Added the tb_locals parameter. + + .. method:: _makeResult() + + This method returns the instance of ``TestResult`` used by :meth:`run`. + It is not intended to be called directly, but can be overridden in + subclasses to provide a custom ``TestResult``. + + ``_makeResult()`` instantiates the class or callable passed in the + ``TextTestRunner`` constructor as the ``resultclass`` argument. It + defaults to :class:`TextTestResult` if no ``resultclass`` is provided. + The result class is instantiated with the following arguments:: + + stream, descriptions, verbosity + + .. method:: run(test) + + This method is the main public interface to the ``TextTestRunner``. This + method takes a :class:`TestSuite` or :class:`TestCase` instance. A + :class:`TestResult` is created by calling + :func:`_makeResult` and the test(s) are run and the + results printed to stdout. + + +.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \ + testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \ + failfast=None, catchbreak=None, buffer=None, warnings=None) + + A command-line program that loads a set of tests from *module* and runs them; + this is primarily for making test modules conveniently executable. + The simplest use for this function is to include the following line at the + end of a test script:: + + if __name__ == '__main__': + unittest.main() + + You can run tests with more detailed information by passing in the verbosity + argument:: + + if __name__ == '__main__': + unittest.main(verbosity=2) + + The *defaultTest* argument is either the name of a single test or an + iterable of test names to run if no test names are specified via *argv*. If + not specified or ``None`` and no test names are provided via *argv*, all + tests found in *module* are run. + + The *argv* argument can be a list of options passed to the program, with the + first element being the program name. If not specified or ``None``, + the values of :data:`sys.argv` are used. + + The *testRunner* argument can either be a test runner class or an already + created instance of it. By default ``main`` calls :func:`sys.exit` with + an exit code indicating success or failure of the tests run. + + The *testLoader* argument has to be a :class:`TestLoader` instance, + and defaults to :data:`defaultTestLoader`. + + ``main`` supports being used from the interactive interpreter by passing in the + argument ``exit=False``. This displays the result on standard output without + calling :func:`sys.exit`:: + + >>> from unittest import main + >>> main(module='test_module', exit=False) + + The *failfast*, *catchbreak* and *buffer* parameters have the same + effect as the same-name `command-line options`_. + + The *warnings* argument specifies the :ref:`warning filter ` + that should be used while running the tests. If it's not specified, it will + remain ``None`` if a :option:`!-W` option is passed to :program:`python` + (see :ref:`Warning control `), + otherwise it will be set to ``'default'``. + + Calling ``main`` actually returns an instance of the ``TestProgram`` class. + This stores the result of the tests run as the ``result`` attribute. + + .. versionchanged:: 3.1 + The *exit* parameter was added. + + .. versionchanged:: 3.2 + The *verbosity*, *failfast*, *catchbreak*, *buffer* + and *warnings* parameters were added. + + .. versionchanged:: 3.4 + The *defaultTest* parameter was changed to also accept an iterable of + test names. + + +load_tests Protocol +################### + +.. versionadded:: 3.2 + +Modules or packages can customize how tests are loaded from them during normal +test runs or test discovery by implementing a function called ``load_tests``. + +If a test module defines ``load_tests`` it will be called by +:meth:`TestLoader.loadTestsFromModule` with the following arguments:: + + load_tests(loader, standard_tests, pattern) + +where *pattern* is passed straight through from ``loadTestsFromModule``. It +defaults to ``None``. + +It should return a :class:`TestSuite`. + +*loader* is the instance of :class:`TestLoader` doing the loading. +*standard_tests* are the tests that would be loaded by default from the +module. It is common for test modules to only want to add or remove tests +from the standard set of tests. +The third argument is used when loading packages as part of test discovery. + +A typical ``load_tests`` function that loads tests from a specific set of +:class:`TestCase` classes may look like:: + + test_cases = (TestCase1, TestCase2, TestCase3) + + def load_tests(loader, tests, pattern): + suite = TestSuite() + for test_class in test_cases: + tests = loader.loadTestsFromTestCase(test_class) + suite.addTests(tests) + return suite + +If discovery is started in a directory containing a package, either from the +command line or by calling :meth:`TestLoader.discover`, then the package +:file:`__init__.py` will be checked for ``load_tests``. If that function does +not exist, discovery will recurse into the package as though it were just +another directory. Otherwise, discovery of the package's tests will be left up +to ``load_tests`` which is called with the following arguments:: + + load_tests(loader, standard_tests, pattern) + +This should return a :class:`TestSuite` representing all the tests +from the package. (``standard_tests`` will only contain tests +collected from :file:`__init__.py`.) + +Because the pattern is passed into ``load_tests`` the package is free to +continue (and potentially modify) test discovery. A 'do nothing' +``load_tests`` function for a test package would look like:: + + def load_tests(loader, standard_tests, pattern): + # top level directory cached on loader instance + this_dir = os.path.dirname(__file__) + package_tests = loader.discover(start_dir=this_dir, pattern=pattern) + standard_tests.addTests(package_tests) + return standard_tests + +.. versionchanged:: 3.5 + Discovery no longer checks package names for matching *pattern* due to the + impossibility of package names matching the default pattern. + + + +Class and Module Fixtures +------------------------- + +Class and module level fixtures are implemented in :class:`TestSuite`. When +the test suite encounters a test from a new class then :meth:`tearDownClass` +from the previous class (if there is one) is called, followed by +:meth:`setUpClass` from the new class. + +Similarly if a test is from a different module from the previous test then +``tearDownModule`` from the previous module is run, followed by +``setUpModule`` from the new module. + +After all the tests have run the final ``tearDownClass`` and +``tearDownModule`` are run. + +Note that shared fixtures do not play well with [potential] features like test +parallelization and they break test isolation. They should be used with care. + +The default ordering of tests created by the unittest test loaders is to group +all tests from the same modules and classes together. This will lead to +``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and +module. If you randomize the order, so that tests from different modules and +classes are adjacent to each other, then these shared fixture functions may be +called multiple times in a single test run. + +Shared fixtures are not intended to work with suites with non-standard +ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to +support shared fixtures. + +If there are any exceptions raised during one of the shared fixture functions +the test is reported as an error. Because there is no corresponding test +instance an ``_ErrorHolder`` object (that has the same interface as a +:class:`TestCase`) is created to represent the error. If you are just using +the standard unittest test runner then this detail doesn't matter, but if you +are a framework author it may be relevant. + + +setUpClass and tearDownClass +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +These must be implemented as class methods:: + + import unittest + + class Test(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._connection = createExpensiveConnectionObject() + + @classmethod + def tearDownClass(cls): + cls._connection.destroy() + +If you want the ``setUpClass`` and ``tearDownClass`` on base classes called +then you must call up to them yourself. The implementations in +:class:`TestCase` are empty. + +If an exception is raised during a ``setUpClass`` then the tests in the class +are not run and the ``tearDownClass`` is not run. Skipped classes will not +have ``setUpClass`` or ``tearDownClass`` run. If the exception is a +:exc:`SkipTest` exception then the class will be reported as having been skipped +instead of as an error. + + +setUpModule and tearDownModule +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +These should be implemented as functions:: + + def setUpModule(): + createConnection() + + def tearDownModule(): + closeConnection() + +If an exception is raised in a ``setUpModule`` then none of the tests in the +module will be run and the ``tearDownModule`` will not be run. If the exception is a +:exc:`SkipTest` exception then the module will be reported as having been skipped +instead of as an error. + +To add cleanup code that must be run even in the case of an exception, use +``addModuleCleanup``: + + +.. function:: addModuleCleanup(function, /, *args, **kwargs) + + Add a function to be called after :func:`tearDownModule` to cleanup + resources used during the test class. Functions will be called in reverse + order to the order they are added (:abbr:`LIFO (last-in, first-out)`). + They are called with any arguments and keyword arguments passed into + :meth:`addModuleCleanup` when they are added. + + If :meth:`setUpModule` fails, meaning that :func:`tearDownModule` is not + called, then any cleanup functions added will still be called. + + .. versionadded:: 3.8 + + +.. function:: doModuleCleanups() + + This function is called unconditionally after :func:`tearDownModule`, or + after :func:`setUpModule` if :func:`setUpModule` raises an exception. + + It is responsible for calling all the cleanup functions added by + :func:`addCleanupModule`. If you need cleanup functions to be called + *prior* to :func:`tearDownModule` then you can call + :func:`doModuleCleanups` yourself. + + :func:`doModuleCleanups` pops methods off the stack of cleanup + functions one at a time, so it can be called at any time. + + .. versionadded:: 3.8 + +Signal Handling +--------------- + +.. versionadded:: 3.2 + +The :option:`-c/--catch ` command-line option to unittest, +along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide +more friendly handling of control-C during a test run. With catch break +behavior enabled control-C will allow the currently running test to complete, +and the test run will then end and report all the results so far. A second +control-c will raise a :exc:`KeyboardInterrupt` in the usual way. + +The control-c handling signal handler attempts to remain compatible with code or +tests that install their own :const:`signal.SIGINT` handler. If the ``unittest`` +handler is called but *isn't* the installed :const:`signal.SIGINT` handler, +i.e. it has been replaced by the system under test and delegated to, then it +calls the default handler. This will normally be the expected behavior by code +that replaces an installed handler and delegates to it. For individual tests +that need ``unittest`` control-c handling disabled the :func:`removeHandler` +decorator can be used. + +There are a few utility functions for framework authors to enable control-c +handling functionality within test frameworks. + +.. function:: installHandler() + + Install the control-c handler. When a :const:`signal.SIGINT` is received + (usually in response to the user pressing control-c) all registered results + have :meth:`~TestResult.stop` called. + + +.. function:: registerResult(result) + + Register a :class:`TestResult` object for control-c handling. Registering a + result stores a weak reference to it, so it doesn't prevent the result from + being garbage collected. + + Registering a :class:`TestResult` object has no side-effects if control-c + handling is not enabled, so test frameworks can unconditionally register + all results they create independently of whether or not handling is enabled. + + +.. function:: removeResult(result) + + Remove a registered result. Once a result has been removed then + :meth:`~TestResult.stop` will no longer be called on that result object in + response to a control-c. + + +.. function:: removeHandler(function=None) + + When called without arguments this function removes the control-c handler + if it has been installed. This function can also be used as a test decorator + to temporarily remove the handler while the test is being executed:: + + @unittest.removeHandler + def test_signal_handling(self): + ... diff --git a/cpython_2/environment/repo/Doc/library/unix.rst b/cpython_2/environment/repo/Doc/library/unix.rst new file mode 100644 index 0000000000000000000000000000000000000000..04d4081f4a0736ed658a1c51ac9f0bca9d62b11e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/unix.rst @@ -0,0 +1,26 @@ +.. _unix: + +********************** +Unix Specific Services +********************** + +The modules described in this chapter provide interfaces to features that are +unique to the Unix operating system, or in some cases to some or many variants +of it. Here's an overview: + + +.. toctree:: + + posix.rst + pwd.rst + spwd.rst + grp.rst + crypt.rst + termios.rst + tty.rst + pty.rst + fcntl.rst + pipes.rst + resource.rst + nis.rst + syslog.rst diff --git a/cpython_2/environment/repo/Doc/library/urllib.error.rst b/cpython_2/environment/repo/Doc/library/urllib.error.rst new file mode 100644 index 0000000000000000000000000000000000000000..f7d47ed76aca18fbbbbac3e064647c39972b4d5a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/urllib.error.rst @@ -0,0 +1,66 @@ +:mod:`urllib.error` --- Exception classes raised by urllib.request +================================================================== + +.. module:: urllib.error + :synopsis: Exception classes raised by urllib.request. + +.. moduleauthor:: Jeremy Hylton +.. sectionauthor:: Senthil Kumaran + +**Source code:** :source:`Lib/urllib/error.py` + +-------------- + +The :mod:`urllib.error` module defines the exception classes for exceptions +raised by :mod:`urllib.request`. The base exception class is :exc:`URLError`. + +The following exceptions are raised by :mod:`urllib.error` as appropriate: + +.. exception:: URLError + + The handlers raise this exception (or derived exceptions) when they run into + a problem. It is a subclass of :exc:`OSError`. + + .. attribute:: reason + + The reason for this error. It can be a message string or another + exception instance. + + .. versionchanged:: 3.3 + :exc:`URLError` has been made a subclass of :exc:`OSError` instead + of :exc:`IOError`. + + +.. exception:: HTTPError + + Though being an exception (a subclass of :exc:`URLError`), an + :exc:`HTTPError` can also function as a non-exceptional file-like return + value (the same thing that :func:`~urllib.request.urlopen` returns). This + is useful when handling exotic HTTP errors, such as requests for + authentication. + + .. attribute:: code + + An HTTP status code as defined in :rfc:`2616`. This numeric value corresponds + to a value found in the dictionary of codes as found in + :attr:`http.server.BaseHTTPRequestHandler.responses`. + + .. attribute:: reason + + This is usually a string explaining the reason for this error. + + .. attribute:: headers + + The HTTP response headers for the HTTP request that caused the + :exc:`HTTPError`. + + .. versionadded:: 3.4 + +.. exception:: ContentTooShortError(msg, content) + + This exception is raised when the :func:`~urllib.request.urlretrieve` + function detects that + the amount of the downloaded data is less than the expected amount (given by + the *Content-Length* header). The :attr:`content` attribute stores the + downloaded (and supposedly truncated) data. + diff --git a/cpython_2/environment/repo/Doc/library/urllib.parse.rst b/cpython_2/environment/repo/Doc/library/urllib.parse.rst new file mode 100644 index 0000000000000000000000000000000000000000..02f0c01e224ddf8e48f1f3a17bd3a53f30a46ff8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/urllib.parse.rst @@ -0,0 +1,681 @@ +:mod:`urllib.parse` --- Parse URLs into components +================================================== + +.. module:: urllib.parse + :synopsis: Parse URLs into or assemble them from components. + +**Source code:** :source:`Lib/urllib/parse.py` + +.. index:: + single: WWW + single: World Wide Web + single: URL + pair: URL; parsing + pair: relative; URL + +-------------- + +This module defines a standard interface to break Uniform Resource Locator (URL) +strings up in components (addressing scheme, network location, path etc.), to +combine the components back into a URL string, and to convert a "relative URL" +to an absolute URL given a "base URL." + +The module has been designed to match the Internet RFC on Relative Uniform +Resource Locators. It supports the following URL schemes: ``file``, ``ftp``, +``gopher``, ``hdl``, ``http``, ``https``, ``imap``, ``mailto``, ``mms``, +``news``, ``nntp``, ``prospero``, ``rsync``, ``rtsp``, ``rtspu``, ``sftp``, +``shttp``, ``sip``, ``sips``, ``snews``, ``svn``, ``svn+ssh``, ``telnet``, +``wais``, ``ws``, ``wss``. + +The :mod:`urllib.parse` module defines functions that fall into two broad +categories: URL parsing and URL quoting. These are covered in detail in +the following sections. + +URL Parsing +----------- + +The URL parsing functions focus on splitting a URL string into its components, +or on combining URL components into a URL string. + +.. function:: urlparse(urlstring, scheme='', allow_fragments=True) + + Parse a URL into six components, returning a 6-item :term:`named tuple`. This + corresponds to the general structure of a URL: + ``scheme://netloc/path;parameters?query#fragment``. + Each tuple item is a string, possibly empty. The components are not broken up + into smaller parts (for example, the network location is a single string), and % + escapes are not expanded. The delimiters as shown above are not part of the + result, except for a leading slash in the *path* component, which is retained if + present. For example: + + >>> from urllib.parse import urlparse + >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') + >>> o # doctest: +NORMALIZE_WHITESPACE + ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', + params='', query='', fragment='') + >>> o.scheme + 'http' + >>> o.port + 80 + >>> o.geturl() + 'http://www.cwi.nl:80/%7Eguido/Python.html' + + Following the syntax specifications in :rfc:`1808`, urlparse recognizes + a netloc only if it is properly introduced by '//'. Otherwise the + input is presumed to be a relative URL and thus to start with + a path component. + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> from urllib.parse import urlparse + >>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html') + ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', + params='', query='', fragment='') + >>> urlparse('www.cwi.nl/%7Eguido/Python.html') + ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html', + params='', query='', fragment='') + >>> urlparse('help/Python.html') + ParseResult(scheme='', netloc='', path='help/Python.html', params='', + query='', fragment='') + + The *scheme* argument gives the default addressing scheme, to be + used only if the URL does not specify one. It should be the same type + (text or bytes) as *urlstring*, except that the default value ``''`` is + always allowed, and is automatically converted to ``b''`` if appropriate. + + If the *allow_fragments* argument is false, fragment identifiers are not + recognized. Instead, they are parsed as part of the path, parameters + or query component, and :attr:`fragment` is set to the empty string in + the return value. + + The return value is a :term:`named tuple`, which means that its items can + be accessed by index or as named attributes, which are: + + +------------------+-------+--------------------------+----------------------+ + | Attribute | Index | Value | Value if not present | + +==================+=======+==========================+======================+ + | :attr:`scheme` | 0 | URL scheme specifier | *scheme* parameter | + +------------------+-------+--------------------------+----------------------+ + | :attr:`netloc` | 1 | Network location part | empty string | + +------------------+-------+--------------------------+----------------------+ + | :attr:`path` | 2 | Hierarchical path | empty string | + +------------------+-------+--------------------------+----------------------+ + | :attr:`params` | 3 | Parameters for last path | empty string | + | | | element | | + +------------------+-------+--------------------------+----------------------+ + | :attr:`query` | 4 | Query component | empty string | + +------------------+-------+--------------------------+----------------------+ + | :attr:`fragment` | 5 | Fragment identifier | empty string | + +------------------+-------+--------------------------+----------------------+ + | :attr:`username` | | User name | :const:`None` | + +------------------+-------+--------------------------+----------------------+ + | :attr:`password` | | Password | :const:`None` | + +------------------+-------+--------------------------+----------------------+ + | :attr:`hostname` | | Host name (lower case) | :const:`None` | + +------------------+-------+--------------------------+----------------------+ + | :attr:`port` | | Port number as integer, | :const:`None` | + | | | if present | | + +------------------+-------+--------------------------+----------------------+ + + Reading the :attr:`port` attribute will raise a :exc:`ValueError` if + an invalid port is specified in the URL. See section + :ref:`urlparse-result-object` for more information on the result object. + + Unmatched square brackets in the :attr:`netloc` attribute will raise a + :exc:`ValueError`. + + Characters in the :attr:`netloc` attribute that decompose under NFKC + normalization (as used by the IDNA encoding) into any of ``/``, ``?``, + ``#``, ``@``, or ``:`` will raise a :exc:`ValueError`. If the URL is + decomposed before parsing, no error will be raised. + + As is the case with all named tuples, the subclass has a few additional methods + and attributes that are particularly useful. One such method is :meth:`_replace`. + The :meth:`_replace` method will return a new ParseResult object replacing specified + fields with new values. + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> from urllib.parse import urlparse + >>> u = urlparse('//www.cwi.nl:80/%7Eguido/Python.html') + >>> u + ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', + params='', query='', fragment='') + >>> u._replace(scheme='http') + ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', + params='', query='', fragment='') + + + .. versionchanged:: 3.2 + Added IPv6 URL parsing capabilities. + + .. versionchanged:: 3.3 + The fragment is now parsed for all URL schemes (unless *allow_fragment* is + false), in accordance with :rfc:`3986`. Previously, a whitelist of + schemes that support fragments existed. + + .. versionchanged:: 3.6 + Out-of-range port numbers now raise :exc:`ValueError`, instead of + returning :const:`None`. + + .. versionchanged:: 3.8 + Characters that affect netloc parsing under NFKC normalization will + now raise :exc:`ValueError`. + + +.. function:: parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None) + + Parse a query string given as a string argument (data of type + :mimetype:`application/x-www-form-urlencoded`). Data are returned as a + dictionary. The dictionary keys are the unique query variable names and the + values are lists of values for each name. + + The optional argument *keep_blank_values* is a flag indicating whether blank + values in percent-encoded queries should be treated as blank strings. A true value + indicates that blanks should be retained as blank strings. The default false + value indicates that blank values are to be ignored and treated as if they were + not included. + + The optional argument *strict_parsing* is a flag indicating what to do with + parsing errors. If false (the default), errors are silently ignored. If true, + errors raise a :exc:`ValueError` exception. + + The optional *encoding* and *errors* parameters specify how to decode + percent-encoded sequences into Unicode characters, as accepted by the + :meth:`bytes.decode` method. + + The optional argument *max_num_fields* is the maximum number of fields to + read. If set, then throws a :exc:`ValueError` if there are more than + *max_num_fields* fields read. + + Use the :func:`urllib.parse.urlencode` function (with the ``doseq`` + parameter set to ``True``) to convert such dictionaries into query + strings. + + + .. versionchanged:: 3.2 + Add *encoding* and *errors* parameters. + + .. versionchanged:: 3.8 + Added *max_num_fields* parameter. + + +.. function:: parse_qsl(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None) + + Parse a query string given as a string argument (data of type + :mimetype:`application/x-www-form-urlencoded`). Data are returned as a list of + name, value pairs. + + The optional argument *keep_blank_values* is a flag indicating whether blank + values in percent-encoded queries should be treated as blank strings. A true value + indicates that blanks should be retained as blank strings. The default false + value indicates that blank values are to be ignored and treated as if they were + not included. + + The optional argument *strict_parsing* is a flag indicating what to do with + parsing errors. If false (the default), errors are silently ignored. If true, + errors raise a :exc:`ValueError` exception. + + The optional *encoding* and *errors* parameters specify how to decode + percent-encoded sequences into Unicode characters, as accepted by the + :meth:`bytes.decode` method. + + The optional argument *max_num_fields* is the maximum number of fields to + read. If set, then throws a :exc:`ValueError` if there are more than + *max_num_fields* fields read. + + Use the :func:`urllib.parse.urlencode` function to convert such lists of pairs into + query strings. + + .. versionchanged:: 3.2 + Add *encoding* and *errors* parameters. + + .. versionchanged:: 3.8 + Added *max_num_fields* parameter. + + +.. function:: urlunparse(parts) + + Construct a URL from a tuple as returned by ``urlparse()``. The *parts* + argument can be any six-item iterable. This may result in a slightly + different, but equivalent URL, if the URL that was parsed originally had + unnecessary delimiters (for example, a ``?`` with an empty query; the RFC + states that these are equivalent). + + +.. function:: urlsplit(urlstring, scheme='', allow_fragments=True) + + This is similar to :func:`urlparse`, but does not split the params from the URL. + This should generally be used instead of :func:`urlparse` if the more recent URL + syntax allowing parameters to be applied to each segment of the *path* portion + of the URL (see :rfc:`2396`) is wanted. A separate function is needed to + separate the path segments and parameters. This function returns a 5-item + :term:`named tuple`:: + + (addressing scheme, network location, path, query, fragment identifier). + + The return value is a :term:`named tuple`, its items can be accessed by index + or as named attributes: + + +------------------+-------+-------------------------+----------------------+ + | Attribute | Index | Value | Value if not present | + +==================+=======+=========================+======================+ + | :attr:`scheme` | 0 | URL scheme specifier | *scheme* parameter | + +------------------+-------+-------------------------+----------------------+ + | :attr:`netloc` | 1 | Network location part | empty string | + +------------------+-------+-------------------------+----------------------+ + | :attr:`path` | 2 | Hierarchical path | empty string | + +------------------+-------+-------------------------+----------------------+ + | :attr:`query` | 3 | Query component | empty string | + +------------------+-------+-------------------------+----------------------+ + | :attr:`fragment` | 4 | Fragment identifier | empty string | + +------------------+-------+-------------------------+----------------------+ + | :attr:`username` | | User name | :const:`None` | + +------------------+-------+-------------------------+----------------------+ + | :attr:`password` | | Password | :const:`None` | + +------------------+-------+-------------------------+----------------------+ + | :attr:`hostname` | | Host name (lower case) | :const:`None` | + +------------------+-------+-------------------------+----------------------+ + | :attr:`port` | | Port number as integer, | :const:`None` | + | | | if present | | + +------------------+-------+-------------------------+----------------------+ + + Reading the :attr:`port` attribute will raise a :exc:`ValueError` if + an invalid port is specified in the URL. See section + :ref:`urlparse-result-object` for more information on the result object. + + Unmatched square brackets in the :attr:`netloc` attribute will raise a + :exc:`ValueError`. + + Characters in the :attr:`netloc` attribute that decompose under NFKC + normalization (as used by the IDNA encoding) into any of ``/``, ``?``, + ``#``, ``@``, or ``:`` will raise a :exc:`ValueError`. If the URL is + decomposed before parsing, no error will be raised. + + .. versionchanged:: 3.6 + Out-of-range port numbers now raise :exc:`ValueError`, instead of + returning :const:`None`. + + .. versionchanged:: 3.8 + Characters that affect netloc parsing under NFKC normalization will + now raise :exc:`ValueError`. + + +.. function:: urlunsplit(parts) + + Combine the elements of a tuple as returned by :func:`urlsplit` into a + complete URL as a string. The *parts* argument can be any five-item + iterable. This may result in a slightly different, but equivalent URL, if the + URL that was parsed originally had unnecessary delimiters (for example, a ? + with an empty query; the RFC states that these are equivalent). + + +.. function:: urljoin(base, url, allow_fragments=True) + + Construct a full ("absolute") URL by combining a "base URL" (*base*) with + another URL (*url*). Informally, this uses components of the base URL, in + particular the addressing scheme, the network location and (part of) the + path, to provide missing components in the relative URL. For example: + + >>> from urllib.parse import urljoin + >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') + 'http://www.cwi.nl/%7Eguido/FAQ.html' + + The *allow_fragments* argument has the same meaning and default as for + :func:`urlparse`. + + .. note:: + + If *url* is an absolute URL (that is, it starts with ``//`` or ``scheme://``), + the *url*'s hostname and/or scheme will be present in the result. For example: + + .. doctest:: + + >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', + ... '//www.python.org/%7Eguido') + 'http://www.python.org/%7Eguido' + + If you do not want that behavior, preprocess the *url* with :func:`urlsplit` and + :func:`urlunsplit`, removing possible *scheme* and *netloc* parts. + + + .. versionchanged:: 3.5 + + Behavior updated to match the semantics defined in :rfc:`3986`. + + +.. function:: urldefrag(url) + + If *url* contains a fragment identifier, return a modified version of *url* + with no fragment identifier, and the fragment identifier as a separate + string. If there is no fragment identifier in *url*, return *url* unmodified + and an empty string. + + The return value is a :term:`named tuple`, its items can be accessed by index + or as named attributes: + + +------------------+-------+-------------------------+----------------------+ + | Attribute | Index | Value | Value if not present | + +==================+=======+=========================+======================+ + | :attr:`url` | 0 | URL with no fragment | empty string | + +------------------+-------+-------------------------+----------------------+ + | :attr:`fragment` | 1 | Fragment identifier | empty string | + +------------------+-------+-------------------------+----------------------+ + + See section :ref:`urlparse-result-object` for more information on the result + object. + + .. versionchanged:: 3.2 + Result is a structured object rather than a simple 2-tuple. + +.. function:: unwrap(url) + + Extract the url from a wrapped URL (that is, a string formatted as + ````, ````, ``URL:scheme://host/path`` + or ``scheme://host/path``). If *url* is not a wrapped URL, it is returned + without changes. + +.. _parsing-ascii-encoded-bytes: + +Parsing ASCII Encoded Bytes +--------------------------- + +The URL parsing functions were originally designed to operate on character +strings only. In practice, it is useful to be able to manipulate properly +quoted and encoded URLs as sequences of ASCII bytes. Accordingly, the +URL parsing functions in this module all operate on :class:`bytes` and +:class:`bytearray` objects in addition to :class:`str` objects. + +If :class:`str` data is passed in, the result will also contain only +:class:`str` data. If :class:`bytes` or :class:`bytearray` data is +passed in, the result will contain only :class:`bytes` data. + +Attempting to mix :class:`str` data with :class:`bytes` or +:class:`bytearray` in a single function call will result in a +:exc:`TypeError` being raised, while attempting to pass in non-ASCII +byte values will trigger :exc:`UnicodeDecodeError`. + +To support easier conversion of result objects between :class:`str` and +:class:`bytes`, all return values from URL parsing functions provide +either an :meth:`encode` method (when the result contains :class:`str` +data) or a :meth:`decode` method (when the result contains :class:`bytes` +data). The signatures of these methods match those of the corresponding +:class:`str` and :class:`bytes` methods (except that the default encoding +is ``'ascii'`` rather than ``'utf-8'``). Each produces a value of a +corresponding type that contains either :class:`bytes` data (for +:meth:`encode` methods) or :class:`str` data (for +:meth:`decode` methods). + +Applications that need to operate on potentially improperly quoted URLs +that may contain non-ASCII data will need to do their own decoding from +bytes to characters before invoking the URL parsing methods. + +The behaviour described in this section applies only to the URL parsing +functions. The URL quoting functions use their own rules when producing +or consuming byte sequences as detailed in the documentation of the +individual URL quoting functions. + +.. versionchanged:: 3.2 + URL parsing functions now accept ASCII encoded byte sequences + + +.. _urlparse-result-object: + +Structured Parse Results +------------------------ + +The result objects from the :func:`urlparse`, :func:`urlsplit` and +:func:`urldefrag` functions are subclasses of the :class:`tuple` type. +These subclasses add the attributes listed in the documentation for +those functions, the encoding and decoding support described in the +previous section, as well as an additional method: + +.. method:: urllib.parse.SplitResult.geturl() + + Return the re-combined version of the original URL as a string. This may + differ from the original URL in that the scheme may be normalized to lower + case and empty components may be dropped. Specifically, empty parameters, + queries, and fragment identifiers will be removed. + + For :func:`urldefrag` results, only empty fragment identifiers will be removed. + For :func:`urlsplit` and :func:`urlparse` results, all noted changes will be + made to the URL returned by this method. + + The result of this method remains unchanged if passed back through the original + parsing function: + + >>> from urllib.parse import urlsplit + >>> url = 'HTTP://www.Python.org/doc/#' + >>> r1 = urlsplit(url) + >>> r1.geturl() + 'http://www.Python.org/doc/' + >>> r2 = urlsplit(r1.geturl()) + >>> r2.geturl() + 'http://www.Python.org/doc/' + + +The following classes provide the implementations of the structured parse +results when operating on :class:`str` objects: + +.. class:: DefragResult(url, fragment) + + Concrete class for :func:`urldefrag` results containing :class:`str` + data. The :meth:`encode` method returns a :class:`DefragResultBytes` + instance. + + .. versionadded:: 3.2 + +.. class:: ParseResult(scheme, netloc, path, params, query, fragment) + + Concrete class for :func:`urlparse` results containing :class:`str` + data. The :meth:`encode` method returns a :class:`ParseResultBytes` + instance. + +.. class:: SplitResult(scheme, netloc, path, query, fragment) + + Concrete class for :func:`urlsplit` results containing :class:`str` + data. The :meth:`encode` method returns a :class:`SplitResultBytes` + instance. + + +The following classes provide the implementations of the parse results when +operating on :class:`bytes` or :class:`bytearray` objects: + +.. class:: DefragResultBytes(url, fragment) + + Concrete class for :func:`urldefrag` results containing :class:`bytes` + data. The :meth:`decode` method returns a :class:`DefragResult` + instance. + + .. versionadded:: 3.2 + +.. class:: ParseResultBytes(scheme, netloc, path, params, query, fragment) + + Concrete class for :func:`urlparse` results containing :class:`bytes` + data. The :meth:`decode` method returns a :class:`ParseResult` + instance. + + .. versionadded:: 3.2 + +.. class:: SplitResultBytes(scheme, netloc, path, query, fragment) + + Concrete class for :func:`urlsplit` results containing :class:`bytes` + data. The :meth:`decode` method returns a :class:`SplitResult` + instance. + + .. versionadded:: 3.2 + + +URL Quoting +----------- + +The URL quoting functions focus on taking program data and making it safe +for use as URL components by quoting special characters and appropriately +encoding non-ASCII text. They also support reversing these operations to +recreate the original data from the contents of a URL component if that +task isn't already covered by the URL parsing functions above. + +.. function:: quote(string, safe='/', encoding=None, errors=None) + + Replace special characters in *string* using the ``%xx`` escape. Letters, + digits, and the characters ``'_.-~'`` are never quoted. By default, this + function is intended for quoting the path section of a URL. The optional + *safe* parameter specifies additional ASCII characters that should not be + quoted --- its default value is ``'/'``. + + *string* may be either a :class:`str` or a :class:`bytes` object. + + .. versionchanged:: 3.7 + Moved from :rfc:`2396` to :rfc:`3986` for quoting URL strings. "~" is now + included in the set of unreserved characters. + + The optional *encoding* and *errors* parameters specify how to deal with + non-ASCII characters, as accepted by the :meth:`str.encode` method. + *encoding* defaults to ``'utf-8'``. + *errors* defaults to ``'strict'``, meaning unsupported characters raise a + :class:`UnicodeEncodeError`. + *encoding* and *errors* must not be supplied if *string* is a + :class:`bytes`, or a :class:`TypeError` is raised. + + Note that ``quote(string, safe, encoding, errors)`` is equivalent to + ``quote_from_bytes(string.encode(encoding, errors), safe)``. + + Example: ``quote('/El Niño/')`` yields ``'/El%20Ni%C3%B1o/'``. + + +.. function:: quote_plus(string, safe='', encoding=None, errors=None) + + Like :func:`quote`, but also replace spaces with plus signs, as required for + quoting HTML form values when building up a query string to go into a URL. + Plus signs in the original string are escaped unless they are included in + *safe*. It also does not have *safe* default to ``'/'``. + + Example: ``quote_plus('/El Niño/')`` yields ``'%2FEl+Ni%C3%B1o%2F'``. + + +.. function:: quote_from_bytes(bytes, safe='/') + + Like :func:`quote`, but accepts a :class:`bytes` object rather than a + :class:`str`, and does not perform string-to-bytes encoding. + + Example: ``quote_from_bytes(b'a&\xef')`` yields + ``'a%26%EF'``. + + +.. function:: unquote(string, encoding='utf-8', errors='replace') + + Replace ``%xx`` escapes with their single-character equivalent. + The optional *encoding* and *errors* parameters specify how to decode + percent-encoded sequences into Unicode characters, as accepted by the + :meth:`bytes.decode` method. + + *string* may be either a :class:`str` or a :class:`bytes` object. + + *encoding* defaults to ``'utf-8'``. + *errors* defaults to ``'replace'``, meaning invalid sequences are replaced + by a placeholder character. + + Example: ``unquote('/El%20Ni%C3%B1o/')`` yields ``'/El Niño/'``. + + .. versionchanged:: 3.9 + *string* parameter supports bytes and str objects (previously only str). + + + + +.. function:: unquote_plus(string, encoding='utf-8', errors='replace') + + Like :func:`unquote`, but also replace plus signs with spaces, as required + for unquoting HTML form values. + + *string* must be a :class:`str`. + + Example: ``unquote_plus('/El+Ni%C3%B1o/')`` yields ``'/El Niño/'``. + + +.. function:: unquote_to_bytes(string) + + Replace ``%xx`` escapes with their single-octet equivalent, and return a + :class:`bytes` object. + + *string* may be either a :class:`str` or a :class:`bytes` object. + + If it is a :class:`str`, unescaped non-ASCII characters in *string* + are encoded into UTF-8 bytes. + + Example: ``unquote_to_bytes('a%26%EF')`` yields ``b'a&\xef'``. + + +.. function:: urlencode(query, doseq=False, safe='', encoding=None, \ + errors=None, quote_via=quote_plus) + + Convert a mapping object or a sequence of two-element tuples, which may + contain :class:`str` or :class:`bytes` objects, to a percent-encoded ASCII + text string. If the resultant string is to be used as a *data* for POST + operation with the :func:`~urllib.request.urlopen` function, then + it should be encoded to bytes, otherwise it would result in a + :exc:`TypeError`. + + The resulting string is a series of ``key=value`` pairs separated by ``'&'`` + characters, where both *key* and *value* are quoted using the *quote_via* + function. By default, :func:`quote_plus` is used to quote the values, which + means spaces are quoted as a ``'+'`` character and '/' characters are + encoded as ``%2F``, which follows the standard for GET requests + (``application/x-www-form-urlencoded``). An alternate function that can be + passed as *quote_via* is :func:`quote`, which will encode spaces as ``%20`` + and not encode '/' characters. For maximum control of what is quoted, use + ``quote`` and specify a value for *safe*. + + When a sequence of two-element tuples is used as the *query* + argument, the first element of each tuple is a key and the second is a + value. The value element in itself can be a sequence and in that case, if + the optional parameter *doseq* evaluates to ``True``, individual + ``key=value`` pairs separated by ``'&'`` are generated for each element of + the value sequence for the key. The order of parameters in the encoded + string will match the order of parameter tuples in the sequence. + + The *safe*, *encoding*, and *errors* parameters are passed down to + *quote_via* (the *encoding* and *errors* parameters are only passed + when a query element is a :class:`str`). + + To reverse this encoding process, :func:`parse_qs` and :func:`parse_qsl` are + provided in this module to parse query strings into Python data structures. + + Refer to :ref:`urllib examples ` to find out how the + :func:`urllib.parse.urlencode` method can be used for generating the query + string of a URL or data for a POST request. + + .. versionchanged:: 3.2 + *query* supports bytes and string objects. + + .. versionadded:: 3.5 + *quote_via* parameter. + + +.. seealso:: + + :rfc:`3986` - Uniform Resource Identifiers + This is the current standard (STD66). Any changes to urllib.parse module + should conform to this. Certain deviations could be observed, which are + mostly for backward compatibility purposes and for certain de-facto + parsing requirements as commonly observed in major browsers. + + :rfc:`2732` - Format for Literal IPv6 Addresses in URL's. + This specifies the parsing requirements of IPv6 URLs. + + :rfc:`2396` - Uniform Resource Identifiers (URI): Generic Syntax + Document describing the generic syntactic requirements for both Uniform Resource + Names (URNs) and Uniform Resource Locators (URLs). + + :rfc:`2368` - The mailto URL scheme. + Parsing requirements for mailto URL schemes. + + :rfc:`1808` - Relative Uniform Resource Locators + This Request For Comments includes the rules for joining an absolute and a + relative URL, including a fair number of "Abnormal Examples" which govern the + treatment of border cases. + + :rfc:`1738` - Uniform Resource Locators (URL) + This specifies the formal syntax and semantics of absolute URLs. diff --git a/cpython_2/environment/repo/Doc/library/urllib.request.rst b/cpython_2/environment/repo/Doc/library/urllib.request.rst new file mode 100644 index 0000000000000000000000000000000000000000..03712c1f4a6eeabcdaef7dd39707557dd44f8933 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/urllib.request.rst @@ -0,0 +1,1618 @@ +:mod:`urllib.request` --- Extensible library for opening URLs +============================================================= + +.. module:: urllib.request + :synopsis: Extensible library for opening URLs. + +.. moduleauthor:: Jeremy Hylton +.. sectionauthor:: Moshe Zadka +.. sectionauthor:: Senthil Kumaran + +**Source code:** :source:`Lib/urllib/request.py` + +-------------- + +The :mod:`urllib.request` module defines functions and classes which help in +opening URLs (mostly HTTP) in a complex world --- basic and digest +authentication, redirections, cookies and more. + +.. seealso:: + + The `Requests package `_ + is recommended for a higher-level HTTP client interface. + + +The :mod:`urllib.request` module defines the following functions: + + +.. function:: urlopen(url, data=None[, timeout], *, cafile=None, capath=None, cadefault=False, context=None) + + Open the URL *url*, which can be either a string or a + :class:`Request` object. + + *data* must be an object specifying additional data to be sent to the + server, or ``None`` if no such data is needed. See :class:`Request` + for details. + + urllib.request module uses HTTP/1.1 and includes ``Connection:close`` header + in its HTTP requests. + + The optional *timeout* parameter specifies a timeout in seconds for + blocking operations like the connection attempt (if not specified, + the global default timeout setting will be used). This actually + only works for HTTP, HTTPS and FTP connections. + + If *context* is specified, it must be a :class:`ssl.SSLContext` instance + describing the various SSL options. See :class:`~http.client.HTTPSConnection` + for more details. + + The optional *cafile* and *capath* parameters specify a set of trusted + CA certificates for HTTPS requests. *cafile* should point to a single + file containing a bundle of CA certificates, whereas *capath* should + point to a directory of hashed certificate files. More information can + be found in :meth:`ssl.SSLContext.load_verify_locations`. + + The *cadefault* parameter is ignored. + + This function always returns an object which can work as a + :term:`context manager` and has the properties *url*, *headers*, and *status*. + See :class:`urllib.response.addinfourl` for more detail on these properties. + + For HTTP and HTTPS URLs, this function returns a + :class:`http.client.HTTPResponse` object slightly modified. In addition + to the three new methods above, the msg attribute contains the + same information as the :attr:`~http.client.HTTPResponse.reason` + attribute --- the reason phrase returned by server --- instead of + the response headers as it is specified in the documentation for + :class:`~http.client.HTTPResponse`. + + For FTP, file, and data URLs and requests explicitly handled by legacy + :class:`URLopener` and :class:`FancyURLopener` classes, this function + returns a :class:`urllib.response.addinfourl` object. + + Raises :exc:`~urllib.error.URLError` on protocol errors. + + Note that ``None`` may be returned if no handler handles the request (though + the default installed global :class:`OpenerDirector` uses + :class:`UnknownHandler` to ensure this never happens). + + In addition, if proxy settings are detected (for example, when a ``*_proxy`` + environment variable like :envvar:`http_proxy` is set), + :class:`ProxyHandler` is default installed and makes sure the requests are + handled through the proxy. + + The legacy ``urllib.urlopen`` function from Python 2.6 and earlier has been + discontinued; :func:`urllib.request.urlopen` corresponds to the old + ``urllib2.urlopen``. Proxy handling, which was done by passing a dictionary + parameter to ``urllib.urlopen``, can be obtained by using + :class:`ProxyHandler` objects. + + .. audit-event:: urllib.Request fullurl,data,headers,method urllib.request.urlopen + + The default opener raises an :ref:`auditing event ` + ``urllib.Request`` with arguments ``fullurl``, ``data``, ``headers``, + ``method`` taken from the request object. + + .. versionchanged:: 3.2 + *cafile* and *capath* were added. + + .. versionchanged:: 3.2 + HTTPS virtual hosts are now supported if possible (that is, if + :data:`ssl.HAS_SNI` is true). + + .. versionadded:: 3.2 + *data* can be an iterable object. + + .. versionchanged:: 3.3 + *cadefault* was added. + + .. versionchanged:: 3.4.3 + *context* was added. + + .. deprecated:: 3.6 + + *cafile*, *capath* and *cadefault* are deprecated in favor of *context*. + Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let + :func:`ssl.create_default_context` select the system's trusted CA + certificates for you. + + +.. function:: install_opener(opener) + + Install an :class:`OpenerDirector` instance as the default global opener. + Installing an opener is only necessary if you want urlopen to use that + opener; otherwise, simply call :meth:`OpenerDirector.open` instead of + :func:`~urllib.request.urlopen`. The code does not check for a real + :class:`OpenerDirector`, and any class with the appropriate interface will + work. + + +.. function:: build_opener([handler, ...]) + + Return an :class:`OpenerDirector` instance, which chains the handlers in the + order given. *handler*\s can be either instances of :class:`BaseHandler`, or + subclasses of :class:`BaseHandler` (in which case it must be possible to call + the constructor without any parameters). Instances of the following classes + will be in front of the *handler*\s, unless the *handler*\s contain them, + instances of them or subclasses of them: :class:`ProxyHandler` (if proxy + settings are detected), :class:`UnknownHandler`, :class:`HTTPHandler`, + :class:`HTTPDefaultErrorHandler`, :class:`HTTPRedirectHandler`, + :class:`FTPHandler`, :class:`FileHandler`, :class:`HTTPErrorProcessor`. + + If the Python installation has SSL support (i.e., if the :mod:`ssl` module + can be imported), :class:`HTTPSHandler` will also be added. + + A :class:`BaseHandler` subclass may also change its :attr:`handler_order` + attribute to modify its position in the handlers list. + + +.. function:: pathname2url(path) + + Convert the pathname *path* from the local syntax for a path to the form used in + the path component of a URL. This does not produce a complete URL. The return + value will already be quoted using the :func:`~urllib.parse.quote` function. + + +.. function:: url2pathname(path) + + Convert the path component *path* from a percent-encoded URL to the local syntax for a + path. This does not accept a complete URL. This function uses + :func:`~urllib.parse.unquote` to decode *path*. + +.. function:: getproxies() + + This helper function returns a dictionary of scheme to proxy server URL + mappings. It scans the environment for variables named ``_proxy``, + in a case insensitive approach, for all operating systems first, and when it + cannot find it, looks for proxy information from Mac OSX System + Configuration for Mac OS X and Windows Systems Registry for Windows. + If both lowercase and uppercase environment variables exist (and disagree), + lowercase is preferred. + + .. note:: + + If the environment variable ``REQUEST_METHOD`` is set, which usually + indicates your script is running in a CGI environment, the environment + variable ``HTTP_PROXY`` (uppercase ``_PROXY``) will be ignored. This is + because that variable can be injected by a client using the "Proxy:" HTTP + header. If you need to use an HTTP proxy in a CGI environment, either use + ``ProxyHandler`` explicitly, or make sure the variable name is in + lowercase (or at least the ``_proxy`` suffix). + + +The following classes are provided: + +.. class:: Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None) + + This class is an abstraction of a URL request. + + *url* should be a string containing a valid URL. + + *data* must be an object specifying additional data to send to the + server, or ``None`` if no such data is needed. Currently HTTP + requests are the only ones that use *data*. The supported object + types include bytes, file-like objects, and iterables of bytes-like objects. + If no ``Content-Length`` nor ``Transfer-Encoding`` header field + has been provided, :class:`HTTPHandler` will set these headers according + to the type of *data*. ``Content-Length`` will be used to send + bytes objects, while ``Transfer-Encoding: chunked`` as specified in + :rfc:`7230`, Section 3.3.1 will be used to send files and other iterables. + + For an HTTP POST request method, *data* should be a buffer in the + standard :mimetype:`application/x-www-form-urlencoded` format. The + :func:`urllib.parse.urlencode` function takes a mapping or sequence + of 2-tuples and returns an ASCII string in this format. It should + be encoded to bytes before being used as the *data* parameter. + + *headers* should be a dictionary, and will be treated as if + :meth:`add_header` was called with each key and value as arguments. + This is often used to "spoof" the ``User-Agent`` header value, which is + used by a browser to identify itself -- some HTTP servers only + allow requests coming from common browsers as opposed to scripts. + For example, Mozilla Firefox may identify itself as ``"Mozilla/5.0 + (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"``, while + :mod:`urllib`'s default user agent string is + ``"Python-urllib/2.6"`` (on Python 2.6). + + An appropriate ``Content-Type`` header should be included if the *data* + argument is present. If this header has not been provided and *data* + is not None, ``Content-Type: application/x-www-form-urlencoded`` will + be added as a default. + + The next two arguments are only of interest for correct handling + of third-party HTTP cookies: + + *origin_req_host* should be the request-host of the origin + transaction, as defined by :rfc:`2965`. It defaults to + ``http.cookiejar.request_host(self)``. This is the host name or IP + address of the original request that was initiated by the user. + For example, if the request is for an image in an HTML document, + this should be the request-host of the request for the page + containing the image. + + *unverifiable* should indicate whether the request is unverifiable, + as defined by :rfc:`2965`. It defaults to ``False``. An unverifiable + request is one whose URL the user did not have the option to + approve. For example, if the request is for an image in an HTML + document, and the user had no option to approve the automatic + fetching of the image, this should be true. + + *method* should be a string that indicates the HTTP request method that + will be used (e.g. ``'HEAD'``). If provided, its value is stored in the + :attr:`~Request.method` attribute and is used by :meth:`get_method()`. + The default is ``'GET'`` if *data* is ``None`` or ``'POST'`` otherwise. + Subclasses may indicate a different default method by setting the + :attr:`~Request.method` attribute in the class itself. + + .. note:: + The request will not work as expected if the data object is unable + to deliver its content more than once (e.g. a file or an iterable + that can produce the content only once) and the request is retried + for HTTP redirects or authentication. The *data* is sent to the + HTTP server right away after the headers. There is no support for + a 100-continue expectation in the library. + + .. versionchanged:: 3.3 + :attr:`Request.method` argument is added to the Request class. + + .. versionchanged:: 3.4 + Default :attr:`Request.method` may be indicated at the class level. + + .. versionchanged:: 3.6 + Do not raise an error if the ``Content-Length`` has not been + provided and *data* is neither ``None`` nor a bytes object. + Fall back to use chunked transfer encoding instead. + +.. class:: OpenerDirector() + + The :class:`OpenerDirector` class opens URLs via :class:`BaseHandler`\ s chained + together. It manages the chaining of handlers, and recovery from errors. + + +.. class:: BaseHandler() + + This is the base class for all registered handlers --- and handles only the + simple mechanics of registration. + + +.. class:: HTTPDefaultErrorHandler() + + A class which defines a default handler for HTTP error responses; all responses + are turned into :exc:`~urllib.error.HTTPError` exceptions. + + +.. class:: HTTPRedirectHandler() + + A class to handle redirections. + + +.. class:: HTTPCookieProcessor(cookiejar=None) + + A class to handle HTTP Cookies. + + +.. class:: ProxyHandler(proxies=None) + + Cause requests to go through a proxy. If *proxies* is given, it must be a + dictionary mapping protocol names to URLs of proxies. The default is to read + the list of proxies from the environment variables + ``_proxy``. If no proxy environment variables are set, then + in a Windows environment proxy settings are obtained from the registry's + Internet Settings section, and in a Mac OS X environment proxy information + is retrieved from the OS X System Configuration Framework. + + To disable autodetected proxy pass an empty dictionary. + + The :envvar:`no_proxy` environment variable can be used to specify hosts + which shouldn't be reached via proxy; if set, it should be a comma-separated + list of hostname suffixes, optionally with ``:port`` appended, for example + ``cern.ch,ncsa.uiuc.edu,some.host:8080``. + + .. note:: + + ``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; + see the documentation on :func:`~urllib.request.getproxies`. + + +.. class:: HTTPPasswordMgr() + + Keep a database of ``(realm, uri) -> (user, password)`` mappings. + + +.. class:: HTTPPasswordMgrWithDefaultRealm() + + Keep a database of ``(realm, uri) -> (user, password)`` mappings. A realm of + ``None`` is considered a catch-all realm, which is searched if no other realm + fits. + + +.. class:: HTTPPasswordMgrWithPriorAuth() + + A variant of :class:`HTTPPasswordMgrWithDefaultRealm` that also has a + database of ``uri -> is_authenticated`` mappings. Can be used by a + BasicAuth handler to determine when to send authentication credentials + immediately instead of waiting for a ``401`` response first. + + .. versionadded:: 3.5 + + +.. class:: AbstractBasicAuthHandler(password_mgr=None) + + This is a mixin class that helps with HTTP authentication, both to the remote + host and to a proxy. *password_mgr*, if given, should be something that is + compatible with :class:`HTTPPasswordMgr`; refer to section + :ref:`http-password-mgr` for information on the interface that must be + supported. If *passwd_mgr* also provides ``is_authenticated`` and + ``update_authenticated`` methods (see + :ref:`http-password-mgr-with-prior-auth`), then the handler will use the + ``is_authenticated`` result for a given URI to determine whether or not to + send authentication credentials with the request. If ``is_authenticated`` + returns ``True`` for the URI, credentials are sent. If ``is_authenticated`` + is ``False``, credentials are not sent, and then if a ``401`` response is + received the request is re-sent with the authentication credentials. If + authentication succeeds, ``update_authenticated`` is called to set + ``is_authenticated`` ``True`` for the URI, so that subsequent requests to + the URI or any of its super-URIs will automatically include the + authentication credentials. + + .. versionadded:: 3.5 + Added ``is_authenticated`` support. + + +.. class:: HTTPBasicAuthHandler(password_mgr=None) + + Handle authentication with the remote host. *password_mgr*, if given, should + be something that is compatible with :class:`HTTPPasswordMgr`; refer to + section :ref:`http-password-mgr` for information on the interface that must + be supported. HTTPBasicAuthHandler will raise a :exc:`ValueError` when + presented with a wrong Authentication scheme. + + +.. class:: ProxyBasicAuthHandler(password_mgr=None) + + Handle authentication with the proxy. *password_mgr*, if given, should be + something that is compatible with :class:`HTTPPasswordMgr`; refer to section + :ref:`http-password-mgr` for information on the interface that must be + supported. + + +.. class:: AbstractDigestAuthHandler(password_mgr=None) + + This is a mixin class that helps with HTTP authentication, both to the remote + host and to a proxy. *password_mgr*, if given, should be something that is + compatible with :class:`HTTPPasswordMgr`; refer to section + :ref:`http-password-mgr` for information on the interface that must be + supported. + + +.. class:: HTTPDigestAuthHandler(password_mgr=None) + + Handle authentication with the remote host. *password_mgr*, if given, should + be something that is compatible with :class:`HTTPPasswordMgr`; refer to + section :ref:`http-password-mgr` for information on the interface that must + be supported. When both Digest Authentication Handler and Basic + Authentication Handler are both added, Digest Authentication is always tried + first. If the Digest Authentication returns a 40x response again, it is sent + to Basic Authentication handler to Handle. This Handler method will raise a + :exc:`ValueError` when presented with an authentication scheme other than + Digest or Basic. + + .. versionchanged:: 3.3 + Raise :exc:`ValueError` on unsupported Authentication Scheme. + + + +.. class:: ProxyDigestAuthHandler(password_mgr=None) + + Handle authentication with the proxy. *password_mgr*, if given, should be + something that is compatible with :class:`HTTPPasswordMgr`; refer to section + :ref:`http-password-mgr` for information on the interface that must be + supported. + + +.. class:: HTTPHandler() + + A class to handle opening of HTTP URLs. + + +.. class:: HTTPSHandler(debuglevel=0, context=None, check_hostname=None) + + A class to handle opening of HTTPS URLs. *context* and *check_hostname* + have the same meaning as in :class:`http.client.HTTPSConnection`. + + .. versionchanged:: 3.2 + *context* and *check_hostname* were added. + + +.. class:: FileHandler() + + Open local files. + +.. class:: DataHandler() + + Open data URLs. + + .. versionadded:: 3.4 + +.. class:: FTPHandler() + + Open FTP URLs. + + +.. class:: CacheFTPHandler() + + Open FTP URLs, keeping a cache of open FTP connections to minimize delays. + + +.. class:: UnknownHandler() + + A catch-all class to handle unknown URLs. + + +.. class:: HTTPErrorProcessor() + + Process HTTP error responses. + + +.. _request-objects: + +Request Objects +--------------- + +The following methods describe :class:`Request`'s public interface, +and so all may be overridden in subclasses. It also defines several +public attributes that can be used by clients to inspect the parsed +request. + +.. attribute:: Request.full_url + + The original URL passed to the constructor. + + .. versionchanged:: 3.4 + + Request.full_url is a property with setter, getter and a deleter. Getting + :attr:`~Request.full_url` returns the original request URL with the + fragment, if it was present. + +.. attribute:: Request.type + + The URI scheme. + +.. attribute:: Request.host + + The URI authority, typically a host, but may also contain a port + separated by a colon. + +.. attribute:: Request.origin_req_host + + The original host for the request, without port. + +.. attribute:: Request.selector + + The URI path. If the :class:`Request` uses a proxy, then selector + will be the full URL that is passed to the proxy. + +.. attribute:: Request.data + + The entity body for the request, or ``None`` if not specified. + + .. versionchanged:: 3.4 + Changing value of :attr:`Request.data` now deletes "Content-Length" + header if it was previously set or calculated. + +.. attribute:: Request.unverifiable + + boolean, indicates whether the request is unverifiable as defined + by :rfc:`2965`. + +.. attribute:: Request.method + + The HTTP request method to use. By default its value is :const:`None`, + which means that :meth:`~Request.get_method` will do its normal computation + of the method to be used. Its value can be set (thus overriding the default + computation in :meth:`~Request.get_method`) either by providing a default + value by setting it at the class level in a :class:`Request` subclass, or by + passing a value in to the :class:`Request` constructor via the *method* + argument. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.4 + A default value can now be set in subclasses; previously it could only + be set via the constructor argument. + + +.. method:: Request.get_method() + + Return a string indicating the HTTP request method. If + :attr:`Request.method` is not ``None``, return its value, otherwise return + ``'GET'`` if :attr:`Request.data` is ``None``, or ``'POST'`` if it's not. + This is only meaningful for HTTP requests. + + .. versionchanged:: 3.3 + get_method now looks at the value of :attr:`Request.method`. + + +.. method:: Request.add_header(key, val) + + Add another header to the request. Headers are currently ignored by all + handlers except HTTP handlers, where they are added to the list of headers sent + to the server. Note that there cannot be more than one header with the same + name, and later calls will overwrite previous calls in case the *key* collides. + Currently, this is no loss of HTTP functionality, since all headers which have + meaning when used more than once have a (header-specific) way of gaining the + same functionality using only one header. + + +.. method:: Request.add_unredirected_header(key, header) + + Add a header that will not be added to a redirected request. + + +.. method:: Request.has_header(header) + + Return whether the instance has the named header (checks both regular and + unredirected). + + +.. method:: Request.remove_header(header) + + Remove named header from the request instance (both from regular and + unredirected headers). + + .. versionadded:: 3.4 + + +.. method:: Request.get_full_url() + + Return the URL given in the constructor. + + .. versionchanged:: 3.4 + + Returns :attr:`Request.full_url` + + +.. method:: Request.set_proxy(host, type) + + Prepare the request by connecting to a proxy server. The *host* and *type* will + replace those of the instance, and the instance's selector will be the original + URL given in the constructor. + + +.. method:: Request.get_header(header_name, default=None) + + Return the value of the given header. If the header is not present, return + the default value. + + +.. method:: Request.header_items() + + Return a list of tuples (header_name, header_value) of the Request headers. + +.. versionchanged:: 3.4 + The request methods add_data, has_data, get_data, get_type, get_host, + get_selector, get_origin_req_host and is_unverifiable that were deprecated + since 3.3 have been removed. + + +.. _opener-director-objects: + +OpenerDirector Objects +---------------------- + +:class:`OpenerDirector` instances have the following methods: + + +.. method:: OpenerDirector.add_handler(handler) + + *handler* should be an instance of :class:`BaseHandler`. The following methods + are searched, and added to the possible chains (note that HTTP errors are a + special case). Note that, in the following, *protocol* should be replaced + with the actual protocol to handle, for example :meth:`http_response` would + be the HTTP protocol response handler. Also *type* should be replaced with + the actual HTTP code, for example :meth:`http_error_404` would handle HTTP + 404 errors. + + * :meth:`_open` --- signal that the handler knows how to open *protocol* + URLs. + + See |protocol_open|_ for more information. + + * :meth:`http_error_\` --- signal that the handler knows how to handle HTTP + errors with HTTP error code *type*. + + See |http_error_nnn|_ for more information. + + * :meth:`_error` --- signal that the handler knows how to handle errors + from (non-\ ``http``) *protocol*. + + * :meth:`_request` --- signal that the handler knows how to pre-process + *protocol* requests. + + See |protocol_request|_ for more information. + + * :meth:`_response` --- signal that the handler knows how to + post-process *protocol* responses. + + See |protocol_response|_ for more information. + +.. |protocol_open| replace:: :meth:`BaseHandler._open` +.. |http_error_nnn| replace:: :meth:`BaseHandler.http_error_\` +.. |protocol_request| replace:: :meth:`BaseHandler._request` +.. |protocol_response| replace:: :meth:`BaseHandler._response` + +.. method:: OpenerDirector.open(url, data=None[, timeout]) + + Open the given *url* (which can be a request object or a string), optionally + passing the given *data*. Arguments, return values and exceptions raised are + the same as those of :func:`urlopen` (which simply calls the :meth:`open` + method on the currently installed global :class:`OpenerDirector`). The + optional *timeout* parameter specifies a timeout in seconds for blocking + operations like the connection attempt (if not specified, the global default + timeout setting will be used). The timeout feature actually works only for + HTTP, HTTPS and FTP connections). + + +.. method:: OpenerDirector.error(proto, *args) + + Handle an error of the given protocol. This will call the registered error + handlers for the given protocol with the given arguments (which are protocol + specific). The HTTP protocol is a special case which uses the HTTP response + code to determine the specific error handler; refer to the :meth:`http_error_\` + methods of the handler classes. + + Return values and exceptions raised are the same as those of :func:`urlopen`. + +OpenerDirector objects open URLs in three stages: + +The order in which these methods are called within each stage is determined by +sorting the handler instances. + +#. Every handler with a method named like :meth:`_request` has that + method called to pre-process the request. + +#. Handlers with a method named like :meth:`_open` are called to handle + the request. This stage ends when a handler either returns a non-\ :const:`None` + value (ie. a response), or raises an exception (usually + :exc:`~urllib.error.URLError`). Exceptions are allowed to propagate. + + In fact, the above algorithm is first tried for methods named + :meth:`default_open`. If all such methods return :const:`None`, the algorithm + is repeated for methods named like :meth:`_open`. If all such methods + return :const:`None`, the algorithm is repeated for methods named + :meth:`unknown_open`. + + Note that the implementation of these methods may involve calls of the parent + :class:`OpenerDirector` instance's :meth:`~OpenerDirector.open` and + :meth:`~OpenerDirector.error` methods. + +#. Every handler with a method named like :meth:`_response` has that + method called to post-process the response. + + +.. _base-handler-objects: + +BaseHandler Objects +------------------- + +:class:`BaseHandler` objects provide a couple of methods that are directly +useful, and others that are meant to be used by derived classes. These are +intended for direct use: + + +.. method:: BaseHandler.add_parent(director) + + Add a director as parent. + + +.. method:: BaseHandler.close() + + Remove any parents. + +The following attribute and methods should only be used by classes derived from +:class:`BaseHandler`. + +.. note:: + + The convention has been adopted that subclasses defining + :meth:`_request` or :meth:`_response` methods are named + :class:`\*Processor`; all others are named :class:`\*Handler`. + + +.. attribute:: BaseHandler.parent + + A valid :class:`OpenerDirector`, which can be used to open using a different + protocol, or handle errors. + + +.. method:: BaseHandler.default_open(req) + + This method is *not* defined in :class:`BaseHandler`, but subclasses should + define it if they want to catch all URLs. + + This method, if implemented, will be called by the parent + :class:`OpenerDirector`. It should return a file-like object as described in + the return value of the :meth:`open` of :class:`OpenerDirector`, or ``None``. + It should raise :exc:`~urllib.error.URLError`, unless a truly exceptional + thing happens (for example, :exc:`MemoryError` should not be mapped to + :exc:`URLError`). + + This method will be called before any protocol-specific open method. + + +.. _protocol_open: +.. method:: BaseHandler._open(req) + :noindex: + + This method is *not* defined in :class:`BaseHandler`, but subclasses should + define it if they want to handle URLs with the given protocol. + + This method, if defined, will be called by the parent :class:`OpenerDirector`. + Return values should be the same as for :meth:`default_open`. + + +.. method:: BaseHandler.unknown_open(req) + + This method is *not* defined in :class:`BaseHandler`, but subclasses should + define it if they want to catch all URLs with no specific registered handler to + open it. + + This method, if implemented, will be called by the :attr:`parent` + :class:`OpenerDirector`. Return values should be the same as for + :meth:`default_open`. + + +.. method:: BaseHandler.http_error_default(req, fp, code, msg, hdrs) + + This method is *not* defined in :class:`BaseHandler`, but subclasses should + override it if they intend to provide a catch-all for otherwise unhandled HTTP + errors. It will be called automatically by the :class:`OpenerDirector` getting + the error, and should not normally be called in other circumstances. + + *req* will be a :class:`Request` object, *fp* will be a file-like object with + the HTTP error body, *code* will be the three-digit code of the error, *msg* + will be the user-visible explanation of the code and *hdrs* will be a mapping + object with the headers of the error. + + Return values and exceptions raised should be the same as those of + :func:`urlopen`. + + +.. _http_error_nnn: +.. method:: BaseHandler.http_error_(req, fp, code, msg, hdrs) + + *nnn* should be a three-digit HTTP error code. This method is also not defined + in :class:`BaseHandler`, but will be called, if it exists, on an instance of a + subclass, when an HTTP error with code *nnn* occurs. + + Subclasses should override this method to handle specific HTTP errors. + + Arguments, return values and exceptions raised should be the same as for + :meth:`http_error_default`. + + +.. _protocol_request: +.. method:: BaseHandler._request(req) + :noindex: + + This method is *not* defined in :class:`BaseHandler`, but subclasses should + define it if they want to pre-process requests of the given protocol. + + This method, if defined, will be called by the parent :class:`OpenerDirector`. + *req* will be a :class:`Request` object. The return value should be a + :class:`Request` object. + + +.. _protocol_response: +.. method:: BaseHandler._response(req, response) + :noindex: + + This method is *not* defined in :class:`BaseHandler`, but subclasses should + define it if they want to post-process responses of the given protocol. + + This method, if defined, will be called by the parent :class:`OpenerDirector`. + *req* will be a :class:`Request` object. *response* will be an object + implementing the same interface as the return value of :func:`urlopen`. The + return value should implement the same interface as the return value of + :func:`urlopen`. + + +.. _http-redirect-handler: + +HTTPRedirectHandler Objects +--------------------------- + +.. note:: + + Some HTTP redirections require action from this module's client code. If this + is the case, :exc:`~urllib.error.HTTPError` is raised. See :rfc:`2616` for + details of the precise meanings of the various redirection codes. + + An :class:`HTTPError` exception raised as a security consideration if the + HTTPRedirectHandler is presented with a redirected URL which is not an HTTP, + HTTPS or FTP URL. + + +.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl) + + Return a :class:`Request` or ``None`` in response to a redirect. This is called + by the default implementations of the :meth:`http_error_30\*` methods when a + redirection is received from the server. If a redirection should take place, + return a new :class:`Request` to allow :meth:`http_error_30\*` to perform the + redirect to *newurl*. Otherwise, raise :exc:`~urllib.error.HTTPError` if + no other handler should try to handle this URL, or return ``None`` if you + can't but another handler might. + + .. note:: + + The default implementation of this method does not strictly follow :rfc:`2616`, + which says that 301 and 302 responses to ``POST`` requests must not be + automatically redirected without confirmation by the user. In reality, browsers + do allow automatic redirection of these responses, changing the POST to a + ``GET``, and the default implementation reproduces this behavior. + + +.. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs) + + Redirect to the ``Location:`` or ``URI:`` URL. This method is called by the + parent :class:`OpenerDirector` when getting an HTTP 'moved permanently' response. + + +.. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs) + + The same as :meth:`http_error_301`, but called for the 'found' response. + + +.. method:: HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs) + + The same as :meth:`http_error_301`, but called for the 'see other' response. + + +.. method:: HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs) + + The same as :meth:`http_error_301`, but called for the 'temporary redirect' + response. + + +.. _http-cookie-processor: + +HTTPCookieProcessor Objects +--------------------------- + +:class:`HTTPCookieProcessor` instances have one attribute: + +.. attribute:: HTTPCookieProcessor.cookiejar + + The :class:`http.cookiejar.CookieJar` in which cookies are stored. + + +.. _proxy-handler: + +ProxyHandler Objects +-------------------- + + +.. method:: ProxyHandler._open(request) + :noindex: + + The :class:`ProxyHandler` will have a method :meth:`_open` for every + *protocol* which has a proxy in the *proxies* dictionary given in the + constructor. The method will modify requests to go through the proxy, by + calling ``request.set_proxy()``, and call the next handler in the chain to + actually execute the protocol. + + +.. _http-password-mgr: + +HTTPPasswordMgr Objects +----------------------- + +These methods are available on :class:`HTTPPasswordMgr` and +:class:`HTTPPasswordMgrWithDefaultRealm` objects. + + +.. method:: HTTPPasswordMgr.add_password(realm, uri, user, passwd) + + *uri* can be either a single URI, or a sequence of URIs. *realm*, *user* and + *passwd* must be strings. This causes ``(user, passwd)`` to be used as + authentication tokens when authentication for *realm* and a super-URI of any of + the given URIs is given. + + +.. method:: HTTPPasswordMgr.find_user_password(realm, authuri) + + Get user/password for given realm and URI, if any. This method will return + ``(None, None)`` if there is no matching user/password. + + For :class:`HTTPPasswordMgrWithDefaultRealm` objects, the realm ``None`` will be + searched if the given *realm* has no matching user/password. + + +.. _http-password-mgr-with-prior-auth: + +HTTPPasswordMgrWithPriorAuth Objects +------------------------------------ + +This password manager extends :class:`HTTPPasswordMgrWithDefaultRealm` to support +tracking URIs for which authentication credentials should always be sent. + + +.. method:: HTTPPasswordMgrWithPriorAuth.add_password(realm, uri, user, \ + passwd, is_authenticated=False) + + *realm*, *uri*, *user*, *passwd* are as for + :meth:`HTTPPasswordMgr.add_password`. *is_authenticated* sets the initial + value of the ``is_authenticated`` flag for the given URI or list of URIs. + If *is_authenticated* is specified as ``True``, *realm* is ignored. + + +.. method:: HTTPPasswordMgr.find_user_password(realm, authuri) + + Same as for :class:`HTTPPasswordMgrWithDefaultRealm` objects + + +.. method:: HTTPPasswordMgrWithPriorAuth.update_authenticated(self, uri, \ + is_authenticated=False) + + Update the ``is_authenticated`` flag for the given *uri* or list + of URIs. + + +.. method:: HTTPPasswordMgrWithPriorAuth.is_authenticated(self, authuri) + + Returns the current state of the ``is_authenticated`` flag for + the given URI. + + +.. _abstract-basic-auth-handler: + +AbstractBasicAuthHandler Objects +-------------------------------- + + +.. method:: AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers) + + Handle an authentication request by getting a user/password pair, and re-trying + the request. *authreq* should be the name of the header where the information + about the realm is included in the request, *host* specifies the URL and path to + authenticate for, *req* should be the (failed) :class:`Request` object, and + *headers* should be the error headers. + + *host* is either an authority (e.g. ``"python.org"``) or a URL containing an + authority component (e.g. ``"http://python.org/"``). In either case, the + authority must not contain a userinfo component (so, ``"python.org"`` and + ``"python.org:80"`` are fine, ``"joe:password@python.org"`` is not). + + +.. _http-basic-auth-handler: + +HTTPBasicAuthHandler Objects +---------------------------- + + +.. method:: HTTPBasicAuthHandler.http_error_401(req, fp, code, msg, hdrs) + + Retry the request with authentication information, if available. + + +.. _proxy-basic-auth-handler: + +ProxyBasicAuthHandler Objects +----------------------------- + + +.. method:: ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs) + + Retry the request with authentication information, if available. + + +.. _abstract-digest-auth-handler: + +AbstractDigestAuthHandler Objects +--------------------------------- + + +.. method:: AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers) + + *authreq* should be the name of the header where the information about the realm + is included in the request, *host* should be the host to authenticate to, *req* + should be the (failed) :class:`Request` object, and *headers* should be the + error headers. + + +.. _http-digest-auth-handler: + +HTTPDigestAuthHandler Objects +----------------------------- + + +.. method:: HTTPDigestAuthHandler.http_error_401(req, fp, code, msg, hdrs) + + Retry the request with authentication information, if available. + + +.. _proxy-digest-auth-handler: + +ProxyDigestAuthHandler Objects +------------------------------ + + +.. method:: ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs) + + Retry the request with authentication information, if available. + + +.. _http-handler-objects: + +HTTPHandler Objects +------------------- + + +.. method:: HTTPHandler.http_open(req) + + Send an HTTP request, which can be either GET or POST, depending on + ``req.has_data()``. + + +.. _https-handler-objects: + +HTTPSHandler Objects +-------------------- + + +.. method:: HTTPSHandler.https_open(req) + + Send an HTTPS request, which can be either GET or POST, depending on + ``req.has_data()``. + + +.. _file-handler-objects: + +FileHandler Objects +------------------- + + +.. method:: FileHandler.file_open(req) + + Open the file locally, if there is no host name, or the host name is + ``'localhost'``. + + .. versionchanged:: 3.2 + This method is applicable only for local hostnames. When a remote + hostname is given, an :exc:`~urllib.error.URLError` is raised. + + +.. _data-handler-objects: + +DataHandler Objects +------------------- + +.. method:: DataHandler.data_open(req) + + Read a data URL. This kind of URL contains the content encoded in the URL + itself. The data URL syntax is specified in :rfc:`2397`. This implementation + ignores white spaces in base64 encoded data URLs so the URL may be wrapped + in whatever source file it comes from. But even though some browsers don't + mind about a missing padding at the end of a base64 encoded data URL, this + implementation will raise an :exc:`ValueError` in that case. + + +.. _ftp-handler-objects: + +FTPHandler Objects +------------------ + + +.. method:: FTPHandler.ftp_open(req) + + Open the FTP file indicated by *req*. The login is always done with empty + username and password. + + +.. _cacheftp-handler-objects: + +CacheFTPHandler Objects +----------------------- + +:class:`CacheFTPHandler` objects are :class:`FTPHandler` objects with the +following additional methods: + + +.. method:: CacheFTPHandler.setTimeout(t) + + Set timeout of connections to *t* seconds. + + +.. method:: CacheFTPHandler.setMaxConns(m) + + Set maximum number of cached connections to *m*. + + +.. _unknown-handler-objects: + +UnknownHandler Objects +---------------------- + + +.. method:: UnknownHandler.unknown_open() + + Raise a :exc:`~urllib.error.URLError` exception. + + +.. _http-error-processor-objects: + +HTTPErrorProcessor Objects +-------------------------- + +.. method:: HTTPErrorProcessor.http_response(request, response) + + Process HTTP error responses. + + For 200 error codes, the response object is returned immediately. + + For non-200 error codes, this simply passes the job on to the + :meth:`http_error_\` handler methods, via :meth:`OpenerDirector.error`. + Eventually, :class:`HTTPDefaultErrorHandler` will raise an + :exc:`~urllib.error.HTTPError` if no other handler handles the error. + + +.. method:: HTTPErrorProcessor.https_response(request, response) + + Process HTTPS error responses. + + The behavior is same as :meth:`http_response`. + + +.. _urllib-request-examples: + +Examples +-------- + +In addition to the examples below, more examples are given in +:ref:`urllib-howto`. + +This example gets the python.org main page and displays the first 300 bytes of +it. :: + + >>> import urllib.request + >>> with urllib.request.urlopen('http://www.python.org/') as f: + ... print(f.read(300)) + ... + b'\n\n\n\n\n\n + \n + Python Programming ' + +Note that urlopen returns a bytes object. This is because there is no way +for urlopen to automatically determine the encoding of the byte stream +it receives from the HTTP server. In general, a program will decode +the returned bytes object to string once it determines or guesses +the appropriate encoding. + +The following W3C document, https://www.w3.org/International/O-charset\ , lists +the various ways in which an (X)HTML or an XML document could have specified its +encoding information. + +As the python.org website uses *utf-8* encoding as specified in its meta tag, we +will use the same for decoding the bytes object. :: + + >>> with urllib.request.urlopen('http://www.python.org/') as f: + ... print(f.read(100).decode('utf-8')) + ... + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtm + +It is also possible to achieve the same result without using the +:term:`context manager` approach. :: + + >>> import urllib.request + >>> f = urllib.request.urlopen('http://www.python.org/') + >>> print(f.read(100).decode('utf-8')) + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtm + +In the following example, we are sending a data-stream to the stdin of a CGI +and reading the data it returns to us. Note that this example will only work +when the Python installation supports SSL. :: + + >>> import urllib.request + >>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi', + ... data=b'This data is passed to stdin of the CGI') + >>> with urllib.request.urlopen(req) as f: + ... print(f.read().decode('utf-8')) + ... + Got Data: "This data is passed to stdin of the CGI" + +The code for the sample CGI used in the above example is:: + + #!/usr/bin/env python + import sys + data = sys.stdin.read() + print('Content-type: text/plain\n\nGot Data: "%s"' % data) + +Here is an example of doing a ``PUT`` request using :class:`Request`:: + + import urllib.request + DATA = b'some data' + req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT') + with urllib.request.urlopen(req) as f: + pass + print(f.status) + print(f.reason) + +Use of Basic HTTP Authentication:: + + import urllib.request + # Create an OpenerDirector with support for Basic HTTP Authentication... + auth_handler = urllib.request.HTTPBasicAuthHandler() + auth_handler.add_password(realm='PDQ Application', + uri='https://mahler:8092/site-updates.py', + user='klem', + passwd='kadidd!ehopper') + opener = urllib.request.build_opener(auth_handler) + # ...and install it globally so it can be used with urlopen. + urllib.request.install_opener(opener) + urllib.request.urlopen('http://www.example.com/login.html') + +:func:`build_opener` provides many handlers by default, including a +:class:`ProxyHandler`. By default, :class:`ProxyHandler` uses the environment +variables named ``<scheme>_proxy``, where ``<scheme>`` is the URL scheme +involved. For example, the :envvar:`http_proxy` environment variable is read to +obtain the HTTP proxy's URL. + +This example replaces the default :class:`ProxyHandler` with one that uses +programmatically-supplied proxy URLs, and adds proxy authorization support with +:class:`ProxyBasicAuthHandler`. :: + + proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'}) + proxy_auth_handler = urllib.request.ProxyBasicAuthHandler() + proxy_auth_handler.add_password('realm', 'host', 'username', 'password') + + opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler) + # This time, rather than install the OpenerDirector, we use it directly: + opener.open('http://www.example.com/login.html') + +Adding HTTP headers: + +Use the *headers* argument to the :class:`Request` constructor, or:: + + import urllib.request + req = urllib.request.Request('http://www.example.com/') + req.add_header('Referer', 'http://www.python.org/') + # Customize the default User-Agent header value: + req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)') + r = urllib.request.urlopen(req) + +:class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to +every :class:`Request`. To change this:: + + import urllib.request + opener = urllib.request.build_opener() + opener.addheaders = [('User-agent', 'Mozilla/5.0')] + opener.open('http://www.example.com/') + +Also, remember that a few standard headers (:mailheader:`Content-Length`, +:mailheader:`Content-Type` and :mailheader:`Host`) +are added when the :class:`Request` is passed to :func:`urlopen` (or +:meth:`OpenerDirector.open`). + +.. _urllib-examples: + +Here is an example session that uses the ``GET`` method to retrieve a URL +containing parameters:: + + >>> import urllib.request + >>> import urllib.parse + >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) + >>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params + >>> with urllib.request.urlopen(url) as f: + ... print(f.read().decode('utf-8')) + ... + +The following example uses the ``POST`` method instead. Note that params output +from urlencode is encoded to bytes before it is sent to urlopen as data:: + + >>> import urllib.request + >>> import urllib.parse + >>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) + >>> data = data.encode('ascii') + >>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f: + ... print(f.read().decode('utf-8')) + ... + +The following example uses an explicitly specified HTTP proxy, overriding +environment settings:: + + >>> import urllib.request + >>> proxies = {'http': 'http://proxy.example.com:8080/'} + >>> opener = urllib.request.FancyURLopener(proxies) + >>> with opener.open("http://www.python.org") as f: + ... f.read().decode('utf-8') + ... + +The following example uses no proxies at all, overriding environment settings:: + + >>> import urllib.request + >>> opener = urllib.request.FancyURLopener({}) + >>> with opener.open("http://www.python.org/") as f: + ... f.read().decode('utf-8') + ... + + +Legacy interface +---------------- + +The following functions and classes are ported from the Python 2 module +``urllib`` (as opposed to ``urllib2``). They might become deprecated at +some point in the future. + +.. function:: urlretrieve(url, filename=None, reporthook=None, data=None) + + Copy a network object denoted by a URL to a local file. If the URL + points to a local file, the object will not be copied unless filename is supplied. + Return a tuple ``(filename, headers)`` where *filename* is the + local file name under which the object can be found, and *headers* is whatever + the :meth:`info` method of the object returned by :func:`urlopen` returned (for + a remote object). Exceptions are the same as for :func:`urlopen`. + + The second argument, if present, specifies the file location to copy to (if + absent, the location will be a tempfile with a generated name). The third + argument, if present, is a callable that will be called once on + establishment of the network connection and once after each block read + thereafter. The callable will be passed three arguments; a count of blocks + transferred so far, a block size in bytes, and the total size of the file. The + third argument may be ``-1`` on older FTP servers which do not return a file + size in response to a retrieval request. + + The following example illustrates the most common usage scenario:: + + >>> import urllib.request + >>> local_filename, headers = urllib.request.urlretrieve('http://python.org/') + >>> html = open(local_filename) + >>> html.close() + + If the *url* uses the :file:`http:` scheme identifier, the optional *data* + argument may be given to specify a ``POST`` request (normally the request + type is ``GET``). The *data* argument must be a bytes object in standard + :mimetype:`application/x-www-form-urlencoded` format; see the + :func:`urllib.parse.urlencode` function. + + :func:`urlretrieve` will raise :exc:`ContentTooShortError` when it detects that + the amount of data available was less than the expected amount (which is the + size reported by a *Content-Length* header). This can occur, for example, when + the download is interrupted. + + The *Content-Length* is treated as a lower bound: if there's more data to read, + urlretrieve reads more data, but if less data is available, it raises the + exception. + + You can still retrieve the downloaded data in this case, it is stored in the + :attr:`content` attribute of the exception instance. + + If no *Content-Length* header was supplied, urlretrieve can not check the size + of the data it has downloaded, and just returns it. In this case you just have + to assume that the download was successful. + +.. function:: urlcleanup() + + Cleans up temporary files that may have been left behind by previous + calls to :func:`urlretrieve`. + +.. class:: URLopener(proxies=None, **x509) + + .. deprecated:: 3.3 + + Base class for opening and reading URLs. Unless you need to support opening + objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`, + you probably want to use :class:`FancyURLopener`. + + By default, the :class:`URLopener` class sends a :mailheader:`User-Agent` header + of ``urllib/VVV``, where *VVV* is the :mod:`urllib` version number. + Applications can define their own :mailheader:`User-Agent` header by subclassing + :class:`URLopener` or :class:`FancyURLopener` and setting the class attribute + :attr:`version` to an appropriate string value in the subclass definition. + + The optional *proxies* parameter should be a dictionary mapping scheme names to + proxy URLs, where an empty dictionary turns proxies off completely. Its default + value is ``None``, in which case environmental proxy settings will be used if + present, as discussed in the definition of :func:`urlopen`, above. + + Additional keyword parameters, collected in *x509*, may be used for + authentication of the client when using the :file:`https:` scheme. The keywords + *key_file* and *cert_file* are supported to provide an SSL key and certificate; + both are needed to support client authentication. + + :class:`URLopener` objects will raise an :exc:`OSError` exception if the server + returns an error code. + + .. method:: open(fullurl, data=None) + + Open *fullurl* using the appropriate protocol. This method sets up cache and + proxy information, then calls the appropriate open method with its input + arguments. If the scheme is not recognized, :meth:`open_unknown` is called. + The *data* argument has the same meaning as the *data* argument of + :func:`urlopen`. + + This method always quotes *fullurl* using :func:`~urllib.parse.quote`. + + .. method:: open_unknown(fullurl, data=None) + + Overridable interface to open unknown URL types. + + + .. method:: retrieve(url, filename=None, reporthook=None, data=None) + + Retrieves the contents of *url* and places it in *filename*. The return value + is a tuple consisting of a local filename and either an + :class:`email.message.Message` object containing the response headers (for remote + URLs) or ``None`` (for local URLs). The caller must then open and read the + contents of *filename*. If *filename* is not given and the URL refers to a + local file, the input filename is returned. If the URL is non-local and + *filename* is not given, the filename is the output of :func:`tempfile.mktemp` + with a suffix that matches the suffix of the last path component of the input + URL. If *reporthook* is given, it must be a function accepting three numeric + parameters: A chunk number, the maximum size chunks are read in and the total size of the download + (-1 if unknown). It will be called once at the start and after each chunk of data is read from the + network. *reporthook* is ignored for local URLs. + + If the *url* uses the :file:`http:` scheme identifier, the optional *data* + argument may be given to specify a ``POST`` request (normally the request type + is ``GET``). The *data* argument must in standard + :mimetype:`application/x-www-form-urlencoded` format; see the + :func:`urllib.parse.urlencode` function. + + + .. attribute:: version + + Variable that specifies the user agent of the opener object. To get + :mod:`urllib` to tell servers that it is a particular user agent, set this in a + subclass as a class variable or in the constructor before calling the base + constructor. + + +.. class:: FancyURLopener(...) + + .. deprecated:: 3.3 + + :class:`FancyURLopener` subclasses :class:`URLopener` providing default handling + for the following HTTP response codes: 301, 302, 303, 307 and 401. For the 30x + response codes listed above, the :mailheader:`Location` header is used to fetch + the actual URL. For 401 response codes (authentication required), basic HTTP + authentication is performed. For the 30x response codes, recursion is bounded + by the value of the *maxtries* attribute, which defaults to 10. + + For all other response codes, the method :meth:`http_error_default` is called + which you can override in subclasses to handle the error appropriately. + + .. note:: + + According to the letter of :rfc:`2616`, 301 and 302 responses to POST requests + must not be automatically redirected without confirmation by the user. In + reality, browsers do allow automatic redirection of these responses, changing + the POST to a GET, and :mod:`urllib` reproduces this behaviour. + + The parameters to the constructor are the same as those for :class:`URLopener`. + + .. note:: + + When performing basic authentication, a :class:`FancyURLopener` instance calls + its :meth:`prompt_user_passwd` method. The default implementation asks the + users for the required information on the controlling terminal. A subclass may + override this method to support more appropriate behavior if needed. + + The :class:`FancyURLopener` class offers one additional method that should be + overloaded to provide the appropriate behavior: + + .. method:: prompt_user_passwd(host, realm) + + Return information needed to authenticate the user at the given host in the + specified security realm. The return value should be a tuple, ``(user, + password)``, which can be used for basic authentication. + + The implementation prompts for this information on the terminal; an application + should override this method to use an appropriate interaction model in the local + environment. + + +:mod:`urllib.request` Restrictions +---------------------------------- + + .. index:: + pair: HTTP; protocol + pair: FTP; protocol + +* Currently, only the following protocols are supported: HTTP (versions 0.9 and + 1.0), FTP, local files, and data URLs. + + .. versionchanged:: 3.4 Added support for data URLs. + +* The caching feature of :func:`urlretrieve` has been disabled until someone + finds the time to hack proper processing of Expiration time headers. + +* There should be a function to query whether a particular URL is in the cache. + +* For backward compatibility, if a URL appears to point to a local file but the + file can't be opened, the URL is re-interpreted using the FTP protocol. This + can sometimes cause confusing error messages. + +* The :func:`urlopen` and :func:`urlretrieve` functions can cause arbitrarily + long delays while waiting for a network connection to be set up. This means + that it is difficult to build an interactive Web client using these functions + without using threads. + + .. index:: + single: HTML + pair: HTTP; protocol + +* The data returned by :func:`urlopen` or :func:`urlretrieve` is the raw data + returned by the server. This may be binary data (such as an image), plain text + or (for example) HTML. The HTTP protocol provides type information in the reply + header, which can be inspected by looking at the :mailheader:`Content-Type` + header. If the returned data is HTML, you can use the module + :mod:`html.parser` to parse it. + + .. index:: single: FTP + +* The code handling the FTP protocol cannot differentiate between a file and a + directory. This can lead to unexpected behavior when attempting to read a URL + that points to a file that is not accessible. If the URL ends in a ``/``, it is + assumed to refer to a directory and will be handled accordingly. But if an + attempt to read a file leads to a 550 error (meaning the URL cannot be found or + is not accessible, often for permission reasons), then the path is treated as a + directory in order to handle the case when a directory is specified by a URL but + the trailing ``/`` has been left off. This can cause misleading results when + you try to fetch a file whose read permissions make it inaccessible; the FTP + code will try to read it, fail with a 550 error, and then perform a directory + listing for the unreadable file. If fine-grained control is needed, consider + using the :mod:`ftplib` module, subclassing :class:`FancyURLopener`, or changing + *_urlopener* to meet your needs. + + + +:mod:`urllib.response` --- Response classes used by urllib +========================================================== + +.. module:: urllib.response + :synopsis: Response classes used by urllib. + +The :mod:`urllib.response` module defines functions and classes which define a +minimal file-like interface, including ``read()`` and ``readline()``. +Functions defined by this module are used internally by the :mod:`urllib.request` module. +The typical response object is a :class:`urllib.response.addinfourl` instance: + +.. class:: addinfourl + + .. attribute:: url + + URL of the resource retrieved, commonly used to determine if a redirect was followed. + + .. attribute:: headers + + Returns the headers of the response in the form of an :class:`~email.message.EmailMessage` instance. + + .. attribute:: status + + .. versionadded:: 3.9 + + Status code returned by server. + + .. method:: geturl() + + .. deprecated:: 3.9 + Deprecated in favor of :attr:`~addinfourl.url`. + + .. method:: info() + + .. deprecated:: 3.9 + Deprecated in favor of :attr:`~addinfourl.headers`. + + .. attribute:: code + + .. deprecated:: 3.9 + Deprecated in favor of :attr:`~addinfourl.status`. + + .. method:: getstatus() + + .. deprecated:: 3.9 + Deprecated in favor of :attr:`~addinfourl.status`. diff --git a/cpython_2/environment/repo/Doc/library/urllib.robotparser.rst b/cpython_2/environment/repo/Doc/library/urllib.robotparser.rst new file mode 100644 index 0000000000000000000000000000000000000000..544f50273dd17c41b1dde334455469c5529be7e9 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/urllib.robotparser.rst @@ -0,0 +1,106 @@ +:mod:`urllib.robotparser` --- Parser for robots.txt +==================================================== + +.. module:: urllib.robotparser + :synopsis: Load a robots.txt file and answer questions about + fetchability of other URLs. + +.. sectionauthor:: Skip Montanaro <skip@pobox.com> + +**Source code:** :source:`Lib/urllib/robotparser.py` + +.. index:: + single: WWW + single: World Wide Web + single: URL + single: robots.txt + +-------------- + +This module provides a single class, :class:`RobotFileParser`, which answers +questions about whether or not a particular user agent can fetch a URL on the +Web site that published the :file:`robots.txt` file. For more details on the +structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html. + + +.. class:: RobotFileParser(url='') + + This class provides methods to read, parse and answer questions about the + :file:`robots.txt` file at *url*. + + .. method:: set_url(url) + + Sets the URL referring to a :file:`robots.txt` file. + + .. method:: read() + + Reads the :file:`robots.txt` URL and feeds it to the parser. + + .. method:: parse(lines) + + Parses the lines argument. + + .. method:: can_fetch(useragent, url) + + Returns ``True`` if the *useragent* is allowed to fetch the *url* + according to the rules contained in the parsed :file:`robots.txt` + file. + + .. method:: mtime() + + Returns the time the ``robots.txt`` file was last fetched. This is + useful for long-running web spiders that need to check for new + ``robots.txt`` files periodically. + + .. method:: modified() + + Sets the time the ``robots.txt`` file was last fetched to the current + time. + + .. method:: crawl_delay(useragent) + + Returns the value of the ``Crawl-delay`` parameter from ``robots.txt`` + for the *useragent* in question. If there is no such parameter or it + doesn't apply to the *useragent* specified or the ``robots.txt`` entry + for this parameter has invalid syntax, return ``None``. + + .. versionadded:: 3.6 + + .. method:: request_rate(useragent) + + Returns the contents of the ``Request-rate`` parameter from + ``robots.txt`` as a :term:`named tuple` ``RequestRate(requests, seconds)``. + If there is no such parameter or it doesn't apply to the *useragent* + specified or the ``robots.txt`` entry for this parameter has invalid + syntax, return ``None``. + + .. versionadded:: 3.6 + + .. method:: site_maps() + + Returns the contents of the ``Sitemap`` parameter from + ``robots.txt`` in the form of a :func:`list`. If there is no such + parameter or the ``robots.txt`` entry for this parameter has + invalid syntax, return ``None``. + + .. versionadded:: 3.8 + + +The following example demonstrates basic use of the :class:`RobotFileParser` +class:: + + >>> import urllib.robotparser + >>> rp = urllib.robotparser.RobotFileParser() + >>> rp.set_url("http://www.musi-cal.com/robots.txt") + >>> rp.read() + >>> rrate = rp.request_rate("*") + >>> rrate.requests + 3 + >>> rrate.seconds + 20 + >>> rp.crawl_delay("*") + 6 + >>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco") + False + >>> rp.can_fetch("*", "http://www.musi-cal.com/") + True diff --git a/cpython_2/environment/repo/Doc/library/urllib.rst b/cpython_2/environment/repo/Doc/library/urllib.rst new file mode 100644 index 0000000000000000000000000000000000000000..624e164625556a88586001dc0ed37034b30e555a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/urllib.rst @@ -0,0 +1,15 @@ +:mod:`urllib` --- URL handling modules +====================================== + +.. module:: urllib + +**Source code:** :source:`Lib/urllib/` + +-------------- + +``urllib`` is a package that collects several modules for working with URLs: + +* :mod:`urllib.request` for opening and reading URLs +* :mod:`urllib.error` containing the exceptions raised by :mod:`urllib.request` +* :mod:`urllib.parse` for parsing URLs +* :mod:`urllib.robotparser` for parsing ``robots.txt`` files diff --git a/cpython_2/environment/repo/Doc/library/uu.rst b/cpython_2/environment/repo/Doc/library/uu.rst new file mode 100644 index 0000000000000000000000000000000000000000..0bc8021e1bdfc7445aaf4a5ac662ef57f90e7e63 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/uu.rst @@ -0,0 +1,66 @@ +:mod:`uu` --- Encode and decode uuencode files +============================================== + +.. module:: uu + :synopsis: Encode and decode files in uuencode format. + +.. moduleauthor:: Lance Ellinghouse + +**Source code:** :source:`Lib/uu.py` + +-------------- + +This module encodes and decodes files in uuencode format, allowing arbitrary +binary data to be transferred over ASCII-only connections. Wherever a file +argument is expected, the methods accept a file-like object. For backwards +compatibility, a string containing a pathname is also accepted, and the +corresponding file will be opened for reading and writing; the pathname ``'-'`` +is understood to mean the standard input or output. However, this interface is +deprecated; it's better for the caller to open the file itself, and be sure +that, when required, the mode is ``'rb'`` or ``'wb'`` on Windows. + +.. index:: + single: Jansen, Jack + single: Ellinghouse, Lance + +This code was contributed by Lance Ellinghouse, and modified by Jack Jansen. + +The :mod:`uu` module defines the following functions: + + +.. function:: encode(in_file, out_file, name=None, mode=None, *, backtick=False) + + Uuencode file *in_file* into file *out_file*. The uuencoded file will have + the header specifying *name* and *mode* as the defaults for the results of + decoding the file. The default defaults are taken from *in_file*, or ``'-'`` + and ``0o666`` respectively. If *backtick* is true, zeros are represented by + ``'`'`` instead of spaces. + + .. versionchanged:: 3.7 + Added the *backtick* parameter. + + +.. function:: decode(in_file, out_file=None, mode=None, quiet=False) + + This call decodes uuencoded file *in_file* placing the result on file + *out_file*. If *out_file* is a pathname, *mode* is used to set the permission + bits if the file must be created. Defaults for *out_file* and *mode* are taken + from the uuencode header. However, if the file specified in the header already + exists, a :exc:`uu.Error` is raised. + + :func:`decode` may print a warning to standard error if the input was produced + by an incorrect uuencoder and Python could recover from that error. Setting + *quiet* to a true value silences this warning. + + +.. exception:: Error() + + Subclass of :exc:`Exception`, this can be raised by :func:`uu.decode` under + various situations, such as described above, but also including a badly + formatted header, or truncated input file. + + +.. seealso:: + + Module :mod:`binascii` + Support module containing ASCII-to-binary and binary-to-ASCII conversions. diff --git a/cpython_2/environment/repo/Doc/library/uuid.rst b/cpython_2/environment/repo/Doc/library/uuid.rst new file mode 100644 index 0000000000000000000000000000000000000000..415e25bef6de7d07d7106e004fd1ea4a59e743d4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/uuid.rst @@ -0,0 +1,303 @@ +:mod:`uuid` --- UUID objects according to :rfc:`4122` +===================================================== + +.. module:: uuid + :synopsis: UUID objects (universally unique identifiers) according to RFC 4122 +.. moduleauthor:: Ka-Ping Yee <ping@zesty.ca> +.. sectionauthor:: George Yoshida <quiver@users.sourceforge.net> + +**Source code:** :source:`Lib/uuid.py` + +-------------- + +This module provides immutable :class:`UUID` objects (the :class:`UUID` class) +and the functions :func:`uuid1`, :func:`uuid3`, :func:`uuid4`, :func:`uuid5` for +generating version 1, 3, 4, and 5 UUIDs as specified in :rfc:`4122`. + +If all you want is a unique ID, you should probably call :func:`uuid1` or +:func:`uuid4`. Note that :func:`uuid1` may compromise privacy since it creates +a UUID containing the computer's network address. :func:`uuid4` creates a +random UUID. + +Depending on support from the underlying platform, :func:`uuid1` may or may +not return a "safe" UUID. A safe UUID is one which is generated using +synchronization methods that ensure no two processes can obtain the same +UUID. All instances of :class:`UUID` have an :attr:`is_safe` attribute +which relays any information about the UUID's safety, using this enumeration: + +.. class:: SafeUUID + + .. versionadded:: 3.7 + + .. attribute:: SafeUUID.safe + + The UUID was generated by the platform in a multiprocessing-safe way. + + .. attribute:: SafeUUID.unsafe + + The UUID was not generated in a multiprocessing-safe way. + + .. attribute:: SafeUUID.unknown + + The platform does not provide information on whether the UUID was + generated safely or not. + +.. class:: UUID(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None, *, is_safe=SafeUUID.unknown) + + Create a UUID from either a string of 32 hexadecimal digits, a string of 16 + bytes in big-endian order as the *bytes* argument, a string of 16 bytes in + little-endian order as the *bytes_le* argument, a tuple of six integers + (32-bit *time_low*, 16-bit *time_mid*, 16-bit *time_hi_version*, + 8-bit *clock_seq_hi_variant*, 8-bit *clock_seq_low*, 48-bit *node*) as the + *fields* argument, or a single 128-bit integer as the *int* argument. + When a string of hex digits is given, curly braces, hyphens, + and a URN prefix are all optional. For example, these + expressions all yield the same UUID:: + + UUID('{12345678-1234-5678-1234-567812345678}') + UUID('12345678123456781234567812345678') + UUID('urn:uuid:12345678-1234-5678-1234-567812345678') + UUID(bytes=b'\x12\x34\x56\x78'*4) + UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' + + b'\x12\x34\x56\x78\x12\x34\x56\x78') + UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) + UUID(int=0x12345678123456781234567812345678) + + Exactly one of *hex*, *bytes*, *bytes_le*, *fields*, or *int* must be given. + The *version* argument is optional; if given, the resulting UUID will have its + variant and version number set according to :rfc:`4122`, overriding bits in the + given *hex*, *bytes*, *bytes_le*, *fields*, or *int*. + + Comparison of UUID objects are made by way of comparing their + :attr:`UUID.int` attributes. Comparison with a non-UUID object + raises a :exc:`TypeError`. + + ``str(uuid)`` returns a string in the form + ``12345678-1234-5678-1234-567812345678`` where the 32 hexadecimal digits + represent the UUID. + +:class:`UUID` instances have these read-only attributes: + +.. attribute:: UUID.bytes + + The UUID as a 16-byte string (containing the six integer fields in big-endian + byte order). + + +.. attribute:: UUID.bytes_le + + The UUID as a 16-byte string (with *time_low*, *time_mid*, and *time_hi_version* + in little-endian byte order). + + +.. attribute:: UUID.fields + + A tuple of the six integer fields of the UUID, which are also available as six + individual attributes and two derived attributes: + + +------------------------------+-------------------------------+ + | Field | Meaning | + +==============================+===============================+ + | :attr:`time_low` | the first 32 bits of the UUID | + +------------------------------+-------------------------------+ + | :attr:`time_mid` | the next 16 bits of the UUID | + +------------------------------+-------------------------------+ + | :attr:`time_hi_version` | the next 16 bits of the UUID | + +------------------------------+-------------------------------+ + | :attr:`clock_seq_hi_variant` | the next 8 bits of the UUID | + +------------------------------+-------------------------------+ + | :attr:`clock_seq_low` | the next 8 bits of the UUID | + +------------------------------+-------------------------------+ + | :attr:`node` | the last 48 bits of the UUID | + +------------------------------+-------------------------------+ + | :attr:`time` | the 60-bit timestamp | + +------------------------------+-------------------------------+ + | :attr:`clock_seq` | the 14-bit sequence number | + +------------------------------+-------------------------------+ + + +.. attribute:: UUID.hex + + The UUID as a 32-character hexadecimal string. + + +.. attribute:: UUID.int + + The UUID as a 128-bit integer. + + +.. attribute:: UUID.urn + + The UUID as a URN as specified in :rfc:`4122`. + + +.. attribute:: UUID.variant + + The UUID variant, which determines the internal layout of the UUID. This will be + one of the constants :const:`RESERVED_NCS`, :const:`RFC_4122`, + :const:`RESERVED_MICROSOFT`, or :const:`RESERVED_FUTURE`. + + +.. attribute:: UUID.version + + The UUID version number (1 through 5, meaningful only when the variant is + :const:`RFC_4122`). + +.. attribute:: UUID.is_safe + + An enumeration of :class:`SafeUUID` which indicates whether the platform + generated the UUID in a multiprocessing-safe way. + + .. versionadded:: 3.7 + +The :mod:`uuid` module defines the following functions: + + +.. function:: getnode() + + Get the hardware address as a 48-bit positive integer. The first time this + runs, it may launch a separate program, which could be quite slow. If all + attempts to obtain the hardware address fail, we choose a random 48-bit + number with the multicast bit (least significant bit of the first octet) + set to 1 as recommended in :rfc:`4122`. "Hardware address" means the MAC + address of a network interface. On a machine with multiple network + interfaces, universally administered MAC addresses (i.e. where the second + least significant bit of the first octet is *unset*) will be preferred over + locally administered MAC addresses, but with no other ordering guarantees. + + .. versionchanged:: 3.7 + Universally administered MAC addresses are preferred over locally + administered MAC addresses, since the former are guaranteed to be + globally unique, while the latter are not. + +.. index:: single: getnode + + +.. function:: uuid1(node=None, clock_seq=None) + + Generate a UUID from a host ID, sequence number, and the current time. If *node* + is not given, :func:`getnode` is used to obtain the hardware address. If + *clock_seq* is given, it is used as the sequence number; otherwise a random + 14-bit sequence number is chosen. + +.. index:: single: uuid1 + + +.. function:: uuid3(namespace, name) + + Generate a UUID based on the MD5 hash of a namespace identifier (which is a + UUID) and a name (which is a string). + +.. index:: single: uuid3 + + +.. function:: uuid4() + + Generate a random UUID. + +.. index:: single: uuid4 + + +.. function:: uuid5(namespace, name) + + Generate a UUID based on the SHA-1 hash of a namespace identifier (which is a + UUID) and a name (which is a string). + +.. index:: single: uuid5 + +The :mod:`uuid` module defines the following namespace identifiers for use with +:func:`uuid3` or :func:`uuid5`. + + +.. data:: NAMESPACE_DNS + + When this namespace is specified, the *name* string is a fully-qualified domain + name. + + +.. data:: NAMESPACE_URL + + When this namespace is specified, the *name* string is a URL. + + +.. data:: NAMESPACE_OID + + When this namespace is specified, the *name* string is an ISO OID. + + +.. data:: NAMESPACE_X500 + + When this namespace is specified, the *name* string is an X.500 DN in DER or a + text output format. + +The :mod:`uuid` module defines the following constants for the possible values +of the :attr:`variant` attribute: + + +.. data:: RESERVED_NCS + + Reserved for NCS compatibility. + + +.. data:: RFC_4122 + + Specifies the UUID layout given in :rfc:`4122`. + + +.. data:: RESERVED_MICROSOFT + + Reserved for Microsoft compatibility. + + +.. data:: RESERVED_FUTURE + + Reserved for future definition. + + +.. seealso:: + + :rfc:`4122` - A Universally Unique IDentifier (UUID) URN Namespace + This specification defines a Uniform Resource Name namespace for UUIDs, the + internal format of UUIDs, and methods of generating UUIDs. + + +.. _uuid-example: + +Example +------- + +Here are some examples of typical usage of the :mod:`uuid` module:: + + >>> import uuid + + >>> # make a UUID based on the host ID and current time + >>> uuid.uuid1() + UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') + + >>> # make a UUID using an MD5 hash of a namespace UUID and a name + >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') + UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') + + >>> # make a random UUID + >>> uuid.uuid4() + UUID('16fd2706-8baf-433b-82eb-8c7fada847da') + + >>> # make a UUID using a SHA-1 hash of a namespace UUID and a name + >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') + UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d') + + >>> # make a UUID from a string of hex digits (braces and hyphens ignored) + >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}') + + >>> # convert a UUID to a string of hex digits in standard form + >>> str(x) + '00010203-0405-0607-0809-0a0b0c0d0e0f' + + >>> # get the raw 16 bytes of the UUID + >>> x.bytes + b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' + + >>> # make a UUID from a 16-byte string + >>> uuid.UUID(bytes=x.bytes) + UUID('00010203-0405-0607-0809-0a0b0c0d0e0f') + diff --git a/cpython_2/environment/repo/Doc/library/venv.rst b/cpython_2/environment/repo/Doc/library/venv.rst new file mode 100644 index 0000000000000000000000000000000000000000..8abadc4df3cac8c651a457eaff166a852fe956bb --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/venv.rst @@ -0,0 +1,492 @@ +:mod:`venv` --- Creation of virtual environments +================================================ + +.. module:: venv + :synopsis: Creation of virtual environments. + +.. moduleauthor:: Vinay Sajip <vinay_sajip@yahoo.co.uk> +.. sectionauthor:: Vinay Sajip <vinay_sajip@yahoo.co.uk> + +.. versionadded:: 3.3 + +**Source code:** :source:`Lib/venv/` + +.. index:: pair: Environments; virtual + +-------------- + +The :mod:`venv` module provides support for creating lightweight "virtual +environments" with their own site directories, optionally isolated from system +site directories. Each virtual environment has its own Python binary (which +matches the version of the binary that was used to create this environment) and +can have its own independent set of installed Python packages in its site +directories. + +See :pep:`405` for more information about Python virtual environments. + +.. seealso:: + + `Python Packaging User Guide: Creating and using virtual environments + <https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment>`__ + + +Creating virtual environments +----------------------------- + +.. include:: /using/venv-create.inc + + +.. _venv-def: + +.. note:: A virtual environment is a Python environment such that the Python + interpreter, libraries and scripts installed into it are isolated from those + installed in other virtual environments, and (by default) any libraries + installed in a "system" Python, i.e., one which is installed as part of your + operating system. + + A virtual environment is a directory tree which contains Python executable + files and other files which indicate that it is a virtual environment. + + Common installation tools such as setuptools_ and pip_ work as + expected with virtual environments. In other words, when a virtual + environment is active, they install Python packages into the virtual + environment without needing to be told to do so explicitly. + + When a virtual environment is active (i.e., the virtual environment's Python + interpreter is running), the attributes :attr:`sys.prefix` and + :attr:`sys.exec_prefix` point to the base directory of the virtual + environment, whereas :attr:`sys.base_prefix` and + :attr:`sys.base_exec_prefix` point to the non-virtual environment Python + installation which was used to create the virtual environment. If a virtual + environment is not active, then :attr:`sys.prefix` is the same as + :attr:`sys.base_prefix` and :attr:`sys.exec_prefix` is the same as + :attr:`sys.base_exec_prefix` (they all point to a non-virtual environment + Python installation). + + When a virtual environment is active, any options that change the + installation path will be ignored from all :mod:`distutils` configuration + files to prevent projects being inadvertently installed outside of the + virtual environment. + + When working in a command shell, users can make a virtual environment active + by running an ``activate`` script in the virtual environment's executables + directory (the precise filename and command to use the file is + shell-dependent), which prepends the virtual environment's directory for + executables to the ``PATH`` environment variable for the running shell. There + should be no need in other circumstances to activate a virtual + environment; scripts installed into virtual environments have a "shebang" + line which points to the virtual environment's Python interpreter. This means + that the script will run with that interpreter regardless of the value of + ``PATH``. On Windows, "shebang" line processing is supported if you have the + Python Launcher for Windows installed (this was added to Python in 3.3 - see + :pep:`397` for more details). Thus, double-clicking an installed script in a + Windows Explorer window should run the script with the correct interpreter + without there needing to be any reference to its virtual environment in + ``PATH``. + + +.. _venv-api: + +API +--- + +.. highlight:: python + +The high-level method described above makes use of a simple API which provides +mechanisms for third-party virtual environment creators to customize environment +creation according to their needs, the :class:`EnvBuilder` class. + +.. class:: EnvBuilder(system_site_packages=False, clear=False, \ + symlinks=False, upgrade=False, with_pip=False, \ + prompt=None, upgrade_deps=False) + + The :class:`EnvBuilder` class accepts the following keyword arguments on + instantiation: + + * ``system_site_packages`` -- a Boolean value indicating that the system Python + site-packages should be available to the environment (defaults to ``False``). + + * ``clear`` -- a Boolean value which, if true, will delete the contents of + any existing target directory, before creating the environment. + + * ``symlinks`` -- a Boolean value indicating whether to attempt to symlink the + Python binary rather than copying. + + * ``upgrade`` -- a Boolean value which, if true, will upgrade an existing + environment with the running Python - for use when that Python has been + upgraded in-place (defaults to ``False``). + + * ``with_pip`` -- a Boolean value which, if true, ensures pip is + installed in the virtual environment. This uses :mod:`ensurepip` with + the ``--default-pip`` option. + + * ``prompt`` -- a String to be used after virtual environment is activated + (defaults to ``None`` which means directory name of the environment would + be used). If the special string ``"."`` is provided, the basename of the + current directory is used as the prompt. + + * ``upgrade_deps`` -- Update the base venv modules to the latest on PyPI + + .. versionchanged:: 3.4 + Added the ``with_pip`` parameter + + .. versionadded:: 3.6 + Added the ``prompt`` parameter + + .. versionadded:: 3.9 + Added the ``upgrade_deps`` parameter + + Creators of third-party virtual environment tools will be free to use the + provided :class:`EnvBuilder` class as a base class. + + The returned env-builder is an object which has a method, ``create``: + + .. method:: create(env_dir) + + Create a virtual environment by specifying the target directory + (absolute or relative to the current directory) which is to contain the + virtual environment. The ``create`` method will either create the + environment in the specified directory, or raise an appropriate + exception. + + The ``create`` method of the :class:`EnvBuilder` class illustrates the + hooks available for subclass customization:: + + def create(self, env_dir): + """ + Create a virtualized Python environment in a directory. + env_dir is the target directory to create an environment in. + """ + env_dir = os.path.abspath(env_dir) + context = self.ensure_directories(env_dir) + self.create_configuration(context) + self.setup_python(context) + self.setup_scripts(context) + self.post_setup(context) + + Each of the methods :meth:`ensure_directories`, + :meth:`create_configuration`, :meth:`setup_python`, + :meth:`setup_scripts` and :meth:`post_setup` can be overridden. + + .. method:: ensure_directories(env_dir) + + Creates the environment directory and all necessary directories, and + returns a context object. This is just a holder for attributes (such as + paths), for use by the other methods. The directories are allowed to + exist already, as long as either ``clear`` or ``upgrade`` were + specified to allow operating on an existing environment directory. + + .. method:: create_configuration(context) + + Creates the ``pyvenv.cfg`` configuration file in the environment. + + .. method:: setup_python(context) + + Creates a copy or symlink to the Python executable in the environment. + On POSIX systems, if a specific executable ``python3.x`` was used, + symlinks to ``python`` and ``python3`` will be created pointing to that + executable, unless files with those names already exist. + + .. method:: setup_scripts(context) + + Installs activation scripts appropriate to the platform into the virtual + environment. + + .. method:: upgrade_dependencies(context) + + Upgrades the core venv dependency packages (currently ``pip`` and + ``setuptools``) in the environment. This is done by shelling out to the + ``pip`` executable in the environment. + + .. versionadded:: 3.9 + + .. method:: post_setup(context) + + A placeholder method which can be overridden in third party + implementations to pre-install packages in the virtual environment or + perform other post-creation steps. + + .. versionchanged:: 3.7.2 + Windows now uses redirector scripts for ``python[w].exe`` instead of + copying the actual binaries. In 3.7.2 only :meth:`setup_python` does + nothing unless running from a build in the source tree. + + .. versionchanged:: 3.7.3 + Windows copies the redirector scripts as part of :meth:`setup_python` + instead of :meth:`setup_scripts`. This was not the case in 3.7.2. + When using symlinks, the original executables will be linked. + + In addition, :class:`EnvBuilder` provides this utility method that can be + called from :meth:`setup_scripts` or :meth:`post_setup` in subclasses to + assist in installing custom scripts into the virtual environment. + + .. method:: install_scripts(context, path) + + *path* is the path to a directory that should contain subdirectories + "common", "posix", "nt", each containing scripts destined for the bin + directory in the environment. The contents of "common" and the + directory corresponding to :data:`os.name` are copied after some text + replacement of placeholders: + + * ``__VENV_DIR__`` is replaced with the absolute path of the environment + directory. + + * ``__VENV_NAME__`` is replaced with the environment name (final path + segment of environment directory). + + * ``__VENV_PROMPT__`` is replaced with the prompt (the environment + name surrounded by parentheses and with a following space) + + * ``__VENV_BIN_NAME__`` is replaced with the name of the bin directory + (either ``bin`` or ``Scripts``). + + * ``__VENV_PYTHON__`` is replaced with the absolute path of the + environment's executable. + + The directories are allowed to exist (for when an existing environment + is being upgraded). + +There is also a module-level convenience function: + +.. function:: create(env_dir, system_site_packages=False, clear=False, \ + symlinks=False, with_pip=False, prompt=None) + + Create an :class:`EnvBuilder` with the given keyword arguments, and call its + :meth:`~EnvBuilder.create` method with the *env_dir* argument. + + .. versionadded:: 3.3 + + .. versionchanged:: 3.4 + Added the ``with_pip`` parameter + + .. versionchanged:: 3.6 + Added the ``prompt`` parameter + +An example of extending ``EnvBuilder`` +-------------------------------------- + +The following script shows how to extend :class:`EnvBuilder` by implementing a +subclass which installs setuptools and pip into a created virtual environment:: + + import os + import os.path + from subprocess import Popen, PIPE + import sys + from threading import Thread + from urllib.parse import urlparse + from urllib.request import urlretrieve + import venv + + class ExtendedEnvBuilder(venv.EnvBuilder): + """ + This builder installs setuptools and pip so that you can pip or + easy_install other packages into the created virtual environment. + + :param nodist: If true, setuptools and pip are not installed into the + created virtual environment. + :param nopip: If true, pip is not installed into the created + virtual environment. + :param progress: If setuptools or pip are installed, the progress of the + installation can be monitored by passing a progress + callable. If specified, it is called with two + arguments: a string indicating some progress, and a + context indicating where the string is coming from. + The context argument can have one of three values: + 'main', indicating that it is called from virtualize() + itself, and 'stdout' and 'stderr', which are obtained + by reading lines from the output streams of a subprocess + which is used to install the app. + + If a callable is not specified, default progress + information is output to sys.stderr. + """ + + def __init__(self, *args, **kwargs): + self.nodist = kwargs.pop('nodist', False) + self.nopip = kwargs.pop('nopip', False) + self.progress = kwargs.pop('progress', None) + self.verbose = kwargs.pop('verbose', False) + super().__init__(*args, **kwargs) + + def post_setup(self, context): + """ + Set up any packages which need to be pre-installed into the + virtual environment being created. + + :param context: The information for the virtual environment + creation request being processed. + """ + os.environ['VIRTUAL_ENV'] = context.env_dir + if not self.nodist: + self.install_setuptools(context) + # Can't install pip without setuptools + if not self.nopip and not self.nodist: + self.install_pip(context) + + def reader(self, stream, context): + """ + Read lines from a subprocess' output stream and either pass to a progress + callable (if specified) or write progress information to sys.stderr. + """ + progress = self.progress + while True: + s = stream.readline() + if not s: + break + if progress is not None: + progress(s, context) + else: + if not self.verbose: + sys.stderr.write('.') + else: + sys.stderr.write(s.decode('utf-8')) + sys.stderr.flush() + stream.close() + + def install_script(self, context, name, url): + _, _, path, _, _, _ = urlparse(url) + fn = os.path.split(path)[-1] + binpath = context.bin_path + distpath = os.path.join(binpath, fn) + # Download script into the virtual environment's binaries folder + urlretrieve(url, distpath) + progress = self.progress + if self.verbose: + term = '\n' + else: + term = '' + if progress is not None: + progress('Installing %s ...%s' % (name, term), 'main') + else: + sys.stderr.write('Installing %s ...%s' % (name, term)) + sys.stderr.flush() + # Install in the virtual environment + args = [context.env_exe, fn] + p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath) + t1 = Thread(target=self.reader, args=(p.stdout, 'stdout')) + t1.start() + t2 = Thread(target=self.reader, args=(p.stderr, 'stderr')) + t2.start() + p.wait() + t1.join() + t2.join() + if progress is not None: + progress('done.', 'main') + else: + sys.stderr.write('done.\n') + # Clean up - no longer needed + os.unlink(distpath) + + def install_setuptools(self, context): + """ + Install setuptools in the virtual environment. + + :param context: The information for the virtual environment + creation request being processed. + """ + url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py' + self.install_script(context, 'setuptools', url) + # clear up the setuptools archive which gets downloaded + pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz') + files = filter(pred, os.listdir(context.bin_path)) + for f in files: + f = os.path.join(context.bin_path, f) + os.unlink(f) + + def install_pip(self, context): + """ + Install pip in the virtual environment. + + :param context: The information for the virtual environment + creation request being processed. + """ + url = 'https://raw.github.com/pypa/pip/master/contrib/get-pip.py' + self.install_script(context, 'pip', url) + + def main(args=None): + compatible = True + if sys.version_info < (3, 3): + compatible = False + elif not hasattr(sys, 'base_prefix'): + compatible = False + if not compatible: + raise ValueError('This script is only for use with ' + 'Python 3.3 or later') + else: + import argparse + + parser = argparse.ArgumentParser(prog=__name__, + description='Creates virtual Python ' + 'environments in one or ' + 'more target ' + 'directories.') + parser.add_argument('dirs', metavar='ENV_DIR', nargs='+', + help='A directory in which to create the + 'virtual environment.') + parser.add_argument('--no-setuptools', default=False, + action='store_true', dest='nodist', + help="Don't install setuptools or pip in the " + "virtual environment.") + parser.add_argument('--no-pip', default=False, + action='store_true', dest='nopip', + help="Don't install pip in the virtual " + "environment.") + parser.add_argument('--system-site-packages', default=False, + action='store_true', dest='system_site', + help='Give the virtual environment access to the ' + 'system site-packages dir.') + if os.name == 'nt': + use_symlinks = False + else: + use_symlinks = True + parser.add_argument('--symlinks', default=use_symlinks, + action='store_true', dest='symlinks', + help='Try to use symlinks rather than copies, ' + 'when symlinks are not the default for ' + 'the platform.') + parser.add_argument('--clear', default=False, action='store_true', + dest='clear', help='Delete the contents of the ' + 'virtual environment ' + 'directory if it already ' + 'exists, before virtual ' + 'environment creation.') + parser.add_argument('--upgrade', default=False, action='store_true', + dest='upgrade', help='Upgrade the virtual ' + 'environment directory to ' + 'use this version of ' + 'Python, assuming Python ' + 'has been upgraded ' + 'in-place.') + parser.add_argument('--verbose', default=False, action='store_true', + dest='verbose', help='Display the output ' + 'from the scripts which ' + 'install setuptools and pip.') + options = parser.parse_args(args) + if options.upgrade and options.clear: + raise ValueError('you cannot supply --upgrade and --clear together.') + builder = ExtendedEnvBuilder(system_site_packages=options.system_site, + clear=options.clear, + symlinks=options.symlinks, + upgrade=options.upgrade, + nodist=options.nodist, + nopip=options.nopip, + verbose=options.verbose) + for d in options.dirs: + builder.create(d) + + if __name__ == '__main__': + rc = 1 + try: + main() + rc = 0 + except Exception as e: + print('Error: %s' % e, file=sys.stderr) + sys.exit(rc) + + +This script is also available for download `online +<https://gist.github.com/vsajip/4673395>`_. + + +.. _setuptools: https://pypi.org/project/setuptools/ +.. _pip: https://pypi.org/project/pip/ diff --git a/cpython_2/environment/repo/Doc/library/warnings.rst b/cpython_2/environment/repo/Doc/library/warnings.rst new file mode 100644 index 0000000000000000000000000000000000000000..a481a3509d4ec83770ea3cfe8679f6859a6d8d8e --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/warnings.rst @@ -0,0 +1,516 @@ +:mod:`warnings` --- Warning control +=================================== + +.. module:: warnings + :synopsis: Issue warning messages and control their disposition. + +**Source code:** :source:`Lib/warnings.py` + +.. index:: single: warnings + +-------------- + +Warning messages are typically issued in situations where it is useful to alert +the user of some condition in a program, where that condition (normally) doesn't +warrant raising an exception and terminating the program. For example, one +might want to issue a warning when a program uses an obsolete module. + +Python programmers issue warnings by calling the :func:`warn` function defined +in this module. (C programmers use :c:func:`PyErr_WarnEx`; see +:ref:`exceptionhandling` for details). + +Warning messages are normally written to :data:`sys.stderr`, but their disposition +can be changed flexibly, from ignoring all warnings to turning them into +exceptions. The disposition of warnings can vary based on the :ref:`warning category +<warning-categories>`, the text of the warning message, and the source location where it +is issued. Repetitions of a particular warning for the same source location are +typically suppressed. + +There are two stages in warning control: first, each time a warning is issued, a +determination is made whether a message should be issued or not; next, if a +message is to be issued, it is formatted and printed using a user-settable hook. + +The determination whether to issue a warning message is controlled by the +:ref:`warning filter <warning-filter>`, which is a sequence of matching rules and actions. Rules can be +added to the filter by calling :func:`filterwarnings` and reset to its default +state by calling :func:`resetwarnings`. + +The printing of warning messages is done by calling :func:`showwarning`, which +may be overridden; the default implementation of this function formats the +message by calling :func:`formatwarning`, which is also available for use by +custom implementations. + +.. seealso:: + :func:`logging.captureWarnings` allows you to handle all warnings with + the standard logging infrastructure. + + +.. _warning-categories: + +Warning Categories +------------------ + +There are a number of built-in exceptions that represent warning categories. +This categorization is useful to be able to filter out groups of warnings. + +While these are technically +:ref:`built-in exceptions <warning-categories-as-exceptions>`, they are +documented here, because conceptually they belong to the warnings mechanism. + +User code can define additional warning categories by subclassing one of the +standard warning categories. A warning category must always be a subclass of +the :exc:`Warning` class. + +The following warnings category classes are currently defined: + +.. tabularcolumns:: |l|p{0.6\linewidth}| + ++----------------------------------+-----------------------------------------------+ +| Class | Description | ++==================================+===============================================+ +| :exc:`Warning` | This is the base class of all warning | +| | category classes. It is a subclass of | +| | :exc:`Exception`. | ++----------------------------------+-----------------------------------------------+ +| :exc:`UserWarning` | The default category for :func:`warn`. | ++----------------------------------+-----------------------------------------------+ +| :exc:`DeprecationWarning` | Base category for warnings about deprecated | +| | features when those warnings are intended for | +| | other Python developers (ignored by default, | +| | unless triggered by code in ``__main__``). | ++----------------------------------+-----------------------------------------------+ +| :exc:`SyntaxWarning` | Base category for warnings about dubious | +| | syntactic features. | ++----------------------------------+-----------------------------------------------+ +| :exc:`RuntimeWarning` | Base category for warnings about dubious | +| | runtime features. | ++----------------------------------+-----------------------------------------------+ +| :exc:`FutureWarning` | Base category for warnings about deprecated | +| | features when those warnings are intended for | +| | end users of applications that are written in | +| | Python. | ++----------------------------------+-----------------------------------------------+ +| :exc:`PendingDeprecationWarning` | Base category for warnings about features | +| | that will be deprecated in the future | +| | (ignored by default). | ++----------------------------------+-----------------------------------------------+ +| :exc:`ImportWarning` | Base category for warnings triggered during | +| | the process of importing a module (ignored by | +| | default). | ++----------------------------------+-----------------------------------------------+ +| :exc:`UnicodeWarning` | Base category for warnings related to | +| | Unicode. | ++----------------------------------+-----------------------------------------------+ +| :exc:`BytesWarning` | Base category for warnings related to | +| | :class:`bytes` and :class:`bytearray`. | ++----------------------------------+-----------------------------------------------+ +| :exc:`ResourceWarning` | Base category for warnings related to | +| | resource usage. | ++----------------------------------+-----------------------------------------------+ + +.. versionchanged:: 3.7 + Previously :exc:`DeprecationWarning` and :exc:`FutureWarning` were + distinguished based on whether a feature was being removed entirely or + changing its behaviour. They are now distinguished based on their + intended audience and the way they're handled by the default warnings + filters. + + +.. _warning-filter: + +The Warnings Filter +------------------- + +The warnings filter controls whether warnings are ignored, displayed, or turned +into errors (raising an exception). + +Conceptually, the warnings filter maintains an ordered list of filter +specifications; any specific warning is matched against each filter +specification in the list in turn until a match is found; the filter determines +the disposition of the match. Each entry is a tuple of the form (*action*, +*message*, *category*, *module*, *lineno*), where: + +* *action* is one of the following strings: + + +---------------+----------------------------------------------+ + | Value | Disposition | + +===============+==============================================+ + | ``"default"`` | print the first occurrence of matching | + | | warnings for each location (module + | + | | line number) where the warning is issued | + +---------------+----------------------------------------------+ + | ``"error"`` | turn matching warnings into exceptions | + +---------------+----------------------------------------------+ + | ``"ignore"`` | never print matching warnings | + +---------------+----------------------------------------------+ + | ``"always"`` | always print matching warnings | + +---------------+----------------------------------------------+ + | ``"module"`` | print the first occurrence of matching | + | | warnings for each module where the warning | + | | is issued (regardless of line number) | + +---------------+----------------------------------------------+ + | ``"once"`` | print only the first occurrence of matching | + | | warnings, regardless of location | + +---------------+----------------------------------------------+ + +* *message* is a string containing a regular expression that the start of + the warning message must match. The expression is compiled to always be + case-insensitive. + +* *category* is a class (a subclass of :exc:`Warning`) of which the warning + category must be a subclass in order to match. + +* *module* is a string containing a regular expression that the module name must + match. The expression is compiled to be case-sensitive. + +* *lineno* is an integer that the line number where the warning occurred must + match, or ``0`` to match all line numbers. + +Since the :exc:`Warning` class is derived from the built-in :exc:`Exception` +class, to turn a warning into an error we simply raise ``category(message)``. + +If a warning is reported and doesn't match any registered filter then the +"default" action is applied (hence its name). + + +.. _describing-warning-filters: + +Describing Warning Filters +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The warnings filter is initialized by :option:`-W` options passed to the Python +interpreter command line and the :envvar:`PYTHONWARNINGS` environment variable. +The interpreter saves the arguments for all supplied entries without +interpretation in :data:`sys.warnoptions`; the :mod:`warnings` module parses these +when it is first imported (invalid options are ignored, after printing a +message to :data:`sys.stderr`). + +Individual warnings filters are specified as a sequence of fields separated by +colons:: + + action:message:category:module:line + +The meaning of each of these fields is as described in :ref:`warning-filter`. +When listing multiple filters on a single line (as for +:envvar:`PYTHONWARNINGS`), the individual filters are separated by commas and +the filters listed later take precedence over those listed before them (as +they're applied left-to-right, and the most recently applied filters take +precedence over earlier ones). + +Commonly used warning filters apply to either all warnings, warnings in a +particular category, or warnings raised by particular modules or packages. +Some examples:: + + default # Show all warnings (even those ignored by default) + ignore # Ignore all warnings + error # Convert all warnings to errors + error::ResourceWarning # Treat ResourceWarning messages as errors + default::DeprecationWarning # Show DeprecationWarning messages + ignore,default:::mymodule # Only report warnings triggered by "mymodule" + error:::mymodule[.*] # Convert warnings to errors in "mymodule" + # and any subpackages of "mymodule" + + +.. _default-warning-filter: + +Default Warning Filter +~~~~~~~~~~~~~~~~~~~~~~ + +By default, Python installs several warning filters, which can be overridden by +the :option:`-W` command-line option, the :envvar:`PYTHONWARNINGS` environment +variable and calls to :func:`filterwarnings`. + +In regular release builds, the default warning filter has the following entries +(in order of precedence):: + + default::DeprecationWarning:__main__ + ignore::DeprecationWarning + ignore::PendingDeprecationWarning + ignore::ImportWarning + ignore::ResourceWarning + +In debug builds, the list of default warning filters is empty. + +.. versionchanged:: 3.2 + :exc:`DeprecationWarning` is now ignored by default in addition to + :exc:`PendingDeprecationWarning`. + +.. versionchanged:: 3.7 + :exc:`DeprecationWarning` is once again shown by default when triggered + directly by code in ``__main__``. + +.. versionchanged:: 3.7 + :exc:`BytesWarning` no longer appears in the default filter list and is + instead configured via :data:`sys.warnoptions` when :option:`-b` is specified + twice. + + +.. _warning-disable: + +Overriding the default filter +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Developers of applications written in Python may wish to hide *all* Python level +warnings from their users by default, and only display them when running tests +or otherwise working on the application. The :data:`sys.warnoptions` attribute +used to pass filter configurations to the interpreter can be used as a marker to +indicate whether or not warnings should be disabled:: + + import sys + + if not sys.warnoptions: + import warnings + warnings.simplefilter("ignore") + +Developers of test runners for Python code are advised to instead ensure that +*all* warnings are displayed by default for the code under test, using code +like:: + + import sys + + if not sys.warnoptions: + import os, warnings + warnings.simplefilter("default") # Change the filter in this process + os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses + +Finally, developers of interactive shells that run user code in a namespace +other than ``__main__`` are advised to ensure that :exc:`DeprecationWarning` +messages are made visible by default, using code like the following (where +``user_ns`` is the module used to execute code entered interactively):: + + import warnings + warnings.filterwarnings("default", category=DeprecationWarning, + module=user_ns.get("__name__")) + + +.. _warning-suppress: + +Temporarily Suppressing Warnings +-------------------------------- + +If you are using code that you know will raise a warning, such as a deprecated +function, but do not want to see the warning (even when warnings have been +explicitly configured via the command line), then it is possible to suppress +the warning using the :class:`catch_warnings` context manager:: + + import warnings + + def fxn(): + warnings.warn("deprecated", DeprecationWarning) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + fxn() + +While within the context manager all warnings will simply be ignored. This +allows you to use known-deprecated code without having to see the warning while +not suppressing the warning for other code that might not be aware of its use +of deprecated code. Note: this can only be guaranteed in a single-threaded +application. If two or more threads use the :class:`catch_warnings` context +manager at the same time, the behavior is undefined. + + + +.. _warning-testing: + +Testing Warnings +---------------- + +To test warnings raised by code, use the :class:`catch_warnings` context +manager. With it you can temporarily mutate the warnings filter to facilitate +your testing. For instance, do the following to capture all raised warnings to +check:: + + import warnings + + def fxn(): + warnings.warn("deprecated", DeprecationWarning) + + with warnings.catch_warnings(record=True) as w: + # Cause all warnings to always be triggered. + warnings.simplefilter("always") + # Trigger a warning. + fxn() + # Verify some things + assert len(w) == 1 + assert issubclass(w[-1].category, DeprecationWarning) + assert "deprecated" in str(w[-1].message) + +One can also cause all warnings to be exceptions by using ``error`` instead of +``always``. One thing to be aware of is that if a warning has already been +raised because of a ``once``/``default`` rule, then no matter what filters are +set the warning will not be seen again unless the warnings registry related to +the warning has been cleared. + +Once the context manager exits, the warnings filter is restored to its state +when the context was entered. This prevents tests from changing the warnings +filter in unexpected ways between tests and leading to indeterminate test +results. The :func:`showwarning` function in the module is also restored to +its original value. Note: this can only be guaranteed in a single-threaded +application. If two or more threads use the :class:`catch_warnings` context +manager at the same time, the behavior is undefined. + +When testing multiple operations that raise the same kind of warning, it +is important to test them in a manner that confirms each operation is raising +a new warning (e.g. set warnings to be raised as exceptions and check the +operations raise exceptions, check that the length of the warning list +continues to increase after each operation, or else delete the previous +entries from the warnings list before each new operation). + + +.. _warning-ignored: + +Updating Code For New Versions of Dependencies +---------------------------------------------- + +Warning categories that are primarily of interest to Python developers (rather +than end users of applications written in Python) are ignored by default. + +Notably, this "ignored by default" list includes :exc:`DeprecationWarning` +(for every module except ``__main__``), which means developers should make sure +to test their code with typically ignored warnings made visible in order to +receive timely notifications of future breaking API changes (whether in the +standard library or third party packages). + +In the ideal case, the code will have a suitable test suite, and the test runner +will take care of implicitly enabling all warnings when running tests +(the test runner provided by the :mod:`unittest` module does this). + +In less ideal cases, applications can be checked for use of deprecated +interfaces by passing :option:`-Wd <-W>` to the Python interpreter (this is +shorthand for :option:`!-W default`) or setting ``PYTHONWARNINGS=default`` in +the environment. This enables default handling for all warnings, including those +that are ignored by default. To change what action is taken for encountered +warnings you can change what argument is passed to :option:`-W` (e.g. +:option:`!-W error`). See the :option:`-W` flag for more details on what is +possible. + + +.. _warning-functions: + +Available Functions +------------------- + + +.. function:: warn(message, category=None, stacklevel=1, source=None) + + Issue a warning, or maybe ignore it or raise an exception. The *category* + argument, if given, must be a :ref:`warning category class <warning-categories>`; it + defaults to :exc:`UserWarning`. Alternatively, *message* can be a :exc:`Warning` instance, + in which case *category* will be ignored and ``message.__class__`` will be used. + In this case, the message text will be ``str(message)``. This function raises an + exception if the particular warning issued is changed into an error by the + :ref:`warnings filter <warning-filter>`. The *stacklevel* argument can be used by wrapper + functions written in Python, like this:: + + def deprecation(message): + warnings.warn(message, DeprecationWarning, stacklevel=2) + + This makes the warning refer to :func:`deprecation`'s caller, rather than to the + source of :func:`deprecation` itself (since the latter would defeat the purpose + of the warning message). + + *source*, if supplied, is the destroyed object which emitted a + :exc:`ResourceWarning`. + + .. versionchanged:: 3.6 + Added *source* parameter. + + +.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None) + + This is a low-level interface to the functionality of :func:`warn`, passing in + explicitly the message, category, filename and line number, and optionally the + module name and the registry (which should be the ``__warningregistry__`` + dictionary of the module). The module name defaults to the filename with + ``.py`` stripped; if no registry is passed, the warning is never suppressed. + *message* must be a string and *category* a subclass of :exc:`Warning` or + *message* may be a :exc:`Warning` instance, in which case *category* will be + ignored. + + *module_globals*, if supplied, should be the global namespace in use by the code + for which the warning is issued. (This argument is used to support displaying + source for modules found in zipfiles or other non-filesystem import + sources). + + *source*, if supplied, is the destroyed object which emitted a + :exc:`ResourceWarning`. + + .. versionchanged:: 3.6 + Add the *source* parameter. + + +.. function:: showwarning(message, category, filename, lineno, file=None, line=None) + + Write a warning to a file. The default implementation calls + ``formatwarning(message, category, filename, lineno, line)`` and writes the + resulting string to *file*, which defaults to :data:`sys.stderr`. You may replace + this function with any callable 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 + try to read the line specified by *filename* and *lineno*. + + +.. function:: formatwarning(message, category, filename, lineno, line=None) + + Format a warning the standard way. This returns a string which may contain + embedded newlines and ends in a newline. *line* is a line of source code to + be included in the warning message; if *line* is not supplied, + :func:`formatwarning` will try to read the line specified by *filename* and + *lineno*. + + +.. function:: filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False) + + Insert an entry into the list of :ref:`warnings filter specifications + <warning-filter>`. The entry is inserted at the front by default; if + *append* is true, it is inserted at the end. This checks the types of the + arguments, compiles the *message* and *module* regular expressions, and + inserts them as a tuple in the list of warnings filters. Entries closer to + the front of the list override entries later in the list, if both match a + particular warning. Omitted arguments default to a value that matches + everything. + + +.. function:: simplefilter(action, category=Warning, lineno=0, append=False) + + Insert a simple entry into the list of :ref:`warnings filter specifications + <warning-filter>`. The meaning of the function parameters is as for + :func:`filterwarnings`, but regular expressions are not needed as the filter + inserted always matches any message in any module as long as the category and + line number match. + + +.. function:: resetwarnings() + + Reset the warnings filter. This discards the effect of all previous calls to + :func:`filterwarnings`, including that of the :option:`-W` command line options + and calls to :func:`simplefilter`. + + +Available Context Managers +-------------------------- + +.. class:: catch_warnings(\*, record=False, module=None) + + A context manager that copies and, upon exit, restores the warnings filter + and the :func:`showwarning` function. + If the *record* argument is :const:`False` (the default) the context manager + returns :class:`None` on entry. If *record* is :const:`True`, a list is + returned that is progressively populated with objects as seen by a custom + :func:`showwarning` function (which also suppresses output to ``sys.stdout``). + Each object in the list has attributes with the same names as the arguments to + :func:`showwarning`. + + The *module* argument takes a module that will be used instead of the + module returned when you import :mod:`warnings` whose filter will be + protected. This argument exists primarily for testing the :mod:`warnings` + module itself. + + .. note:: + + The :class:`catch_warnings` manager works by replacing and + then later restoring the module's + :func:`showwarning` function and internal list of filter + specifications. This means the context manager is modifying + global state and therefore is not thread-safe. diff --git a/cpython_2/environment/repo/Doc/library/wave.rst b/cpython_2/environment/repo/Doc/library/wave.rst new file mode 100644 index 0000000000000000000000000000000000000000..f63e0d3dce19c6383828cf2bedbc587f88f2888b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/wave.rst @@ -0,0 +1,242 @@ +:mod:`wave` --- Read and write WAV files +======================================== + +.. module:: wave + :synopsis: Provide an interface to the WAV sound format. + +.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il> +.. Documentations stolen from comments in file. + +**Source code:** :source:`Lib/wave.py` + +-------------- + +The :mod:`wave` module provides a convenient interface to the WAV sound format. +It does not support compression/decompression, but it does support mono/stereo. + +The :mod:`wave` module defines the following function and exception: + + +.. function:: open(file, mode=None) + + If *file* is a string, open the file by that name, otherwise treat it as a + file-like object. *mode* can be: + + ``'rb'`` + Read only mode. + + ``'wb'`` + Write only mode. + + Note that it does not allow read/write WAV files. + + A *mode* of ``'rb'`` returns a :class:`Wave_read` object, while a *mode* of + ``'wb'`` returns a :class:`Wave_write` object. If *mode* is omitted and a + file-like object is passed as *file*, ``file.mode`` is used as the default + value for *mode*. + + If you pass in a file-like object, the wave object will not close it when its + :meth:`close` method is called; it is the caller's responsibility to close + the file object. + + The :func:`.open` function may be used in a :keyword:`with` statement. When + the :keyword:`!with` block completes, the :meth:`Wave_read.close() + <wave.Wave_read.close>` or :meth:`Wave_write.close() + <wave.Wave_write.close()>` method is called. + + .. versionchanged:: 3.4 + Added support for unseekable files. + +.. exception:: Error + + An error raised when something is impossible because it violates the WAV + specification or hits an implementation deficiency. + + +.. _wave-read-objects: + +Wave_read Objects +----------------- + +Wave_read objects, as returned by :func:`.open`, have the following methods: + + +.. method:: Wave_read.close() + + Close the stream if it was opened by :mod:`wave`, and make the instance + unusable. This is called automatically on object collection. + + +.. method:: Wave_read.getnchannels() + + Returns number of audio channels (``1`` for mono, ``2`` for stereo). + + +.. method:: Wave_read.getsampwidth() + + Returns sample width in bytes. + + +.. method:: Wave_read.getframerate() + + Returns sampling frequency. + + +.. method:: Wave_read.getnframes() + + Returns number of audio frames. + + +.. method:: Wave_read.getcomptype() + + Returns compression type (``'NONE'`` is the only supported type). + + +.. method:: Wave_read.getcompname() + + Human-readable version of :meth:`getcomptype`. Usually ``'not compressed'`` + parallels ``'NONE'``. + + +.. method:: Wave_read.getparams() + + Returns a :func:`~collections.namedtuple` ``(nchannels, sampwidth, + framerate, nframes, comptype, compname)``, equivalent to output of the + :meth:`get\*` methods. + + +.. method:: Wave_read.readframes(n) + + Reads and returns at most *n* frames of audio, as a :class:`bytes` object. + + +.. method:: Wave_read.rewind() + + Rewind the file pointer to the beginning of the audio stream. + +The following two methods are defined for compatibility with the :mod:`aifc` +module, and don't do anything interesting. + + +.. method:: Wave_read.getmarkers() + + Returns ``None``. + + +.. method:: Wave_read.getmark(id) + + Raise an error. + +The following two methods define a term "position" which is compatible between +them, and is otherwise implementation dependent. + + +.. method:: Wave_read.setpos(pos) + + Set the file pointer to the specified position. + + +.. method:: Wave_read.tell() + + Return current file pointer position. + + +.. _wave-write-objects: + +Wave_write Objects +------------------ + +For seekable output streams, the ``wave`` header will automatically be updated +to reflect the number of frames actually written. For unseekable streams, the +*nframes* value must be accurate when the first frame data is written. An +accurate *nframes* value can be achieved either by calling +:meth:`~Wave_write.setnframes` or :meth:`~Wave_write.setparams` with the number +of frames that will be written before :meth:`~Wave_write.close` is called and +then using :meth:`~Wave_write.writeframesraw` to write the frame data, or by +calling :meth:`~Wave_write.writeframes` with all of the frame data to be +written. In the latter case :meth:`~Wave_write.writeframes` will calculate +the number of frames in the data and set *nframes* accordingly before writing +the frame data. + +Wave_write objects, as returned by :func:`.open`, have the following methods: + +.. versionchanged:: 3.4 + Added support for unseekable files. + + +.. method:: Wave_write.close() + + Make sure *nframes* is correct, and close the file if it was opened by + :mod:`wave`. This method is called upon object collection. It will raise + an exception if the output stream is not seekable and *nframes* does not + match the number of frames actually written. + + +.. method:: Wave_write.setnchannels(n) + + Set the number of channels. + + +.. method:: Wave_write.setsampwidth(n) + + Set the sample width to *n* bytes. + + +.. method:: Wave_write.setframerate(n) + + Set the frame rate to *n*. + + .. versionchanged:: 3.2 + A non-integral input to this method is rounded to the nearest + integer. + + +.. method:: Wave_write.setnframes(n) + + Set the number of frames to *n*. This will be changed later if the number + of frames actually written is different (this update attempt will + raise an error if the output stream is not seekable). + + +.. method:: Wave_write.setcomptype(type, name) + + Set the compression type and description. At the moment, only compression type + ``NONE`` is supported, meaning no compression. + + +.. method:: Wave_write.setparams(tuple) + + The *tuple* should be ``(nchannels, sampwidth, framerate, nframes, comptype, + compname)``, with values valid for the :meth:`set\*` methods. Sets all + parameters. + + +.. method:: Wave_write.tell() + + Return current position in the file, with the same disclaimer for the + :meth:`Wave_read.tell` and :meth:`Wave_read.setpos` methods. + + +.. method:: Wave_write.writeframesraw(data) + + Write audio frames, without correcting *nframes*. + + .. versionchanged:: 3.4 + Any :term:`bytes-like object` is now accepted. + + +.. method:: Wave_write.writeframes(data) + + Write audio frames and make sure *nframes* is correct. It will raise an + error if the output stream is not seekable and the total number of frames + that have been written after *data* has been written does not match the + previously set value for *nframes*. + + .. versionchanged:: 3.4 + Any :term:`bytes-like object` is now accepted. + + +Note that it is invalid to set any parameters after calling :meth:`writeframes` +or :meth:`writeframesraw`, and any attempt to do so will raise +:exc:`wave.Error`. + diff --git a/cpython_2/environment/repo/Doc/library/weakref.rst b/cpython_2/environment/repo/Doc/library/weakref.rst new file mode 100644 index 0000000000000000000000000000000000000000..12eb985c3443597e5599c5f43c329e93d2ff4e57 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/weakref.rst @@ -0,0 +1,582 @@ +:mod:`weakref` --- Weak references +================================== + +.. module:: weakref + :synopsis: Support for weak references and weak dictionaries. + +.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org> +.. moduleauthor:: Neil Schemenauer <nas@arctrix.com> +.. moduleauthor:: Martin von Löwis <martin@loewis.home.cs.tu-berlin.de> +.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> + +**Source code:** :source:`Lib/weakref.py` + +-------------- + +The :mod:`weakref` module allows the Python programmer to create :dfn:`weak +references` to objects. + +.. When making changes to the examples in this file, be sure to update + Lib/test/test_weakref.py::libreftest too! + +In the following, the term :dfn:`referent` means the object which is referred to +by a weak reference. + +A weak reference to an object is not enough to keep the object alive: when the +only remaining references to a referent are weak references, +:term:`garbage collection` is free to destroy the referent and reuse its memory +for something else. However, until the object is actually destroyed the weak +reference may return the object even if there are no strong references to it. + +A primary use for weak references is to implement caches or +mappings holding large objects, where it's desired that a large object not be +kept alive solely because it appears in a cache or mapping. + +For example, if you have a number of large binary image objects, you may wish to +associate a name with each. If you used a Python dictionary to map names to +images, or images to names, the image objects would remain alive just because +they appeared as values or keys in the dictionaries. The +:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by +the :mod:`weakref` module are an alternative, using weak references to construct +mappings that don't keep objects alive solely because they appear in the mapping +objects. If, for example, an image object is a value in a +:class:`WeakValueDictionary`, then when the last remaining references to that +image object are the weak references held by weak mappings, garbage collection +can reclaim the object, and its corresponding entries in weak mappings are +simply deleted. + +:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references +in their implementation, setting up callback functions on the weak references +that notify the weak dictionaries when a key or value has been reclaimed by +garbage collection. :class:`WeakSet` implements the :class:`set` interface, +but keeps weak references to its elements, just like a +:class:`WeakKeyDictionary` does. + +:class:`finalize` provides a straight forward way to register a +cleanup function to be called when an object is garbage collected. +This is simpler to use than setting up a callback function on a raw +weak reference, since the module automatically ensures that the finalizer +remains alive until the object is collected. + +Most programs should find that using one of these weak container types +or :class:`finalize` is all they need -- it's not usually necessary to +create your own weak references directly. The low-level machinery is +exposed by the :mod:`weakref` module for the benefit of advanced uses. + +Not all objects can be weakly referenced; those objects which can include class +instances, functions written in Python (but not in C), instance methods, sets, +frozensets, some :term:`file objects <file object>`, :term:`generators <generator>`, +type objects, sockets, arrays, deques, regular expression pattern objects, and code +objects. + +.. versionchanged:: 3.2 + Added support for thread.lock, threading.Lock, and code objects. + +Several built-in types such as :class:`list` and :class:`dict` do not directly +support weak references but can add support through subclassing:: + + class Dict(dict): + pass + + obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable + +.. impl-detail:: + + Other built-in types such as :class:`tuple` and :class:`int` do not support weak + references even when subclassed. + +Extension types can easily be made to support weak references; see +:ref:`weakref-support`. + + +.. class:: ref(object[, callback]) + + Return a weak reference to *object*. The original object can be retrieved by + calling the reference object if the referent is still alive; if the referent is + no longer alive, calling the reference object will cause :const:`None` to be + returned. If *callback* is provided and not :const:`None`, and the returned + weakref object is still alive, the callback will be called when the object is + about to be finalized; the weak reference object will be passed as the only + parameter to the callback; the referent will no longer be available. + + It is allowable for many weak references to be constructed for the same object. + Callbacks registered for each weak reference will be called from the most + recently registered callback to the oldest registered callback. + + Exceptions raised by the callback will be noted on the standard error output, + but cannot be propagated; they are handled in exactly the same way as exceptions + raised from an object's :meth:`__del__` method. + + Weak references are :term:`hashable` if the *object* is hashable. They will + maintain their hash value even after the *object* was deleted. If + :func:`hash` is called the first time only after the *object* was deleted, + the call will raise :exc:`TypeError`. + + Weak references support tests for equality, but not ordering. If the referents + are still alive, two references have the same equality relationship as their + referents (regardless of the *callback*). If either referent has been deleted, + the references are equal only if the reference objects are the same object. + + This is a subclassable type rather than a factory function. + + .. attribute:: __callback__ + + This read-only attribute returns the callback currently associated to the + weakref. If there is no callback or if the referent of the weakref is + no longer alive then this attribute will have value ``None``. + + .. versionchanged:: 3.4 + Added the :attr:`__callback__` attribute. + + +.. function:: proxy(object[, callback]) + + Return a proxy to *object* which uses a weak reference. This supports use of + the proxy in most contexts instead of requiring the explicit dereferencing used + with weak reference objects. The returned object will have a type of either + ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is + callable. Proxy objects are not :term:`hashable` regardless of the referent; this + avoids a number of problems related to their fundamentally mutable nature, and + prevent their use as dictionary keys. *callback* is the same as the parameter + of the same name to the :func:`ref` function. + + .. versionchanged:: 3.8 + Extended the operator support on proxy objects to include the matrix + multiplication operators ``@`` and ``@=``. + + +.. function:: getweakrefcount(object) + + Return the number of weak references and proxies which refer to *object*. + + +.. function:: getweakrefs(object) + + Return a list of all weak reference and proxy objects which refer to *object*. + + +.. class:: WeakKeyDictionary([dict]) + + Mapping class that references keys weakly. Entries in the dictionary will be + discarded when there is no longer a strong reference to the key. This can be + used to associate additional data with an object owned by other parts of an + application without adding attributes to those objects. This can be especially + useful with objects that override attribute accesses. + + .. note:: + + Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python + dictionary, it must not change size when iterating over it. This can be + difficult to ensure for a :class:`WeakKeyDictionary` because actions + performed by the program during iteration may cause items in the + dictionary to vanish "by magic" (as a side effect of garbage collection). + + .. versionchanged:: 3.9 + Added support for ``|`` and ``|=`` operators, specified in :pep:`584`. + +:class:`WeakKeyDictionary` objects have an additional method that +exposes the internal references directly. The references are not guaranteed to +be "live" at the time they are used, so the result of calling the references +needs to be checked before being used. This can be used to avoid creating +references that will cause the garbage collector to keep the keys around longer +than needed. + + +.. method:: WeakKeyDictionary.keyrefs() + + Return an iterable of the weak references to the keys. + + +.. class:: WeakValueDictionary([dict]) + + Mapping class that references values weakly. Entries in the dictionary will be + discarded when no strong reference to the value exists any more. + + .. note:: + + Caution: Because a :class:`WeakValueDictionary` is built on top of a Python + dictionary, it must not change size when iterating over it. This can be + difficult to ensure for a :class:`WeakValueDictionary` because actions performed + by the program during iteration may cause items in the dictionary to vanish "by + magic" (as a side effect of garbage collection). + + .. versionchanged:: 3.9 + Added support for ``|`` and ``|=`` operators, as specified in :pep:`584`. + +:class:`WeakValueDictionary` objects have an additional method that has the +same issues as the :meth:`keyrefs` method of :class:`WeakKeyDictionary` +objects. + + +.. method:: WeakValueDictionary.valuerefs() + + Return an iterable of the weak references to the values. + + +.. class:: WeakSet([elements]) + + Set class that keeps weak references to its elements. An element will be + discarded when no strong reference to it exists any more. + + +.. class:: WeakMethod(method) + + A custom :class:`ref` subclass which simulates a weak reference to a bound + method (i.e., a method defined on a class and looked up on an instance). + Since a bound method is ephemeral, a standard weak reference cannot keep + hold of it. :class:`WeakMethod` has special code to recreate the bound + method until either the object or the original function dies:: + + >>> class C: + ... def method(self): + ... print("method called!") + ... + >>> c = C() + >>> r = weakref.ref(c.method) + >>> r() + >>> r = weakref.WeakMethod(c.method) + >>> r() + <bound method C.method of <__main__.C object at 0x7fc859830220>> + >>> r()() + method called! + >>> del c + >>> gc.collect() + 0 + >>> r() + >>> + + .. versionadded:: 3.4 + +.. class:: finalize(obj, func, /, *args, **kwargs) + + Return a callable finalizer object which will be called when *obj* + is garbage collected. Unlike an ordinary weak reference, a finalizer + will always survive until the reference object is collected, greatly + simplifying lifecycle management. + + A finalizer is considered *alive* until it is called (either explicitly + or at garbage collection), and after that it is *dead*. Calling a live + finalizer returns the result of evaluating ``func(*arg, **kwargs)``, + whereas calling a dead finalizer returns :const:`None`. + + Exceptions raised by finalizer callbacks during garbage collection + will be shown on the standard error output, but cannot be + propagated. They are handled in the same way as exceptions raised + from an object's :meth:`__del__` method or a weak reference's + callback. + + When the program exits, each remaining live finalizer is called + unless its :attr:`atexit` attribute has been set to false. They + are called in reverse order of creation. + + A finalizer will never invoke its callback during the later part of + the :term:`interpreter shutdown` when module globals are liable to have + been replaced by :const:`None`. + + .. method:: __call__() + + If *self* is alive then mark it as dead and return the result of + calling ``func(*args, **kwargs)``. If *self* is dead then return + :const:`None`. + + .. method:: detach() + + If *self* is alive then mark it as dead and return the tuple + ``(obj, func, args, kwargs)``. If *self* is dead then return + :const:`None`. + + .. method:: peek() + + If *self* is alive then return the tuple ``(obj, func, args, + kwargs)``. If *self* is dead then return :const:`None`. + + .. attribute:: alive + + Property which is true if the finalizer is alive, false otherwise. + + .. attribute:: atexit + + A writable boolean property which by default is true. When the + program exits, it calls all remaining live finalizers for which + :attr:`.atexit` is true. They are called in reverse order of + creation. + + .. note:: + + It is important to ensure that *func*, *args* and *kwargs* do + not own any references to *obj*, either directly or indirectly, + since otherwise *obj* will never be garbage collected. In + particular, *func* should not be a bound method of *obj*. + + .. versionadded:: 3.4 + + +.. data:: ReferenceType + + The type object for weak references objects. + + +.. data:: ProxyType + + The type object for proxies of objects which are not callable. + + +.. data:: CallableProxyType + + The type object for proxies of callable objects. + + +.. data:: ProxyTypes + + Sequence containing all the type objects for proxies. This can make it simpler + to test if an object is a proxy without being dependent on naming both proxy + types. + + +.. seealso:: + + :pep:`205` - Weak References + The proposal and rationale for this feature, including links to earlier + implementations and information about similar features in other languages. + + +.. _weakref-objects: + +Weak Reference Objects +---------------------- + +Weak reference objects have no methods and no attributes besides +:attr:`ref.__callback__`. A weak reference object allows the referent to be +obtained, if it still exists, by calling it: + + >>> import weakref + >>> class Object: + ... pass + ... + >>> o = Object() + >>> r = weakref.ref(o) + >>> o2 = r() + >>> o is o2 + True + +If the referent no longer exists, calling the reference object returns +:const:`None`: + + >>> del o, o2 + >>> print(r()) + None + +Testing that a weak reference object is still live should be done using the +expression ``ref() is not None``. Normally, application code that needs to use +a reference object should follow this pattern:: + + # r is a weak reference object + o = r() + if o is None: + # referent has been garbage collected + print("Object has been deallocated; can't frobnicate.") + else: + print("Object is still live!") + o.do_something_useful() + +Using a separate test for "liveness" creates race conditions in threaded +applications; another thread can cause a weak reference to become invalidated +before the weak reference is called; the idiom shown above is safe in threaded +applications as well as single-threaded applications. + +Specialized versions of :class:`ref` objects can be created through subclassing. +This is used in the implementation of the :class:`WeakValueDictionary` to reduce +the memory overhead for each entry in the mapping. This may be most useful to +associate additional information with a reference, but could also be used to +insert additional processing on calls to retrieve the referent. + +This example shows how a subclass of :class:`ref` can be used to store +additional information about an object and affect the value that's returned when +the referent is accessed:: + + import weakref + + class ExtendedRef(weakref.ref): + def __init__(self, ob, callback=None, /, **annotations): + super(ExtendedRef, self).__init__(ob, callback) + self.__counter = 0 + for k, v in annotations.items(): + setattr(self, k, v) + + def __call__(self): + """Return a pair containing the referent and the number of + times the reference has been called. + """ + ob = super(ExtendedRef, self).__call__() + if ob is not None: + self.__counter += 1 + ob = (ob, self.__counter) + return ob + + +.. _weakref-example: + +Example +------- + +This simple example shows how an application can use object IDs to retrieve +objects that it has seen before. The IDs of the objects can then be used in +other data structures without forcing the objects to remain alive, but the +objects can still be retrieved by ID if they do. + +.. Example contributed by Tim Peters. + +:: + + import weakref + + _id2obj_dict = weakref.WeakValueDictionary() + + def remember(obj): + oid = id(obj) + _id2obj_dict[oid] = obj + return oid + + def id2obj(oid): + return _id2obj_dict[oid] + + +.. _finalize-examples: + +Finalizer Objects +----------------- + +The main benefit of using :class:`finalize` is that it makes it simple +to register a callback without needing to preserve the returned finalizer +object. For instance + + >>> import weakref + >>> class Object: + ... pass + ... + >>> kenny = Object() + >>> weakref.finalize(kenny, print, "You killed Kenny!") #doctest:+ELLIPSIS + <finalize object at ...; for 'Object' at ...> + >>> del kenny + You killed Kenny! + +The finalizer can be called directly as well. However the finalizer +will invoke the callback at most once. + + >>> def callback(x, y, z): + ... print("CALLBACK") + ... return x + y + z + ... + >>> obj = Object() + >>> f = weakref.finalize(obj, callback, 1, 2, z=3) + >>> assert f.alive + >>> assert f() == 6 + CALLBACK + >>> assert not f.alive + >>> f() # callback not called because finalizer dead + >>> del obj # callback not called because finalizer dead + +You can unregister a finalizer using its :meth:`~finalize.detach` +method. This kills the finalizer and returns the arguments passed to +the constructor when it was created. + + >>> obj = Object() + >>> f = weakref.finalize(obj, callback, 1, 2, z=3) + >>> f.detach() #doctest:+ELLIPSIS + (<...Object object ...>, <function callback ...>, (1, 2), {'z': 3}) + >>> newobj, func, args, kwargs = _ + >>> assert not f.alive + >>> assert newobj is obj + >>> assert func(*args, **kwargs) == 6 + CALLBACK + +Unless you set the :attr:`~finalize.atexit` attribute to +:const:`False`, a finalizer will be called when the program exits if it +is still alive. For instance + +.. doctest:: + :options: +SKIP + + >>> obj = Object() + >>> weakref.finalize(obj, print, "obj dead or exiting") + <finalize object at ...; for 'Object' at ...> + >>> exit() + obj dead or exiting + + +Comparing finalizers with :meth:`__del__` methods +------------------------------------------------- + +Suppose we want to create a class whose instances represent temporary +directories. The directories should be deleted with their contents +when the first of the following events occurs: + +* the object is garbage collected, +* the object's :meth:`remove` method is called, or +* the program exits. + +We might try to implement the class using a :meth:`__del__` method as +follows:: + + class TempDir: + def __init__(self): + self.name = tempfile.mkdtemp() + + def remove(self): + if self.name is not None: + shutil.rmtree(self.name) + self.name = None + + @property + def removed(self): + return self.name is None + + def __del__(self): + self.remove() + +Starting with Python 3.4, :meth:`__del__` methods no longer prevent +reference cycles from being garbage collected, and module globals are +no longer forced to :const:`None` during :term:`interpreter shutdown`. +So this code should work without any issues on CPython. + +However, handling of :meth:`__del__` methods is notoriously implementation +specific, since it depends on internal details of the interpreter's garbage +collector implementation. + +A more robust alternative can be to define a finalizer which only references +the specific functions and objects that it needs, rather than having access +to the full state of the object:: + + class TempDir: + def __init__(self): + self.name = tempfile.mkdtemp() + self._finalizer = weakref.finalize(self, shutil.rmtree, self.name) + + def remove(self): + self._finalizer() + + @property + def removed(self): + return not self._finalizer.alive + +Defined like this, our finalizer only receives a reference to the details +it needs to clean up the directory appropriately. If the object never gets +garbage collected the finalizer will still be called at exit. + +The other advantage of weakref based finalizers is that they can be used to +register finalizers for classes where the definition is controlled by a +third party, such as running code when a module is unloaded:: + + import weakref, sys + def unloading_module(): + # implicit reference to the module globals from the function body + weakref.finalize(sys.modules[__name__], unloading_module) + + +.. note:: + + If you create a finalizer object in a daemonic thread just as the program + exits then there is the possibility that the finalizer + does not get called at exit. However, in a daemonic thread + :func:`atexit.register`, ``try: ... finally: ...`` and ``with: ...`` + do not guarantee that cleanup occurs either. diff --git a/cpython_2/environment/repo/Doc/library/webbrowser.rst b/cpython_2/environment/repo/Doc/library/webbrowser.rst new file mode 100644 index 0000000000000000000000000000000000000000..b7bfb655a71579fbccca89a3deb5846c3741c3fb --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/webbrowser.rst @@ -0,0 +1,220 @@ +:mod:`webbrowser` --- Convenient Web-browser controller +======================================================= + +.. module:: webbrowser + :synopsis: Easy-to-use controller for Web browsers. + +.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org> +.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> + +**Source code:** :source:`Lib/webbrowser.py` + +-------------- + +The :mod:`webbrowser` module provides a high-level interface to allow displaying +Web-based documents to users. Under most circumstances, simply calling the +:func:`.open` function from this module will do the right thing. + +Under Unix, graphical browsers are preferred under X11, but text-mode browsers +will be used if graphical browsers are not available or an X11 display isn't +available. If text-mode browsers are used, the calling process will block until +the user exits the browser. + +If the environment variable :envvar:`BROWSER` exists, it is interpreted as the +:data:`os.pathsep`-separated list of browsers to try ahead of the platform +defaults. When the value of a list part contains the string ``%s``, then it is +interpreted as a literal browser command line to be used with the argument URL +substituted for ``%s``; if the part does not contain ``%s``, it is simply +interpreted as the name of the browser to launch. [1]_ + +For non-Unix platforms, or when a remote browser is available on Unix, the +controlling process will not wait for the user to finish with the browser, but +allow the remote browser to maintain its own windows on the display. If remote +browsers are not available on Unix, the controlling process will launch a new +browser and wait. + +The script :program:`webbrowser` can be used as a command-line interface for the +module. It accepts a URL as the argument. It accepts the following optional +parameters: ``-n`` opens the URL in a new browser window, if possible; +``-t`` opens the URL in a new browser page ("tab"). The options are, +naturally, mutually exclusive. Usage example:: + + python -m webbrowser -t "http://www.python.org" + +The following exception is defined: + + +.. exception:: Error + + Exception raised when a browser control error occurs. + +The following functions are defined: + + +.. function:: open(url, new=0, autoraise=True) + + Display *url* using the default browser. If *new* is 0, the *url* is opened + in the same browser window if possible. If *new* is 1, a new browser window + is opened if possible. If *new* is 2, a new browser page ("tab") is opened + if possible. If *autoraise* is ``True``, the window is raised if possible + (note that under many window managers this will occur regardless of the + setting of this variable). + + Note that on some platforms, trying to open a filename using this function, + may work and start the operating system's associated program. However, this + is neither supported nor portable. + + .. audit-event:: webbrowser.open url webbrowser.open + + +.. function:: open_new(url) + + Open *url* in a new window of the default browser, if possible, otherwise, open + *url* in the only browser window. + +.. function:: open_new_tab(url) + + Open *url* in a new page ("tab") of the default browser, if possible, otherwise + equivalent to :func:`open_new`. + + +.. function:: get(using=None) + + Return a controller object for the browser type *using*. If *using* is + ``None``, return a controller for a default browser appropriate to the + caller's environment. + + +.. function:: register(name, constructor, instance=None, *, preferred=False) + + Register the browser type *name*. Once a browser type is registered, the + :func:`get` function can return a controller for that browser type. If + *instance* is not provided, or is ``None``, *constructor* will be called without + parameters to create an instance when needed. If *instance* is provided, + *constructor* will never be called, and may be ``None``. + + Setting *preferred* to ``True`` makes this browser a preferred result for + a :func:`get` call with no argument. Otherwise, this entry point is only + useful if you plan to either set the :envvar:`BROWSER` variable or call + :func:`get` with a nonempty argument matching the name of a handler you + declare. + + .. versionchanged:: 3.7 + *preferred* keyword-only parameter was added. + +A number of browser types are predefined. This table gives the type names that +may be passed to the :func:`get` function and the corresponding instantiations +for the controller classes, all defined in this module. + ++------------------------+-----------------------------------------+-------+ +| Type Name | Class Name | Notes | ++========================+=========================================+=======+ +| ``'mozilla'`` | :class:`Mozilla('mozilla')` | | ++------------------------+-----------------------------------------+-------+ +| ``'firefox'`` | :class:`Mozilla('mozilla')` | | ++------------------------+-----------------------------------------+-------+ +| ``'netscape'`` | :class:`Mozilla('netscape')` | | ++------------------------+-----------------------------------------+-------+ +| ``'galeon'`` | :class:`Galeon('galeon')` | | ++------------------------+-----------------------------------------+-------+ +| ``'epiphany'`` | :class:`Galeon('epiphany')` | | ++------------------------+-----------------------------------------+-------+ +| ``'skipstone'`` | :class:`BackgroundBrowser('skipstone')` | | ++------------------------+-----------------------------------------+-------+ +| ``'kfmclient'`` | :class:`Konqueror()` | \(1) | ++------------------------+-----------------------------------------+-------+ +| ``'konqueror'`` | :class:`Konqueror()` | \(1) | ++------------------------+-----------------------------------------+-------+ +| ``'kfm'`` | :class:`Konqueror()` | \(1) | ++------------------------+-----------------------------------------+-------+ +| ``'mosaic'`` | :class:`BackgroundBrowser('mosaic')` | | ++------------------------+-----------------------------------------+-------+ +| ``'opera'`` | :class:`Opera()` | | ++------------------------+-----------------------------------------+-------+ +| ``'grail'`` | :class:`Grail()` | | ++------------------------+-----------------------------------------+-------+ +| ``'links'`` | :class:`GenericBrowser('links')` | | ++------------------------+-----------------------------------------+-------+ +| ``'elinks'`` | :class:`Elinks('elinks')` | | ++------------------------+-----------------------------------------+-------+ +| ``'lynx'`` | :class:`GenericBrowser('lynx')` | | ++------------------------+-----------------------------------------+-------+ +| ``'w3m'`` | :class:`GenericBrowser('w3m')` | | ++------------------------+-----------------------------------------+-------+ +| ``'windows-default'`` | :class:`WindowsDefault` | \(2) | ++------------------------+-----------------------------------------+-------+ +| ``'macosx'`` | :class:`MacOSX('default')` | \(3) | ++------------------------+-----------------------------------------+-------+ +| ``'safari'`` | :class:`MacOSX('safari')` | \(3) | ++------------------------+-----------------------------------------+-------+ +| ``'google-chrome'`` | :class:`Chrome('google-chrome')` | | ++------------------------+-----------------------------------------+-------+ +| ``'chrome'`` | :class:`Chrome('chrome')` | | ++------------------------+-----------------------------------------+-------+ +| ``'chromium'`` | :class:`Chromium('chromium')` | | ++------------------------+-----------------------------------------+-------+ +| ``'chromium-browser'`` | :class:`Chromium('chromium-browser')` | | ++------------------------+-----------------------------------------+-------+ + +Notes: + +(1) + "Konqueror" is the file manager for the KDE desktop environment for Unix, and + only makes sense to use if KDE is running. Some way of reliably detecting KDE + would be nice; the :envvar:`KDEDIR` variable is not sufficient. Note also that + the name "kfm" is used even when using the :program:`konqueror` command with KDE + 2 --- the implementation selects the best strategy for running Konqueror. + +(2) + Only on Windows platforms. + +(3) + Only on Mac OS X platform. + +.. versionadded:: 3.3 + Support for Chrome/Chromium has been added. + +Here are some simple examples:: + + url = 'http://docs.python.org/' + + # Open URL in a new tab, if a browser window is already open. + webbrowser.open_new_tab(url) + + # Open URL in new window, raising the window if possible. + webbrowser.open_new(url) + + +.. _browser-controllers: + +Browser Controller Objects +-------------------------- + +Browser controllers provide these methods which parallel three of the +module-level convenience functions: + + +.. method:: controller.open(url, new=0, autoraise=True) + + Display *url* using the browser handled by this controller. If *new* is 1, a new + browser window is opened if possible. If *new* is 2, a new browser page ("tab") + is opened if possible. + + +.. method:: controller.open_new(url) + + Open *url* in a new window of the browser handled by this controller, if + possible, otherwise, open *url* in the only browser window. Alias + :func:`open_new`. + + +.. method:: controller.open_new_tab(url) + + Open *url* in a new page ("tab") of the browser handled by this controller, if + possible, otherwise equivalent to :func:`open_new`. + + +.. rubric:: Footnotes + +.. [1] Executables named here without a full path will be searched in the + directories given in the :envvar:`PATH` environment variable. diff --git a/cpython_2/environment/repo/Doc/library/windows.rst b/cpython_2/environment/repo/Doc/library/windows.rst new file mode 100644 index 0000000000000000000000000000000000000000..b60d4e4ccf51d9c2a8a192ebb061842ce1bc6883 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/windows.rst @@ -0,0 +1,15 @@ +.. _mswin-specific-services: + +**************************** +MS Windows Specific Services +**************************** + +This chapter describes modules that are only available on MS Windows platforms. + + +.. toctree:: + + msilib.rst + msvcrt.rst + winreg.rst + winsound.rst diff --git a/cpython_2/environment/repo/Doc/library/winreg.rst b/cpython_2/environment/repo/Doc/library/winreg.rst new file mode 100644 index 0000000000000000000000000000000000000000..dccb7db27e90cc0df30976b213af0d816dc8f7e6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/winreg.rst @@ -0,0 +1,805 @@ +:mod:`winreg` --- Windows registry access +========================================= + +.. module:: winreg + :platform: Windows + :synopsis: Routines and objects for manipulating the Windows registry. + +.. sectionauthor:: Mark Hammond <MarkH@ActiveState.com> + +-------------- + +These functions expose the Windows registry API to Python. Instead of using an +integer as the registry handle, a :ref:`handle object <handle-object>` is used +to ensure that the handles are closed correctly, even if the programmer neglects +to explicitly close them. + +.. _exception-changed: + +.. versionchanged:: 3.3 + Several functions in this module used to raise a + :exc:`WindowsError`, which is now an alias of :exc:`OSError`. + +.. _functions: + +Functions +------------------ + +This module offers the following functions: + + +.. function:: CloseKey(hkey) + + Closes a previously opened registry key. The *hkey* argument specifies a + previously opened key. + + .. note:: + + If *hkey* is not closed using this method (or via :meth:`hkey.Close() + <PyHKEY.Close>`), it is closed when the *hkey* object is destroyed by + Python. + + +.. function:: ConnectRegistry(computer_name, key) + + Establishes a connection to a predefined registry handle on another computer, + and returns a :ref:`handle object <handle-object>`. + + *computer_name* is the name of the remote computer, of the form + ``r"\\computername"``. If ``None``, the local computer is used. + + *key* is the predefined handle to connect to. + + The return value is the handle of the opened key. If the function fails, an + :exc:`OSError` exception is raised. + + .. audit-event:: winreg.ConnectRegistry computer_name,key winreg.ConnectRegistry + + .. versionchanged:: 3.3 + See :ref:`above <exception-changed>`. + + +.. function:: CreateKey(key, sub_key) + + Creates or opens the specified key, returning a + :ref:`handle object <handle-object>`. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *sub_key* is a string that names the key this method opens or creates. + + If *key* is one of the predefined keys, *sub_key* may be ``None``. In that + case, the handle returned is the same key handle passed in to the function. + + If the key already exists, this function opens the existing key. + + The return value is the handle of the opened key. If the function fails, an + :exc:`OSError` exception is raised. + + .. audit-event:: winreg.CreateKey key,sub_key,access winreg.CreateKey + + .. audit-event:: winreg.OpenKey/result key winreg.CreateKey + + .. versionchanged:: 3.3 + See :ref:`above <exception-changed>`. + + +.. function:: CreateKeyEx(key, sub_key, reserved=0, access=KEY_WRITE) + + Creates or opens the specified key, returning a + :ref:`handle object <handle-object>`. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *sub_key* is a string that names the key this method opens or creates. + + *reserved* is a reserved integer, and must be zero. The default is zero. + + *access* is an integer that specifies an access mask that describes the desired + security access for the key. Default is :const:`KEY_WRITE`. See + :ref:`Access Rights <access-rights>` for other allowed values. + + If *key* is one of the predefined keys, *sub_key* may be ``None``. In that + case, the handle returned is the same key handle passed in to the function. + + If the key already exists, this function opens the existing key. + + The return value is the handle of the opened key. If the function fails, an + :exc:`OSError` exception is raised. + + .. audit-event:: winreg.CreateKey key,sub_key,access winreg.CreateKeyEx + + .. audit-event:: winreg.OpenKey/result key winreg.CreateKeyEx + + .. versionadded:: 3.2 + + .. versionchanged:: 3.3 + See :ref:`above <exception-changed>`. + + +.. function:: DeleteKey(key, sub_key) + + Deletes the specified key. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *sub_key* is a string that must be a subkey of the key identified by the *key* + parameter. This value must not be ``None``, and the key may not have subkeys. + + *This method can not delete keys with subkeys.* + + If the method succeeds, the entire key, including all of its values, is removed. + If the method fails, an :exc:`OSError` exception is raised. + + .. audit-event:: winreg.DeleteKey key,sub_key,access winreg.DeleteKey + + .. versionchanged:: 3.3 + See :ref:`above <exception-changed>`. + + +.. function:: DeleteKeyEx(key, sub_key, access=KEY_WOW64_64KEY, reserved=0) + + Deletes the specified key. + + .. note:: + The :func:`DeleteKeyEx` function is implemented with the RegDeleteKeyEx + Windows API function, which is specific to 64-bit versions of Windows. + See the `RegDeleteKeyEx documentation + <https://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx>`__. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *sub_key* is a string that must be a subkey of the key identified by the + *key* parameter. This value must not be ``None``, and the key may not have + subkeys. + + *reserved* is a reserved integer, and must be zero. The default is zero. + + *access* is an integer that specifies an access mask that describes the desired + security access for the key. Default is :const:`KEY_WOW64_64KEY`. See + :ref:`Access Rights <access-rights>` for other allowed values. + + *This method can not delete keys with subkeys.* + + If the method succeeds, the entire key, including all of its values, is + removed. If the method fails, an :exc:`OSError` exception is raised. + + On unsupported Windows versions, :exc:`NotImplementedError` is raised. + + .. audit-event:: winreg.DeleteKey key,sub_key,access winreg.DeleteKeyEx + + .. versionadded:: 3.2 + + .. versionchanged:: 3.3 + See :ref:`above <exception-changed>`. + + +.. function:: DeleteValue(key, value) + + Removes a named value from a registry key. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *value* is a string that identifies the value to remove. + + .. audit-event:: winreg.DeleteValue key,value winreg.DeleteValue + + +.. function:: EnumKey(key, index) + + Enumerates subkeys of an open registry key, returning a string. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *index* is an integer that identifies the index of the key to retrieve. + + The function retrieves the name of one subkey each time it is called. It is + typically called repeatedly until an :exc:`OSError` exception is + raised, indicating, no more values are available. + + .. audit-event:: winreg.EnumKey key,index winreg.EnumKey + + .. versionchanged:: 3.3 + See :ref:`above <exception-changed>`. + + +.. function:: EnumValue(key, index) + + Enumerates values of an open registry key, returning a tuple. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *index* is an integer that identifies the index of the value to retrieve. + + The function retrieves the name of one subkey each time it is called. It is + typically called repeatedly, until an :exc:`OSError` exception is + raised, indicating no more values. + + The result is a tuple of 3 items: + + +-------+--------------------------------------------+ + | Index | Meaning | + +=======+============================================+ + | ``0`` | A string that identifies the value name | + +-------+--------------------------------------------+ + | ``1`` | An object that holds the value data, and | + | | whose type depends on the underlying | + | | registry type | + +-------+--------------------------------------------+ + | ``2`` | An integer that identifies the type of the | + | | value data (see table in docs for | + | | :meth:`SetValueEx`) | + +-------+--------------------------------------------+ + + .. audit-event:: winreg.EnumValue key,index winreg.EnumValue + + .. versionchanged:: 3.3 + See :ref:`above <exception-changed>`. + + +.. index:: + single: % (percent); environment variables expansion (Windows) + +.. function:: ExpandEnvironmentStrings(str) + + Expands environment variable placeholders ``%NAME%`` in strings like + :const:`REG_EXPAND_SZ`:: + + >>> ExpandEnvironmentStrings('%windir%') + 'C:\\Windows' + + .. audit-event:: winreg.ExpandEnvironmentStrings str winreg.ExpandEnvironmentStrings + + +.. function:: FlushKey(key) + + Writes all the attributes of a key to the registry. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + It is not necessary to call :func:`FlushKey` to change a key. Registry changes are + flushed to disk by the registry using its lazy flusher. Registry changes are + also flushed to disk at system shutdown. Unlike :func:`CloseKey`, the + :func:`FlushKey` method returns only when all the data has been written to the + registry. An application should only call :func:`FlushKey` if it requires + absolute certainty that registry changes are on disk. + + .. note:: + + If you don't know whether a :func:`FlushKey` call is required, it probably + isn't. + + +.. function:: LoadKey(key, sub_key, file_name) + + Creates a subkey under the specified key and stores registration information + from a specified file into that subkey. + + *key* is a handle returned by :func:`ConnectRegistry` or one of the constants + :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`. + + *sub_key* is a string that identifies the subkey to load. + + *file_name* is the name of the file to load registry data from. This file must + have been created with the :func:`SaveKey` function. Under the file allocation + table (FAT) file system, the filename may not have an extension. + + A call to :func:`LoadKey` fails if the calling process does not have the + :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different + from permissions -- see the `RegLoadKey documentation + <https://msdn.microsoft.com/en-us/library/ms724889%28v=VS.85%29.aspx>`__ for + more details. + + If *key* is a handle returned by :func:`ConnectRegistry`, then the path + specified in *file_name* is relative to the remote computer. + + .. audit-event:: winreg.LoadKey key,sub_key,file_name winreg.LoadKey + + +.. function:: OpenKey(key, sub_key, reserved=0, access=KEY_READ) + OpenKeyEx(key, sub_key, reserved=0, access=KEY_READ) + + Opens the specified key, returning a :ref:`handle object <handle-object>`. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *sub_key* is a string that identifies the sub_key to open. + + *reserved* is a reserved integer, and must be zero. The default is zero. + + *access* is an integer that specifies an access mask that describes the desired + security access for the key. Default is :const:`KEY_READ`. See :ref:`Access + Rights <access-rights>` for other allowed values. + + The result is a new handle to the specified key. + + If the function fails, :exc:`OSError` is raised. + + .. audit-event:: winreg.OpenKey key,sub_key,access winreg.OpenKey + + .. audit-event:: winreg.OpenKey/result key winreg.OpenKey + + .. versionchanged:: 3.2 + Allow the use of named arguments. + + .. versionchanged:: 3.3 + See :ref:`above <exception-changed>`. + + +.. function:: QueryInfoKey(key) + + Returns information about a key, as a tuple. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + The result is a tuple of 3 items: + + +-------+---------------------------------------------+ + | Index | Meaning | + +=======+=============================================+ + | ``0`` | An integer giving the number of sub keys | + | | this key has. | + +-------+---------------------------------------------+ + | ``1`` | An integer giving the number of values this | + | | key has. | + +-------+---------------------------------------------+ + | ``2`` | An integer giving when the key was last | + | | modified (if available) as 100's of | + | | nanoseconds since Jan 1, 1601. | + +-------+---------------------------------------------+ + + .. audit-event:: winreg.QueryInfoKey key winreg.QueryInfoKey + + +.. function:: QueryValue(key, sub_key) + + Retrieves the unnamed value for a key, as a string. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *sub_key* is a string that holds the name of the subkey with which the value is + associated. If this parameter is ``None`` or empty, the function retrieves the + value set by the :func:`SetValue` method for the key identified by *key*. + + Values in the registry have name, type, and data components. This method + retrieves the data for a key's first value that has a ``NULL`` name. But the + underlying API call doesn't return the type, so always use + :func:`QueryValueEx` if possible. + + .. audit-event:: winreg.QueryValue key,sub_key,value_name winreg.QueryValue + + +.. function:: QueryValueEx(key, value_name) + + Retrieves the type and data for a specified value name associated with + an open registry key. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *value_name* is a string indicating the value to query. + + The result is a tuple of 2 items: + + +-------+-----------------------------------------+ + | Index | Meaning | + +=======+=========================================+ + | ``0`` | The value of the registry item. | + +-------+-----------------------------------------+ + | ``1`` | An integer giving the registry type for | + | | this value (see table in docs for | + | | :meth:`SetValueEx`) | + +-------+-----------------------------------------+ + + .. audit-event:: winreg.QueryValue key,sub_key,value_name winreg.QueryValueEx + + +.. function:: SaveKey(key, file_name) + + Saves the specified key, and all its subkeys to the specified file. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *file_name* is the name of the file to save registry data to. This file + cannot already exist. If this filename includes an extension, it cannot be + used on file allocation table (FAT) file systems by the :meth:`LoadKey` + method. + + If *key* represents a key on a remote computer, the path described by + *file_name* is relative to the remote computer. The caller of this method must + possess the :const:`SeBackupPrivilege` security privilege. Note that + privileges are different than permissions -- see the + `Conflicts Between User Rights and Permissions documentation + <https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx>`__ + for more details. + + This function passes ``NULL`` for *security_attributes* to the API. + + .. audit-event:: winreg.SaveKey key,file_name winreg.SaveKey + + +.. function:: SetValue(key, sub_key, type, value) + + Associates a value with a specified key. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *sub_key* is a string that names the subkey with which the value is associated. + + *type* is an integer that specifies the type of the data. Currently this must be + :const:`REG_SZ`, meaning only strings are supported. Use the :func:`SetValueEx` + function for support for other data types. + + *value* is a string that specifies the new value. + + If the key specified by the *sub_key* parameter does not exist, the SetValue + function creates it. + + Value lengths are limited by available memory. Long values (more than 2048 + bytes) should be stored as files with the filenames stored in the configuration + registry. This helps the registry perform efficiently. + + The key identified by the *key* parameter must have been opened with + :const:`KEY_SET_VALUE` access. + + .. audit-event:: winreg.SetValue key,sub_key,type,value winreg.SetValue + + +.. function:: SetValueEx(key, value_name, reserved, type, value) + + Stores data in the value field of an open registry key. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + *value_name* is a string that names the subkey with which the value is + associated. + + *reserved* can be anything -- zero is always passed to the API. + + *type* is an integer that specifies the type of the data. See + :ref:`Value Types <value-types>` for the available types. + + *value* is a string that specifies the new value. + + This method can also set additional value and type information for the specified + key. The key identified by the key parameter must have been opened with + :const:`KEY_SET_VALUE` access. + + To open the key, use the :func:`CreateKey` or :func:`OpenKey` methods. + + Value lengths are limited by available memory. Long values (more than 2048 + bytes) should be stored as files with the filenames stored in the configuration + registry. This helps the registry perform efficiently. + + .. audit-event:: winreg.SetValue key,sub_key,type,value winreg.SetValueEx + + +.. function:: DisableReflectionKey(key) + + Disables registry reflection for 32-bit processes running on a 64-bit + operating system. + + *key* is an already open key, or one of the predefined :ref:`HKEY_* constants + <hkey-constants>`. + + Will generally raise :exc:`NotImplementedError` if executed on a 32-bit operating + system. + + If the key is not on the reflection list, the function succeeds but has no + effect. Disabling reflection for a key does not affect reflection of any + subkeys. + + .. audit-event:: winreg.DisableReflectionKey key winreg.DisableReflectionKey + + +.. function:: EnableReflectionKey(key) + + Restores registry reflection for the specified disabled key. + + *key* is an already open key, or one of the predefined :ref:`HKEY_* constants + <hkey-constants>`. + + Will generally raise :exc:`NotImplementedError` if executed on a 32-bit operating + system. + + Restoring reflection for a key does not affect reflection of any subkeys. + + .. audit-event:: winreg.EnableReflectionKey key winreg.EnableReflectionKey + + +.. function:: QueryReflectionKey(key) + + Determines the reflection state for the specified key. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants <hkey-constants>`. + + Returns ``True`` if reflection is disabled. + + Will generally raise :exc:`NotImplementedError` if executed on a 32-bit + operating system. + + .. audit-event:: winreg.QueryReflectionKey key winreg.QueryReflectionKey + + +.. _constants: + +Constants +------------------ + +The following constants are defined for use in many :mod:`_winreg` functions. + +.. _hkey-constants: + +HKEY_* Constants +++++++++++++++++ + +.. data:: HKEY_CLASSES_ROOT + + Registry entries subordinate to this key define types (or classes) of + documents and the properties associated with those types. Shell and + COM applications use the information stored under this key. + + +.. data:: HKEY_CURRENT_USER + + Registry entries subordinate to this key define the preferences of + the current user. These preferences include the settings of + environment variables, data about program groups, colors, printers, + network connections, and application preferences. + +.. data:: HKEY_LOCAL_MACHINE + + Registry entries subordinate to this key define the physical state + of the computer, including data about the bus type, system memory, + and installed hardware and software. + +.. data:: HKEY_USERS + + Registry entries subordinate to this key define the default user + configuration for new users on the local computer and the user + configuration for the current user. + +.. data:: HKEY_PERFORMANCE_DATA + + Registry entries subordinate to this key allow you to access + performance data. The data is not actually stored in the registry; + the registry functions cause the system to collect the data from + its source. + + +.. data:: HKEY_CURRENT_CONFIG + + Contains information about the current hardware profile of the + local computer system. + +.. data:: HKEY_DYN_DATA + + This key is not used in versions of Windows after 98. + + +.. _access-rights: + +Access Rights ++++++++++++++ + +For more information, see `Registry Key Security and Access +<https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx>`__. + +.. data:: KEY_ALL_ACCESS + + Combines the STANDARD_RIGHTS_REQUIRED, :const:`KEY_QUERY_VALUE`, + :const:`KEY_SET_VALUE`, :const:`KEY_CREATE_SUB_KEY`, + :const:`KEY_ENUMERATE_SUB_KEYS`, :const:`KEY_NOTIFY`, + and :const:`KEY_CREATE_LINK` access rights. + +.. data:: KEY_WRITE + + Combines the STANDARD_RIGHTS_WRITE, :const:`KEY_SET_VALUE`, and + :const:`KEY_CREATE_SUB_KEY` access rights. + +.. data:: KEY_READ + + Combines the STANDARD_RIGHTS_READ, :const:`KEY_QUERY_VALUE`, + :const:`KEY_ENUMERATE_SUB_KEYS`, and :const:`KEY_NOTIFY` values. + +.. data:: KEY_EXECUTE + + Equivalent to :const:`KEY_READ`. + +.. data:: KEY_QUERY_VALUE + + Required to query the values of a registry key. + +.. data:: KEY_SET_VALUE + + Required to create, delete, or set a registry value. + +.. data:: KEY_CREATE_SUB_KEY + + Required to create a subkey of a registry key. + +.. data:: KEY_ENUMERATE_SUB_KEYS + + Required to enumerate the subkeys of a registry key. + +.. data:: KEY_NOTIFY + + Required to request change notifications for a registry key or for + subkeys of a registry key. + +.. data:: KEY_CREATE_LINK + + Reserved for system use. + + +.. _64-bit-access-rights: + +64-bit Specific +*************** + +For more information, see `Accessing an Alternate Registry View +<https://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx>`__. + +.. data:: KEY_WOW64_64KEY + + Indicates that an application on 64-bit Windows should operate on + the 64-bit registry view. + +.. data:: KEY_WOW64_32KEY + + Indicates that an application on 64-bit Windows should operate on + the 32-bit registry view. + + +.. _value-types: + +Value Types ++++++++++++ + +For more information, see `Registry Value Types +<https://msdn.microsoft.com/en-us/library/ms724884%28v=VS.85%29.aspx>`__. + +.. data:: REG_BINARY + + Binary data in any form. + +.. data:: REG_DWORD + + 32-bit number. + +.. data:: REG_DWORD_LITTLE_ENDIAN + + A 32-bit number in little-endian format. Equivalent to :const:`REG_DWORD`. + +.. data:: REG_DWORD_BIG_ENDIAN + + A 32-bit number in big-endian format. + +.. data:: REG_EXPAND_SZ + + Null-terminated string containing references to environment + variables (``%PATH%``). + +.. data:: REG_LINK + + A Unicode symbolic link. + +.. data:: REG_MULTI_SZ + + A sequence of null-terminated strings, terminated by two null characters. + (Python handles this termination automatically.) + +.. data:: REG_NONE + + No defined value type. + +.. data:: REG_QWORD + + A 64-bit number. + + .. versionadded:: 3.6 + +.. data:: REG_QWORD_LITTLE_ENDIAN + + A 64-bit number in little-endian format. Equivalent to :const:`REG_QWORD`. + + .. versionadded:: 3.6 + +.. data:: REG_RESOURCE_LIST + + A device-driver resource list. + +.. data:: REG_FULL_RESOURCE_DESCRIPTOR + + A hardware setting. + +.. data:: REG_RESOURCE_REQUIREMENTS_LIST + + A hardware resource list. + +.. data:: REG_SZ + + A null-terminated string. + + +.. _handle-object: + +Registry Handle Objects +----------------------- + +This object wraps a Windows HKEY object, automatically closing it when the +object is destroyed. To guarantee cleanup, you can call either the +:meth:`~PyHKEY.Close` method on the object, or the :func:`CloseKey` function. + +All registry functions in this module return one of these objects. + +All registry functions in this module which accept a handle object also accept +an integer, however, use of the handle object is encouraged. + +Handle objects provide semantics for :meth:`__bool__` -- thus :: + + if handle: + print("Yes") + +will print ``Yes`` if the handle is currently valid (has not been closed or +detached). + +The object also support comparison semantics, so handle objects will compare +true if they both reference the same underlying Windows handle value. + +Handle objects can be converted to an integer (e.g., using the built-in +:func:`int` function), in which case the underlying Windows handle value is +returned. You can also use the :meth:`~PyHKEY.Detach` method to return the +integer handle, and also disconnect the Windows handle from the handle object. + + +.. method:: PyHKEY.Close() + + Closes the underlying Windows handle. + + If the handle is already closed, no error is raised. + + +.. method:: PyHKEY.Detach() + + Detaches the Windows handle from the handle object. + + The result is an integer that holds the value of the handle before it is + detached. If the handle is already detached or closed, this will return + zero. + + After calling this function, the handle is effectively invalidated, but the + handle is not closed. You would call this function when you need the + underlying Win32 handle to exist beyond the lifetime of the handle object. + + .. audit-event:: winreg.PyHKEY.Detach key winreg.PyHKEY.Detach + + +.. method:: PyHKEY.__enter__() + PyHKEY.__exit__(\*exc_info) + + The HKEY object implements :meth:`~object.__enter__` and + :meth:`~object.__exit__` and thus supports the context protocol for the + :keyword:`with` statement:: + + with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key: + ... # work with key + + will automatically close *key* when control leaves the :keyword:`with` block. + + diff --git a/cpython_2/environment/repo/Doc/library/winsound.rst b/cpython_2/environment/repo/Doc/library/winsound.rst new file mode 100644 index 0000000000000000000000000000000000000000..372f792a0f938e17961fdee1a3ab72619f2e403a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/winsound.rst @@ -0,0 +1,161 @@ +:mod:`winsound` --- Sound-playing interface for Windows +======================================================= + +.. module:: winsound + :platform: Windows + :synopsis: Access to the sound-playing machinery for Windows. + +.. moduleauthor:: Toby Dickenson <htrd90@zepler.org> +.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> + +-------------- + +The :mod:`winsound` module provides access to the basic sound-playing machinery +provided by Windows platforms. It includes functions and several constants. + + +.. function:: Beep(frequency, duration) + + Beep the PC's speaker. The *frequency* parameter specifies frequency, in hertz, + of the sound, and must be in the range 37 through 32,767. The *duration* + parameter specifies the number of milliseconds the sound should last. If the + system is not able to beep the speaker, :exc:`RuntimeError` is raised. + + +.. function:: PlaySound(sound, flags) + + Call the underlying :c:func:`PlaySound` function from the Platform API. The + *sound* parameter may be a filename, a system sound alias, audio data as a + :term:`bytes-like object`, or ``None``. Its + interpretation depends on the value of *flags*, which can be a bitwise ORed + combination of the constants described below. If the *sound* parameter is + ``None``, any currently playing waveform sound is stopped. If the system + indicates an error, :exc:`RuntimeError` is raised. + + +.. function:: MessageBeep(type=MB_OK) + + Call the underlying :c:func:`MessageBeep` function from the Platform API. This + plays a sound as specified in the registry. The *type* argument specifies which + sound to play; possible values are ``-1``, ``MB_ICONASTERISK``, + ``MB_ICONEXCLAMATION``, ``MB_ICONHAND``, ``MB_ICONQUESTION``, and ``MB_OK``, all + described below. The value ``-1`` produces a "simple beep"; this is the final + fallback if a sound cannot be played otherwise. If the system indicates an + error, :exc:`RuntimeError` is raised. + + +.. data:: SND_FILENAME + + The *sound* parameter is the name of a WAV file. Do not use with + :const:`SND_ALIAS`. + + +.. data:: SND_ALIAS + + The *sound* parameter is a sound association name from the registry. If the + registry contains no such name, play the system default sound unless + :const:`SND_NODEFAULT` is also specified. If no default sound is registered, + raise :exc:`RuntimeError`. Do not use with :const:`SND_FILENAME`. + + All Win32 systems support at least the following; most systems support many + more: + + +--------------------------+----------------------------------------+ + | :func:`PlaySound` *name* | Corresponding Control Panel Sound name | + +==========================+========================================+ + | ``'SystemAsterisk'`` | Asterisk | + +--------------------------+----------------------------------------+ + | ``'SystemExclamation'`` | Exclamation | + +--------------------------+----------------------------------------+ + | ``'SystemExit'`` | Exit Windows | + +--------------------------+----------------------------------------+ + | ``'SystemHand'`` | Critical Stop | + +--------------------------+----------------------------------------+ + | ``'SystemQuestion'`` | Question | + +--------------------------+----------------------------------------+ + + For example:: + + import winsound + # Play Windows exit sound. + winsound.PlaySound("SystemExit", winsound.SND_ALIAS) + + # Probably play Windows default sound, if any is registered (because + # "*" probably isn't the registered name of any sound). + winsound.PlaySound("*", winsound.SND_ALIAS) + + +.. data:: SND_LOOP + + Play the sound repeatedly. The :const:`SND_ASYNC` flag must also be used to + avoid blocking. Cannot be used with :const:`SND_MEMORY`. + + +.. data:: SND_MEMORY + + The *sound* parameter to :func:`PlaySound` is a memory image of a WAV file, as a + :term:`bytes-like object`. + + .. note:: + + This module does not support playing from a memory image asynchronously, so a + combination of this flag and :const:`SND_ASYNC` will raise :exc:`RuntimeError`. + + +.. data:: SND_PURGE + + Stop playing all instances of the specified sound. + + .. note:: + + This flag is not supported on modern Windows platforms. + + +.. data:: SND_ASYNC + + Return immediately, allowing sounds to play asynchronously. + + +.. data:: SND_NODEFAULT + + If the specified sound cannot be found, do not play the system default sound. + + +.. data:: SND_NOSTOP + + Do not interrupt sounds currently playing. + + +.. data:: SND_NOWAIT + + Return immediately if the sound driver is busy. + + .. note:: + + This flag is not supported on modern Windows platforms. + + +.. data:: MB_ICONASTERISK + + Play the ``SystemDefault`` sound. + + +.. data:: MB_ICONEXCLAMATION + + Play the ``SystemExclamation`` sound. + + +.. data:: MB_ICONHAND + + Play the ``SystemHand`` sound. + + +.. data:: MB_ICONQUESTION + + Play the ``SystemQuestion`` sound. + + +.. data:: MB_OK + + Play the ``SystemDefault`` sound. + diff --git a/cpython_2/environment/repo/Doc/library/wsgiref.rst b/cpython_2/environment/repo/Doc/library/wsgiref.rst new file mode 100644 index 0000000000000000000000000000000000000000..1e30aa4a898c13bb7eef7442b762a5462c52d65f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/wsgiref.rst @@ -0,0 +1,789 @@ +:mod:`wsgiref` --- WSGI Utilities and Reference Implementation +============================================================== + +.. module:: wsgiref + :synopsis: WSGI Utilities and Reference Implementation. + +.. moduleauthor:: Phillip J. Eby <pje@telecommunity.com> +.. sectionauthor:: Phillip J. Eby <pje@telecommunity.com> + +-------------- + +The Web Server Gateway Interface (WSGI) is a standard interface between web +server software and web applications written in Python. Having a standard +interface makes it easy to use an application that supports WSGI with a number +of different web servers. + +Only authors of web servers and programming frameworks need to know every detail +and corner case of the WSGI design. You don't need to understand every detail +of WSGI just to install a WSGI application or to write a web application using +an existing framework. + +:mod:`wsgiref` is a reference implementation of the WSGI specification that can +be used to add WSGI support to a web server or framework. It provides utilities +for manipulating WSGI environment variables and response headers, base classes +for implementing WSGI servers, a demo HTTP server that serves WSGI applications, +and a validation tool that checks WSGI servers and applications for conformance +to the WSGI specification (:pep:`3333`). + +See `wsgi.readthedocs.io <https://wsgi.readthedocs.io/>`_ for more information about WSGI, and links +to tutorials and other resources. + +.. XXX If you're just trying to write a web application... + + +:mod:`wsgiref.util` -- WSGI environment utilities +------------------------------------------------- + +.. module:: wsgiref.util + :synopsis: WSGI environment utilities. + + +This module provides a variety of utility functions for working with WSGI +environments. A WSGI environment is a dictionary containing HTTP request +variables as described in :pep:`3333`. All of the functions taking an *environ* +parameter expect a WSGI-compliant dictionary to be supplied; please see +:pep:`3333` for a detailed specification. + + +.. function:: guess_scheme(environ) + + Return a guess for whether ``wsgi.url_scheme`` should be "http" or "https", by + checking for a ``HTTPS`` environment variable in the *environ* dictionary. The + return value is a string. + + This function is useful when creating a gateway that wraps CGI or a CGI-like + protocol such as FastCGI. Typically, servers providing such protocols will + include a ``HTTPS`` variable with a value of "1", "yes", or "on" when a request + is received via SSL. So, this function returns "https" if such a value is + found, and "http" otherwise. + + +.. function:: request_uri(environ, include_query=True) + + Return the full request URI, optionally including the query string, using the + algorithm found in the "URL Reconstruction" section of :pep:`3333`. If + *include_query* is false, the query string is not included in the resulting URI. + + +.. function:: application_uri(environ) + + Similar to :func:`request_uri`, except that the ``PATH_INFO`` and + ``QUERY_STRING`` variables are ignored. The result is the base URI of the + application object addressed by the request. + + +.. function:: shift_path_info(environ) + + Shift a single name from ``PATH_INFO`` to ``SCRIPT_NAME`` and return the name. + The *environ* dictionary is *modified* in-place; use a copy if you need to keep + the original ``PATH_INFO`` or ``SCRIPT_NAME`` intact. + + If there are no remaining path segments in ``PATH_INFO``, ``None`` is returned. + + Typically, this routine is used to process each portion of a request URI path, + for example to treat the path as a series of dictionary keys. This routine + modifies the passed-in environment to make it suitable for invoking another WSGI + application that is located at the target URI. For example, if there is a WSGI + application at ``/foo``, and the request URI path is ``/foo/bar/baz``, and the + WSGI application at ``/foo`` calls :func:`shift_path_info`, it will receive the + string "bar", and the environment will be updated to be suitable for passing to + a WSGI application at ``/foo/bar``. That is, ``SCRIPT_NAME`` will change from + ``/foo`` to ``/foo/bar``, and ``PATH_INFO`` will change from ``/bar/baz`` to + ``/baz``. + + When ``PATH_INFO`` is just a "/", this routine returns an empty string and + appends a trailing slash to ``SCRIPT_NAME``, even though empty path segments are + normally ignored, and ``SCRIPT_NAME`` doesn't normally end in a slash. This is + intentional behavior, to ensure that an application can tell the difference + between URIs ending in ``/x`` from ones ending in ``/x/`` when using this + routine to do object traversal. + + +.. function:: setup_testing_defaults(environ) + + Update *environ* with trivial defaults for testing purposes. + + This routine adds various parameters required for WSGI, including ``HTTP_HOST``, + ``SERVER_NAME``, ``SERVER_PORT``, ``REQUEST_METHOD``, ``SCRIPT_NAME``, + ``PATH_INFO``, and all of the :pep:`3333`\ -defined ``wsgi.*`` variables. It + only supplies default values, and does not replace any existing settings for + these variables. + + This routine is intended to make it easier for unit tests of WSGI servers and + applications to set up dummy environments. It should NOT be used by actual WSGI + servers or applications, since the data is fake! + + Example usage:: + + from wsgiref.util import setup_testing_defaults + from wsgiref.simple_server import make_server + + # A relatively simple WSGI application. It's going to print out the + # environment dictionary after being updated by setup_testing_defaults + def simple_app(environ, start_response): + setup_testing_defaults(environ) + + status = '200 OK' + headers = [('Content-type', 'text/plain; charset=utf-8')] + + start_response(status, headers) + + ret = [("%s: %s\n" % (key, value)).encode("utf-8") + for key, value in environ.items()] + return ret + + with make_server('', 8000, simple_app) as httpd: + print("Serving on port 8000...") + httpd.serve_forever() + + +In addition to the environment functions above, the :mod:`wsgiref.util` module +also provides these miscellaneous utilities: + + +.. function:: is_hop_by_hop(header_name) + + Return ``True`` if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header, as defined by + :rfc:`2616`. + + +.. class:: FileWrapper(filelike, blksize=8192) + + A wrapper to convert a file-like object to an :term:`iterator`. The resulting objects + support both :meth:`__getitem__` and :meth:`__iter__` iteration styles, for + compatibility with Python 2.1 and Jython. As the object is iterated over, the + optional *blksize* parameter will be repeatedly passed to the *filelike* + object's :meth:`read` method to obtain bytestrings to yield. When :meth:`read` + returns an empty bytestring, iteration is ended and is not resumable. + + If *filelike* has a :meth:`close` method, the returned object will also have a + :meth:`close` method, and it will invoke the *filelike* object's :meth:`close` + method when called. + + Example usage:: + + from io import StringIO + from wsgiref.util import FileWrapper + + # We're using a StringIO-buffer for as the file-like object + filelike = StringIO("This is an example file-like object"*10) + wrapper = FileWrapper(filelike, blksize=5) + + for chunk in wrapper: + print(chunk) + + .. deprecated:: 3.8 + Support for :meth:`sequence protocol <__getitem__>` is deprecated. + + +:mod:`wsgiref.headers` -- WSGI response header tools +---------------------------------------------------- + +.. module:: wsgiref.headers + :synopsis: WSGI response header tools. + + +This module provides a single class, :class:`Headers`, for convenient +manipulation of WSGI response headers using a mapping-like interface. + + +.. class:: Headers([headers]) + + Create a mapping-like object wrapping *headers*, which must be a list of header + name/value tuples as described in :pep:`3333`. The default value of *headers* is + an empty list. + + :class:`Headers` objects support typical mapping operations including + :meth:`__getitem__`, :meth:`get`, :meth:`__setitem__`, :meth:`setdefault`, + :meth:`__delitem__` and :meth:`__contains__`. For each of + these methods, the key is the header name (treated case-insensitively), and the + value is the first value associated with that header name. Setting a header + deletes any existing values for that header, then adds a new value at the end of + the wrapped header list. Headers' existing order is generally maintained, with + new headers added to the end of the wrapped list. + + Unlike a dictionary, :class:`Headers` objects do not raise an error when you try + to get or delete a key that isn't in the wrapped header list. Getting a + nonexistent header just returns ``None``, and deleting a nonexistent header does + nothing. + + :class:`Headers` objects also support :meth:`keys`, :meth:`values`, and + :meth:`items` methods. The lists returned by :meth:`keys` and :meth:`items` can + include the same key more than once if there is a multi-valued header. The + ``len()`` of a :class:`Headers` object is the same as the length of its + :meth:`items`, which is the same as the length of the wrapped header list. In + fact, the :meth:`items` method just returns a copy of the wrapped header list. + + Calling ``bytes()`` on a :class:`Headers` object returns a formatted bytestring + suitable for transmission as HTTP response headers. Each header is placed on a + line with its value, separated by a colon and a space. Each line is terminated + by a carriage return and line feed, and the bytestring is terminated with a + blank line. + + In addition to their mapping interface and formatting features, :class:`Headers` + objects also have the following methods for querying and adding multi-valued + headers, and for adding headers with MIME parameters: + + + .. method:: Headers.get_all(name) + + Return a list of all the values for the named header. + + The returned list will be sorted in the order they appeared in the original + header list or were added to this instance, and may contain duplicates. Any + fields deleted and re-inserted are always appended to the header list. If no + fields exist with the given name, returns an empty list. + + + .. method:: Headers.add_header(name, value, **_params) + + Add a (possibly multi-valued) header, with optional MIME parameters specified + via keyword arguments. + + *name* is the header field to add. Keyword arguments can be used to set MIME + parameters for the header field. Each parameter must be a string or ``None``. + Underscores in parameter names are converted to dashes, since dashes are illegal + in Python identifiers, but many MIME parameter names include dashes. If the + parameter value is a string, it is added to the header value parameters in the + form ``name="value"``. If it is ``None``, only the parameter name is added. + (This is used for MIME parameters without a value.) Example usage:: + + h.add_header('content-disposition', 'attachment', filename='bud.gif') + + The above will add a header that looks like this:: + + Content-Disposition: attachment; filename="bud.gif" + + + .. versionchanged:: 3.5 + *headers* parameter is optional. + + +:mod:`wsgiref.simple_server` -- a simple WSGI HTTP server +--------------------------------------------------------- + +.. module:: wsgiref.simple_server + :synopsis: A simple WSGI HTTP server. + + +This module implements a simple HTTP server (based on :mod:`http.server`) +that serves WSGI applications. Each server instance serves a single WSGI +application on a given host and port. If you want to serve multiple +applications on a single host and port, you should create a WSGI application +that parses ``PATH_INFO`` to select which application to invoke for each +request. (E.g., using the :func:`shift_path_info` function from +:mod:`wsgiref.util`.) + + +.. function:: make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler) + + Create a new WSGI server listening on *host* and *port*, accepting connections + for *app*. The return value is an instance of the supplied *server_class*, and + will process requests using the specified *handler_class*. *app* must be a WSGI + application object, as defined by :pep:`3333`. + + Example usage:: + + from wsgiref.simple_server import make_server, demo_app + + with make_server('', 8000, demo_app) as httpd: + print("Serving HTTP on port 8000...") + + # Respond to requests until process is killed + httpd.serve_forever() + + # Alternative: serve one request, then exit + httpd.handle_request() + + +.. function:: demo_app(environ, start_response) + + This function is a small but complete WSGI application that returns a text page + containing the message "Hello world!" and a list of the key/value pairs provided + in the *environ* parameter. It's useful for verifying that a WSGI server (such + as :mod:`wsgiref.simple_server`) is able to run a simple WSGI application + correctly. + + +.. class:: WSGIServer(server_address, RequestHandlerClass) + + Create a :class:`WSGIServer` instance. *server_address* should be a + ``(host,port)`` tuple, and *RequestHandlerClass* should be the subclass of + :class:`http.server.BaseHTTPRequestHandler` that will be used to process + requests. + + You do not normally need to call this constructor, as the :func:`make_server` + function can handle all the details for you. + + :class:`WSGIServer` is a subclass of :class:`http.server.HTTPServer`, so all + of its methods (such as :meth:`serve_forever` and :meth:`handle_request`) are + available. :class:`WSGIServer` also provides these WSGI-specific methods: + + + .. method:: WSGIServer.set_app(application) + + Sets the callable *application* as the WSGI application that will receive + requests. + + + .. method:: WSGIServer.get_app() + + Returns the currently-set application callable. + + Normally, however, you do not need to use these additional methods, as + :meth:`set_app` is normally called by :func:`make_server`, and the + :meth:`get_app` exists mainly for the benefit of request handler instances. + + +.. class:: WSGIRequestHandler(request, client_address, server) + + Create an HTTP handler for the given *request* (i.e. a socket), *client_address* + (a ``(host,port)`` tuple), and *server* (:class:`WSGIServer` instance). + + You do not need to create instances of this class directly; they are + automatically created as needed by :class:`WSGIServer` objects. You can, + however, subclass this class and supply it as a *handler_class* to the + :func:`make_server` function. Some possibly relevant methods for overriding in + subclasses: + + + .. method:: WSGIRequestHandler.get_environ() + + Returns a dictionary containing the WSGI environment for a request. The default + implementation copies the contents of the :class:`WSGIServer` object's + :attr:`base_environ` dictionary attribute and then adds various headers derived + from the HTTP request. Each call to this method should return a new dictionary + containing all of the relevant CGI environment variables as specified in + :pep:`3333`. + + + .. method:: WSGIRequestHandler.get_stderr() + + Return the object that should be used as the ``wsgi.errors`` stream. The default + implementation just returns ``sys.stderr``. + + + .. method:: WSGIRequestHandler.handle() + + Process the HTTP request. The default implementation creates a handler instance + using a :mod:`wsgiref.handlers` class to implement the actual WSGI application + interface. + + +:mod:`wsgiref.validate` --- WSGI conformance checker +---------------------------------------------------- + +.. module:: wsgiref.validate + :synopsis: WSGI conformance checker. + + +When creating new WSGI application objects, frameworks, servers, or middleware, +it can be useful to validate the new code's conformance using +:mod:`wsgiref.validate`. This module provides a function that creates WSGI +application objects that validate communications between a WSGI server or +gateway and a WSGI application object, to check both sides for protocol +conformance. + +Note that this utility does not guarantee complete :pep:`3333` compliance; an +absence of errors from this module does not necessarily mean that errors do not +exist. However, if this module does produce an error, then it is virtually +certain that either the server or application is not 100% compliant. + +This module is based on the :mod:`paste.lint` module from Ian Bicking's "Python +Paste" library. + + +.. function:: validator(application) + + Wrap *application* and return a new WSGI application object. The returned + application will forward all requests to the original *application*, and will + check that both the *application* and the server invoking it are conforming to + the WSGI specification and to :rfc:`2616`. + + Any detected nonconformance results in an :exc:`AssertionError` being raised; + note, however, that how these errors are handled is server-dependent. For + example, :mod:`wsgiref.simple_server` and other servers based on + :mod:`wsgiref.handlers` (that don't override the error handling methods to do + something else) will simply output a message that an error has occurred, and + dump the traceback to ``sys.stderr`` or some other error stream. + + This wrapper may also generate output using the :mod:`warnings` module to + indicate behaviors that are questionable but which may not actually be + prohibited by :pep:`3333`. Unless they are suppressed using Python command-line + options or the :mod:`warnings` API, any such warnings will be written to + ``sys.stderr`` (*not* ``wsgi.errors``, unless they happen to be the same + object). + + Example usage:: + + from wsgiref.validate import validator + from wsgiref.simple_server import make_server + + # 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 = '200 OK' # HTTP Status + headers = [('Content-type', 'text/plain')] # HTTP Headers + start_response(status, headers) + + # This is going to break because we need to return a list, and + # the validator is going to inform us + return b"Hello World" + + # This is the application wrapped in a validator + validator_app = validator(simple_app) + + with make_server('', 8000, validator_app) as httpd: + print("Listening on port 8000....") + httpd.serve_forever() + + +:mod:`wsgiref.handlers` -- server/gateway base classes +------------------------------------------------------ + +.. module:: wsgiref.handlers + :synopsis: WSGI server/gateway base classes. + + +This module provides base handler classes for implementing WSGI servers and +gateways. These base classes handle most of the work of communicating with a +WSGI application, as long as they are given a CGI-like environment, along with +input, output, and error streams. + + +.. class:: CGIHandler() + + CGI-based invocation via ``sys.stdin``, ``sys.stdout``, ``sys.stderr`` and + ``os.environ``. This is useful when you have a WSGI application and want to run + it as a CGI script. Simply invoke ``CGIHandler().run(app)``, where ``app`` is + the WSGI application object you wish to invoke. + + This class is a subclass of :class:`BaseCGIHandler` that sets ``wsgi.run_once`` + to true, ``wsgi.multithread`` to false, and ``wsgi.multiprocess`` to true, and + always uses :mod:`sys` and :mod:`os` to obtain the necessary CGI streams and + environment. + + +.. class:: IISCGIHandler() + + A specialized alternative to :class:`CGIHandler`, for use when deploying on + Microsoft's IIS web server, without having set the config allowPathInfo + option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7). + + By default, IIS gives a ``PATH_INFO`` that duplicates the ``SCRIPT_NAME`` at + the front, causing problems for WSGI applications that wish to implement + routing. This handler strips any such duplicated path. + + IIS can be configured to pass the correct ``PATH_INFO``, but this causes + another bug where ``PATH_TRANSLATED`` is wrong. Luckily this variable is + rarely used and is not guaranteed by WSGI. On IIS<7, though, the + setting can only be made on a vhost level, affecting all other script + mappings, many of which break when exposed to the ``PATH_TRANSLATED`` bug. + For this reason IIS<7 is almost never deployed with the fix. (Even IIS7 + rarely uses it because there is still no UI for it.) + + There is no way for CGI code to tell whether the option was set, so a + separate handler class is provided. It is used in the same way as + :class:`CGIHandler`, i.e., by calling ``IISCGIHandler().run(app)``, where + ``app`` is the WSGI application object you wish to invoke. + + .. versionadded:: 3.2 + + +.. class:: BaseCGIHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False) + + Similar to :class:`CGIHandler`, but instead of using the :mod:`sys` and + :mod:`os` modules, the CGI environment and I/O streams are specified explicitly. + The *multithread* and *multiprocess* values are used to set the + ``wsgi.multithread`` and ``wsgi.multiprocess`` flags for any applications run by + the handler instance. + + This class is a subclass of :class:`SimpleHandler` intended for use with + software other than HTTP "origin servers". If you are writing a gateway + protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a + ``Status:`` header to send an HTTP status, you probably want to subclass this + instead of :class:`SimpleHandler`. + + +.. class:: SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False) + + Similar to :class:`BaseCGIHandler`, but designed for use with HTTP origin + servers. If you are writing an HTTP server implementation, you will probably + want to subclass this instead of :class:`BaseCGIHandler`. + + This class is a subclass of :class:`BaseHandler`. It overrides the + :meth:`__init__`, :meth:`get_stdin`, :meth:`get_stderr`, :meth:`add_cgi_vars`, + :meth:`_write`, and :meth:`_flush` methods to support explicitly setting the + environment and streams via the constructor. The supplied environment and + streams are stored in the :attr:`stdin`, :attr:`stdout`, :attr:`stderr`, and + :attr:`environ` attributes. + + The :meth:`~io.BufferedIOBase.write` method of *stdout* should write + each chunk in full, like :class:`io.BufferedIOBase`. + + +.. class:: BaseHandler() + + This is an abstract base class for running WSGI applications. Each instance + will handle a single HTTP request, although in principle you could create a + subclass that was reusable for multiple requests. + + :class:`BaseHandler` instances have only one method intended for external use: + + + .. method:: BaseHandler.run(app) + + Run the specified WSGI application, *app*. + + All of the other :class:`BaseHandler` methods are invoked by this method in the + process of running the application, and thus exist primarily to allow + customizing the process. + + The following methods MUST be overridden in a subclass: + + + .. method:: BaseHandler._write(data) + + Buffer the bytes *data* for transmission to the client. It's okay if this + method actually transmits the data; :class:`BaseHandler` just separates write + and flush operations for greater efficiency when the underlying system actually + has such a distinction. + + + .. method:: BaseHandler._flush() + + Force buffered data to be transmitted to the client. It's okay if this method + is a no-op (i.e., if :meth:`_write` actually sends the data). + + + .. method:: BaseHandler.get_stdin() + + Return an input stream object suitable for use as the ``wsgi.input`` of the + request currently being processed. + + + .. method:: BaseHandler.get_stderr() + + Return an output stream object suitable for use as the ``wsgi.errors`` of the + request currently being processed. + + + .. method:: BaseHandler.add_cgi_vars() + + Insert CGI variables for the current request into the :attr:`environ` attribute. + + Here are some other methods and attributes you may wish to override. This list + is only a summary, however, and does not include every method that can be + overridden. You should consult the docstrings and source code for additional + information before attempting to create a customized :class:`BaseHandler` + subclass. + + Attributes and methods for customizing the WSGI environment: + + + .. attribute:: BaseHandler.wsgi_multithread + + The value to be used for the ``wsgi.multithread`` environment variable. It + defaults to true in :class:`BaseHandler`, but may have a different default (or + be set by the constructor) in the other subclasses. + + + .. attribute:: BaseHandler.wsgi_multiprocess + + The value to be used for the ``wsgi.multiprocess`` environment variable. It + defaults to true in :class:`BaseHandler`, but may have a different default (or + be set by the constructor) in the other subclasses. + + + .. attribute:: BaseHandler.wsgi_run_once + + The value to be used for the ``wsgi.run_once`` environment variable. It + defaults to false in :class:`BaseHandler`, but :class:`CGIHandler` sets it to + true by default. + + + .. attribute:: BaseHandler.os_environ + + The default environment variables to be included in every request's WSGI + environment. By default, this is a copy of ``os.environ`` at the time that + :mod:`wsgiref.handlers` was imported, but subclasses can either create their own + at the class or instance level. Note that the dictionary should be considered + read-only, since the default value is shared between multiple classes and + instances. + + + .. attribute:: BaseHandler.server_software + + If the :attr:`origin_server` attribute is set, this attribute's value is used to + set the default ``SERVER_SOFTWARE`` WSGI environment variable, and also to set a + default ``Server:`` header in HTTP responses. It is ignored for handlers (such + as :class:`BaseCGIHandler` and :class:`CGIHandler`) that are not HTTP origin + servers. + + .. versionchanged:: 3.3 + The term "Python" is replaced with implementation specific term like + "CPython", "Jython" etc. + + .. method:: BaseHandler.get_scheme() + + Return the URL scheme being used for the current request. The default + implementation uses the :func:`guess_scheme` function from :mod:`wsgiref.util` + to guess whether the scheme should be "http" or "https", based on the current + request's :attr:`environ` variables. + + + .. method:: BaseHandler.setup_environ() + + Set the :attr:`environ` attribute to a fully-populated WSGI environment. The + default implementation uses all of the above methods and attributes, plus the + :meth:`get_stdin`, :meth:`get_stderr`, and :meth:`add_cgi_vars` methods and the + :attr:`wsgi_file_wrapper` attribute. It also inserts a ``SERVER_SOFTWARE`` key + if not present, as long as the :attr:`origin_server` attribute is a true value + and the :attr:`server_software` attribute is set. + + Methods and attributes for customizing exception handling: + + + .. method:: BaseHandler.log_exception(exc_info) + + Log the *exc_info* tuple in the server log. *exc_info* is a ``(type, value, + traceback)`` tuple. The default implementation simply writes the traceback to + the request's ``wsgi.errors`` stream and flushes it. Subclasses can override + this method to change the format or retarget the output, mail the traceback to + an administrator, or whatever other action may be deemed suitable. + + + .. attribute:: BaseHandler.traceback_limit + + The maximum number of frames to include in tracebacks output by the default + :meth:`log_exception` method. If ``None``, all frames are included. + + + .. method:: BaseHandler.error_output(environ, start_response) + + This method is a WSGI application to generate an error page for the user. It is + only invoked if an error occurs before headers are sent to the client. + + This method can access the current error information using ``sys.exc_info()``, + and should pass that information to *start_response* when calling it (as + described in the "Error Handling" section of :pep:`3333`). + + The default implementation just uses the :attr:`error_status`, + :attr:`error_headers`, and :attr:`error_body` attributes to generate an output + page. Subclasses can override this to produce more dynamic error output. + + Note, however, that it's not recommended from a security perspective to spit out + diagnostics to any old user; ideally, you should have to do something special to + enable diagnostic output, which is why the default implementation doesn't + include any. + + + .. attribute:: BaseHandler.error_status + + The HTTP status used for error responses. This should be a status string as + defined in :pep:`3333`; it defaults to a 500 code and message. + + + .. attribute:: BaseHandler.error_headers + + The HTTP headers used for error responses. This should be a list of WSGI + response headers (``(name, value)`` tuples), as described in :pep:`3333`. The + default list just sets the content type to ``text/plain``. + + + .. attribute:: BaseHandler.error_body + + The error response body. This should be an HTTP response body bytestring. It + defaults to the plain text, "A server error occurred. Please contact the + administrator." + + Methods and attributes for :pep:`3333`'s "Optional Platform-Specific File + Handling" feature: + + + .. attribute:: BaseHandler.wsgi_file_wrapper + + A ``wsgi.file_wrapper`` factory, or ``None``. The default value of this + attribute is the :class:`wsgiref.util.FileWrapper` class. + + + .. method:: BaseHandler.sendfile() + + Override to implement platform-specific file transmission. This method is + called only if the application's return value is an instance of the class + specified by the :attr:`wsgi_file_wrapper` attribute. It should return a true + value if it was able to successfully transmit the file, so that the default + transmission code will not be executed. The default implementation of this + method just returns a false value. + + Miscellaneous methods and attributes: + + + .. attribute:: BaseHandler.origin_server + + This attribute should be set to a true value if the handler's :meth:`_write` and + :meth:`_flush` are being used to communicate directly to the client, rather than + via a CGI-like gateway protocol that wants the HTTP status in a special + ``Status:`` header. + + This attribute's default value is true in :class:`BaseHandler`, but false in + :class:`BaseCGIHandler` and :class:`CGIHandler`. + + + .. attribute:: BaseHandler.http_version + + If :attr:`origin_server` is true, this string attribute is used to set the HTTP + version of the response set to the client. It defaults to ``"1.0"``. + + +.. function:: read_environ() + + Transcode CGI variables from ``os.environ`` to :pep:`3333` "bytes in unicode" + strings, returning a new dictionary. This function is used by + :class:`CGIHandler` and :class:`IISCGIHandler` in place of directly using + ``os.environ``, which is not necessarily WSGI-compliant on all platforms + and web servers using Python 3 -- specifically, ones where the OS's + actual environment is Unicode (i.e. Windows), or ones where the environment + is bytes, but the system encoding used by Python to decode it is anything + other than ISO-8859-1 (e.g. Unix systems using UTF-8). + + If you are implementing a CGI-based handler of your own, you probably want + to use this routine instead of just copying values out of ``os.environ`` + directly. + + .. versionadded:: 3.2 + + +Examples +-------- + +This is a working "Hello World" WSGI application:: + + from wsgiref.simple_server import make_server + + # Every WSGI application must have an application object - a callable + # object that accepts two arguments. For that purpose, we're going to + # use a function (note that you're not limited to a function, you can + # use a class for example). The first argument passed to the function + # is a dictionary containing CGI-style environment variables and the + # second variable is the callable object. + def hello_world_app(environ, start_response): + status = '200 OK' # HTTP Status + headers = [('Content-type', 'text/plain; charset=utf-8')] # HTTP Headers + start_response(status, headers) + + # The returned object is going to be printed + return [b"Hello World"] + + with make_server('', 8000, hello_world_app) as httpd: + print("Serving on port 8000...") + + # Serve until process is killed + httpd.serve_forever() + + +Example of a WSGI application serving the current directory, accept optional +directory and port number (default: 8000) on the command line: + +.. literalinclude:: ../../Tools/scripts/serve.py diff --git a/cpython_2/environment/repo/Doc/library/xdrlib.rst b/cpython_2/environment/repo/Doc/library/xdrlib.rst new file mode 100644 index 0000000000000000000000000000000000000000..42a03a46754d03f0012f1660226eca4ffb863f5f --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xdrlib.rst @@ -0,0 +1,278 @@ +:mod:`xdrlib` --- Encode and decode XDR data +============================================ + +.. module:: xdrlib + :synopsis: Encoders and decoders for the External Data Representation (XDR). + +**Source code:** :source:`Lib/xdrlib.py` + +.. index:: + single: XDR + single: External Data Representation + +-------------- + +The :mod:`xdrlib` module supports the External Data Representation Standard as +described in :rfc:`1014`, written by Sun Microsystems, Inc. June 1987. It +supports most of the data types described in the RFC. + +The :mod:`xdrlib` module defines two classes, one for packing variables into XDR +representation, and another for unpacking from XDR representation. There are +also two exception classes. + + +.. class:: Packer() + + :class:`Packer` is the class for packing data into XDR representation. The + :class:`Packer` class is instantiated with no arguments. + + +.. class:: Unpacker(data) + + ``Unpacker`` is the complementary class which unpacks XDR data values from a + string buffer. The input buffer is given as *data*. + + +.. seealso:: + + :rfc:`1014` - XDR: External Data Representation Standard + This RFC defined the encoding of data which was XDR at the time this module was + originally written. It has apparently been obsoleted by :rfc:`1832`. + + :rfc:`1832` - XDR: External Data Representation Standard + Newer RFC that provides a revised definition of XDR. + + +.. _xdr-packer-objects: + +Packer Objects +-------------- + +:class:`Packer` instances have the following methods: + + +.. method:: Packer.get_buffer() + + Returns the current pack buffer as a string. + + +.. method:: Packer.reset() + + Resets the pack buffer to the empty string. + +In general, you can pack any of the most common XDR data types by calling the +appropriate ``pack_type()`` method. Each method takes a single argument, the +value to pack. The following simple data type packing methods are supported: +:meth:`pack_uint`, :meth:`pack_int`, :meth:`pack_enum`, :meth:`pack_bool`, +:meth:`pack_uhyper`, and :meth:`pack_hyper`. + + +.. method:: Packer.pack_float(value) + + Packs the single-precision floating point number *value*. + + +.. method:: Packer.pack_double(value) + + Packs the double-precision floating point number *value*. + +The following methods support packing strings, bytes, and opaque data: + + +.. method:: Packer.pack_fstring(n, s) + + Packs a fixed length string, *s*. *n* is the length of the string but it is + *not* packed into the data buffer. The string is padded with null bytes if + necessary to guaranteed 4 byte alignment. + + +.. method:: Packer.pack_fopaque(n, data) + + Packs a fixed length opaque data stream, similarly to :meth:`pack_fstring`. + + +.. method:: Packer.pack_string(s) + + Packs a variable length string, *s*. The length of the string is first packed + as an unsigned integer, then the string data is packed with + :meth:`pack_fstring`. + + +.. method:: Packer.pack_opaque(data) + + Packs a variable length opaque data string, similarly to :meth:`pack_string`. + + +.. method:: Packer.pack_bytes(bytes) + + Packs a variable length byte stream, similarly to :meth:`pack_string`. + +The following methods support packing arrays and lists: + + +.. method:: Packer.pack_list(list, pack_item) + + Packs a *list* of homogeneous items. This method is useful for lists with an + indeterminate size; i.e. the size is not available until the entire list has + been walked. For each item in the list, an unsigned integer ``1`` is packed + first, followed by the data value from the list. *pack_item* is the function + that is called to pack the individual item. At the end of the list, an unsigned + integer ``0`` is packed. + + For example, to pack a list of integers, the code might appear like this:: + + import xdrlib + p = xdrlib.Packer() + p.pack_list([1, 2, 3], p.pack_int) + + +.. method:: Packer.pack_farray(n, array, pack_item) + + Packs a fixed length list (*array*) of homogeneous items. *n* is the length of + the list; it is *not* packed into the buffer, but a :exc:`ValueError` exception + is raised if ``len(array)`` is not equal to *n*. As above, *pack_item* is the + function used to pack each element. + + +.. method:: Packer.pack_array(list, pack_item) + + Packs a variable length *list* of homogeneous items. First, the length of the + list is packed as an unsigned integer, then each element is packed as in + :meth:`pack_farray` above. + + +.. _xdr-unpacker-objects: + +Unpacker Objects +---------------- + +The :class:`Unpacker` class offers the following methods: + + +.. method:: Unpacker.reset(data) + + Resets the string buffer with the given *data*. + + +.. method:: Unpacker.get_position() + + Returns the current unpack position in the data buffer. + + +.. method:: Unpacker.set_position(position) + + Sets the data buffer unpack position to *position*. You should be careful about + using :meth:`get_position` and :meth:`set_position`. + + +.. method:: Unpacker.get_buffer() + + Returns the current unpack data buffer as a string. + + +.. method:: Unpacker.done() + + Indicates unpack completion. Raises an :exc:`Error` exception if all of the + data has not been unpacked. + +In addition, every data type that can be packed with a :class:`Packer`, can be +unpacked with an :class:`Unpacker`. Unpacking methods are of the form +``unpack_type()``, and take no arguments. They return the unpacked object. + + +.. method:: Unpacker.unpack_float() + + Unpacks a single-precision floating point number. + + +.. method:: Unpacker.unpack_double() + + Unpacks a double-precision floating point number, similarly to + :meth:`unpack_float`. + +In addition, the following methods unpack strings, bytes, and opaque data: + + +.. method:: Unpacker.unpack_fstring(n) + + Unpacks and returns a fixed length string. *n* is the number of characters + expected. Padding with null bytes to guaranteed 4 byte alignment is assumed. + + +.. method:: Unpacker.unpack_fopaque(n) + + Unpacks and returns a fixed length opaque data stream, similarly to + :meth:`unpack_fstring`. + + +.. method:: Unpacker.unpack_string() + + Unpacks and returns a variable length string. The length of the string is first + unpacked as an unsigned integer, then the string data is unpacked with + :meth:`unpack_fstring`. + + +.. method:: Unpacker.unpack_opaque() + + Unpacks and returns a variable length opaque data string, similarly to + :meth:`unpack_string`. + + +.. method:: Unpacker.unpack_bytes() + + Unpacks and returns a variable length byte stream, similarly to + :meth:`unpack_string`. + +The following methods support unpacking arrays and lists: + + +.. method:: Unpacker.unpack_list(unpack_item) + + Unpacks and returns a list of homogeneous items. The list is unpacked one + element at a time by first unpacking an unsigned integer flag. If the flag is + ``1``, then the item is unpacked and appended to the list. A flag of ``0`` + indicates the end of the list. *unpack_item* is the function that is called to + unpack the items. + + +.. method:: Unpacker.unpack_farray(n, unpack_item) + + Unpacks and returns (as a list) a fixed length array of homogeneous items. *n* + is number of list elements to expect in the buffer. As above, *unpack_item* is + the function used to unpack each element. + + +.. method:: Unpacker.unpack_array(unpack_item) + + Unpacks and returns a variable length *list* of homogeneous items. First, the + length of the list is unpacked as an unsigned integer, then each element is + unpacked as in :meth:`unpack_farray` above. + + +.. _xdr-exceptions: + +Exceptions +---------- + +Exceptions in this module are coded as class instances: + + +.. exception:: Error + + The base exception class. :exc:`Error` has a single public attribute + :attr:`msg` containing the description of the error. + + +.. exception:: ConversionError + + Class derived from :exc:`Error`. Contains no additional instance variables. + +Here is an example of how you would catch one of these exceptions:: + + import xdrlib + p = xdrlib.Packer() + try: + p.pack_double(8.01) + except xdrlib.ConversionError as instance: + print('packing the double failed:', instance.msg) + diff --git a/cpython_2/environment/repo/Doc/library/xml.dom.minidom.rst b/cpython_2/environment/repo/Doc/library/xml.dom.minidom.rst new file mode 100644 index 0000000000000000000000000000000000000000..2c78cd939243a8059a8b56e7f7c588f50c5ae19c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xml.dom.minidom.rst @@ -0,0 +1,267 @@ +:mod:`xml.dom.minidom` --- Minimal DOM implementation +===================================================== + +.. module:: xml.dom.minidom + :synopsis: Minimal Document Object Model (DOM) implementation. + +.. moduleauthor:: Paul Prescod <paul@prescod.net> +.. sectionauthor:: Paul Prescod <paul@prescod.net> +.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de> + +**Source code:** :source:`Lib/xml/dom/minidom.py` + +-------------- + +:mod:`xml.dom.minidom` is a minimal implementation of the Document Object +Model interface, with an API similar to that in other languages. It is intended +to be simpler than the full DOM and also significantly smaller. Users who are +not already proficient with the DOM should consider using the +:mod:`xml.etree.ElementTree` module for their XML processing instead. + + +.. warning:: + + The :mod:`xml.dom.minidom` module is not secure against + maliciously constructed data. If you need to parse untrusted or + unauthenticated data see :ref:`xml-vulnerabilities`. + + +DOM applications typically start by parsing some XML into a DOM. With +:mod:`xml.dom.minidom`, this is done through the parse functions:: + + from xml.dom.minidom import parse, parseString + + dom1 = parse('c:\\temp\\mydata.xml') # parse an XML file by name + + datasource = open('c:\\temp\\mydata.xml') + dom2 = parse(datasource) # parse an open file + + dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>') + +The :func:`parse` function can take either a filename or an open file object. + + +.. function:: parse(filename_or_file, parser=None, bufsize=None) + + Return a :class:`Document` from the given input. *filename_or_file* may be + either a file name, or a file-like object. *parser*, if given, must be a SAX2 + parser object. This function will change the document handler of the parser and + activate namespace support; other parser configuration (like setting an entity + resolver) must have been done in advance. + +If you have XML in a string, you can use the :func:`parseString` function +instead: + + +.. function:: parseString(string, parser=None) + + Return a :class:`Document` that represents the *string*. This method creates an + :class:`io.StringIO` object for the string and passes that on to :func:`parse`. + +Both functions return a :class:`Document` object representing the content of the +document. + +What the :func:`parse` and :func:`parseString` functions do is connect an XML +parser with a "DOM builder" that can accept parse events from any SAX parser and +convert them into a DOM tree. The name of the functions are perhaps misleading, +but are easy to grasp when learning the interfaces. The parsing of the document +will be completed before these functions return; it's simply that these +functions do not provide a parser implementation themselves. + +You can also create a :class:`Document` by calling a method on a "DOM +Implementation" object. You can get this object either by calling the +:func:`getDOMImplementation` function in the :mod:`xml.dom` package or the +:mod:`xml.dom.minidom` module. Once you have a :class:`Document`, you +can add child nodes to it to populate the DOM:: + + from xml.dom.minidom import getDOMImplementation + + impl = getDOMImplementation() + + newdoc = impl.createDocument(None, "some_tag", None) + top_element = newdoc.documentElement + text = newdoc.createTextNode('Some textual content.') + top_element.appendChild(text) + +Once you have a DOM document object, you can access the parts of your XML +document through its properties and methods. These properties are defined in +the DOM specification. The main property of the document object is the +:attr:`documentElement` property. It gives you the main element in the XML +document: the one that holds all others. Here is an example program:: + + dom3 = parseString("<myxml>Some data</myxml>") + assert dom3.documentElement.tagName == "myxml" + +When you are finished with a DOM tree, you may optionally call the +:meth:`unlink` method to encourage early cleanup of the now-unneeded +objects. :meth:`unlink` is an :mod:`xml.dom.minidom`\ -specific +extension to the DOM API that renders the node and its descendants are +essentially useless. Otherwise, Python's garbage collector will +eventually take care of the objects in the tree. + +.. seealso:: + + `Document Object Model (DOM) Level 1 Specification <https://www.w3.org/TR/REC-DOM-Level-1/>`_ + The W3C recommendation for the DOM supported by :mod:`xml.dom.minidom`. + + +.. _minidom-objects: + +DOM Objects +----------- + +The definition of the DOM API for Python is given as part of the :mod:`xml.dom` +module documentation. This section lists the differences between the API and +:mod:`xml.dom.minidom`. + + +.. method:: Node.unlink() + + Break internal references within the DOM so that it will be garbage collected on + versions of Python without cyclic GC. Even when cyclic GC is available, using + this can make large amounts of memory available sooner, so calling this on DOM + objects as soon as they are no longer needed is good practice. This only needs + to be called on the :class:`Document` object, but may be called on child nodes + to discard children of that node. + + You can avoid calling this method explicitly by using the :keyword:`with` + statement. The following code will automatically unlink *dom* when the + :keyword:`!with` block is exited:: + + with xml.dom.minidom.parse(datasource) as dom: + ... # Work with dom. + + +.. method:: Node.writexml(writer, indent="", addindent="", newl="", + encoding=None, standalone=None) + + Write XML to the writer object. The writer receives texts but not bytes as input, + it should have a :meth:`write` method which matches that of the file object + interface. The *indent* parameter is the indentation of the current node. + The *addindent* parameter is the incremental indentation to use for subnodes + of the current one. The *newl* parameter specifies the string to use to + terminate newlines. + + For the :class:`Document` node, an additional keyword argument *encoding* can + be used to specify the encoding field of the XML header. + + Silimarly, explicitly stating the *standalone* argument causes the + standalone document declarations to be added to the prologue of the XML + document. + If the value is set to `True`, `standalone="yes"` is added, + otherwise it is set to `"no"`. + Not stating the argument will omit the declaration from the document. + + .. versionchanged:: 3.8 + The :meth:`writexml` method now preserves the attribute order specified + by the user. + +.. method:: Node.toxml(encoding=None, standalone=None) + + Return a string or byte string containing the XML represented by + the DOM node. + + With an explicit *encoding* [1]_ argument, the result is a byte + string in the specified encoding. + With no *encoding* argument, the result is a Unicode string, and the + XML declaration in the resulting string does not specify an + encoding. Encoding this string in an encoding other than UTF-8 is + likely incorrect, since UTF-8 is the default encoding of XML. + + The *standalone* argument behaves exactly as in :meth:`writexml`. + + .. versionchanged:: 3.8 + The :meth:`toxml` method now preserves the attribute order specified + by the user. + +.. method:: Node.toprettyxml(indent="\\t", newl="\\n", encoding=None, + standalone=None) + + Return a pretty-printed version of the document. *indent* specifies the + indentation string and defaults to a tabulator; *newl* specifies the string + emitted at the end of each line and defaults to ``\n``. + + The *encoding* argument behaves like the corresponding argument of + :meth:`toxml`. + + The *standalone* argument behaves exactly as in :meth:`writexml`. + + .. versionchanged:: 3.8 + The :meth:`toprettyxml` method now preserves the attribute order specified + by the user. + + +.. _dom-example: + +DOM Example +----------- + +This example program is a fairly realistic example of a simple program. In this +particular case, we do not take much advantage of the flexibility of the DOM. + +.. literalinclude:: ../includes/minidom-example.py + + +.. _minidom-and-dom: + +minidom and the DOM standard +---------------------------- + +The :mod:`xml.dom.minidom` module is essentially a DOM 1.0-compatible DOM with +some DOM 2 features (primarily namespace features). + +Usage of the DOM interface in Python is straight-forward. The following mapping +rules apply: + +* Interfaces are accessed through instance objects. Applications should not + instantiate the classes themselves; they should use the creator functions + available on the :class:`Document` object. Derived interfaces support all + operations (and attributes) from the base interfaces, plus any new operations. + +* Operations are used as methods. Since the DOM uses only :keyword:`in` + parameters, the arguments are passed in normal order (from left to right). + There are no optional arguments. ``void`` operations return ``None``. + +* IDL attributes map to instance attributes. For compatibility with the OMG IDL + language mapping for Python, an attribute ``foo`` can also be accessed through + accessor methods :meth:`_get_foo` and :meth:`_set_foo`. ``readonly`` + attributes must not be changed; this is not enforced at runtime. + +* The types ``short int``, ``unsigned int``, ``unsigned long long``, and + ``boolean`` all map to Python integer objects. + +* The type ``DOMString`` maps to Python strings. :mod:`xml.dom.minidom` supports + either bytes or strings, but will normally produce strings. + Values of type ``DOMString`` may also be ``None`` where allowed to have the IDL + ``null`` value by the DOM specification from the W3C. + +* ``const`` declarations map to variables in their respective scope (e.g. + ``xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE``); they must not be changed. + +* ``DOMException`` is currently not supported in :mod:`xml.dom.minidom`. + Instead, :mod:`xml.dom.minidom` uses standard Python exceptions such as + :exc:`TypeError` and :exc:`AttributeError`. + +* :class:`NodeList` objects are implemented using Python's built-in list type. + These objects provide the interface defined in the DOM specification, but with + earlier versions of Python they do not support the official API. They are, + however, much more "Pythonic" than the interface defined in the W3C + recommendations. + +The following interfaces have no implementation in :mod:`xml.dom.minidom`: + +* :class:`DOMTimeStamp` + +* :class:`EntityReference` + +Most of these reflect information in the XML document that is not of general +utility to most DOM users. + +.. rubric:: Footnotes + +.. [1] The encoding name included in the XML output should conform to + the appropriate standards. For example, "UTF-8" is valid, but + "UTF8" is not valid in an XML document's declaration, even though + Python accepts it as an encoding name. + See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl + and https://www.iana.org/assignments/character-sets/character-sets.xhtml. diff --git a/cpython_2/environment/repo/Doc/library/xml.dom.pulldom.rst b/cpython_2/environment/repo/Doc/library/xml.dom.pulldom.rst new file mode 100644 index 0000000000000000000000000000000000000000..660c75c1a1b340dc2f740bbd5f4af7f52b325876 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xml.dom.pulldom.rst @@ -0,0 +1,147 @@ +:mod:`xml.dom.pulldom` --- Support for building partial DOM trees +================================================================= + +.. module:: xml.dom.pulldom + :synopsis: Support for building partial DOM trees from SAX events. + +.. moduleauthor:: Paul Prescod <paul@prescod.net> + +**Source code:** :source:`Lib/xml/dom/pulldom.py` + +-------------- + +The :mod:`xml.dom.pulldom` module provides a "pull parser" which can also be +asked to produce DOM-accessible fragments of the document where necessary. The +basic concept involves pulling "events" from a stream of incoming XML and +processing them. In contrast to SAX which also employs an event-driven +processing model together with callbacks, the user of a pull parser is +responsible for explicitly pulling events from the stream, looping over those +events until either processing is finished or an error condition occurs. + + +.. warning:: + + The :mod:`xml.dom.pulldom` module is not secure against + maliciously constructed data. If you need to parse untrusted or + unauthenticated data see :ref:`xml-vulnerabilities`. + +.. versionchanged:: 3.7.1 + + The SAX parser no longer processes general external entities by default to + increase security by default. To enable processing of external entities, + pass a custom parser instance in:: + + from xml.dom.pulldom import parse + from xml.sax import make_parser + from xml.sax.handler import feature_external_ges + + parser = make_parser() + parser.setFeature(feature_external_ges, True) + parse(filename, parser=parser) + + +Example:: + + from xml.dom import pulldom + + doc = pulldom.parse('sales_items.xml') + for event, node in doc: + if event == pulldom.START_ELEMENT and node.tagName == 'item': + if int(node.getAttribute('price')) > 50: + doc.expandNode(node) + print(node.toxml()) + +``event`` is a constant and can be one of: + +* :data:`START_ELEMENT` +* :data:`END_ELEMENT` +* :data:`COMMENT` +* :data:`START_DOCUMENT` +* :data:`END_DOCUMENT` +* :data:`CHARACTERS` +* :data:`PROCESSING_INSTRUCTION` +* :data:`IGNORABLE_WHITESPACE` + +``node`` is an object of type :class:`xml.dom.minidom.Document`, +:class:`xml.dom.minidom.Element` or :class:`xml.dom.minidom.Text`. + +Since the document is treated as a "flat" stream of events, the document "tree" +is implicitly traversed and the desired elements are found regardless of their +depth in the tree. In other words, one does not need to consider hierarchical +issues such as recursive searching of the document nodes, although if the +context of elements were important, one would either need to maintain some +context-related state (i.e. remembering where one is in the document at any +given point) or to make use of the :func:`DOMEventStream.expandNode` method +and switch to DOM-related processing. + + +.. class:: PullDom(documentFactory=None) + + Subclass of :class:`xml.sax.handler.ContentHandler`. + + +.. class:: SAX2DOM(documentFactory=None) + + Subclass of :class:`xml.sax.handler.ContentHandler`. + + +.. function:: parse(stream_or_string, parser=None, bufsize=None) + + Return a :class:`DOMEventStream` from the given input. *stream_or_string* may be + either a file name, or a file-like object. *parser*, if given, must be an + :class:`~xml.sax.xmlreader.XMLReader` object. This function will change the + document handler of the + parser and activate namespace support; other parser configuration (like + setting an entity resolver) must have been done in advance. + +If you have XML in a string, you can use the :func:`parseString` function instead: + +.. function:: parseString(string, parser=None) + + Return a :class:`DOMEventStream` that represents the (Unicode) *string*. + +.. data:: default_bufsize + + Default value for the *bufsize* parameter to :func:`parse`. + + The value of this variable can be changed before calling :func:`parse` and + the new value will take effect. + +.. _domeventstream-objects: + +DOMEventStream Objects +---------------------- + +.. class:: DOMEventStream(stream, parser, bufsize) + + .. deprecated:: 3.8 + Support for :meth:`sequence protocol <__getitem__>` is deprecated. + + .. method:: getEvent() + + Return a tuple containing *event* and the current *node* as + :class:`xml.dom.minidom.Document` if event equals :data:`START_DOCUMENT`, + :class:`xml.dom.minidom.Element` if event equals :data:`START_ELEMENT` or + :data:`END_ELEMENT` or :class:`xml.dom.minidom.Text` if event equals + :data:`CHARACTERS`. + The current node does not contain information about its children, unless + :func:`expandNode` is called. + + .. method:: expandNode(node) + + Expands all children of *node* into *node*. Example:: + + from xml.dom import pulldom + + xml = '<html><title>Foo

Some text

and more

' + doc = pulldom.parseString(xml) + for event, node in doc: + if event == pulldom.START_ELEMENT and node.tagName == 'p': + # Following statement only prints '

' + print(node.toxml()) + doc.expandNode(node) + # Following statement prints node with all its children '

Some text

and more

' + print(node.toxml()) + + .. method:: DOMEventStream.reset() + diff --git a/cpython_2/environment/repo/Doc/library/xml.dom.rst b/cpython_2/environment/repo/Doc/library/xml.dom.rst new file mode 100644 index 0000000000000000000000000000000000000000..98454e18ff1f8795c79d688854ed6654d3ff349b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xml.dom.rst @@ -0,0 +1,1033 @@ +:mod:`xml.dom` --- The Document Object Model API +================================================ + +.. module:: xml.dom + :synopsis: Document Object Model API for Python. + +.. sectionauthor:: Paul Prescod +.. sectionauthor:: Martin v. Löwis + +**Source code:** :source:`Lib/xml/dom/__init__.py` + +-------------- + +The Document Object Model, or "DOM," is a cross-language API from the World Wide +Web Consortium (W3C) for accessing and modifying XML documents. A DOM +implementation presents an XML document as a tree structure, or allows client +code to build such a structure from scratch. It then gives access to the +structure through a set of objects which provided well-known interfaces. + +The DOM is extremely useful for random-access applications. SAX only allows you +a view of one bit of the document at a time. If you are looking at one SAX +element, you have no access to another. If you are looking at a text node, you +have no access to a containing element. When you write a SAX application, you +need to keep track of your program's position in the document somewhere in your +own code. SAX does not do it for you. Also, if you need to look ahead in the +XML document, you are just out of luck. + +Some applications are simply impossible in an event driven model with no access +to a tree. Of course you could build some sort of tree yourself in SAX events, +but the DOM allows you to avoid writing that code. The DOM is a standard tree +representation for XML data. + +The Document Object Model is being defined by the W3C in stages, or "levels" in +their terminology. The Python mapping of the API is substantially based on the +DOM Level 2 recommendation. + +.. What if your needs are somewhere between SAX and the DOM? Perhaps + you cannot afford to load the entire tree in memory but you find the + SAX model somewhat cumbersome and low-level. There is also a module + called xml.dom.pulldom that allows you to build trees of only the + parts of a document that you need structured access to. It also has + features that allow you to find your way around the DOM. + See http://www.prescod.net/python/pulldom + +DOM applications typically start by parsing some XML into a DOM. How this is +accomplished is not covered at all by DOM Level 1, and Level 2 provides only +limited improvements: There is a :class:`DOMImplementation` object class which +provides access to :class:`Document` creation methods, but no way to access an +XML reader/parser/Document builder in an implementation-independent way. There +is also no well-defined way to access these methods without an existing +:class:`Document` object. In Python, each DOM implementation will provide a +function :func:`getDOMImplementation`. DOM Level 3 adds a Load/Store +specification, which defines an interface to the reader, but this is not yet +available in the Python standard library. + +Once you have a DOM document object, you can access the parts of your XML +document through its properties and methods. These properties are defined in +the DOM specification; this portion of the reference manual describes the +interpretation of the specification in Python. + +The specification provided by the W3C defines the DOM API for Java, ECMAScript, +and OMG IDL. The Python mapping defined here is based in large part on the IDL +version of the specification, but strict compliance is not required (though +implementations are free to support the strict mapping from IDL). See section +:ref:`dom-conformance` for a detailed discussion of mapping requirements. + + +.. seealso:: + + `Document Object Model (DOM) Level 2 Specification `_ + The W3C recommendation upon which the Python DOM API is based. + + `Document Object Model (DOM) Level 1 Specification `_ + The W3C recommendation for the DOM supported by :mod:`xml.dom.minidom`. + + `Python Language Mapping Specification `_ + This specifies the mapping from OMG IDL to Python. + + +Module Contents +--------------- + +The :mod:`xml.dom` contains the following functions: + + +.. function:: registerDOMImplementation(name, factory) + + Register the *factory* function with the name *name*. The factory function + should return an object which implements the :class:`DOMImplementation` + interface. The factory function can return the same object every time, or a new + one for each call, as appropriate for the specific implementation (e.g. if that + implementation supports some customization). + + +.. function:: getDOMImplementation(name=None, features=()) + + Return a suitable DOM implementation. The *name* is either well-known, the + module name of a DOM implementation, or ``None``. If it is not ``None``, imports + the corresponding module and returns a :class:`DOMImplementation` object if the + import succeeds. If no name is given, and if the environment variable + :envvar:`PYTHON_DOM` is set, this variable is used to find the implementation. + + If name is not given, this examines the available implementations to find one + with the required feature set. If no implementation can be found, raise an + :exc:`ImportError`. The features list must be a sequence of ``(feature, + version)`` pairs which are passed to the :meth:`hasFeature` method on available + :class:`DOMImplementation` objects. + +Some convenience constants are also provided: + + +.. data:: EMPTY_NAMESPACE + + The value used to indicate that no namespace is associated with a node in the + DOM. This is typically found as the :attr:`namespaceURI` of a node, or used as + the *namespaceURI* parameter to a namespaces-specific method. + + +.. data:: XML_NAMESPACE + + The namespace URI associated with the reserved prefix ``xml``, as defined by + `Namespaces in XML `_ (section 4). + + +.. data:: XMLNS_NAMESPACE + + The namespace URI for namespace declarations, as defined by `Document Object + Model (DOM) Level 2 Core Specification + `_ (section 1.1.8). + + +.. data:: XHTML_NAMESPACE + + The URI of the XHTML namespace as defined by `XHTML 1.0: The Extensible + HyperText Markup Language `_ (section 3.1.1). + + +In addition, :mod:`xml.dom` contains a base :class:`Node` class and the DOM +exception classes. The :class:`Node` class provided by this module does not +implement any of the methods or attributes defined by the DOM specification; +concrete DOM implementations must provide those. The :class:`Node` class +provided as part of this module does provide the constants used for the +:attr:`nodeType` attribute on concrete :class:`Node` objects; they are located +within the class rather than at the module level to conform with the DOM +specifications. + +.. Should the Node documentation go here? + + +.. _dom-objects: + +Objects in the DOM +------------------ + +The definitive documentation for the DOM is the DOM specification from the W3C. + +Note that DOM attributes may also be manipulated as nodes instead of as simple +strings. It is fairly rare that you must do this, however, so this usage is not +yet documented. + ++--------------------------------+-----------------------------------+---------------------------------+ +| Interface | Section | Purpose | ++================================+===================================+=================================+ +| :class:`DOMImplementation` | :ref:`dom-implementation-objects` | Interface to the underlying | +| | | implementation. | ++--------------------------------+-----------------------------------+---------------------------------+ +| :class:`Node` | :ref:`dom-node-objects` | Base interface for most objects | +| | | in a document. | ++--------------------------------+-----------------------------------+---------------------------------+ +| :class:`NodeList` | :ref:`dom-nodelist-objects` | Interface for a sequence of | +| | | nodes. | ++--------------------------------+-----------------------------------+---------------------------------+ +| :class:`DocumentType` | :ref:`dom-documenttype-objects` | Information about the | +| | | declarations needed to process | +| | | a document. | ++--------------------------------+-----------------------------------+---------------------------------+ +| :class:`Document` | :ref:`dom-document-objects` | Object which represents an | +| | | entire document. | ++--------------------------------+-----------------------------------+---------------------------------+ +| :class:`Element` | :ref:`dom-element-objects` | Element nodes in the document | +| | | hierarchy. | ++--------------------------------+-----------------------------------+---------------------------------+ +| :class:`Attr` | :ref:`dom-attr-objects` | Attribute value nodes on | +| | | element nodes. | ++--------------------------------+-----------------------------------+---------------------------------+ +| :class:`Comment` | :ref:`dom-comment-objects` | Representation of comments in | +| | | the source document. | ++--------------------------------+-----------------------------------+---------------------------------+ +| :class:`Text` | :ref:`dom-text-objects` | Nodes containing textual | +| | | content from the document. | ++--------------------------------+-----------------------------------+---------------------------------+ +| :class:`ProcessingInstruction` | :ref:`dom-pi-objects` | Processing instruction | +| | | representation. | ++--------------------------------+-----------------------------------+---------------------------------+ + +An additional section describes the exceptions defined for working with the DOM +in Python. + + +.. _dom-implementation-objects: + +DOMImplementation Objects +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The :class:`DOMImplementation` interface provides a way for applications to +determine the availability of particular features in the DOM they are using. +DOM Level 2 added the ability to create new :class:`Document` and +:class:`DocumentType` objects using the :class:`DOMImplementation` as well. + + +.. method:: DOMImplementation.hasFeature(feature, version) + + Return ``True`` if the feature identified by the pair of strings *feature* and + *version* is implemented. + + +.. method:: DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype) + + Return a new :class:`Document` object (the root of the DOM), with a child + :class:`Element` object having the given *namespaceUri* and *qualifiedName*. The + *doctype* must be a :class:`DocumentType` object created by + :meth:`createDocumentType`, or ``None``. In the Python DOM API, the first two + arguments can also be ``None`` in order to indicate that no :class:`Element` + child is to be created. + + +.. method:: DOMImplementation.createDocumentType(qualifiedName, publicId, systemId) + + Return a new :class:`DocumentType` object that encapsulates the given + *qualifiedName*, *publicId*, and *systemId* strings, representing the + information contained in an XML document type declaration. + + +.. _dom-node-objects: + +Node Objects +^^^^^^^^^^^^ + +All of the components of an XML document are subclasses of :class:`Node`. + + +.. attribute:: Node.nodeType + + An integer representing the node type. Symbolic constants for the types are on + the :class:`Node` object: :const:`ELEMENT_NODE`, :const:`ATTRIBUTE_NODE`, + :const:`TEXT_NODE`, :const:`CDATA_SECTION_NODE`, :const:`ENTITY_NODE`, + :const:`PROCESSING_INSTRUCTION_NODE`, :const:`COMMENT_NODE`, + :const:`DOCUMENT_NODE`, :const:`DOCUMENT_TYPE_NODE`, :const:`NOTATION_NODE`. + This is a read-only attribute. + + +.. attribute:: Node.parentNode + + The parent of the current node, or ``None`` for the document node. The value is + always a :class:`Node` object or ``None``. For :class:`Element` nodes, this + will be the parent element, except for the root element, in which case it will + be the :class:`Document` object. For :class:`Attr` nodes, this is always + ``None``. This is a read-only attribute. + + +.. attribute:: Node.attributes + + A :class:`NamedNodeMap` of attribute objects. Only elements have actual values + for this; others provide ``None`` for this attribute. This is a read-only + attribute. + + +.. attribute:: Node.previousSibling + + The node that immediately precedes this one with the same parent. For + instance the element with an end-tag that comes just before the *self* + element's start-tag. Of course, XML documents are made up of more than just + elements so the previous sibling could be text, a comment, or something else. + If this node is the first child of the parent, this attribute will be + ``None``. This is a read-only attribute. + + +.. attribute:: Node.nextSibling + + The node that immediately follows this one with the same parent. See also + :attr:`previousSibling`. If this is the last child of the parent, this + attribute will be ``None``. This is a read-only attribute. + + +.. attribute:: Node.childNodes + + A list of nodes contained within this node. This is a read-only attribute. + + +.. attribute:: Node.firstChild + + The first child of the node, if there are any, or ``None``. This is a read-only + attribute. + + +.. attribute:: Node.lastChild + + The last child of the node, if there are any, or ``None``. This is a read-only + attribute. + + +.. attribute:: Node.localName + + The part of the :attr:`tagName` following the colon if there is one, else the + entire :attr:`tagName`. The value is a string. + + +.. attribute:: Node.prefix + + The part of the :attr:`tagName` preceding the colon if there is one, else the + empty string. The value is a string, or ``None``. + + +.. attribute:: Node.namespaceURI + + The namespace associated with the element name. This will be a string or + ``None``. This is a read-only attribute. + + +.. attribute:: Node.nodeName + + This has a different meaning for each node type; see the DOM specification for + details. You can always get the information you would get here from another + property such as the :attr:`tagName` property for elements or the :attr:`name` + property for attributes. For all node types, the value of this attribute will be + either a string or ``None``. This is a read-only attribute. + + +.. attribute:: Node.nodeValue + + This has a different meaning for each node type; see the DOM specification for + details. The situation is similar to that with :attr:`nodeName`. The value is + a string or ``None``. + + +.. method:: Node.hasAttributes() + + Return ``True`` if the node has any attributes. + + +.. method:: Node.hasChildNodes() + + Return ``True`` if the node has any child nodes. + + +.. method:: Node.isSameNode(other) + + Return ``True`` if *other* refers to the same node as this node. This is especially + useful for DOM implementations which use any sort of proxy architecture (because + more than one object can refer to the same node). + + .. note:: + + This is based on a proposed DOM Level 3 API which is still in the "working + draft" stage, but this particular interface appears uncontroversial. Changes + from the W3C will not necessarily affect this method in the Python DOM interface + (though any new W3C API for this would also be supported). + + +.. method:: Node.appendChild(newChild) + + Add a new child node to this node at the end of the list of + children, returning *newChild*. If the node was already in + the tree, it is removed first. + + +.. method:: Node.insertBefore(newChild, refChild) + + Insert a new child node before an existing child. It must be the case that + *refChild* is a child of this node; if not, :exc:`ValueError` is raised. + *newChild* is returned. If *refChild* is ``None``, it inserts *newChild* at the + end of the children's list. + + +.. method:: Node.removeChild(oldChild) + + Remove a child node. *oldChild* must be a child of this node; if not, + :exc:`ValueError` is raised. *oldChild* is returned on success. If *oldChild* + will not be used further, its :meth:`unlink` method should be called. + + +.. method:: Node.replaceChild(newChild, oldChild) + + Replace an existing node with a new node. It must be the case that *oldChild* + is a child of this node; if not, :exc:`ValueError` is raised. + + +.. method:: Node.normalize() + + Join adjacent text nodes so that all stretches of text are stored as single + :class:`Text` instances. This simplifies processing text from a DOM tree for + many applications. + + +.. method:: Node.cloneNode(deep) + + Clone this node. Setting *deep* means to clone all child nodes as well. This + returns the clone. + + +.. _dom-nodelist-objects: + +NodeList Objects +^^^^^^^^^^^^^^^^ + +A :class:`NodeList` represents a sequence of nodes. These objects are used in +two ways in the DOM Core recommendation: an :class:`Element` object provides +one as its list of child nodes, and the :meth:`getElementsByTagName` and +:meth:`getElementsByTagNameNS` methods of :class:`Node` return objects with this +interface to represent query results. + +The DOM Level 2 recommendation defines one method and one attribute for these +objects: + + +.. method:: NodeList.item(i) + + Return the *i*'th item from the sequence, if there is one, or ``None``. The + index *i* is not allowed to be less than zero or greater than or equal to the + length of the sequence. + + +.. attribute:: NodeList.length + + The number of nodes in the sequence. + +In addition, the Python DOM interface requires that some additional support is +provided to allow :class:`NodeList` objects to be used as Python sequences. All +:class:`NodeList` implementations must include support for +:meth:`~object.__len__` and +:meth:`~object.__getitem__`; this allows iteration over the :class:`NodeList` in +:keyword:`for` statements and proper support for the :func:`len` built-in +function. + +If a DOM implementation supports modification of the document, the +:class:`NodeList` implementation must also support the +:meth:`~object.__setitem__` and :meth:`~object.__delitem__` methods. + + +.. _dom-documenttype-objects: + +DocumentType Objects +^^^^^^^^^^^^^^^^^^^^ + +Information about the notations and entities declared by a document (including +the external subset if the parser uses it and can provide the information) is +available from a :class:`DocumentType` object. The :class:`DocumentType` for a +document is available from the :class:`Document` object's :attr:`doctype` +attribute; if there is no ``DOCTYPE`` declaration for the document, the +document's :attr:`doctype` attribute will be set to ``None`` instead of an +instance of this interface. + +:class:`DocumentType` is a specialization of :class:`Node`, and adds the +following attributes: + + +.. attribute:: DocumentType.publicId + + The public identifier for the external subset of the document type definition. + This will be a string or ``None``. + + +.. attribute:: DocumentType.systemId + + The system identifier for the external subset of the document type definition. + This will be a URI as a string, or ``None``. + + +.. attribute:: DocumentType.internalSubset + + A string giving the complete internal subset from the document. This does not + include the brackets which enclose the subset. If the document has no internal + subset, this should be ``None``. + + +.. attribute:: DocumentType.name + + The name of the root element as given in the ``DOCTYPE`` declaration, if + present. + + +.. attribute:: DocumentType.entities + + This is a :class:`NamedNodeMap` giving the definitions of external entities. + For entity names defined more than once, only the first definition is provided + (others are ignored as required by the XML recommendation). This may be + ``None`` if the information is not provided by the parser, or if no entities are + defined. + + +.. attribute:: DocumentType.notations + + This is a :class:`NamedNodeMap` giving the definitions of notations. For + notation names defined more than once, only the first definition is provided + (others are ignored as required by the XML recommendation). This may be + ``None`` if the information is not provided by the parser, or if no notations + are defined. + + +.. _dom-document-objects: + +Document Objects +^^^^^^^^^^^^^^^^ + +A :class:`Document` represents an entire XML document, including its constituent +elements, attributes, processing instructions, comments etc. Remember that it +inherits properties from :class:`Node`. + + +.. attribute:: Document.documentElement + + The one and only root element of the document. + + +.. method:: Document.createElement(tagName) + + Create and return a new element node. The element is not inserted into the + document when it is created. You need to explicitly insert it with one of the + other methods such as :meth:`insertBefore` or :meth:`appendChild`. + + +.. method:: Document.createElementNS(namespaceURI, tagName) + + Create and return a new element with a namespace. The *tagName* may have a + prefix. The element is not inserted into the document when it is created. You + need to explicitly insert it with one of the other methods such as + :meth:`insertBefore` or :meth:`appendChild`. + + +.. method:: Document.createTextNode(data) + + Create and return a text node containing the data passed as a parameter. As + with the other creation methods, this one does not insert the node into the + tree. + + +.. method:: Document.createComment(data) + + Create and return a comment node containing the data passed as a parameter. As + with the other creation methods, this one does not insert the node into the + tree. + + +.. method:: Document.createProcessingInstruction(target, data) + + Create and return a processing instruction node containing the *target* and + *data* passed as parameters. As with the other creation methods, this one does + not insert the node into the tree. + + +.. method:: Document.createAttribute(name) + + Create and return an attribute node. This method does not associate the + attribute node with any particular element. You must use + :meth:`setAttributeNode` on the appropriate :class:`Element` object to use the + newly created attribute instance. + + +.. method:: Document.createAttributeNS(namespaceURI, qualifiedName) + + Create and return an attribute node with a namespace. The *tagName* may have a + prefix. This method does not associate the attribute node with any particular + element. You must use :meth:`setAttributeNode` on the appropriate + :class:`Element` object to use the newly created attribute instance. + + +.. method:: Document.getElementsByTagName(tagName) + + Search for all descendants (direct children, children's children, etc.) with a + particular element type name. + + +.. method:: Document.getElementsByTagNameNS(namespaceURI, localName) + + Search for all descendants (direct children, children's children, etc.) with a + particular namespace URI and localname. The localname is the part of the + namespace after the prefix. + + +.. _dom-element-objects: + +Element Objects +^^^^^^^^^^^^^^^ + +:class:`Element` is a subclass of :class:`Node`, so inherits all the attributes +of that class. + + +.. attribute:: Element.tagName + + The element type name. In a namespace-using document it may have colons in it. + The value is a string. + + +.. method:: Element.getElementsByTagName(tagName) + + Same as equivalent method in the :class:`Document` class. + + +.. method:: Element.getElementsByTagNameNS(namespaceURI, localName) + + Same as equivalent method in the :class:`Document` class. + + +.. method:: Element.hasAttribute(name) + + Return ``True`` if the element has an attribute named by *name*. + + +.. method:: Element.hasAttributeNS(namespaceURI, localName) + + Return ``True`` if the element has an attribute named by *namespaceURI* and + *localName*. + + +.. method:: Element.getAttribute(name) + + Return the value of the attribute named by *name* as a string. If no such + attribute exists, an empty string is returned, as if the attribute had no value. + + +.. method:: Element.getAttributeNode(attrname) + + Return the :class:`Attr` node for the attribute named by *attrname*. + + +.. method:: Element.getAttributeNS(namespaceURI, localName) + + Return the value of the attribute named by *namespaceURI* and *localName* as a + string. If no such attribute exists, an empty string is returned, as if the + attribute had no value. + + +.. method:: Element.getAttributeNodeNS(namespaceURI, localName) + + Return an attribute value as a node, given a *namespaceURI* and *localName*. + + +.. method:: Element.removeAttribute(name) + + Remove an attribute by name. If there is no matching attribute, a + :exc:`NotFoundErr` is raised. + + +.. method:: Element.removeAttributeNode(oldAttr) + + Remove and return *oldAttr* from the attribute list, if present. If *oldAttr* is + not present, :exc:`NotFoundErr` is raised. + + +.. method:: Element.removeAttributeNS(namespaceURI, localName) + + Remove an attribute by name. Note that it uses a localName, not a qname. No + exception is raised if there is no matching attribute. + + +.. method:: Element.setAttribute(name, value) + + Set an attribute value from a string. + + +.. method:: Element.setAttributeNode(newAttr) + + Add a new attribute node to the element, replacing an existing attribute if + necessary if the :attr:`name` attribute matches. If a replacement occurs, the + old attribute node will be returned. If *newAttr* is already in use, + :exc:`InuseAttributeErr` will be raised. + + +.. method:: Element.setAttributeNodeNS(newAttr) + + Add a new attribute node to the element, replacing an existing attribute if + necessary if the :attr:`namespaceURI` and :attr:`localName` attributes match. + If a replacement occurs, the old attribute node will be returned. If *newAttr* + is already in use, :exc:`InuseAttributeErr` will be raised. + + +.. method:: Element.setAttributeNS(namespaceURI, qname, value) + + Set an attribute value from a string, given a *namespaceURI* and a *qname*. + Note that a qname is the whole attribute name. This is different than above. + + +.. _dom-attr-objects: + +Attr Objects +^^^^^^^^^^^^ + +:class:`Attr` inherits from :class:`Node`, so inherits all its attributes. + + +.. attribute:: Attr.name + + The attribute name. + In a namespace-using document it may include a colon. + + +.. attribute:: Attr.localName + + The part of the name following the colon if there is one, else the + entire name. + This is a read-only attribute. + + +.. attribute:: Attr.prefix + + The part of the name preceding the colon if there is one, else the + empty string. + + +.. attribute:: Attr.value + + The text value of the attribute. This is a synonym for the + :attr:`nodeValue` attribute. + + +.. _dom-attributelist-objects: + +NamedNodeMap Objects +^^^^^^^^^^^^^^^^^^^^ + +:class:`NamedNodeMap` does *not* inherit from :class:`Node`. + + +.. attribute:: NamedNodeMap.length + + The length of the attribute list. + + +.. method:: NamedNodeMap.item(index) + + Return an attribute with a particular index. The order you get the attributes + in is arbitrary but will be consistent for the life of a DOM. Each item is an + attribute node. Get its value with the :attr:`value` attribute. + +There are also experimental methods that give this class more mapping behavior. +You can use them or you can use the standardized :meth:`getAttribute\*` family +of methods on the :class:`Element` objects. + + +.. _dom-comment-objects: + +Comment Objects +^^^^^^^^^^^^^^^ + +:class:`Comment` represents a comment in the XML document. It is a subclass of +:class:`Node`, but cannot have child nodes. + + +.. attribute:: Comment.data + + The content of the comment as a string. The attribute contains all characters + between the leading ````, but does not + include them. + + +.. _dom-text-objects: + +Text and CDATASection Objects +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The :class:`Text` interface represents text in the XML document. If the parser +and DOM implementation support the DOM's XML extension, portions of the text +enclosed in CDATA marked sections are stored in :class:`CDATASection` objects. +These two interfaces are identical, but provide different values for the +:attr:`nodeType` attribute. + +These interfaces extend the :class:`Node` interface. They cannot have child +nodes. + + +.. attribute:: Text.data + + The content of the text node as a string. + +.. note:: + + The use of a :class:`CDATASection` node does not indicate that the node + represents a complete CDATA marked section, only that the content of the node + was part of a CDATA section. A single CDATA section may be represented by more + than one node in the document tree. There is no way to determine whether two + adjacent :class:`CDATASection` nodes represent different CDATA marked sections. + + +.. _dom-pi-objects: + +ProcessingInstruction Objects +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Represents a processing instruction in the XML document; this inherits from the +:class:`Node` interface and cannot have child nodes. + + +.. attribute:: ProcessingInstruction.target + + The content of the processing instruction up to the first whitespace character. + This is a read-only attribute. + + +.. attribute:: ProcessingInstruction.data + + The content of the processing instruction following the first whitespace + character. + + +.. _dom-exceptions: + +Exceptions +^^^^^^^^^^ + +The DOM Level 2 recommendation defines a single exception, :exc:`DOMException`, +and a number of constants that allow applications to determine what sort of +error occurred. :exc:`DOMException` instances carry a :attr:`code` attribute +that provides the appropriate value for the specific exception. + +The Python DOM interface provides the constants, but also expands the set of +exceptions so that a specific exception exists for each of the exception codes +defined by the DOM. The implementations must raise the appropriate specific +exception, each of which carries the appropriate value for the :attr:`code` +attribute. + + +.. exception:: DOMException + + Base exception class used for all specific DOM exceptions. This exception class + cannot be directly instantiated. + + +.. exception:: DomstringSizeErr + + Raised when a specified range of text does not fit into a string. This is not + known to be used in the Python DOM implementations, but may be received from DOM + implementations not written in Python. + + +.. exception:: HierarchyRequestErr + + Raised when an attempt is made to insert a node where the node type is not + allowed. + + +.. exception:: IndexSizeErr + + Raised when an index or size parameter to a method is negative or exceeds the + allowed values. + + +.. exception:: InuseAttributeErr + + Raised when an attempt is made to insert an :class:`Attr` node that is already + present elsewhere in the document. + + +.. exception:: InvalidAccessErr + + Raised if a parameter or an operation is not supported on the underlying object. + + +.. exception:: InvalidCharacterErr + + This exception is raised when a string parameter contains a character that is + not permitted in the context it's being used in by the XML 1.0 recommendation. + For example, attempting to create an :class:`Element` node with a space in the + element type name will cause this error to be raised. + + +.. exception:: InvalidModificationErr + + Raised when an attempt is made to modify the type of a node. + + +.. exception:: InvalidStateErr + + Raised when an attempt is made to use an object that is not defined or is no + longer usable. + + +.. exception:: NamespaceErr + + If an attempt is made to change any object in a way that is not permitted with + regard to the `Namespaces in XML `_ + recommendation, this exception is raised. + + +.. exception:: NotFoundErr + + Exception when a node does not exist in the referenced context. For example, + :meth:`NamedNodeMap.removeNamedItem` will raise this if the node passed in does + not exist in the map. + + +.. exception:: NotSupportedErr + + Raised when the implementation does not support the requested type of object or + operation. + + +.. exception:: NoDataAllowedErr + + This is raised if data is specified for a node which does not support data. + + .. XXX a better explanation is needed! + + +.. exception:: NoModificationAllowedErr + + Raised on attempts to modify an object where modifications are not allowed (such + as for read-only nodes). + + +.. exception:: SyntaxErr + + Raised when an invalid or illegal string is specified. + + .. XXX how is this different from InvalidCharacterErr? + + +.. exception:: WrongDocumentErr + + Raised when a node is inserted in a different document than it currently belongs + to, and the implementation does not support migrating the node from one document + to the other. + +The exception codes defined in the DOM recommendation map to the exceptions +described above according to this table: + ++--------------------------------------+---------------------------------+ +| Constant | Exception | ++======================================+=================================+ +| :const:`DOMSTRING_SIZE_ERR` | :exc:`DomstringSizeErr` | ++--------------------------------------+---------------------------------+ +| :const:`HIERARCHY_REQUEST_ERR` | :exc:`HierarchyRequestErr` | ++--------------------------------------+---------------------------------+ +| :const:`INDEX_SIZE_ERR` | :exc:`IndexSizeErr` | ++--------------------------------------+---------------------------------+ +| :const:`INUSE_ATTRIBUTE_ERR` | :exc:`InuseAttributeErr` | ++--------------------------------------+---------------------------------+ +| :const:`INVALID_ACCESS_ERR` | :exc:`InvalidAccessErr` | ++--------------------------------------+---------------------------------+ +| :const:`INVALID_CHARACTER_ERR` | :exc:`InvalidCharacterErr` | ++--------------------------------------+---------------------------------+ +| :const:`INVALID_MODIFICATION_ERR` | :exc:`InvalidModificationErr` | ++--------------------------------------+---------------------------------+ +| :const:`INVALID_STATE_ERR` | :exc:`InvalidStateErr` | ++--------------------------------------+---------------------------------+ +| :const:`NAMESPACE_ERR` | :exc:`NamespaceErr` | ++--------------------------------------+---------------------------------+ +| :const:`NOT_FOUND_ERR` | :exc:`NotFoundErr` | ++--------------------------------------+---------------------------------+ +| :const:`NOT_SUPPORTED_ERR` | :exc:`NotSupportedErr` | ++--------------------------------------+---------------------------------+ +| :const:`NO_DATA_ALLOWED_ERR` | :exc:`NoDataAllowedErr` | ++--------------------------------------+---------------------------------+ +| :const:`NO_MODIFICATION_ALLOWED_ERR` | :exc:`NoModificationAllowedErr` | ++--------------------------------------+---------------------------------+ +| :const:`SYNTAX_ERR` | :exc:`SyntaxErr` | ++--------------------------------------+---------------------------------+ +| :const:`WRONG_DOCUMENT_ERR` | :exc:`WrongDocumentErr` | ++--------------------------------------+---------------------------------+ + + +.. _dom-conformance: + +Conformance +----------- + +This section describes the conformance requirements and relationships between +the Python DOM API, the W3C DOM recommendations, and the OMG IDL mapping for +Python. + + +.. _dom-type-mapping: + +Type Mapping +^^^^^^^^^^^^ + +The IDL types used in the DOM specification are mapped to Python types +according to the following table. + ++------------------+-------------------------------------------+ +| IDL Type | Python Type | ++==================+===========================================+ +| ``boolean`` | ``bool`` or ``int`` | ++------------------+-------------------------------------------+ +| ``int`` | ``int`` | ++------------------+-------------------------------------------+ +| ``long int`` | ``int`` | ++------------------+-------------------------------------------+ +| ``unsigned int`` | ``int`` | ++------------------+-------------------------------------------+ +| ``DOMString`` | ``str`` or ``bytes`` | ++------------------+-------------------------------------------+ +| ``null`` | ``None`` | ++------------------+-------------------------------------------+ + +.. _dom-accessor-methods: + +Accessor Methods +^^^^^^^^^^^^^^^^ + +The mapping from OMG IDL to Python defines accessor functions for IDL +``attribute`` declarations in much the way the Java mapping does. +Mapping the IDL declarations :: + + readonly attribute string someValue; + attribute string anotherValue; + +yields three accessor functions: a "get" method for :attr:`someValue` +(:meth:`_get_someValue`), and "get" and "set" methods for :attr:`anotherValue` +(:meth:`_get_anotherValue` and :meth:`_set_anotherValue`). The mapping, in +particular, does not require that the IDL attributes are accessible as normal +Python attributes: ``object.someValue`` is *not* required to work, and may +raise an :exc:`AttributeError`. + +The Python DOM API, however, *does* require that normal attribute access work. +This means that the typical surrogates generated by Python IDL compilers are not +likely to work, and wrapper objects may be needed on the client if the DOM +objects are accessed via CORBA. While this does require some additional +consideration for CORBA DOM clients, the implementers with experience using DOM +over CORBA from Python do not consider this a problem. Attributes that are +declared ``readonly`` may not restrict write access in all DOM +implementations. + +In the Python DOM API, accessor functions are not required. If provided, they +should take the form defined by the Python IDL mapping, but these methods are +considered unnecessary since the attributes are accessible directly from Python. +"Set" accessors should never be provided for ``readonly`` attributes. + +The IDL definitions do not fully embody the requirements of the W3C DOM API, +such as the notion of certain objects, such as the return value of +:meth:`getElementsByTagName`, being "live". The Python DOM API does not require +implementations to enforce such requirements. + diff --git a/cpython_2/environment/repo/Doc/library/xml.etree.elementtree.rst b/cpython_2/environment/repo/Doc/library/xml.etree.elementtree.rst new file mode 100644 index 0000000000000000000000000000000000000000..658bc3a54f86e560a0b6967567f0bc635ca0c5cb --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xml.etree.elementtree.rst @@ -0,0 +1,1471 @@ +:mod:`xml.etree.ElementTree` --- The ElementTree XML API +======================================================== + +.. module:: xml.etree.ElementTree + :synopsis: Implementation of the ElementTree API. + +.. moduleauthor:: Fredrik Lundh + +**Source code:** :source:`Lib/xml/etree/ElementTree.py` + +-------------- + +The :mod:`xml.etree.ElementTree` module implements a simple and efficient API +for parsing and creating XML data. + +.. versionchanged:: 3.3 + This module will use a fast implementation whenever available. + The :mod:`xml.etree.cElementTree` module is deprecated. + + +.. warning:: + + The :mod:`xml.etree.ElementTree` module is not secure against + maliciously constructed data. If you need to parse untrusted or + unauthenticated data see :ref:`xml-vulnerabilities`. + +Tutorial +-------- + +This is a short tutorial for using :mod:`xml.etree.ElementTree` (``ET`` in +short). The goal is to demonstrate some of the building blocks and basic +concepts of the module. + +XML tree and elements +^^^^^^^^^^^^^^^^^^^^^ + +XML is an inherently hierarchical data format, and the most natural way to +represent it is with a tree. ``ET`` has two classes for this purpose - +:class:`ElementTree` represents the whole XML document as a tree, and +:class:`Element` represents a single node in this tree. Interactions with +the whole document (reading and writing to/from files) are usually done +on the :class:`ElementTree` level. Interactions with a single XML element +and its sub-elements are done on the :class:`Element` level. + +.. _elementtree-parsing-xml: + +Parsing XML +^^^^^^^^^^^ + +We'll be using the following XML document as the sample data for this section: + +.. code-block:: xml + + + + + 1 + 2008 + 141100 + + + + + 4 + 2011 + 59900 + + + + 68 + 2011 + 13600 + + + + + +We can import this data by reading from a file:: + + import xml.etree.ElementTree as ET + tree = ET.parse('country_data.xml') + root = tree.getroot() + +Or directly from a string:: + + root = ET.fromstring(country_data_as_string) + +:func:`fromstring` parses XML from a string directly into an :class:`Element`, +which is the root element of the parsed tree. Other parsing functions may +create an :class:`ElementTree`. Check the documentation to be sure. + +As an :class:`Element`, ``root`` has a tag and a dictionary of attributes:: + + >>> root.tag + 'data' + >>> root.attrib + {} + +It also has children nodes over which we can iterate:: + + >>> for child in root: + ... print(child.tag, child.attrib) + ... + country {'name': 'Liechtenstein'} + country {'name': 'Singapore'} + country {'name': 'Panama'} + +Children are nested, and we can access specific child nodes by index:: + + >>> root[0][1].text + '2008' + + +.. note:: + + Not all elements of the XML input will end up as elements of the + parsed tree. Currently, this module skips over any XML comments, + processing instructions, and document type declarations in the + input. Nevertheless, trees built using this module's API rather + than parsing from XML text can have comments and processing + instructions in them; they will be included when generating XML + output. A document type declaration may be accessed by passing a + custom :class:`TreeBuilder` instance to the :class:`XMLParser` + constructor. + + +.. _elementtree-pull-parsing: + +Pull API for non-blocking parsing +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Most parsing functions provided by this module require the whole document +to be read at once before returning any result. It is possible to use an +:class:`XMLParser` and feed data into it incrementally, but it is a push API that +calls methods on a callback target, which is too low-level and inconvenient for +most needs. Sometimes what the user really wants is to be able to parse XML +incrementally, without blocking operations, while enjoying the convenience of +fully constructed :class:`Element` objects. + +The most powerful tool for doing this is :class:`XMLPullParser`. It does not +require a blocking read to obtain the XML data, and is instead fed with data +incrementally with :meth:`XMLPullParser.feed` calls. To get the parsed XML +elements, call :meth:`XMLPullParser.read_events`. Here is an example:: + + >>> parser = ET.XMLPullParser(['start', 'end']) + >>> parser.feed('sometext') + >>> list(parser.read_events()) + [('start', )] + >>> parser.feed(' more text') + >>> for event, elem in parser.read_events(): + ... print(event) + ... print(elem.tag, 'text=', elem.text) + ... + end + +The obvious use case is applications that operate in a non-blocking fashion +where the XML data is being received from a socket or read incrementally from +some storage device. In such cases, blocking reads are unacceptable. + +Because it's so flexible, :class:`XMLPullParser` can be inconvenient to use for +simpler use-cases. If you don't mind your application blocking on reading XML +data but would still like to have incremental parsing capabilities, take a look +at :func:`iterparse`. It can be useful when you're reading a large XML document +and don't want to hold it wholly in memory. + +Finding interesting elements +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:class:`Element` has some useful methods that help iterate recursively over all +the sub-tree below it (its children, their children, and so on). For example, +:meth:`Element.iter`:: + + >>> for neighbor in root.iter('neighbor'): + ... print(neighbor.attrib) + ... + {'name': 'Austria', 'direction': 'E'} + {'name': 'Switzerland', 'direction': 'W'} + {'name': 'Malaysia', 'direction': 'N'} + {'name': 'Costa Rica', 'direction': 'W'} + {'name': 'Colombia', 'direction': 'E'} + +:meth:`Element.findall` finds only elements with a tag which are direct +children of the current element. :meth:`Element.find` finds the *first* child +with a particular tag, and :attr:`Element.text` accesses the element's text +content. :meth:`Element.get` accesses the element's attributes:: + + >>> for country in root.findall('country'): + ... rank = country.find('rank').text + ... name = country.get('name') + ... print(name, rank) + ... + Liechtenstein 1 + Singapore 4 + Panama 68 + +More sophisticated specification of which elements to look for is possible by +using :ref:`XPath `. + +Modifying an XML File +^^^^^^^^^^^^^^^^^^^^^ + +:class:`ElementTree` provides a simple way to build XML documents and write them to files. +The :meth:`ElementTree.write` method serves this purpose. + +Once created, an :class:`Element` object may be manipulated by directly changing +its fields (such as :attr:`Element.text`), adding and modifying attributes +(:meth:`Element.set` method), as well as adding new children (for example +with :meth:`Element.append`). + +Let's say we want to add one to each country's rank, and add an ``updated`` +attribute to the rank element:: + + >>> for rank in root.iter('rank'): + ... new_rank = int(rank.text) + 1 + ... rank.text = str(new_rank) + ... rank.set('updated', 'yes') + ... + >>> tree.write('output.xml') + +Our XML now looks like this: + +.. code-block:: xml + + + + + 2 + 2008 + 141100 + + + + + 5 + 2011 + 59900 + + + + 69 + 2011 + 13600 + + + + + +We can remove elements using :meth:`Element.remove`. Let's say we want to +remove all countries with a rank higher than 50:: + + >>> for country in root.findall('country'): + ... rank = int(country.find('rank').text) + ... if rank > 50: + ... root.remove(country) + ... + >>> tree.write('output.xml') + +Our XML now looks like this: + +.. code-block:: xml + + + + + 2 + 2008 + 141100 + + + + + 5 + 2011 + 59900 + + + + +Building XML documents +^^^^^^^^^^^^^^^^^^^^^^ + +The :func:`SubElement` function also provides a convenient way to create new +sub-elements for a given element:: + + >>> a = ET.Element('a') + >>> b = ET.SubElement(a, 'b') + >>> c = ET.SubElement(a, 'c') + >>> d = ET.SubElement(c, 'd') + >>> ET.dump(a) +
+ +Parsing XML with Namespaces +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If the XML input has `namespaces +`__, tags and attributes +with prefixes in the form ``prefix:sometag`` get expanded to +``{uri}sometag`` where the *prefix* is replaced by the full *URI*. +Also, if there is a `default namespace +`__, +that full URI gets prepended to all of the non-prefixed tags. + +Here is an XML example that incorporates two namespaces, one with the +prefix "fictional" and the other serving as the default namespace: + +.. code-block:: xml + + + + + John Cleese + Lancelot + Archie Leach + + + Eric Idle + Sir Robin + Gunther + Commander Clement + + + +One way to search and explore this XML example is to manually add the +URI to every tag or attribute in the xpath of a +:meth:`~Element.find` or :meth:`~Element.findall`:: + + root = fromstring(xml_text) + for actor in root.findall('{http://people.example.com}actor'): + name = actor.find('{http://people.example.com}name') + print(name.text) + for char in actor.findall('{http://characters.example.com}character'): + print(' |-->', char.text) + +A better way to search the namespaced XML example is to create a +dictionary with your own prefixes and use those in the search functions:: + + ns = {'real_person': 'http://people.example.com', + 'role': 'http://characters.example.com'} + + for actor in root.findall('real_person:actor', ns): + name = actor.find('real_person:name', ns) + print(name.text) + for char in actor.findall('role:character', ns): + print(' |-->', char.text) + +These two approaches both output:: + + John Cleese + |--> Lancelot + |--> Archie Leach + Eric Idle + |--> Sir Robin + |--> Gunther + |--> Commander Clement + + +Additional resources +^^^^^^^^^^^^^^^^^^^^ + +See http://effbot.org/zone/element-index.htm for tutorials and links to other +docs. + + +.. _elementtree-xpath: + +XPath support +------------- + +This module provides limited support for +`XPath expressions `_ for locating elements in a +tree. The goal is to support a small subset of the abbreviated syntax; a full +XPath engine is outside the scope of the module. + +Example +^^^^^^^ + +Here's an example that demonstrates some of the XPath capabilities of the +module. We'll be using the ``countrydata`` XML document from the +:ref:`Parsing XML ` section:: + + import xml.etree.ElementTree as ET + + root = ET.fromstring(countrydata) + + # Top-level elements + root.findall(".") + + # All 'neighbor' grand-children of 'country' children of the top-level + # elements + root.findall("./country/neighbor") + + # Nodes with name='Singapore' that have a 'year' child + root.findall(".//year/..[@name='Singapore']") + + # 'year' nodes that are children of nodes with name='Singapore' + root.findall(".//*[@name='Singapore']/year") + + # All 'neighbor' nodes that are the second child of their parent + root.findall(".//neighbor[2]") + +For XML with namespaces, use the usual qualified ``{namespace}tag`` notation:: + + # All dublin-core "title" tags in the document + root.findall(".//{http://purl.org/dc/elements/1.1/}title") + + +Supported XPath syntax +^^^^^^^^^^^^^^^^^^^^^^ + +.. tabularcolumns:: |l|L| + ++-----------------------+------------------------------------------------------+ +| Syntax | Meaning | ++=======================+======================================================+ +| ``tag`` | Selects all child elements with the given tag. | +| | For example, ``spam`` selects all child elements | +| | named ``spam``, and ``spam/egg`` selects all | +| | grandchildren named ``egg`` in all children named | +| | ``spam``. ``{namespace}*`` selects all tags in the | +| | given namespace, ``{*}spam`` selects tags named | +| | ``spam`` in any (or no) namespace, and ``{}*`` | +| | only selects tags that are not in a namespace. | +| | | +| | .. versionchanged:: 3.8 | +| | Support for star-wildcards was added. | ++-----------------------+------------------------------------------------------+ +| ``*`` | Selects all child elements, including comments and | +| | processing instructions. For example, ``*/egg`` | +| | selects all grandchildren named ``egg``. | ++-----------------------+------------------------------------------------------+ +| ``.`` | Selects the current node. This is mostly useful | +| | at the beginning of the path, to indicate that it's | +| | a relative path. | ++-----------------------+------------------------------------------------------+ +| ``//`` | Selects all subelements, on all levels beneath the | +| | current element. For example, ``.//egg`` selects | +| | all ``egg`` elements in the entire tree. | ++-----------------------+------------------------------------------------------+ +| ``..`` | Selects the parent element. Returns ``None`` if the | +| | path attempts to reach the ancestors of the start | +| | element (the element ``find`` was called on). | ++-----------------------+------------------------------------------------------+ +| ``[@attrib]`` | Selects all elements that have the given attribute. | ++-----------------------+------------------------------------------------------+ +| ``[@attrib='value']`` | Selects all elements for which the given attribute | +| | has the given value. The value cannot contain | +| | quotes. | ++-----------------------+------------------------------------------------------+ +| ``[tag]`` | Selects all elements that have a child named | +| | ``tag``. Only immediate children are supported. | ++-----------------------+------------------------------------------------------+ +| ``[.='text']`` | Selects all elements whose complete text content, | +| | including descendants, equals the given ``text``. | +| | | +| | .. versionadded:: 3.7 | ++-----------------------+------------------------------------------------------+ +| ``[tag='text']`` | Selects all elements that have a child named | +| | ``tag`` whose complete text content, including | +| | descendants, equals the given ``text``. | ++-----------------------+------------------------------------------------------+ +| ``[position]`` | Selects all elements that are located at the given | +| | position. The position can be either an integer | +| | (1 is the first position), the expression ``last()`` | +| | (for the last position), or a position relative to | +| | the last position (e.g. ``last()-1``). | ++-----------------------+------------------------------------------------------+ + +Predicates (expressions within square brackets) must be preceded by a tag +name, an asterisk, or another predicate. ``position`` predicates must be +preceded by a tag name. + +Reference +--------- + +.. _elementtree-functions: + +Functions +^^^^^^^^^ + +.. function:: canonicalize(xml_data=None, *, out=None, from_file=None, **options) + + `C14N 2.0 `_ transformation function. + + Canonicalization is a way to normalise XML output in a way that allows + byte-by-byte comparisons and digital signatures. It reduced the freedom + that XML serializers have and instead generates a more constrained XML + representation. The main restrictions regard the placement of namespace + declarations, the ordering of attributes, and ignorable whitespace. + + This function takes an XML data string (*xml_data*) or a file path or + file-like object (*from_file*) as input, converts it to the canonical + form, and writes it out using the *out* file(-like) object, if provided, + or returns it as a text string if not. The output file receives text, + not bytes. It should therefore be opened in text mode with ``utf-8`` + encoding. + + Typical uses:: + + xml_data = "..." + print(canonicalize(xml_data)) + + with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file: + canonicalize(xml_data, out=out_file) + + with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file: + canonicalize(from_file="inputfile.xml", out=out_file) + + The configuration *options* are as follows: + + - *with_comments*: set to true to include comments (default: false) + - *strip_text*: set to true to strip whitespace before and after text content + (default: false) + - *rewrite_prefixes*: set to true to replace namespace prefixes by "n{number}" + (default: false) + - *qname_aware_tags*: a set of qname aware tag names in which prefixes + should be replaced in text content (default: empty) + - *qname_aware_attrs*: a set of qname aware attribute names in which prefixes + should be replaced in text content (default: empty) + - *exclude_attrs*: a set of attribute names that should not be serialised + - *exclude_tags*: a set of tag names that should not be serialised + + In the option list above, "a set" refers to any collection or iterable of + strings, no ordering is expected. + + .. versionadded:: 3.8 + + +.. function:: Comment(text=None) + + Comment element factory. This factory function creates a special element + that will be serialized as an XML comment by the standard serializer. The + comment string can be either a bytestring or a Unicode string. *text* is a + string containing the comment string. Returns an element instance + representing a comment. + + Note that :class:`XMLParser` skips over comments in the input + instead of creating comment objects for them. An :class:`ElementTree` will + only contain comment nodes if they have been inserted into to + the tree using one of the :class:`Element` methods. + +.. function:: dump(elem) + + Writes an element tree or element structure to sys.stdout. This function + should be used for debugging only. + + The exact output format is implementation dependent. In this version, it's + written as an ordinary XML file. + + *elem* is an element tree or an individual element. + + .. versionchanged:: 3.8 + The :func:`dump` function now preserves the attribute order specified + by the user. + + +.. function:: fromstring(text, parser=None) + + Parses an XML section from a string constant. Same as :func:`XML`. *text* + is a string containing XML data. *parser* is an optional parser instance. + If not given, the standard :class:`XMLParser` parser is used. + Returns an :class:`Element` instance. + + +.. function:: fromstringlist(sequence, parser=None) + + Parses an XML document from a sequence of string fragments. *sequence* is a + list or other sequence containing XML data fragments. *parser* is an + optional parser instance. If not given, the standard :class:`XMLParser` + parser is used. Returns an :class:`Element` instance. + + .. versionadded:: 3.2 + + +.. function:: indent(tree, space=" ", level=0) + + Appends whitespace to the subtree to indent the tree visually. + This can be used to generate pretty-printed XML output. + *tree* can be an Element or ElementTree. *space* is the whitespace + string that will be inserted for each indentation level, two space + characters by default. For indenting partial subtrees inside of an + already indented tree, pass the initial indentation level as *level*. + + .. versionadded:: 3.9 + + +.. function:: iselement(element) + + Check if an object appears to be a valid element object. *element* is an + element instance. Return ``True`` if this is an element object. + + +.. function:: iterparse(source, events=None, parser=None) + + Parses an XML section into an element tree incrementally, and reports what's + going on to the user. *source* is a filename or :term:`file object` + containing XML data. *events* is a sequence of events to report back. The + supported events are the strings ``"start"``, ``"end"``, ``"comment"``, + ``"pi"``, ``"start-ns"`` and ``"end-ns"`` + (the "ns" events are used to get detailed namespace + information). If *events* is omitted, only ``"end"`` events are reported. + *parser* is an optional parser instance. If not given, the standard + :class:`XMLParser` parser is used. *parser* must be a subclass of + :class:`XMLParser` and can only use the default :class:`TreeBuilder` as a + target. Returns an :term:`iterator` providing ``(event, elem)`` pairs. + + Note that while :func:`iterparse` builds the tree incrementally, it issues + blocking reads on *source* (or the file it names). As such, it's unsuitable + for applications where blocking reads can't be made. For fully non-blocking + parsing, see :class:`XMLPullParser`. + + .. note:: + + :func:`iterparse` only guarantees that it has seen the ">" character of a + starting tag when it emits a "start" event, so the attributes are defined, + but the contents of the text and tail attributes are undefined at that + point. The same applies to the element children; they may or may not be + present. + + If you need a fully populated element, look for "end" events instead. + + .. deprecated:: 3.4 + The *parser* argument. + + .. versionchanged:: 3.8 + The ``comment`` and ``pi`` events were added. + + +.. function:: parse(source, parser=None) + + Parses an XML section into an element tree. *source* is a filename or file + object containing XML data. *parser* is an optional parser instance. If + not given, the standard :class:`XMLParser` parser is used. Returns an + :class:`ElementTree` instance. + + +.. function:: ProcessingInstruction(target, text=None) + + PI element factory. This factory function creates a special element that + will be serialized as an XML processing instruction. *target* is a string + containing the PI target. *text* is a string containing the PI contents, if + given. Returns an element instance, representing a processing instruction. + + Note that :class:`XMLParser` skips over processing instructions + in the input instead of creating comment objects for them. An + :class:`ElementTree` will only contain processing instruction nodes if + they have been inserted into to the tree using one of the + :class:`Element` methods. + +.. function:: register_namespace(prefix, uri) + + Registers a namespace prefix. The registry is global, and any existing + mapping for either the given prefix or the namespace URI will be removed. + *prefix* is a namespace prefix. *uri* is a namespace uri. Tags and + attributes in this namespace will be serialized with the given prefix, if at + all possible. + + .. versionadded:: 3.2 + + +.. function:: SubElement(parent, tag, attrib={}, **extra) + + Subelement factory. This function creates an element instance, and appends + it to an existing element. + + The element name, attribute names, and attribute values can be either + bytestrings or Unicode strings. *parent* is the parent element. *tag* is + the subelement name. *attrib* is an optional dictionary, containing element + attributes. *extra* contains additional attributes, given as keyword + arguments. Returns an element instance. + + +.. function:: tostring(element, encoding="us-ascii", method="xml", *, \ + xml_declaration=None, default_namespace=None, \ + short_empty_elements=True) + + Generates a string representation of an XML element, including all + subelements. *element* is an :class:`Element` instance. *encoding* [1]_ is + the output encoding (default is US-ASCII). Use ``encoding="unicode"`` to + generate a Unicode string (otherwise, a bytestring is generated). *method* + is either ``"xml"``, ``"html"`` or ``"text"`` (default is ``"xml"``). + *xml_declaration*, *default_namespace* and *short_empty_elements* has the same + meaning as in :meth:`ElementTree.write`. Returns an (optionally) encoded string + containing the XML data. + + .. versionadded:: 3.4 + The *short_empty_elements* parameter. + + .. versionadded:: 3.8 + The *xml_declaration* and *default_namespace* parameters. + + .. versionchanged:: 3.8 + The :func:`tostring` function now preserves the attribute order + specified by the user. + + +.. function:: tostringlist(element, encoding="us-ascii", method="xml", *, \ + xml_declaration=None, default_namespace=None, \ + short_empty_elements=True) + + Generates a string representation of an XML element, including all + subelements. *element* is an :class:`Element` instance. *encoding* [1]_ is + the output encoding (default is US-ASCII). Use ``encoding="unicode"`` to + generate a Unicode string (otherwise, a bytestring is generated). *method* + is either ``"xml"``, ``"html"`` or ``"text"`` (default is ``"xml"``). + *xml_declaration*, *default_namespace* and *short_empty_elements* has the same + meaning as in :meth:`ElementTree.write`. Returns a list of (optionally) encoded + strings containing the XML data. It does not guarantee any specific sequence, + except that ``b"".join(tostringlist(element)) == tostring(element)``. + + .. versionadded:: 3.2 + + .. versionadded:: 3.4 + The *short_empty_elements* parameter. + + .. versionadded:: 3.8 + The *xml_declaration* and *default_namespace* parameters. + + .. versionchanged:: 3.8 + The :func:`tostringlist` function now preserves the attribute order + specified by the user. + + +.. function:: XML(text, parser=None) + + Parses an XML section from a string constant. This function can be used to + embed "XML literals" in Python code. *text* is a string containing XML + data. *parser* is an optional parser instance. If not given, the standard + :class:`XMLParser` parser is used. Returns an :class:`Element` instance. + + +.. function:: XMLID(text, parser=None) + + Parses an XML section from a string constant, and also returns a dictionary + which maps from element id:s to elements. *text* is a string containing XML + data. *parser* is an optional parser instance. If not given, the standard + :class:`XMLParser` parser is used. Returns a tuple containing an + :class:`Element` instance and a dictionary. + + +.. _elementtree-xinclude: + +XInclude support +---------------- + +This module provides limited support for +`XInclude directives `_, via the :mod:`xml.etree.ElementInclude` helper module. This module can be used to insert subtrees and text strings into element trees, based on information in the tree. + +Example +^^^^^^^ + +Here's an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the ``{http://www.w3.org/2001/XInclude}include`` element and set the **parse** attribute to ``"xml"``, and use the **href** attribute to specify the document to include. + +.. code-block:: xml + + + + + + +By default, the **href** attribute is treated as a file name. You can use custom loaders to override this behaviour. Also note that the standard helper does not support XPointer syntax. + +To process this file, load it as usual, and pass the root element to the :mod:`xml.etree.ElementTree` module: + +.. code-block:: python + + from xml.etree import ElementTree, ElementInclude + + tree = ElementTree.parse("document.xml") + root = tree.getroot() + + ElementInclude.include(root) + +The ElementInclude module replaces the ``{http://www.w3.org/2001/XInclude}include`` element with the root element from the **source.xml** document. The result might look something like this: + +.. code-block:: xml + + + This is a paragraph. + + +If the **parse** attribute is omitted, it defaults to "xml". The href attribute is required. + +To include a text document, use the ``{http://www.w3.org/2001/XInclude}include`` element, and set the **parse** attribute to "text": + +.. code-block:: xml + + + + Copyright (c) . + + +The result might look something like: + +.. code-block:: xml + + + Copyright (c) 2003. + + +Reference +--------- + +.. _elementinclude-functions: + +Functions +^^^^^^^^^ + +.. function:: xml.etree.ElementInclude.default_loader( href, parse, encoding=None) + + Default loader. This default loader reads an included resource from disk. *href* is a URL. + *parse* is for parse mode either "xml" or "text". *encoding* + is an optional text encoding. If not given, encoding is ``utf-8``. Returns the + expanded resource. If the parse mode is ``"xml"``, this is an ElementTree + instance. If the parse mode is "text", this is a Unicode string. If the + loader fails, it can return None or raise an exception. + + +.. function:: xml.etree.ElementInclude.include( elem, loader=None) + + This function expands XInclude directives. *elem* is the root element. *loader* is + an optional resource loader. If omitted, it defaults to :func:`default_loader`. + If given, it should be a callable that implements the same interface as + :func:`default_loader`. Returns the expanded resource. If the parse mode is + ``"xml"``, this is an ElementTree instance. If the parse mode is "text", + this is a Unicode string. If the loader fails, it can return None or + raise an exception. + + +.. _elementtree-element-objects: + +Element Objects +^^^^^^^^^^^^^^^ + +.. class:: Element(tag, attrib={}, **extra) + + Element class. This class defines the Element interface, and provides a + reference implementation of this interface. + + The element name, attribute names, and attribute values can be either + bytestrings or Unicode strings. *tag* is the element name. *attrib* is + an optional dictionary, containing element attributes. *extra* contains + additional attributes, given as keyword arguments. + + + .. attribute:: tag + + A string identifying what kind of data this element represents (the + element type, in other words). + + + .. attribute:: text + tail + + These attributes can be used to hold additional data associated with + the element. Their values are usually strings but may be any + application-specific object. If the element is created from + an XML file, the *text* attribute holds either the text between + the element's start tag and its first child or end tag, or ``None``, and + the *tail* attribute holds either the text between the element's + end tag and the next tag, or ``None``. For the XML data + + .. code-block:: xml + + 1234 + + the *a* element has ``None`` for both *text* and *tail* attributes, + the *b* element has *text* ``"1"`` and *tail* ``"4"``, + the *c* element has *text* ``"2"`` and *tail* ``None``, + and the *d* element has *text* ``None`` and *tail* ``"3"``. + + To collect the inner text of an element, see :meth:`itertext`, for + example ``"".join(element.itertext())``. + + Applications may store arbitrary objects in these attributes. + + + .. attribute:: attrib + + A dictionary containing the element's attributes. Note that while the + *attrib* value is always a real mutable Python dictionary, an ElementTree + implementation may choose to use another internal representation, and + create the dictionary only if someone asks for it. To take advantage of + such implementations, use the dictionary methods below whenever possible. + + The following dictionary-like methods work on the element attributes. + + + .. method:: clear() + + Resets an element. This function removes all subelements, clears all + attributes, and sets the text and tail attributes to ``None``. + + + .. method:: get(key, default=None) + + Gets the element attribute named *key*. + + Returns the attribute value, or *default* if the attribute was not found. + + + .. method:: items() + + Returns the element attributes as a sequence of (name, value) pairs. The + attributes are returned in an arbitrary order. + + + .. method:: keys() + + Returns the elements attribute names as a list. The names are returned + in an arbitrary order. + + + .. method:: set(key, value) + + Set the attribute *key* on the element to *value*. + + The following methods work on the element's children (subelements). + + + .. method:: append(subelement) + + Adds the element *subelement* to the end of this element's internal list + of subelements. Raises :exc:`TypeError` if *subelement* is not an + :class:`Element`. + + + .. method:: extend(subelements) + + Appends *subelements* from a sequence object with zero or more elements. + Raises :exc:`TypeError` if a subelement is not an :class:`Element`. + + .. versionadded:: 3.2 + + + .. method:: find(match, namespaces=None) + + Finds the first subelement matching *match*. *match* may be a tag name + or a :ref:`path `. Returns an element instance + or ``None``. *namespaces* is an optional mapping from namespace prefix + to full name. Pass ``''`` as prefix to move all unprefixed tag names + in the expression into the given namespace. + + + .. method:: findall(match, namespaces=None) + + Finds all matching subelements, by tag name or + :ref:`path `. Returns a list containing all matching + elements in document order. *namespaces* is an optional mapping from + namespace prefix to full name. Pass ``''`` as prefix to move all + unprefixed tag names in the expression into the given namespace. + + + .. method:: findtext(match, default=None, namespaces=None) + + Finds text for the first subelement matching *match*. *match* may be + a tag name or a :ref:`path `. Returns the text content + of the first matching element, or *default* if no element was found. + Note that if the matching element has no text content an empty string + is returned. *namespaces* is an optional mapping from namespace prefix + to full name. Pass ``''`` as prefix to move all unprefixed tag names + in the expression into the given namespace. + + + .. method:: insert(index, subelement) + + Inserts *subelement* at the given position in this element. Raises + :exc:`TypeError` if *subelement* is not an :class:`Element`. + + + .. method:: iter(tag=None) + + Creates a tree :term:`iterator` with the current element as the root. + The iterator iterates over this element and all elements below it, in + document (depth first) order. If *tag* is not ``None`` or ``'*'``, only + elements whose tag equals *tag* are returned from the iterator. If the + tree structure is modified during iteration, the result is undefined. + + .. versionadded:: 3.2 + + + .. method:: iterfind(match, namespaces=None) + + Finds all matching subelements, by tag name or + :ref:`path `. Returns an iterable yielding all + matching elements in document order. *namespaces* is an optional mapping + from namespace prefix to full name. + + + .. versionadded:: 3.2 + + + .. method:: itertext() + + Creates a text iterator. The iterator loops over this element and all + subelements, in document order, and returns all inner text. + + .. versionadded:: 3.2 + + + .. method:: makeelement(tag, attrib) + + Creates a new element object of the same type as this element. Do not + call this method, use the :func:`SubElement` factory function instead. + + + .. method:: remove(subelement) + + Removes *subelement* from the element. Unlike the find\* methods this + method compares elements based on the instance identity, not on tag value + or contents. + + :class:`Element` objects also support the following sequence type methods + for working with subelements: :meth:`~object.__delitem__`, + :meth:`~object.__getitem__`, :meth:`~object.__setitem__`, + :meth:`~object.__len__`. + + Caution: Elements with no subelements will test as ``False``. This behavior + will change in future versions. Use specific ``len(elem)`` or ``elem is + None`` test instead. :: + + element = root.find('foo') + + if not element: # careful! + print("element not found, or element has no subelements") + + if element is None: + print("element not found") + + Prior to Python 3.8, the serialisation order of the XML attributes of + elements was artificially made predictable by sorting the attributes by + their name. Based on the now guaranteed ordering of dicts, this arbitrary + reordering was removed in Python 3.8 to preserve the order in which + attributes were originally parsed or created by user code. + + In general, user code should try not to depend on a specific ordering of + attributes, given that the `XML Information Set + `_ explicitly excludes the attribute + order from conveying information. Code should be prepared to deal with + any ordering on input. In cases where deterministic XML output is required, + e.g. for cryptographic signing or test data sets, canonical serialisation + is available with the :func:`canonicalize` function. + + In cases where canonical output is not applicable but a specific attribute + order is still desirable on output, code should aim for creating the + attributes directly in the desired order, to avoid perceptual mismatches + for readers of the code. In cases where this is difficult to achieve, a + recipe like the following can be applied prior to serialisation to enforce + an order independently from the Element creation:: + + def reorder_attributes(root): + for el in root.iter(): + attrib = el.attrib + if len(attrib) > 1: + # adjust attribute order, e.g. by sorting + attribs = sorted(attrib.items()) + attrib.clear() + attrib.update(attribs) + + +.. _elementtree-elementtree-objects: + +ElementTree Objects +^^^^^^^^^^^^^^^^^^^ + + +.. class:: ElementTree(element=None, file=None) + + ElementTree wrapper class. This class represents an entire element + hierarchy, and adds some extra support for serialization to and from + standard XML. + + *element* is the root element. The tree is initialized with the contents + of the XML *file* if given. + + + .. method:: _setroot(element) + + Replaces the root element for this tree. This discards the current + contents of the tree, and replaces it with the given element. Use with + care. *element* is an element instance. + + + .. method:: find(match, namespaces=None) + + Same as :meth:`Element.find`, starting at the root of the tree. + + + .. method:: findall(match, namespaces=None) + + Same as :meth:`Element.findall`, starting at the root of the tree. + + + .. method:: findtext(match, default=None, namespaces=None) + + Same as :meth:`Element.findtext`, starting at the root of the tree. + + + .. method:: getroot() + + Returns the root element for this tree. + + + .. method:: iter(tag=None) + + Creates and returns a tree iterator for the root element. The iterator + loops over all elements in this tree, in section order. *tag* is the tag + to look for (default is to return all elements). + + + .. method:: iterfind(match, namespaces=None) + + Same as :meth:`Element.iterfind`, starting at the root of the tree. + + .. versionadded:: 3.2 + + + .. method:: parse(source, parser=None) + + Loads an external XML section into this element tree. *source* is a file + name or :term:`file object`. *parser* is an optional parser instance. + If not given, the standard :class:`XMLParser` parser is used. Returns the + section root element. + + + .. method:: write(file, encoding="us-ascii", xml_declaration=None, \ + default_namespace=None, method="xml", *, \ + short_empty_elements=True) + + Writes the element tree to a file, as XML. *file* is a file name, or a + :term:`file object` opened for writing. *encoding* [1]_ is the output + encoding (default is US-ASCII). + *xml_declaration* controls if an XML declaration should be added to the + file. Use ``False`` for never, ``True`` for always, ``None`` + for only if not US-ASCII or UTF-8 or Unicode (default is ``None``). + *default_namespace* sets the default XML namespace (for "xmlns"). + *method* is either ``"xml"``, ``"html"`` or ``"text"`` (default is + ``"xml"``). + The keyword-only *short_empty_elements* parameter controls the formatting + of elements that contain no content. If ``True`` (the default), they are + emitted as a single self-closed tag, otherwise they are emitted as a pair + of start/end tags. + + The output is either a string (:class:`str`) or binary (:class:`bytes`). + This is controlled by the *encoding* argument. If *encoding* is + ``"unicode"``, the output is a string; otherwise, it's binary. Note that + this may conflict with the type of *file* if it's an open + :term:`file object`; make sure you do not try to write a string to a + binary stream and vice versa. + + .. versionadded:: 3.4 + The *short_empty_elements* parameter. + + .. versionchanged:: 3.8 + The :meth:`write` method now preserves the attribute order specified + by the user. + + +This is the XML file that is going to be manipulated:: + + + + Example page + + +

Moved to example.org + or example.com.

+ + + +Example of changing the attribute "target" of every link in first paragraph:: + + >>> from xml.etree.ElementTree import ElementTree + >>> tree = ElementTree() + >>> tree.parse("index.xhtml") + + >>> p = tree.find("body/p") # Finds first occurrence of tag p in body + >>> p + + >>> links = list(p.iter("a")) # Returns list of all links + >>> links + [, ] + >>> for i in links: # Iterates through all found links + ... i.attrib["target"] = "blank" + >>> tree.write("output.xhtml") + +.. _elementtree-qname-objects: + +QName Objects +^^^^^^^^^^^^^ + + +.. class:: QName(text_or_uri, tag=None) + + QName wrapper. This can be used to wrap a QName attribute value, in order + to get proper namespace handling on output. *text_or_uri* is a string + containing the QName value, in the form {uri}local, or, if the tag argument + is given, the URI part of a QName. If *tag* is given, the first argument is + interpreted as a URI, and this argument is interpreted as a local name. + :class:`QName` instances are opaque. + + + +.. _elementtree-treebuilder-objects: + +TreeBuilder Objects +^^^^^^^^^^^^^^^^^^^ + + +.. class:: TreeBuilder(element_factory=None, *, comment_factory=None, \ + pi_factory=None, insert_comments=False, insert_pis=False) + + Generic element structure builder. This builder converts a sequence of + start, data, end, comment and pi method calls to a well-formed element + structure. You can use this class to build an element structure using + a custom XML parser, or a parser for some other XML-like format. + + *element_factory*, when given, must be a callable accepting two positional + arguments: a tag and a dict of attributes. It is expected to return a new + element instance. + + The *comment_factory* and *pi_factory* functions, when given, should behave + like the :func:`Comment` and :func:`ProcessingInstruction` functions to + create comments and processing instructions. When not given, the default + factories will be used. When *insert_comments* and/or *insert_pis* is true, + comments/pis will be inserted into the tree if they appear within the root + element (but not outside of it). + + .. method:: close() + + Flushes the builder buffers, and returns the toplevel document + element. Returns an :class:`Element` instance. + + + .. method:: data(data) + + Adds text to the current element. *data* is a string. This should be + either a bytestring, or a Unicode string. + + + .. method:: end(tag) + + Closes the current element. *tag* is the element name. Returns the + closed element. + + + .. method:: start(tag, attrs) + + Opens a new element. *tag* is the element name. *attrs* is a dictionary + containing element attributes. Returns the opened element. + + + .. method:: comment(text) + + Creates a comment with the given *text*. If ``insert_comments`` is true, + this will also add it to the tree. + + .. versionadded:: 3.8 + + + .. method:: pi(target, text) + + Creates a comment with the given *target* name and *text*. If + ``insert_pis`` is true, this will also add it to the tree. + + .. versionadded:: 3.8 + + + In addition, a custom :class:`TreeBuilder` object can provide the + following methods: + + .. method:: doctype(name, pubid, system) + + Handles a doctype declaration. *name* is the doctype name. *pubid* is + the public identifier. *system* is the system identifier. This method + does not exist on the default :class:`TreeBuilder` class. + + .. versionadded:: 3.2 + + .. method:: start_ns(prefix, uri) + + Is called whenever the parser encounters a new namespace declaration, + before the ``start()`` callback for the opening element that defines it. + *prefix* is ``''`` for the default namespace and the declared + namespace prefix name otherwise. *uri* is the namespace URI. + + .. versionadded:: 3.8 + + .. method:: end_ns(prefix) + + Is called after the ``end()`` callback of an element that declared + a namespace prefix mapping, with the name of the *prefix* that went + out of scope. + + .. versionadded:: 3.8 + + +.. class:: C14NWriterTarget(write, *, \ + with_comments=False, strip_text=False, rewrite_prefixes=False, \ + qname_aware_tags=None, qname_aware_attrs=None, \ + exclude_attrs=None, exclude_tags=None) + + A `C14N 2.0 `_ writer. Arguments are the + same as for the :func:`canonicalize` function. This class does not build a + tree but translates the callback events directly into a serialised form + using the *write* function. + + .. versionadded:: 3.8 + + +.. _elementtree-xmlparser-objects: + +XMLParser Objects +^^^^^^^^^^^^^^^^^ + + +.. class:: XMLParser(*, target=None, encoding=None) + + This class is the low-level building block of the module. It uses + :mod:`xml.parsers.expat` for efficient, event-based parsing of XML. It can + be fed XML data incrementally with the :meth:`feed` method, and parsing + events are translated to a push API - by invoking callbacks on the *target* + object. If *target* is omitted, the standard :class:`TreeBuilder` is used. + If *encoding* [1]_ is given, the value overrides the + encoding specified in the XML file. + + .. versionchanged:: 3.8 + Parameters are now :ref:`keyword-only `. + The *html* argument no longer supported. + + + .. method:: close() + + Finishes feeding data to the parser. Returns the result of calling the + ``close()`` method of the *target* passed during construction; by default, + this is the toplevel document element. + + + .. method:: feed(data) + + Feeds data to the parser. *data* is encoded data. + + :meth:`XMLParser.feed` calls *target*\'s ``start(tag, attrs_dict)`` method + for each opening tag, its ``end(tag)`` method for each closing tag, and data + is processed by method ``data(data)``. For further supported callback + methods, see the :class:`TreeBuilder` class. :meth:`XMLParser.close` calls + *target*\'s method ``close()``. :class:`XMLParser` 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 XMLParser + >>> class MaxDepth: # The target object of the parser + ... maxDepth = 0 + ... depth = 0 + ... def start(self, tag, attrib): # Called for each opening tag. + ... 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): + ... 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 = XMLParser(target=target) + >>> exampleXml = """ + ... + ... + ... + ... + ... + ... + ... + ... + ... + ... """ + >>> parser.feed(exampleXml) + >>> parser.close() + 4 + + +.. _elementtree-xmlpullparser-objects: + +XMLPullParser Objects +^^^^^^^^^^^^^^^^^^^^^ + +.. class:: XMLPullParser(events=None) + + A pull parser suitable for non-blocking applications. Its input-side API is + similar to that of :class:`XMLParser`, but instead of pushing calls to a + callback target, :class:`XMLPullParser` collects an internal list of parsing + events and lets the user read from it. *events* is a sequence of events to + report back. The supported events are the strings ``"start"``, ``"end"``, + ``"comment"``, ``"pi"``, ``"start-ns"`` and ``"end-ns"`` (the "ns" events + are used to get detailed namespace information). If *events* is omitted, + only ``"end"`` events are reported. + + .. method:: feed(data) + + Feed the given bytes data to the parser. + + .. method:: close() + + Signal the parser that the data stream is terminated. Unlike + :meth:`XMLParser.close`, this method always returns :const:`None`. + Any events not yet retrieved when the parser is closed can still be + read with :meth:`read_events`. + + .. method:: read_events() + + Return an iterator over the events which have been encountered in the + data fed to the + parser. The iterator yields ``(event, elem)`` pairs, where *event* is a + string representing the type of event (e.g. ``"end"``) and *elem* is the + encountered :class:`Element` object, or other context value as follows. + + * ``start``, ``end``: the current Element. + * ``comment``, ``pi``: the current comment / processing instruction + * ``start-ns``: a tuple ``(prefix, uri)`` naming the declared namespace + mapping. + * ``end-ns``: :const:`None` (this may change in a future version) + + Events provided in a previous call to :meth:`read_events` will not be + yielded again. Events are consumed from the internal queue only when + they are retrieved from the iterator, so multiple readers iterating in + parallel over iterators obtained from :meth:`read_events` will have + unpredictable results. + + .. note:: + + :class:`XMLPullParser` only guarantees that it has seen the ">" + character of a starting tag when it emits a "start" event, so the + attributes are defined, but the contents of the text and tail attributes + are undefined at that point. The same applies to the element children; + they may or may not be present. + + If you need a fully populated element, look for "end" events instead. + + .. versionadded:: 3.4 + + .. versionchanged:: 3.8 + The ``comment`` and ``pi`` events were added. + + +Exceptions +^^^^^^^^^^ + +.. class:: ParseError + + XML parse error, raised by the various parsing methods in this module when + parsing fails. The string representation of an instance of this exception + will contain a user-friendly error message. In addition, it will have + the following attributes available: + + .. attribute:: code + + A numeric error code from the expat parser. See the documentation of + :mod:`xml.parsers.expat` for the list of error codes and their meanings. + + .. attribute:: position + + A tuple of *line*, *column* numbers, specifying where the error occurred. + +.. rubric:: Footnotes + +.. [1] The encoding string included in XML output should conform to the + appropriate standards. For example, "UTF-8" is valid, but "UTF8" is + not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl + and https://www.iana.org/assignments/character-sets/character-sets.xhtml. diff --git a/cpython_2/environment/repo/Doc/library/xml.rst b/cpython_2/environment/repo/Doc/library/xml.rst new file mode 100644 index 0000000000000000000000000000000000000000..fb86b6f5564d7673ebedab8fcf788fe9a6ad7f33 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xml.rst @@ -0,0 +1,139 @@ +.. _xml: + +XML Processing Modules +====================== + +.. module:: xml + :synopsis: Package containing XML processing modules + +.. sectionauthor:: Christian Heimes +.. sectionauthor:: Georg Brandl + +**Source code:** :source:`Lib/xml/` + +-------------- + +Python's interfaces for processing XML are grouped in the ``xml`` package. + +.. warning:: + + The XML modules are not secure against erroneous or maliciously + constructed data. If you need to parse untrusted or + unauthenticated data see the :ref:`xml-vulnerabilities` and + :ref:`defused-packages` sections. + +It is important to note that modules in the :mod:`xml` package require that +there be at least one SAX-compliant XML parser available. The Expat parser is +included with Python, so the :mod:`xml.parsers.expat` module will always be +available. + +The documentation for the :mod:`xml.dom` and :mod:`xml.sax` packages are the +definition of the Python bindings for the DOM and SAX interfaces. + +The XML handling submodules are: + +* :mod:`xml.etree.ElementTree`: the ElementTree API, a simple and lightweight + XML processor + +.. + +* :mod:`xml.dom`: the DOM API definition +* :mod:`xml.dom.minidom`: a minimal DOM implementation +* :mod:`xml.dom.pulldom`: support for building partial DOM trees + +.. + +* :mod:`xml.sax`: SAX2 base classes and convenience functions +* :mod:`xml.parsers.expat`: the Expat parser binding + + +.. _xml-vulnerabilities: + +XML vulnerabilities +------------------- + +The XML processing modules are not secure against maliciously constructed data. +An attacker can abuse XML features to carry out denial of service attacks, +access local files, generate network connections to other machines, or +circumvent firewalls. + +The following table gives an overview of the known attacks and whether +the various modules are vulnerable to them. + +========================= ============== =============== ============== ============== ============== +kind sax etree minidom pulldom xmlrpc +========================= ============== =============== ============== ============== ============== +billion laughs **Vulnerable** **Vulnerable** **Vulnerable** **Vulnerable** **Vulnerable** +quadratic blowup **Vulnerable** **Vulnerable** **Vulnerable** **Vulnerable** **Vulnerable** +external entity expansion Safe (4) Safe (1) Safe (2) Safe (4) Safe (3) +`DTD`_ retrieval Safe (4) Safe Safe Safe (4) Safe +decompression bomb Safe Safe Safe Safe **Vulnerable** +========================= ============== =============== ============== ============== ============== + +1. :mod:`xml.etree.ElementTree` doesn't expand external entities and raises a + :exc:`ParserError` when an entity occurs. +2. :mod:`xml.dom.minidom` doesn't expand external entities and simply returns + the unexpanded entity verbatim. +3. :mod:`xmlrpclib` doesn't expand external entities and omits them. +4. Since Python 3.7.1, external general entities are no longer processed by + default. + + +billion laughs / exponential entity expansion + The `Billion Laughs`_ attack -- also known as exponential entity expansion -- + uses multiple levels of nested entities. Each entity refers to another entity + several times, and the final entity definition contains a small string. + The exponential expansion results in several gigabytes of text and + consumes lots of memory and CPU time. + +quadratic blowup entity expansion + A quadratic blowup attack is similar to a `Billion Laughs`_ attack; it abuses + entity expansion, too. Instead of nested entities it repeats one large entity + with a couple of thousand chars over and over again. The attack isn't as + efficient as the exponential case but it avoids triggering parser countermeasures + that forbid deeply-nested entities. + +external entity expansion + Entity declarations can contain more than just text for replacement. They can + also point to external resources or local files. The XML + parser accesses the resource and embeds the content into the XML document. + +`DTD`_ retrieval + Some XML libraries like Python's :mod:`xml.dom.pulldom` retrieve document type + definitions from remote or local locations. The feature has similar + implications as the external entity expansion issue. + +decompression bomb + Decompression bombs (aka `ZIP bomb`_) apply to all XML libraries + that can parse compressed XML streams such as gzipped HTTP streams or + LZMA-compressed + files. For an attacker it can reduce the amount of transmitted data by three + magnitudes or more. + +The documentation for `defusedxml`_ on PyPI has further information about +all known attack vectors with examples and references. + +.. _defused-packages: + +The :mod:`defusedxml` and :mod:`defusedexpat` Packages +------------------------------------------------------ + +`defusedxml`_ is a pure Python package with modified subclasses of all stdlib +XML parsers that prevent any potentially malicious operation. Use of this +package is recommended for any server code that parses untrusted XML data. The +package also ships with example exploits and extended documentation on more +XML exploits such as XPath injection. + +`defusedexpat`_ provides a modified libexpat and a patched +:mod:`pyexpat` module that have countermeasures against entity expansion +DoS attacks. The :mod:`defusedexpat` module still allows a sane and configurable amount of entity +expansions. The modifications may be included in some future release of Python, +but will not be included in any bugfix releases of +Python because they break backward compatibility. + + +.. _defusedxml: https://pypi.org/project/defusedxml/ +.. _defusedexpat: https://pypi.org/project/defusedexpat/ +.. _Billion Laughs: https://en.wikipedia.org/wiki/Billion_laughs +.. _ZIP bomb: https://en.wikipedia.org/wiki/Zip_bomb +.. _DTD: https://en.wikipedia.org/wiki/Document_type_definition diff --git a/cpython_2/environment/repo/Doc/library/xml.sax.handler.rst b/cpython_2/environment/repo/Doc/library/xml.sax.handler.rst new file mode 100644 index 0000000000000000000000000000000000000000..ae0877ca90db07b7dff8a38c8a408b6bbe3cd229 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xml.sax.handler.rst @@ -0,0 +1,415 @@ +:mod:`xml.sax.handler` --- Base classes for SAX handlers +======================================================== + +.. module:: xml.sax.handler + :synopsis: Base classes for SAX event handlers. + +.. moduleauthor:: Lars Marius Garshol +.. sectionauthor:: Martin v. Löwis + +**Source code:** :source:`Lib/xml/sax/handler.py` + +-------------- + +The SAX API defines four kinds of handlers: content handlers, DTD handlers, +error handlers, and entity resolvers. Applications normally only need to +implement those interfaces whose events they are interested in; they can +implement the interfaces in a single object or in multiple objects. Handler +implementations should inherit from the base classes provided in the module +:mod:`xml.sax.handler`, so that all methods get default implementations. + + +.. class:: ContentHandler + + This is the main callback interface in SAX, and the one most important to + applications. The order of events in this interface mirrors the order of the + information in the document. + + +.. class:: DTDHandler + + Handle DTD events. + + This interface specifies only those DTD events required for basic parsing + (unparsed entities and attributes). + + +.. class:: EntityResolver + + Basic interface for resolving entities. If you create an object implementing + this interface, then register the object with your Parser, the parser will call + the method in your object to resolve all external entities. + + +.. class:: ErrorHandler + + Interface used by the parser to present error and warning messages to the + application. The methods of this object control whether errors are immediately + converted to exceptions or are handled in some other way. + +In addition to these classes, :mod:`xml.sax.handler` provides symbolic constants +for the feature and property names. + + +.. data:: feature_namespaces + + | value: ``"http://xml.org/sax/features/namespaces"`` + | true: Perform Namespace processing. + | false: Optionally do not perform Namespace processing (implies + namespace-prefixes; default). + | access: (parsing) read-only; (not parsing) read/write + + +.. data:: feature_namespace_prefixes + + | value: ``"http://xml.org/sax/features/namespace-prefixes"`` + | true: Report the original prefixed names and attributes used for Namespace + declarations. + | false: Do not report attributes used for Namespace declarations, and + optionally do not report original prefixed names (default). + | access: (parsing) read-only; (not parsing) read/write + + +.. data:: feature_string_interning + + | value: ``"http://xml.org/sax/features/string-interning"`` + | true: All element names, prefixes, attribute names, Namespace URIs, and + local names are interned using the built-in intern function. + | false: Names are not necessarily interned, although they may be (default). + | access: (parsing) read-only; (not parsing) read/write + + +.. data:: feature_validation + + | value: ``"http://xml.org/sax/features/validation"`` + | true: Report all validation errors (implies external-general-entities and + external-parameter-entities). + | false: Do not report validation errors. + | access: (parsing) read-only; (not parsing) read/write + + +.. data:: feature_external_ges + + | value: ``"http://xml.org/sax/features/external-general-entities"`` + | true: Include all external general (text) entities. + | false: Do not include external general entities. + | access: (parsing) read-only; (not parsing) read/write + + +.. data:: feature_external_pes + + | value: ``"http://xml.org/sax/features/external-parameter-entities"`` + | true: Include all external parameter entities, including the external DTD + subset. + | false: Do not include any external parameter entities, even the external + DTD subset. + | access: (parsing) read-only; (not parsing) read/write + + +.. data:: all_features + + List of all features. + + +.. data:: property_lexical_handler + + | value: ``"http://xml.org/sax/properties/lexical-handler"`` + | data type: xml.sax.sax2lib.LexicalHandler (not supported in Python 2) + | description: An optional extension handler for lexical events like + comments. + | access: read/write + + +.. data:: property_declaration_handler + + | value: ``"http://xml.org/sax/properties/declaration-handler"`` + | data type: xml.sax.sax2lib.DeclHandler (not supported in Python 2) + | description: An optional extension handler for DTD-related events other + than notations and unparsed entities. + | access: read/write + + +.. data:: property_dom_node + + | value: ``"http://xml.org/sax/properties/dom-node"`` + | data type: org.w3c.dom.Node (not supported in Python 2) + | description: When parsing, the current DOM node being visited if this is + a DOM iterator; when not parsing, the root DOM node for iteration. + | access: (parsing) read-only; (not parsing) read/write + + +.. data:: property_xml_string + + | value: ``"http://xml.org/sax/properties/xml-string"`` + | data type: String + | description: The literal string of characters that was the source for the + current event. + | access: read-only + + +.. data:: all_properties + + List of all known property names. + + +.. _content-handler-objects: + +ContentHandler Objects +---------------------- + +Users are expected to subclass :class:`ContentHandler` to support their +application. The following methods are called by the parser on the appropriate +events in the input document: + + +.. method:: ContentHandler.setDocumentLocator(locator) + + Called by the parser to give the application a locator for locating the origin + of document events. + + SAX parsers are strongly encouraged (though not absolutely required) to supply a + locator: if it does so, it must supply the locator to the application by + invoking this method before invoking any of the other methods in the + DocumentHandler interface. + + The locator allows the application to determine the end position of any + document-related event, even if the parser is not reporting an error. Typically, + the application will use this information for reporting its own errors (such as + character content that does not match an application's business rules). The + information returned by the locator is probably not sufficient for use with a + search engine. + + Note that the locator will return correct information only during the invocation + of the events in this interface. The application should not attempt to use it at + any other time. + + +.. method:: ContentHandler.startDocument() + + Receive notification of the beginning of a document. + + The SAX parser will invoke this method only once, before any other methods in + this interface or in DTDHandler (except for :meth:`setDocumentLocator`). + + +.. method:: ContentHandler.endDocument() + + Receive notification of the end of a document. + + The SAX parser will invoke this method only once, and it will be the last method + invoked during the parse. The parser shall not invoke this method until it has + either abandoned parsing (because of an unrecoverable error) or reached the end + of input. + + +.. method:: ContentHandler.startPrefixMapping(prefix, uri) + + Begin the scope of a prefix-URI Namespace mapping. + + The information from this event is not necessary for normal Namespace + processing: the SAX XML reader will automatically replace prefixes for element + and attribute names when the ``feature_namespaces`` feature is enabled (the + default). + + There are cases, however, when applications need to use prefixes in character + data or in attribute values, where they cannot safely be expanded automatically; + the :meth:`startPrefixMapping` and :meth:`endPrefixMapping` events supply the + information to the application to expand prefixes in those contexts itself, if + necessary. + + .. XXX This is not really the default, is it? MvL + + Note that :meth:`startPrefixMapping` and :meth:`endPrefixMapping` events are not + guaranteed to be properly nested relative to each-other: all + :meth:`startPrefixMapping` events will occur before the corresponding + :meth:`startElement` event, and all :meth:`endPrefixMapping` events will occur + after the corresponding :meth:`endElement` event, but their order is not + guaranteed. + + +.. method:: ContentHandler.endPrefixMapping(prefix) + + End the scope of a prefix-URI mapping. + + See :meth:`startPrefixMapping` for details. This event will always occur after + the corresponding :meth:`endElement` event, but the order of + :meth:`endPrefixMapping` events is not otherwise guaranteed. + + +.. method:: ContentHandler.startElement(name, attrs) + + Signals the start of an element in non-namespace mode. + + The *name* parameter contains the raw XML 1.0 name of the element type as a + string and the *attrs* parameter holds an object of the + :class:`~xml.sax.xmlreader.Attributes` + interface (see :ref:`attributes-objects`) containing the attributes of + the element. The object passed as *attrs* may be re-used by the parser; holding + on to a reference to it is not a reliable way to keep a copy of the attributes. + To keep a copy of the attributes, use the :meth:`copy` method of the *attrs* + object. + + +.. method:: ContentHandler.endElement(name) + + Signals the end of an element in non-namespace mode. + + The *name* parameter contains the name of the element type, just as with the + :meth:`startElement` event. + + +.. method:: ContentHandler.startElementNS(name, qname, attrs) + + Signals the start of an element in namespace mode. + + The *name* parameter contains the name of the element type as a ``(uri, + localname)`` tuple, the *qname* parameter contains the raw XML 1.0 name used in + the source document, and the *attrs* parameter holds an instance of the + :class:`~xml.sax.xmlreader.AttributesNS` interface (see + :ref:`attributes-ns-objects`) + containing the attributes of the element. If no namespace is associated with + the element, the *uri* component of *name* will be ``None``. The object passed + as *attrs* may be re-used by the parser; holding on to a reference to it is not + a reliable way to keep a copy of the attributes. To keep a copy of the + attributes, use the :meth:`copy` method of the *attrs* object. + + Parsers may set the *qname* parameter to ``None``, unless the + ``feature_namespace_prefixes`` feature is activated. + + +.. method:: ContentHandler.endElementNS(name, qname) + + Signals the end of an element in namespace mode. + + The *name* parameter contains the name of the element type, just as with the + :meth:`startElementNS` method, likewise the *qname* parameter. + + +.. method:: ContentHandler.characters(content) + + Receive notification of character data. + + The Parser will call this method to report each chunk of character data. SAX + parsers may return all contiguous character data in a single chunk, or they may + split it into several chunks; however, all of the characters in any single event + must come from the same external entity so that the Locator provides useful + information. + + *content* may be a string or bytes instance; the ``expat`` reader module + always produces strings. + + .. note:: + + The earlier SAX 1 interface provided by the Python XML Special Interest Group + used a more Java-like interface for this method. Since most parsers used from + Python did not take advantage of the older interface, the simpler signature was + chosen to replace it. To convert old code to the new interface, use *content* + instead of slicing content with the old *offset* and *length* parameters. + + +.. method:: ContentHandler.ignorableWhitespace(whitespace) + + Receive notification of ignorable whitespace in element content. + + Validating Parsers must use this method to report each chunk of ignorable + whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating + parsers may also use this method if they are capable of parsing and using + content models. + + SAX parsers may return all contiguous whitespace in a single chunk, or they may + split it into several chunks; however, all of the characters in any single event + must come from the same external entity, so that the Locator provides useful + information. + + +.. method:: ContentHandler.processingInstruction(target, data) + + Receive notification of a processing instruction. + + The Parser will invoke this method once for each processing instruction found: + note that processing instructions may occur before or after the main document + element. + + A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a + text declaration (XML 1.0, section 4.3.1) using this method. + + +.. method:: ContentHandler.skippedEntity(name) + + Receive notification of a skipped entity. + + The Parser will invoke this method once for each entity skipped. Non-validating + processors may skip entities if they have not seen the declarations (because, + for example, the entity was declared in an external DTD subset). All processors + may skip external entities, depending on the values of the + ``feature_external_ges`` and the ``feature_external_pes`` properties. + + +.. _dtd-handler-objects: + +DTDHandler Objects +------------------ + +:class:`DTDHandler` instances provide the following methods: + + +.. method:: DTDHandler.notationDecl(name, publicId, systemId) + + Handle a notation declaration event. + + +.. method:: DTDHandler.unparsedEntityDecl(name, publicId, systemId, ndata) + + Handle an unparsed entity declaration event. + + +.. _entity-resolver-objects: + +EntityResolver Objects +---------------------- + + +.. method:: EntityResolver.resolveEntity(publicId, systemId) + + Resolve the system identifier of an entity and return either the system + identifier to read from as a string, or an InputSource to read from. The default + implementation returns *systemId*. + + +.. _sax-error-handler: + +ErrorHandler Objects +-------------------- + +Objects with this interface are used to receive error and warning information +from the :class:`~xml.sax.xmlreader.XMLReader`. If you create an object that +implements this interface, then register the object with your +:class:`~xml.sax.xmlreader.XMLReader`, the parser +will call the methods in your object to report all warnings and errors. There +are three levels of errors available: warnings, (possibly) recoverable errors, +and unrecoverable errors. All methods take a :exc:`SAXParseException` as the +only parameter. Errors and warnings may be converted to an exception by raising +the passed-in exception object. + + +.. method:: ErrorHandler.error(exception) + + Called when the parser encounters a recoverable error. If this method does not + raise an exception, parsing may continue, but further document information + should not be expected by the application. Allowing the parser to continue may + allow additional errors to be discovered in the input document. + + +.. method:: ErrorHandler.fatalError(exception) + + Called when the parser encounters an error it cannot recover from; parsing is + expected to terminate when this method returns. + + +.. method:: ErrorHandler.warning(exception) + + Called when the parser presents minor warning information to the application. + Parsing is expected to continue when this method returns, and document + information will continue to be passed to the application. Raising an exception + in this method will cause parsing to end. + diff --git a/cpython_2/environment/repo/Doc/library/xml.sax.reader.rst b/cpython_2/environment/repo/Doc/library/xml.sax.reader.rst new file mode 100644 index 0000000000000000000000000000000000000000..113e9e93fb04ff4c19fae65f400e069c43bb3d3b --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xml.sax.reader.rst @@ -0,0 +1,397 @@ +:mod:`xml.sax.xmlreader` --- Interface for XML parsers +====================================================== + +.. module:: xml.sax.xmlreader + :synopsis: Interface which SAX-compliant XML parsers must implement. + +.. moduleauthor:: Lars Marius Garshol +.. sectionauthor:: Martin v. Löwis + +**Source code:** :source:`Lib/xml/sax/xmlreader.py` + +-------------- + +SAX parsers implement the :class:`XMLReader` interface. They are implemented in +a Python module, which must provide a function :func:`create_parser`. This +function is invoked by :func:`xml.sax.make_parser` with no arguments to create +a new parser object. + + +.. class:: XMLReader() + + Base class which can be inherited by SAX parsers. + + +.. class:: IncrementalParser() + + In some cases, it is desirable not to parse an input source at once, but to feed + chunks of the document as they get available. Note that the reader will normally + not read the entire file, but read it in chunks as well; still :meth:`parse` + won't return until the entire document is processed. So these interfaces should + be used if the blocking behaviour of :meth:`parse` is not desirable. + + When the parser is instantiated it is ready to begin accepting data from the + feed method immediately. After parsing has been finished with a call to close + the reset method must be called to make the parser ready to accept new data, + either from feed or using the parse method. + + Note that these methods must *not* be called during parsing, that is, after + parse has been called and before it returns. + + By default, the class also implements the parse method of the XMLReader + interface using the feed, close and reset methods of the IncrementalParser + interface as a convenience to SAX 2.0 driver writers. + + +.. class:: Locator() + + Interface for associating a SAX event with a document location. A locator object + will return valid results only during calls to DocumentHandler methods; at any + other time, the results are unpredictable. If information is not available, + methods may return ``None``. + + +.. class:: InputSource(system_id=None) + + Encapsulation of the information needed by the :class:`XMLReader` to read + entities. + + This class may include information about the public identifier, system + identifier, byte stream (possibly with character encoding information) and/or + the character stream of an entity. + + Applications will create objects of this class for use in the + :meth:`XMLReader.parse` method and for returning from + EntityResolver.resolveEntity. + + An :class:`InputSource` belongs to the application, the :class:`XMLReader` is + not allowed to modify :class:`InputSource` objects passed to it from the + application, although it may make copies and modify those. + + +.. class:: AttributesImpl(attrs) + + This is an implementation of the :class:`Attributes` interface (see section + :ref:`attributes-objects`). This is a dictionary-like object which + represents the element attributes in a :meth:`startElement` call. In addition + to the most useful dictionary operations, it supports a number of other + methods as described by the interface. Objects of this class should be + instantiated by readers; *attrs* must be a dictionary-like object containing + a mapping from attribute names to attribute values. + + +.. class:: AttributesNSImpl(attrs, qnames) + + Namespace-aware variant of :class:`AttributesImpl`, which will be passed to + :meth:`startElementNS`. It is derived from :class:`AttributesImpl`, but + understands attribute names as two-tuples of *namespaceURI* and + *localname*. In addition, it provides a number of methods expecting qualified + names as they appear in the original document. This class implements the + :class:`AttributesNS` interface (see section :ref:`attributes-ns-objects`). + + +.. _xmlreader-objects: + +XMLReader Objects +----------------- + +The :class:`XMLReader` interface supports the following methods: + + +.. method:: XMLReader.parse(source) + + Process an input source, producing SAX events. The *source* object can be a + system identifier (a string identifying the input source -- typically a file + name or a URL), a :class:`pathlib.Path` or :term:`path-like ` + object, or an :class:`InputSource` object. When + :meth:`parse` returns, the input is completely processed, and the parser object + can be discarded or reset. + + .. versionchanged:: 3.5 + Added support of character streams. + + .. versionchanged:: 3.8 + Added support of path-like objects. + + +.. method:: XMLReader.getContentHandler() + + Return the current :class:`~xml.sax.handler.ContentHandler`. + + +.. method:: XMLReader.setContentHandler(handler) + + Set the current :class:`~xml.sax.handler.ContentHandler`. If no + :class:`~xml.sax.handler.ContentHandler` is set, content events will be + discarded. + + +.. method:: XMLReader.getDTDHandler() + + Return the current :class:`~xml.sax.handler.DTDHandler`. + + +.. method:: XMLReader.setDTDHandler(handler) + + Set the current :class:`~xml.sax.handler.DTDHandler`. If no + :class:`~xml.sax.handler.DTDHandler` is set, DTD + events will be discarded. + + +.. method:: XMLReader.getEntityResolver() + + Return the current :class:`~xml.sax.handler.EntityResolver`. + + +.. method:: XMLReader.setEntityResolver(handler) + + Set the current :class:`~xml.sax.handler.EntityResolver`. If no + :class:`~xml.sax.handler.EntityResolver` is set, + attempts to resolve an external entity will result in opening the system + identifier for the entity, and fail if it is not available. + + +.. method:: XMLReader.getErrorHandler() + + Return the current :class:`~xml.sax.handler.ErrorHandler`. + + +.. method:: XMLReader.setErrorHandler(handler) + + Set the current error handler. If no :class:`~xml.sax.handler.ErrorHandler` + is set, errors will be raised as exceptions, and warnings will be printed. + + +.. method:: XMLReader.setLocale(locale) + + Allow an application to set the locale for errors and warnings. + + SAX parsers are not required to provide localization for errors and warnings; if + they cannot support the requested locale, however, they must raise a SAX + exception. Applications may request a locale change in the middle of a parse. + + +.. method:: XMLReader.getFeature(featurename) + + Return the current setting for feature *featurename*. If the feature is not + recognized, :exc:`SAXNotRecognizedException` is raised. The well-known + featurenames are listed in the module :mod:`xml.sax.handler`. + + +.. method:: XMLReader.setFeature(featurename, value) + + Set the *featurename* to *value*. If the feature is not recognized, + :exc:`SAXNotRecognizedException` is raised. If the feature or its setting is not + supported by the parser, *SAXNotSupportedException* is raised. + + +.. method:: XMLReader.getProperty(propertyname) + + Return the current setting for property *propertyname*. If the property is not + recognized, a :exc:`SAXNotRecognizedException` is raised. The well-known + propertynames are listed in the module :mod:`xml.sax.handler`. + + +.. method:: XMLReader.setProperty(propertyname, value) + + Set the *propertyname* to *value*. If the property is not recognized, + :exc:`SAXNotRecognizedException` is raised. If the property or its setting is + not supported by the parser, *SAXNotSupportedException* is raised. + + +.. _incremental-parser-objects: + +IncrementalParser Objects +------------------------- + +Instances of :class:`IncrementalParser` offer the following additional methods: + + +.. method:: IncrementalParser.feed(data) + + Process a chunk of *data*. + + +.. method:: IncrementalParser.close() + + Assume the end of the document. That will check well-formedness conditions that + can be checked only at the end, invoke handlers, and may clean up resources + allocated during parsing. + + +.. method:: IncrementalParser.reset() + + This method is called after close has been called to reset the parser so that it + is ready to parse new documents. The results of calling parse or feed after + close without calling reset are undefined. + + +.. _locator-objects: + +Locator Objects +--------------- + +Instances of :class:`Locator` provide these methods: + + +.. method:: Locator.getColumnNumber() + + Return the column number where the current event begins. + + +.. method:: Locator.getLineNumber() + + Return the line number where the current event begins. + + +.. method:: Locator.getPublicId() + + Return the public identifier for the current event. + + +.. method:: Locator.getSystemId() + + Return the system identifier for the current event. + + +.. _input-source-objects: + +InputSource Objects +------------------- + + +.. method:: InputSource.setPublicId(id) + + Sets the public identifier of this :class:`InputSource`. + + +.. method:: InputSource.getPublicId() + + Returns the public identifier of this :class:`InputSource`. + + +.. method:: InputSource.setSystemId(id) + + Sets the system identifier of this :class:`InputSource`. + + +.. method:: InputSource.getSystemId() + + Returns the system identifier of this :class:`InputSource`. + + +.. method:: InputSource.setEncoding(encoding) + + Sets the character encoding of this :class:`InputSource`. + + The encoding must be a string acceptable for an XML encoding declaration (see + section 4.3.3 of the XML recommendation). + + The encoding attribute of the :class:`InputSource` is ignored if the + :class:`InputSource` also contains a character stream. + + +.. method:: InputSource.getEncoding() + + Get the character encoding of this InputSource. + + +.. method:: InputSource.setByteStream(bytefile) + + Set the byte stream (a :term:`binary file`) for this input source. + + The SAX parser will ignore this if there is also a character stream specified, + but it will use a byte stream in preference to opening a URI connection itself. + + If the application knows the character encoding of the byte stream, it should + set it with the setEncoding method. + + +.. method:: InputSource.getByteStream() + + Get the byte stream for this input source. + + The getEncoding method will return the character encoding for this byte stream, + or ``None`` if unknown. + + +.. method:: InputSource.setCharacterStream(charfile) + + Set the character stream (a :term:`text file`) for this input source. + + If there is a character stream specified, the SAX parser will ignore any byte + stream and will not attempt to open a URI connection to the system identifier. + + +.. method:: InputSource.getCharacterStream() + + Get the character stream for this input source. + + +.. _attributes-objects: + +The :class:`Attributes` Interface +--------------------------------- + +:class:`Attributes` objects implement a portion of the :term:`mapping protocol +`, including the methods :meth:`~collections.abc.Mapping.copy`, +:meth:`~collections.abc.Mapping.get`, :meth:`~object.__contains__`, +:meth:`~collections.abc.Mapping.items`, :meth:`~collections.abc.Mapping.keys`, +and :meth:`~collections.abc.Mapping.values`. The following methods +are also provided: + + +.. method:: Attributes.getLength() + + Return the number of attributes. + + +.. method:: Attributes.getNames() + + Return the names of the attributes. + + +.. method:: Attributes.getType(name) + + Returns the type of the attribute *name*, which is normally ``'CDATA'``. + + +.. method:: Attributes.getValue(name) + + Return the value of attribute *name*. + +.. getValueByQName, getNameByQName, getQNameByName, getQNames available +.. here already, but documented only for derived class. + + +.. _attributes-ns-objects: + +The :class:`AttributesNS` Interface +----------------------------------- + +This interface is a subtype of the :class:`Attributes` interface (see section +:ref:`attributes-objects`). All methods supported by that interface are also +available on :class:`AttributesNS` objects. + +The following methods are also available: + + +.. method:: AttributesNS.getValueByQName(name) + + Return the value for a qualified name. + + +.. method:: AttributesNS.getNameByQName(name) + + Return the ``(namespace, localname)`` pair for a qualified *name*. + + +.. method:: AttributesNS.getQNameByName(name) + + Return the qualified name for a ``(namespace, localname)`` pair. + + +.. method:: AttributesNS.getQNames() + + Return the qualified names of all attributes. + diff --git a/cpython_2/environment/repo/Doc/library/xml.sax.rst b/cpython_2/environment/repo/Doc/library/xml.sax.rst new file mode 100644 index 0000000000000000000000000000000000000000..6d351dfb4d70722bd76d5ecaa32301eac986a7f0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xml.sax.rst @@ -0,0 +1,176 @@ +:mod:`xml.sax` --- Support for SAX2 parsers +=========================================== + +.. module:: xml.sax + :synopsis: Package containing SAX2 base classes and convenience functions. + +.. moduleauthor:: Lars Marius Garshol +.. sectionauthor:: Fred L. Drake, Jr. +.. sectionauthor:: Martin v. Löwis + +**Source code:** :source:`Lib/xml/sax/__init__.py` + +-------------- + +The :mod:`xml.sax` package provides a number of modules which implement the +Simple API for XML (SAX) interface for Python. The package itself provides the +SAX exceptions and the convenience functions which will be most used by users of +the SAX API. + + +.. warning:: + + The :mod:`xml.sax` module is not secure against maliciously + constructed data. If you need to parse untrusted or unauthenticated data see + :ref:`xml-vulnerabilities`. + +.. versionchanged:: 3.7.1 + + The SAX parser no longer processes general external entities by default + to increase security. Before, the parser created network connections + to fetch remote files or loaded local files from the file + system for DTD and entities. The feature can be enabled again with method + :meth:`~xml.sax.xmlreader.XMLReader.setFeature` on the parser object + and argument :data:`~xml.sax.handler.feature_external_ges`. + +The convenience functions are: + + +.. function:: make_parser(parser_list=[]) + + Create and return a SAX :class:`~xml.sax.xmlreader.XMLReader` object. The + first parser found will + be used. If *parser_list* is provided, it must be an iterable of strings which + name modules that have a function named :func:`create_parser`. Modules listed + in *parser_list* will be used before modules in the default list of parsers. + + .. versionchanged:: 3.8 + The *parser_list* argument can be any iterable, not just a list. + + +.. function:: parse(filename_or_stream, handler, error_handler=handler.ErrorHandler()) + + Create a SAX parser and use it to parse a document. The document, passed in as + *filename_or_stream*, can be a filename or a file object. The *handler* + parameter needs to be a SAX :class:`~handler.ContentHandler` instance. If + *error_handler* is given, it must be a SAX :class:`~handler.ErrorHandler` + instance; if + omitted, :exc:`SAXParseException` will be raised on all errors. There is no + return value; all work must be done by the *handler* passed in. + + +.. function:: parseString(string, handler, error_handler=handler.ErrorHandler()) + + Similar to :func:`parse`, but parses from a buffer *string* received as a + parameter. *string* must be a :class:`str` instance or a + :term:`bytes-like object`. + + .. versionchanged:: 3.5 + Added support of :class:`str` instances. + +A typical SAX application uses three kinds of objects: readers, handlers and +input sources. "Reader" in this context is another term for parser, i.e. some +piece of code that reads the bytes or characters from the input source, and +produces a sequence of events. The events then get distributed to the handler +objects, i.e. the reader invokes a method on the handler. A SAX application +must therefore obtain a reader object, create or open the input sources, create +the handlers, and connect these objects all together. As the final step of +preparation, the reader is called to parse the input. During parsing, methods on +the handler objects are called based on structural and syntactic events from the +input data. + +For these objects, only the interfaces are relevant; they are normally not +instantiated by the application itself. Since Python does not have an explicit +notion of interface, they are formally introduced as classes, but applications +may use implementations which do not inherit from the provided classes. The +:class:`~xml.sax.xmlreader.InputSource`, :class:`~xml.sax.xmlreader.Locator`, +:class:`~xml.sax.xmlreader.Attributes`, :class:`~xml.sax.xmlreader.AttributesNS`, +and :class:`~xml.sax.xmlreader.XMLReader` interfaces are defined in the +module :mod:`xml.sax.xmlreader`. The handler interfaces are defined in +:mod:`xml.sax.handler`. For convenience, +:class:`~xml.sax.xmlreader.InputSource` (which is often +instantiated directly) and the handler classes are also available from +:mod:`xml.sax`. These interfaces are described below. + +In addition to these classes, :mod:`xml.sax` provides the following exception +classes. + + +.. exception:: SAXException(msg, exception=None) + + Encapsulate an XML error or warning. This class can contain basic error or + warning information from either the XML parser or the application: it can be + subclassed to provide additional functionality or to add localization. Note + that although the handlers defined in the + :class:`~xml.sax.handler.ErrorHandler` interface + receive instances of this exception, it is not required to actually raise the + exception --- it is also useful as a container for information. + + When instantiated, *msg* should be a human-readable description of the error. + The optional *exception* parameter, if given, should be ``None`` or an exception + that was caught by the parsing code and is being passed along as information. + + This is the base class for the other SAX exception classes. + + +.. exception:: SAXParseException(msg, exception, locator) + + Subclass of :exc:`SAXException` raised on parse errors. Instances of this + class are passed to the methods of the SAX + :class:`~xml.sax.handler.ErrorHandler` interface to provide information + about the parse error. This class supports the SAX + :class:`~xml.sax.xmlreader.Locator` interface as well as the + :class:`SAXException` interface. + + +.. exception:: SAXNotRecognizedException(msg, exception=None) + + Subclass of :exc:`SAXException` raised when a SAX + :class:`~xml.sax.xmlreader.XMLReader` is + confronted with an unrecognized feature or property. SAX applications and + extensions may use this class for similar purposes. + + +.. exception:: SAXNotSupportedException(msg, exception=None) + + Subclass of :exc:`SAXException` raised when a SAX + :class:`~xml.sax.xmlreader.XMLReader` is asked to + enable a feature that is not supported, or to set a property to a value that the + implementation does not support. SAX applications and extensions may use this + class for similar purposes. + + +.. seealso:: + + `SAX: The Simple API for XML `_ + This site is the focal point for the definition of the SAX API. It provides a + Java implementation and online documentation. Links to implementations and + historical information are also available. + + Module :mod:`xml.sax.handler` + Definitions of the interfaces for application-provided objects. + + Module :mod:`xml.sax.saxutils` + Convenience functions for use in SAX applications. + + Module :mod:`xml.sax.xmlreader` + Definitions of the interfaces for parser-provided objects. + + +.. _sax-exception-objects: + +SAXException Objects +-------------------- + +The :class:`SAXException` exception class supports the following methods: + + +.. method:: SAXException.getMessage() + + Return a human-readable message describing the error condition. + + +.. method:: SAXException.getException() + + Return an encapsulated exception object, or ``None``. + diff --git a/cpython_2/environment/repo/Doc/library/xml.sax.utils.rst b/cpython_2/environment/repo/Doc/library/xml.sax.utils.rst new file mode 100644 index 0000000000000000000000000000000000000000..e46fefdf997510d3455dff1e0864931ef2e52518 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xml.sax.utils.rst @@ -0,0 +1,91 @@ +:mod:`xml.sax.saxutils` --- SAX Utilities +========================================= + +.. module:: xml.sax.saxutils + :synopsis: Convenience functions and classes for use with SAX. + +.. moduleauthor:: Lars Marius Garshol +.. sectionauthor:: Martin v. Löwis + +**Source code:** :source:`Lib/xml/sax/saxutils.py` + +-------------- + +The module :mod:`xml.sax.saxutils` contains a number of classes and functions +that are commonly useful when creating SAX applications, either in direct use, +or as base classes. + + +.. function:: escape(data, entities={}) + + Escape ``'&'``, ``'<'``, and ``'>'`` in a string of data. + + You can escape other strings of data by passing a dictionary as the optional + *entities* parameter. The keys and values must all be strings; each key will be + replaced with its corresponding value. The characters ``'&'``, ``'<'`` and + ``'>'`` are always escaped, even if *entities* is provided. + + +.. function:: unescape(data, entities={}) + + Unescape ``'&'``, ``'<'``, and ``'>'`` in a string of data. + + You can unescape other strings of data by passing a dictionary as the optional + *entities* parameter. The keys and values must all be strings; each key will be + replaced with its corresponding value. ``'&'``, ``'<'``, and ``'>'`` + are always unescaped, even if *entities* is provided. + + +.. function:: quoteattr(data, entities={}) + + Similar to :func:`escape`, but also prepares *data* to be used as an + attribute value. The return value is a quoted version of *data* with any + additional required replacements. :func:`quoteattr` will select a quote + character based on the content of *data*, attempting to avoid encoding any + quote characters in the string. If both single- and double-quote characters + are already in *data*, the double-quote characters will be encoded and *data* + will be wrapped in double-quotes. The resulting string can be used directly + as an attribute value:: + + >>> print("" % quoteattr("ab ' cd \" ef")) + + + This function is useful when generating attribute values for HTML or any SGML + using the reference concrete syntax. + + +.. class:: XMLGenerator(out=None, encoding='iso-8859-1', short_empty_elements=False) + + This class implements the :class:`~xml.sax.handler.ContentHandler` interface + by writing SAX + events back into an XML document. In other words, using an :class:`XMLGenerator` + as the content handler will reproduce the original document being parsed. *out* + should be a file-like object which will default to *sys.stdout*. *encoding* is + the encoding of the output stream which defaults to ``'iso-8859-1'``. + *short_empty_elements* controls the formatting of elements that contain no + content: if ``False`` (the default) they are emitted as a pair of start/end + tags, if set to ``True`` they are emitted as a single self-closed tag. + + .. versionadded:: 3.2 + The *short_empty_elements* parameter. + + +.. class:: XMLFilterBase(base) + + This class is designed to sit between an + :class:`~xml.sax.xmlreader.XMLReader` and the client + application's event handlers. By default, it does nothing but pass requests up + to the reader and events on to the handlers unmodified, but subclasses can + override specific methods to modify the event stream or the configuration + requests as they pass through. + + +.. function:: prepare_input_source(source, base='') + + This function takes an input source and an optional base URL and returns a + fully resolved :class:`~xml.sax.xmlreader.InputSource` object ready for + reading. The input source can be given as a string, a file-like object, or + an :class:`~xml.sax.xmlreader.InputSource` object; parsers will use this + function to implement the polymorphic *source* argument to their + :meth:`parse` method. + diff --git a/cpython_2/environment/repo/Doc/library/xmlrpc.client.rst b/cpython_2/environment/repo/Doc/library/xmlrpc.client.rst new file mode 100644 index 0000000000000000000000000000000000000000..32403819531aa82d02e4935de5fd229d30839f6a --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xmlrpc.client.rst @@ -0,0 +1,612 @@ +:mod:`xmlrpc.client` --- XML-RPC client access +============================================== + +.. module:: xmlrpc.client + :synopsis: XML-RPC client access. + +.. moduleauthor:: Fredrik Lundh +.. sectionauthor:: Eric S. Raymond + +**Source code:** :source:`Lib/xmlrpc/client.py` + +.. XXX Not everything is documented yet. It might be good to describe + Marshaller, Unmarshaller, getparser and Transport. + +-------------- + +XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a +transport. With it, a client can call methods with parameters on a remote +server (the server is named by a URI) and get back structured data. This module +supports writing XML-RPC client code; it handles all the details of translating +between conformable Python objects and XML on the wire. + + +.. warning:: + + The :mod:`xmlrpc.client` module is not secure against maliciously + constructed data. If you need to parse untrusted or unauthenticated data see + :ref:`xml-vulnerabilities`. + +.. versionchanged:: 3.5 + + For HTTPS URIs, :mod:`xmlrpc.client` now performs all the necessary + certificate and hostname checks by default. + +.. class:: ServerProxy(uri, transport=None, encoding=None, verbose=False, \ + allow_none=False, use_datetime=False, \ + use_builtin_types=False, *, headers=(), context=None) + + A :class:`ServerProxy` instance is an object that manages communication with a + remote XML-RPC server. The required first argument is a URI (Uniform Resource + Indicator), and will normally be the URL of the server. The optional second + argument is a transport factory instance; by default it is an internal + :class:`SafeTransport` instance for https: URLs and an internal HTTP + :class:`Transport` instance otherwise. The optional third argument is an + encoding, by default UTF-8. The optional fourth argument is a debugging flag. + + The following parameters govern the use of the returned proxy instance. + If *allow_none* is true, the Python constant ``None`` will be translated into + XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is + a commonly-used extension to the XML-RPC specification, but isn't supported by + all clients and servers; see `http://ontosys.com/xml-rpc/extensions.php + `_ + for a description. + The *use_builtin_types* flag can be used to cause date/time values + to be presented as :class:`datetime.datetime` objects and binary data to be + presented as :class:`bytes` objects; this flag is false by default. + :class:`datetime.datetime`, :class:`bytes` and :class:`bytearray` objects + may be passed to calls. + The *headers* parameter is an optional sequence of HTTP headers to send with + each request, expressed as a sequence of 2-tuples representing the header + name and value. (e.g. `[('Header-Name', 'value')]`). + The obsolete *use_datetime* flag is similar to *use_builtin_types* but it + applies only to date/time values. + +.. versionchanged:: 3.3 + The *use_builtin_types* flag was added. + +.. versionchanged:: 3.8 + The *headers* parameter was added. + + Both the HTTP and HTTPS transports support the URL syntax extension for HTTP + Basic Authentication: ``http://user:pass@host:port/path``. The ``user:pass`` + portion will be base64-encoded as an HTTP 'Authorization' header, and sent to + the remote server as part of the connection process when invoking an XML-RPC + method. You only need to use this if the remote server requires a Basic + Authentication user and password. If an HTTPS URL is provided, *context* may + be :class:`ssl.SSLContext` and configures the SSL settings of the underlying + HTTPS connection. + + The returned instance is a proxy object with methods that can be used to invoke + corresponding RPC calls on the remote server. If the remote server supports the + introspection API, the proxy can also be used to query the remote server for the + methods it supports (service discovery) and fetch other server-associated + metadata. + + Types that are conformable (e.g. that can be marshalled through XML), + include the following (and except where noted, they are unmarshalled + as the same Python type): + + .. tabularcolumns:: |l|L| + + +----------------------+-------------------------------------------------------+ + | XML-RPC type | Python type | + +======================+=======================================================+ + | ``boolean`` | :class:`bool` | + +----------------------+-------------------------------------------------------+ + | ``int``, ``i1``, | :class:`int` in range from -2147483648 to 2147483647. | + | ``i2``, ``i4``, | Values get the ```` tag. | + | ``i8`` or | | + | ``biginteger`` | | + +----------------------+-------------------------------------------------------+ + | ``double`` or | :class:`float`. Values get the ```` tag. | + | ``float`` | | + +----------------------+-------------------------------------------------------+ + | ``string`` | :class:`str` | + +----------------------+-------------------------------------------------------+ + | ``array`` | :class:`list` or :class:`tuple` containing | + | | conformable elements. Arrays are returned as | + | | :class:`lists `. | + +----------------------+-------------------------------------------------------+ + | ``struct`` | :class:`dict`. Keys must be strings, values may be | + | | any conformable type. Objects of user-defined | + | | classes can be passed in; only their | + | | :attr:`~object.__dict__` attribute is transmitted. | + +----------------------+-------------------------------------------------------+ + | ``dateTime.iso8601`` | :class:`DateTime` or :class:`datetime.datetime`. | + | | Returned type depends on values of | + | | *use_builtin_types* and *use_datetime* flags. | + +----------------------+-------------------------------------------------------+ + | ``base64`` | :class:`Binary`, :class:`bytes` or | + | | :class:`bytearray`. Returned type depends on the | + | | value of the *use_builtin_types* flag. | + +----------------------+-------------------------------------------------------+ + | ``nil`` | The ``None`` constant. Passing is allowed only if | + | | *allow_none* is true. | + +----------------------+-------------------------------------------------------+ + | ``bigdecimal`` | :class:`decimal.Decimal`. Returned type only. | + +----------------------+-------------------------------------------------------+ + + This is the full set of data types supported by XML-RPC. Method calls may also + raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or + :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer. + Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called + :exc:`Error`. Note that the xmlrpc client module currently does not marshal + instances of subclasses of built-in types. + + When passing strings, characters special to XML such as ``<``, ``>``, and ``&`` + will be automatically escaped. However, it's the caller's responsibility to + ensure that the string is free of characters that aren't allowed in XML, such as + the control characters with ASCII values between 0 and 31 (except, of course, + tab, newline and carriage return); failing to do this will result in an XML-RPC + request that isn't well-formed XML. If you have to pass arbitrary bytes + via XML-RPC, use :class:`bytes` or :class:`bytearray` classes or the + :class:`Binary` wrapper class described below. + + :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards + compatibility. New code should use :class:`ServerProxy`. + + .. versionchanged:: 3.5 + Added the *context* argument. + + .. versionchanged:: 3.6 + Added support of type tags with prefixes (e.g. ``ex:nil``). + Added support of unmarshalling additional types used by Apache XML-RPC + implementation for numerics: ``i1``, ``i2``, ``i8``, ``biginteger``, + ``float`` and ``bigdecimal``. + See http://ws.apache.org/xmlrpc/types.html for a description. + + +.. seealso:: + + `XML-RPC HOWTO `_ + A good description of XML-RPC operation and client software in several languages. + Contains pretty much everything an XML-RPC client developer needs to know. + + `XML-RPC Introspection `_ + Describes the XML-RPC protocol extension for introspection. + + `XML-RPC Specification `_ + The official specification. + + `Unofficial XML-RPC Errata `_ + Fredrik Lundh's "unofficial errata, intended to clarify certain + details in the XML-RPC specification, as well as hint at + 'best practices' to use when designing your own XML-RPC + implementations." + +.. _serverproxy-objects: + +ServerProxy Objects +------------------- + +A :class:`ServerProxy` instance has a method corresponding to each remote +procedure call accepted by the XML-RPC server. Calling the method performs an +RPC, dispatched by both name and argument signature (e.g. the same method name +can be overloaded with multiple argument signatures). The RPC finishes by +returning a value, which may be either returned data in a conformant type or a +:class:`Fault` or :class:`ProtocolError` object indicating an error. + +Servers that support the XML introspection API support some common methods +grouped under the reserved :attr:`~ServerProxy.system` attribute: + + +.. method:: ServerProxy.system.listMethods() + + This method returns a list of strings, one for each (non-system) method + supported by the XML-RPC server. + + +.. method:: ServerProxy.system.methodSignature(name) + + This method takes one parameter, the name of a method implemented by the XML-RPC + server. It returns an array of possible signatures for this method. A signature + is an array of types. The first of these types is the return type of the method, + the rest are parameters. + + Because multiple signatures (ie. overloading) is permitted, this method returns + a list of signatures rather than a singleton. + + Signatures themselves are restricted to the top level parameters expected by a + method. For instance if a method expects one array of structs as a parameter, + and it returns a string, its signature is simply "string, array". If it expects + three integers and returns a string, its signature is "string, int, int, int". + + If no signature is defined for the method, a non-array value is returned. In + Python this means that the type of the returned value will be something other + than list. + + +.. method:: ServerProxy.system.methodHelp(name) + + This method takes one parameter, the name of a method implemented by the XML-RPC + server. It returns a documentation string describing the use of that method. If + no such string is available, an empty string is returned. The documentation + string may contain HTML markup. + +.. versionchanged:: 3.5 + + Instances of :class:`ServerProxy` support the :term:`context manager` protocol + for closing the underlying transport. + + +A working example follows. The server code:: + + from xmlrpc.server import SimpleXMLRPCServer + + def is_even(n): + return n % 2 == 0 + + server = SimpleXMLRPCServer(("localhost", 8000)) + print("Listening on port 8000...") + server.register_function(is_even, "is_even") + server.serve_forever() + +The client code for the preceding server:: + + import xmlrpc.client + + with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy: + print("3 is even: %s" % str(proxy.is_even(3))) + print("100 is even: %s" % str(proxy.is_even(100))) + +.. _datetime-objects: + +DateTime Objects +---------------- + +.. class:: DateTime + + This class may be initialized with seconds since the epoch, a time + tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime` + instance. It has the following methods, supported mainly for internal + use by the marshalling/unmarshalling code: + + + .. method:: decode(string) + + Accept a string as the instance's new time value. + + + .. method:: encode(out) + + Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream + object. + + It also supports certain of Python's built-in operators through rich comparison + and :meth:`__repr__` methods. + +A working example follows. The server code:: + + import datetime + from xmlrpc.server import SimpleXMLRPCServer + import xmlrpc.client + + def today(): + today = datetime.datetime.today() + return xmlrpc.client.DateTime(today) + + server = SimpleXMLRPCServer(("localhost", 8000)) + print("Listening on port 8000...") + server.register_function(today, "today") + server.serve_forever() + +The client code for the preceding server:: + + import xmlrpc.client + import datetime + + proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") + + today = proxy.today() + # convert the ISO8601 string to a datetime object + converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S") + print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")) + +.. _binary-objects: + +Binary Objects +-------------- + +.. class:: Binary + + This class may be initialized from bytes data (which may include NULs). The + primary access to the content of a :class:`Binary` object is provided by an + attribute: + + + .. attribute:: data + + The binary data encapsulated by the :class:`Binary` instance. The data is + provided as a :class:`bytes` object. + + :class:`Binary` objects have the following methods, supported mainly for + internal use by the marshalling/unmarshalling code: + + + .. method:: decode(bytes) + + Accept a base64 :class:`bytes` object and decode it as the instance's new data. + + + .. method:: encode(out) + + Write the XML-RPC base 64 encoding of this binary item to the *out* stream object. + + The encoded data will have newlines every 76 characters as per + :rfc:`RFC 2045 section 6.8 <2045#section-6.8>`, + which was the de facto standard base64 specification when the + XML-RPC spec was written. + + It also supports certain of Python's built-in operators through :meth:`__eq__` + and :meth:`__ne__` methods. + +Example usage of the binary objects. We're going to transfer an image over +XMLRPC:: + + from xmlrpc.server import SimpleXMLRPCServer + import xmlrpc.client + + def python_logo(): + with open("python_logo.jpg", "rb") as handle: + return xmlrpc.client.Binary(handle.read()) + + server = SimpleXMLRPCServer(("localhost", 8000)) + print("Listening on port 8000...") + server.register_function(python_logo, 'python_logo') + + server.serve_forever() + +The client gets the image and saves it to a file:: + + import xmlrpc.client + + proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") + with open("fetched_python_logo.jpg", "wb") as handle: + handle.write(proxy.python_logo().data) + +.. _fault-objects: + +Fault Objects +------------- + +.. class:: Fault + + A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault + objects have the following attributes: + + + .. attribute:: faultCode + + A string indicating the fault type. + + + .. attribute:: faultString + + A string containing a diagnostic message associated with the fault. + +In the following example we're going to intentionally cause a :exc:`Fault` by +returning a complex type object. The server code:: + + from xmlrpc.server import SimpleXMLRPCServer + + # A marshalling error is going to occur because we're returning a + # complex number + def add(x, y): + return x+y+0j + + server = SimpleXMLRPCServer(("localhost", 8000)) + print("Listening on port 8000...") + server.register_function(add, 'add') + + server.serve_forever() + +The client code for the preceding server:: + + import xmlrpc.client + + proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") + try: + proxy.add(2, 5) + except xmlrpc.client.Fault as err: + print("A fault occurred") + print("Fault code: %d" % err.faultCode) + print("Fault string: %s" % err.faultString) + + + +.. _protocol-error-objects: + +ProtocolError Objects +--------------------- + +.. class:: ProtocolError + + A :class:`ProtocolError` object describes a protocol error in the underlying + transport layer (such as a 404 'not found' error if the server named by the URI + does not exist). It has the following attributes: + + + .. attribute:: url + + The URI or URL that triggered the error. + + + .. attribute:: errcode + + The error code. + + + .. attribute:: errmsg + + The error message or diagnostic string. + + + .. attribute:: headers + + A dict containing the headers of the HTTP/HTTPS request that triggered the + error. + +In the following example we're going to intentionally cause a :exc:`ProtocolError` +by providing an invalid URI:: + + import xmlrpc.client + + # create a ServerProxy with a URI that doesn't respond to XMLRPC requests + proxy = xmlrpc.client.ServerProxy("http://google.com/") + + try: + proxy.some_method() + except xmlrpc.client.ProtocolError as err: + print("A protocol error occurred") + print("URL: %s" % err.url) + print("HTTP/HTTPS headers: %s" % err.headers) + print("Error code: %d" % err.errcode) + print("Error message: %s" % err.errmsg) + +MultiCall Objects +----------------- + +The :class:`MultiCall` object provides a way to encapsulate multiple calls to a +remote server into a single request [#]_. + + +.. class:: MultiCall(server) + + Create an object used to boxcar method calls. *server* is the eventual target of + the call. Calls can be made to the result object, but they will immediately + return ``None``, and only store the call name and parameters in the + :class:`MultiCall` object. Calling the object itself causes all stored calls to + be transmitted as a single ``system.multicall`` request. The result of this call + is a :term:`generator`; iterating over this generator yields the individual + results. + +A usage example of this class follows. The server code:: + + from xmlrpc.server import SimpleXMLRPCServer + + def add(x, y): + return x + y + + def subtract(x, y): + return x - y + + def multiply(x, y): + return x * y + + def divide(x, y): + return x // y + + # A simple server with simple arithmetic functions + server = SimpleXMLRPCServer(("localhost", 8000)) + print("Listening on port 8000...") + server.register_multicall_functions() + server.register_function(add, 'add') + server.register_function(subtract, 'subtract') + server.register_function(multiply, 'multiply') + server.register_function(divide, 'divide') + server.serve_forever() + +The client code for the preceding server:: + + import xmlrpc.client + + proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") + multicall = xmlrpc.client.MultiCall(proxy) + multicall.add(7, 3) + multicall.subtract(7, 3) + multicall.multiply(7, 3) + multicall.divide(7, 3) + result = multicall() + + print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result)) + + +Convenience Functions +--------------------- + +.. function:: dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False) + + Convert *params* into an XML-RPC request. or into a response if *methodresponse* + is true. *params* can be either a tuple of arguments or an instance of the + :exc:`Fault` exception class. If *methodresponse* is true, only a single value + can be returned, meaning that *params* must be of length 1. *encoding*, if + supplied, is the encoding to use in the generated XML; the default is UTF-8. + Python's :const:`None` value cannot be used in standard XML-RPC; to allow using + it via an extension, provide a true value for *allow_none*. + + +.. function:: loads(data, use_datetime=False, use_builtin_types=False) + + Convert an XML-RPC request or response into Python objects, a ``(params, + methodname)``. *params* is a tuple of argument; *methodname* is a string, or + ``None`` if no method name is present in the packet. If the XML-RPC packet + represents a fault condition, this function will raise a :exc:`Fault` exception. + The *use_builtin_types* flag can be used to cause date/time values to be + presented as :class:`datetime.datetime` objects and binary data to be + presented as :class:`bytes` objects; this flag is false by default. + + The obsolete *use_datetime* flag is similar to *use_builtin_types* but it + applies only to date/time values. + + .. versionchanged:: 3.3 + The *use_builtin_types* flag was added. + + +.. _xmlrpc-client-example: + +Example of Client Usage +----------------------- + +:: + + # simple test program (from the XML-RPC specification) + from xmlrpc.client import ServerProxy, Error + + # server = ServerProxy("http://localhost:8000") # local server + with ServerProxy("http://betty.userland.com") as proxy: + + print(proxy) + + try: + print(proxy.examples.getStateName(41)) + except Error as v: + print("ERROR", v) + +To access an XML-RPC server through a HTTP proxy, you need to define a custom +transport. The following example shows how:: + + import http.client + import xmlrpc.client + + class ProxiedTransport(xmlrpc.client.Transport): + + def set_proxy(self, host, port=None, headers=None): + self.proxy = host, port + self.proxy_headers = headers + + def make_connection(self, host): + connection = http.client.HTTPConnection(*self.proxy) + connection.set_tunnel(host, headers=self.proxy_headers) + self._connection = host, connection + return connection + + transport = ProxiedTransport() + transport.set_proxy('proxy-server', 8080) + server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport) + print(server.examples.getStateName(41)) + + +Example of Client and Server Usage +---------------------------------- + +See :ref:`simplexmlrpcserver-example`. + + +.. rubric:: Footnotes + +.. [#] This approach has been first presented in `a discussion on xmlrpc.com + `_. +.. the link now points to webarchive since the one at +.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin +.. doesn't reply) diff --git a/cpython_2/environment/repo/Doc/library/xmlrpc.rst b/cpython_2/environment/repo/Doc/library/xmlrpc.rst new file mode 100644 index 0000000000000000000000000000000000000000..ae68157b0f63c1445560f369906cbae1fee460dd --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xmlrpc.rst @@ -0,0 +1,12 @@ +:mod:`xmlrpc` --- XMLRPC server and client modules +================================================== + +XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a +transport. With it, a client can call methods with parameters on a remote +server (the server is named by a URI) and get back structured data. + +``xmlrpc`` is a package that collects server and client modules implementing +XML-RPC. The modules are: + +* :mod:`xmlrpc.client` +* :mod:`xmlrpc.server` diff --git a/cpython_2/environment/repo/Doc/library/xmlrpc.server.rst b/cpython_2/environment/repo/Doc/library/xmlrpc.server.rst new file mode 100644 index 0000000000000000000000000000000000000000..7d561e2303f89848112981c7fc851b27320316d5 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/xmlrpc.server.rst @@ -0,0 +1,445 @@ +:mod:`xmlrpc.server` --- Basic XML-RPC servers +============================================== + +.. module:: xmlrpc.server + :synopsis: Basic XML-RPC server implementations. + +.. moduleauthor:: Brian Quinlan +.. sectionauthor:: Fred L. Drake, Jr. + +**Source code:** :source:`Lib/xmlrpc/server.py` + +-------------- + +The :mod:`xmlrpc.server` module provides a basic server framework for XML-RPC +servers written in Python. Servers can either be free standing, using +:class:`SimpleXMLRPCServer`, or embedded in a CGI environment, using +:class:`CGIXMLRPCRequestHandler`. + + +.. warning:: + + The :mod:`xmlrpc.server` module is not secure against maliciously + constructed data. If you need to parse untrusted or unauthenticated data see + :ref:`xml-vulnerabilities`. + + +.. class:: SimpleXMLRPCServer(addr, requestHandler=SimpleXMLRPCRequestHandler,\ + logRequests=True, allow_none=False, encoding=None,\ + bind_and_activate=True, use_builtin_types=False) + + Create a new server instance. This class provides methods for registration of + functions that can be called by the XML-RPC protocol. The *requestHandler* + parameter should be a factory for request handler instances; it defaults to + :class:`SimpleXMLRPCRequestHandler`. The *addr* and *requestHandler* parameters + are passed to the :class:`socketserver.TCPServer` constructor. If *logRequests* + is true (the default), requests will be logged; setting this parameter to false + will turn off logging. The *allow_none* and *encoding* parameters are passed + on to :mod:`xmlrpc.client` and control the XML-RPC responses that will be returned + from the server. The *bind_and_activate* parameter controls whether + :meth:`server_bind` and :meth:`server_activate` are called immediately by the + constructor; it defaults to true. Setting it to false allows code to manipulate + the *allow_reuse_address* class variable before the address is bound. + The *use_builtin_types* parameter is passed to the + :func:`~xmlrpc.client.loads` function and controls which types are processed + when date/times values or binary data are received; it defaults to false. + + .. versionchanged:: 3.3 + The *use_builtin_types* flag was added. + + +.. class:: CGIXMLRPCRequestHandler(allow_none=False, encoding=None,\ + use_builtin_types=False) + + Create a new instance to handle XML-RPC requests in a CGI environment. The + *allow_none* and *encoding* parameters are passed on to :mod:`xmlrpc.client` + and control the XML-RPC responses that will be returned from the server. + The *use_builtin_types* parameter is passed to the + :func:`~xmlrpc.client.loads` function and controls which types are processed + when date/times values or binary data are received; it defaults to false. + + .. versionchanged:: 3.3 + The *use_builtin_types* flag was added. + + +.. class:: SimpleXMLRPCRequestHandler() + + Create a new request handler instance. This request handler supports ``POST`` + requests and modifies logging so that the *logRequests* parameter to the + :class:`SimpleXMLRPCServer` constructor parameter is honored. + + +.. _simple-xmlrpc-servers: + +SimpleXMLRPCServer Objects +-------------------------- + +The :class:`SimpleXMLRPCServer` class is based on +:class:`socketserver.TCPServer` and provides a means of creating simple, stand +alone XML-RPC servers. + + +.. method:: SimpleXMLRPCServer.register_function(function=None, name=None) + + Register a function that can respond to XML-RPC requests. If *name* is given, + it will be the method name associated with *function*, otherwise + ``function.__name__`` will be used. *name* is a string, and may contain + characters not legal in Python identifiers, including the period character. + + This method can also be used as a decorator. When used as a decorator, + *name* can only be given as a keyword argument to register *function* under + *name*. If no *name* is given, ``function.__name__`` will be used. + + .. versionchanged:: 3.7 + :meth:`register_function` can be used as a decorator. + + +.. method:: SimpleXMLRPCServer.register_instance(instance, allow_dotted_names=False) + + Register an object which is used to expose method names which have not been + registered using :meth:`register_function`. If *instance* contains a + :meth:`_dispatch` method, it is called with the requested method name and the + parameters from the request. Its API is ``def _dispatch(self, method, params)`` + (note that *params* does not represent a variable argument list). If it calls + an underlying function to perform its task, that function is called as + ``func(*params)``, expanding the parameter list. The return value from + :meth:`_dispatch` is returned to the client as the result. If *instance* does + not have a :meth:`_dispatch` method, it is searched for an attribute matching + the name of the requested method. + + If the optional *allow_dotted_names* argument is true and the instance does not + have a :meth:`_dispatch` method, then if the requested method name contains + periods, each component of the method name is searched for individually, with + the effect that a simple hierarchical search is performed. The value found from + this search is then called with the parameters from the request, and the return + value is passed back to the client. + + .. warning:: + + Enabling the *allow_dotted_names* option allows intruders to access your + module's global variables and may allow intruders to execute arbitrary code on + your machine. Only use this option on a secure, closed network. + + +.. method:: SimpleXMLRPCServer.register_introspection_functions() + + Registers the XML-RPC introspection functions ``system.listMethods``, + ``system.methodHelp`` and ``system.methodSignature``. + + +.. method:: SimpleXMLRPCServer.register_multicall_functions() + + Registers the XML-RPC multicall function system.multicall. + + +.. attribute:: SimpleXMLRPCRequestHandler.rpc_paths + + An attribute value that must be a tuple listing valid path portions of the URL + for receiving XML-RPC requests. Requests posted to other paths will result in a + 404 "no such page" HTTP error. If this tuple is empty, all paths will be + considered valid. The default value is ``('/', '/RPC2')``. + + +.. _simplexmlrpcserver-example: + +SimpleXMLRPCServer Example +^^^^^^^^^^^^^^^^^^^^^^^^^^ +Server code:: + + from xmlrpc.server import SimpleXMLRPCServer + from xmlrpc.server import SimpleXMLRPCRequestHandler + + # Restrict to a particular path. + class RequestHandler(SimpleXMLRPCRequestHandler): + rpc_paths = ('/RPC2',) + + # Create server + with SimpleXMLRPCServer(('localhost', 8000), + requestHandler=RequestHandler) as server: + server.register_introspection_functions() + + # Register pow() function; this will use the value of + # pow.__name__ as the name, which is just 'pow'. + server.register_function(pow) + + # Register a function under a different name + def adder_function(x, y): + return x + y + server.register_function(adder_function, 'add') + + # Register an instance; all the methods of the instance are + # published as XML-RPC methods (in this case, just 'mul'). + class MyFuncs: + def mul(self, x, y): + return x * y + + server.register_instance(MyFuncs()) + + # Run the server's main loop + server.serve_forever() + +The following client code will call the methods made available by the preceding +server:: + + import xmlrpc.client + + s = xmlrpc.client.ServerProxy('http://localhost:8000') + print(s.pow(2,3)) # Returns 2**3 = 8 + print(s.add(2,3)) # Returns 5 + print(s.mul(5,2)) # Returns 5*2 = 10 + + # Print list of available methods + print(s.system.listMethods()) + +:meth:`register_function` can also be used as a decorator. The previous server +example can register functions in a decorator way:: + + from xmlrpc.server import SimpleXMLRPCServer + from xmlrpc.server import SimpleXMLRPCRequestHandler + + class RequestHandler(SimpleXMLRPCRequestHandler): + rpc_paths = ('/RPC2',) + + with SimpleXMLRPCServer(('localhost', 8000), + requestHandler=RequestHandler) as server: + server.register_introspection_functions() + + # Register pow() function; this will use the value of + # pow.__name__ as the name, which is just 'pow'. + server.register_function(pow) + + # Register a function under a different name, using + # register_function as a decorator. *name* can only be given + # as a keyword argument. + @server.register_function(name='add') + def adder_function(x, y): + return x + y + + # Register a function under function.__name__. + @server.register_function + def mul(x, y): + return x * y + + server.serve_forever() + +The following example included in the :file:`Lib/xmlrpc/server.py` module shows +a server allowing dotted names and registering a multicall function. + +.. warning:: + + Enabling the *allow_dotted_names* option allows intruders to access your + module's global variables and may allow intruders to execute arbitrary code on + your machine. Only use this example only within a secure, closed network. + +:: + + import datetime + + class ExampleService: + def getData(self): + return '42' + + class currentTime: + @staticmethod + def getCurrentTime(): + return datetime.datetime.now() + + with SimpleXMLRPCServer(("localhost", 8000)) as server: + server.register_function(pow) + server.register_function(lambda x,y: x+y, 'add') + server.register_instance(ExampleService(), allow_dotted_names=True) + server.register_multicall_functions() + print('Serving XML-RPC on localhost port 8000') + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nKeyboard interrupt received, exiting.") + sys.exit(0) + +This ExampleService demo can be invoked from the command line:: + + python -m xmlrpc.server + + +The client that interacts with the above server is included in +`Lib/xmlrpc/client.py`:: + + server = ServerProxy("http://localhost:8000") + + try: + print(server.currentTime.getCurrentTime()) + except Error as v: + print("ERROR", v) + + multi = MultiCall(server) + multi.getData() + multi.pow(2,9) + multi.add(1,2) + try: + for response in multi(): + print(response) + except Error as v: + print("ERROR", v) + +This client which interacts with the demo XMLRPC server can be invoked as:: + + python -m xmlrpc.client + + +CGIXMLRPCRequestHandler +----------------------- + +The :class:`CGIXMLRPCRequestHandler` class can be used to handle XML-RPC +requests sent to Python CGI scripts. + + +.. method:: CGIXMLRPCRequestHandler.register_function(function=None, name=None) + + Register a function that can respond to XML-RPC requests. If *name* is given, + it will be the method name associated with *function*, otherwise + ``function.__name__`` will be used. *name* is a string, and may contain + characters not legal in Python identifiers, including the period character. + + This method can also be used as a decorator. When used as a decorator, + *name* can only be given as a keyword argument to register *function* under + *name*. If no *name* is given, ``function.__name__`` will be used. + + .. versionchanged:: 3.7 + :meth:`register_function` can be used as a decorator. + + +.. method:: CGIXMLRPCRequestHandler.register_instance(instance) + + Register an object which is used to expose method names which have not been + registered using :meth:`register_function`. If instance contains a + :meth:`_dispatch` method, it is called with the requested method name and the + parameters from the request; the return value is returned to the client as the + result. If instance does not have a :meth:`_dispatch` method, it is searched + for an attribute matching the name of the requested method; if the requested + method name contains periods, each component of the method name is searched for + individually, with the effect that a simple hierarchical search is performed. + The value found from this search is then called with the parameters from the + request, and the return value is passed back to the client. + + +.. method:: CGIXMLRPCRequestHandler.register_introspection_functions() + + Register the XML-RPC introspection functions ``system.listMethods``, + ``system.methodHelp`` and ``system.methodSignature``. + + +.. method:: CGIXMLRPCRequestHandler.register_multicall_functions() + + Register the XML-RPC multicall function ``system.multicall``. + + +.. method:: CGIXMLRPCRequestHandler.handle_request(request_text=None) + + Handle an XML-RPC request. If *request_text* is given, it should be the POST + data provided by the HTTP server, otherwise the contents of stdin will be used. + +Example:: + + class MyFuncs: + def mul(self, x, y): + return x * y + + + handler = CGIXMLRPCRequestHandler() + handler.register_function(pow) + handler.register_function(lambda x,y: x+y, 'add') + handler.register_introspection_functions() + handler.register_instance(MyFuncs()) + handler.handle_request() + + +Documenting XMLRPC server +------------------------- + +These classes extend the above classes to serve HTML documentation in response +to HTTP GET requests. Servers can either be free standing, using +:class:`DocXMLRPCServer`, or embedded in a CGI environment, using +:class:`DocCGIXMLRPCRequestHandler`. + + +.. class:: DocXMLRPCServer(addr, requestHandler=DocXMLRPCRequestHandler,\ + logRequests=True, allow_none=False, encoding=None,\ + bind_and_activate=True, use_builtin_types=True) + + Create a new server instance. All parameters have the same meaning as for + :class:`SimpleXMLRPCServer`; *requestHandler* defaults to + :class:`DocXMLRPCRequestHandler`. + + .. versionchanged:: 3.3 + The *use_builtin_types* flag was added. + + +.. class:: DocCGIXMLRPCRequestHandler() + + Create a new instance to handle XML-RPC requests in a CGI environment. + + +.. class:: DocXMLRPCRequestHandler() + + Create a new request handler instance. This request handler supports XML-RPC + POST requests, documentation GET requests, and modifies logging so that the + *logRequests* parameter to the :class:`DocXMLRPCServer` constructor parameter is + honored. + + +.. _doc-xmlrpc-servers: + +DocXMLRPCServer Objects +----------------------- + +The :class:`DocXMLRPCServer` class is derived from :class:`SimpleXMLRPCServer` +and provides a means of creating self-documenting, stand alone XML-RPC +servers. HTTP POST requests are handled as XML-RPC method calls. HTTP GET +requests are handled by generating pydoc-style HTML documentation. This allows a +server to provide its own web-based documentation. + + +.. method:: DocXMLRPCServer.set_server_title(server_title) + + Set the title used in the generated HTML documentation. This title will be used + inside the HTML "title" element. + + +.. method:: DocXMLRPCServer.set_server_name(server_name) + + Set the name used in the generated HTML documentation. This name will appear at + the top of the generated documentation inside a "h1" element. + + +.. method:: DocXMLRPCServer.set_server_documentation(server_documentation) + + Set the description used in the generated HTML documentation. This description + will appear as a paragraph, below the server name, in the documentation. + + +DocCGIXMLRPCRequestHandler +-------------------------- + +The :class:`DocCGIXMLRPCRequestHandler` class is derived from +:class:`CGIXMLRPCRequestHandler` and provides a means of creating +self-documenting, XML-RPC CGI scripts. HTTP POST requests are handled as XML-RPC +method calls. HTTP GET requests are handled by generating pydoc-style HTML +documentation. This allows a server to provide its own web-based documentation. + + +.. method:: DocCGIXMLRPCRequestHandler.set_server_title(server_title) + + Set the title used in the generated HTML documentation. This title will be used + inside the HTML "title" element. + + +.. method:: DocCGIXMLRPCRequestHandler.set_server_name(server_name) + + Set the name used in the generated HTML documentation. This name will appear at + the top of the generated documentation inside a "h1" element. + + +.. method:: DocCGIXMLRPCRequestHandler.set_server_documentation(server_documentation) + + Set the description used in the generated HTML documentation. This description + will appear as a paragraph, below the server name, in the documentation. diff --git a/cpython_2/environment/repo/Doc/library/zipapp.rst b/cpython_2/environment/repo/Doc/library/zipapp.rst new file mode 100644 index 0000000000000000000000000000000000000000..fb40a2b3e964e4d52124d64134451a023dc4465c --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/zipapp.rst @@ -0,0 +1,449 @@ +:mod:`zipapp` --- Manage executable Python zip archives +======================================================= + +.. module:: zipapp + :synopsis: Manage executable Python zip archives + +.. versionadded:: 3.5 + +**Source code:** :source:`Lib/zipapp.py` + +.. index:: + single: Executable Zip Files + +-------------- + +This module provides tools to manage the creation of zip files containing +Python code, which can be :ref:`executed directly by the Python interpreter +`. The module provides both a +:ref:`zipapp-command-line-interface` and a :ref:`zipapp-python-api`. + + +Basic Example +------------- + +The following example shows how the :ref:`zipapp-command-line-interface` +can be used to create an executable archive from a directory containing +Python code. When run, the archive will execute the ``main`` function from +the module ``myapp`` in the archive. + +.. code-block:: shell-session + + $ python -m zipapp myapp -m "myapp:main" + $ python myapp.pyz + + + +.. _zipapp-command-line-interface: + +Command-Line Interface +---------------------- + +When called as a program from the command line, the following form is used: + +.. code-block:: shell-session + + $ python -m zipapp source [options] + +If *source* is a directory, this will create an archive from the contents of +*source*. If *source* is a file, it should be an archive, and it will be +copied to the target archive (or the contents of its shebang line will be +displayed if the --info option is specified). + +The following options are understood: + +.. program:: zipapp + +.. cmdoption:: -o , --output= + + Write the output to a file named *output*. If this option is not specified, + the output filename will be the same as the input *source*, with the + extension ``.pyz`` added. If an explicit filename is given, it is used as + is (so a ``.pyz`` extension should be included if required). + + An output filename must be specified if the *source* is an archive (and in + that case, *output* must not be the same as *source*). + +.. cmdoption:: -p , --python= + + Add a ``#!`` line to the archive specifying *interpreter* as the command + to run. Also, on POSIX, make the archive executable. The default is to + write no ``#!`` line, and not make the file executable. + +.. cmdoption:: -m , --main= + + Write a ``__main__.py`` file to the archive that executes *mainfn*. The + *mainfn* argument should have the form "pkg.mod:fn", where "pkg.mod" is a + package/module in the archive, and "fn" is a callable in the given module. + The ``__main__.py`` file will execute that callable. + + :option:`--main` cannot be specified when copying an archive. + +.. cmdoption:: -c, --compress + + Compress files with the deflate method, reducing the size of the output + file. By default, files are stored uncompressed in the archive. + + :option:`--compress` has no effect when copying an archive. + + .. versionadded:: 3.7 + +.. cmdoption:: --info + + Display the interpreter embedded in the archive, for diagnostic purposes. In + this case, any other options are ignored and SOURCE must be an archive, not a + directory. + +.. cmdoption:: -h, --help + + Print a short usage message and exit. + + +.. _zipapp-python-api: + +Python API +---------- + +The module defines two convenience functions: + + +.. function:: create_archive(source, target=None, interpreter=None, main=None, filter=None, compressed=False) + + Create an application archive from *source*. The source can be any + of the following: + + * The name of a directory, or a :term:`path-like object` referring + to a directory, in which case a new application archive will be + created from the content of that directory. + * The name of an existing application archive file, or a :term:`path-like object` + referring to such a file, in which case the file is copied to + the target (modifying it to reflect the value given for the *interpreter* + argument). The file name should include the ``.pyz`` extension, if required. + * A file object open for reading in bytes mode. The content of the + file should be an application archive, and the file object is + assumed to be positioned at the start of the archive. + + The *target* argument determines where the resulting archive will be + written: + + * If it is the name of a file, or a :term:`path-like object`, + the archive will be written to that file. + * If it is an open file object, the archive will be written to that + file object, which must be open for writing in bytes mode. + * If the target is omitted (or ``None``), the source must be a directory + and the target will be a file with the same name as the source, with + a ``.pyz`` extension added. + + The *interpreter* argument specifies the name of the Python + interpreter with which the archive will be executed. It is written as + a "shebang" line at the start of the archive. On POSIX, this will be + interpreted by the OS, and on Windows it will be handled by the Python + launcher. Omitting the *interpreter* results in no shebang line being + written. If an interpreter is specified, and the target is a + filename, the executable bit of the target file will be set. + + The *main* argument specifies the name of a callable which will be + used as the main program for the archive. It can only be specified if + the source is a directory, and the source does not already contain a + ``__main__.py`` file. The *main* argument should take the form + "pkg.module:callable" and the archive will be run by importing + "pkg.module" and executing the given callable with no arguments. It + is an error to omit *main* if the source is a directory and does not + contain a ``__main__.py`` file, as otherwise the resulting archive + would not be executable. + + The optional *filter* argument specifies a callback function that + is passed a Path object representing the path to the file being added + (relative to the source directory). It should return ``True`` if the + file is to be added. + + The optional *compressed* argument determines whether files are + compressed. If set to ``True``, files in the archive are compressed + with the deflate method; otherwise, files are stored uncompressed. + This argument has no effect when copying an existing archive. + + If a file object is specified for *source* or *target*, it is the + caller's responsibility to close it after calling create_archive. + + When copying an existing archive, file objects supplied only need + ``read`` and ``readline``, or ``write`` methods. When creating an + archive from a directory, if the target is a file object it will be + passed to the ``zipfile.ZipFile`` class, and must supply the methods + needed by that class. + + .. versionadded:: 3.7 + Added the *filter* and *compressed* arguments. + +.. function:: get_interpreter(archive) + + Return the interpreter specified in the ``#!`` line at the start of the + archive. If there is no ``#!`` line, return :const:`None`. + The *archive* argument can be a filename or a file-like object open + for reading in bytes mode. It is assumed to be at the start of the archive. + + +.. _zipapp-examples: + +Examples +-------- + +Pack up a directory into an archive, and run it. + +.. code-block:: shell-session + + $ python -m zipapp myapp + $ python myapp.pyz + + +The same can be done using the :func:`create_archive` function:: + + >>> import zipapp + >>> zipapp.create_archive('myapp', 'myapp.pyz') + +To make the application directly executable on POSIX, specify an interpreter +to use. + +.. code-block:: shell-session + + $ python -m zipapp myapp -p "/usr/bin/env python" + $ ./myapp.pyz + + +To replace the shebang line on an existing archive, create a modified archive +using the :func:`create_archive` function:: + + >>> import zipapp + >>> zipapp.create_archive('old_archive.pyz', 'new_archive.pyz', '/usr/bin/python3') + +To update the file in place, do the replacement in memory using a :class:`BytesIO` +object, and then overwrite the source afterwards. Note that there is a risk +when overwriting a file in place that an error will result in the loss of +the original file. This code does not protect against such errors, but +production code should do so. Also, this method will only work if the archive +fits in memory:: + + >>> import zipapp + >>> import io + >>> temp = io.BytesIO() + >>> zipapp.create_archive('myapp.pyz', temp, '/usr/bin/python2') + >>> with open('myapp.pyz', 'wb') as f: + >>> f.write(temp.getvalue()) + + +.. _zipapp-specifying-the-interpreter: + +Specifying the Interpreter +-------------------------- + +Note that if you specify an interpreter and then distribute your application +archive, you need to ensure that the interpreter used is portable. The Python +launcher for Windows supports most common forms of POSIX ``#!`` line, but there +are other issues to consider: + +* If you use "/usr/bin/env python" (or other forms of the "python" command, + such as "/usr/bin/python"), you need to consider that your users may have + either Python 2 or Python 3 as their default, and write your code to work + under both versions. +* If you use an explicit version, for example "/usr/bin/env python3" your + application will not work for users who do not have that version. (This + may be what you want if you have not made your code Python 2 compatible). +* There is no way to say "python X.Y or later", so be careful of using an + exact version like "/usr/bin/env python3.4" as you will need to change your + shebang line for users of Python 3.5, for example. + +Typically, you should use an "/usr/bin/env python2" or "/usr/bin/env python3", +depending on whether your code is written for Python 2 or 3. + + +Creating Standalone Applications with zipapp +-------------------------------------------- + +Using the :mod:`zipapp` module, it is possible to create self-contained Python +programs, which can be distributed to end users who only need to have a +suitable version of Python installed on their system. The key to doing this +is to bundle all of the application's dependencies into the archive, along +with the application code. + +The steps to create a standalone archive are as follows: + +1. Create your application in a directory as normal, so you have a ``myapp`` + directory containing a ``__main__.py`` file, and any supporting application + code. + +2. Install all of your application's dependencies into the ``myapp`` directory, + using pip: + + .. code-block:: shell-session + + $ python -m pip install -r requirements.txt --target myapp + + (this assumes you have your project requirements in a ``requirements.txt`` + file - if not, you can just list the dependencies manually on the pip command + line). + +3. Optionally, delete the ``.dist-info`` directories created by pip in the + ``myapp`` directory. These hold metadata for pip to manage the packages, and + as you won't be making any further use of pip they aren't required - + although it won't do any harm if you leave them. + +4. Package the application using: + + .. code-block:: shell-session + + $ python -m zipapp -p "interpreter" myapp + +This will produce a standalone executable, which can be run on any machine with +the appropriate interpreter available. See :ref:`zipapp-specifying-the-interpreter` +for details. It can be shipped to users as a single file. + +On Unix, the ``myapp.pyz`` file is executable as it stands. You can rename the +file to remove the ``.pyz`` extension if you prefer a "plain" command name. On +Windows, the ``myapp.pyz[w]`` file is executable by virtue of the fact that +the Python interpreter registers the ``.pyz`` and ``.pyzw`` file extensions +when installed. + + +Making a Windows executable +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +On Windows, registration of the ``.pyz`` extension is optional, and +furthermore, there are certain places that don't recognise registered +extensions "transparently" (the simplest example is that +``subprocess.run(['myapp'])`` won't find your application - you need to +explicitly specify the extension). + +On Windows, therefore, it is often preferable to create an executable from the +zipapp. This is relatively easy, although it does require a C compiler. The +basic approach relies on the fact that zipfiles can have arbitrary data +prepended, and Windows exe files can have arbitrary data appended. So by +creating a suitable launcher and tacking the ``.pyz`` file onto the end of it, +you end up with a single-file executable that runs your application. + +A suitable launcher can be as simple as the following:: + + #define Py_LIMITED_API 1 + #include "Python.h" + + #define WIN32_LEAN_AND_MEAN + #include + + #ifdef WINDOWS + int WINAPI wWinMain( + HINSTANCE hInstance, /* handle to current instance */ + HINSTANCE hPrevInstance, /* handle to previous instance */ + LPWSTR lpCmdLine, /* pointer to command line */ + int nCmdShow /* show state of window */ + ) + #else + int wmain() + #endif + { + wchar_t **myargv = _alloca((__argc + 1) * sizeof(wchar_t*)); + myargv[0] = __wargv[0]; + memcpy(myargv + 1, __wargv, __argc * sizeof(wchar_t *)); + return Py_Main(__argc+1, myargv); + } + +If you define the ``WINDOWS`` preprocessor symbol, this will generate a +GUI executable, and without it, a console executable. + +To compile the executable, you can either just use the standard MSVC +command line tools, or you can take advantage of the fact that distutils +knows how to compile Python source:: + + >>> from distutils.ccompiler import new_compiler + >>> import distutils.sysconfig + >>> import sys + >>> import os + >>> from pathlib import Path + + >>> def compile(src): + >>> src = Path(src) + >>> cc = new_compiler() + >>> exe = src.stem + >>> cc.add_include_dir(distutils.sysconfig.get_python_inc()) + >>> cc.add_library_dir(os.path.join(sys.base_exec_prefix, 'libs')) + >>> # First the CLI executable + >>> objs = cc.compile([str(src)]) + >>> cc.link_executable(objs, exe) + >>> # Now the GUI executable + >>> cc.define_macro('WINDOWS') + >>> objs = cc.compile([str(src)]) + >>> cc.link_executable(objs, exe + 'w') + + >>> if __name__ == "__main__": + >>> compile("zastub.c") + +The resulting launcher uses the "Limited ABI", so it will run unchanged with +any version of Python 3.x. All it needs is for Python (``python3.dll``) to be +on the user's ``PATH``. + +For a fully standalone distribution, you can distribute the launcher with your +application appended, bundled with the Python "embedded" distribution. This +will run on any PC with the appropriate architecture (32 bit or 64 bit). + + +Caveats +~~~~~~~ + +There are some limitations to the process of bundling your application into +a single file. In most, if not all, cases they can be addressed without +needing major changes to your application. + +1. If your application depends on a package that includes a C extension, that + package cannot be run from a zip file (this is an OS limitation, as executable + code must be present in the filesystem for the OS loader to load it). In this + case, you can exclude that dependency from the zipfile, and either require + your users to have it installed, or ship it alongside your zipfile and add code + to your ``__main__.py`` to include the directory containing the unzipped + module in ``sys.path``. In this case, you will need to make sure to ship + appropriate binaries for your target architecture(s) (and potentially pick the + correct version to add to ``sys.path`` at runtime, based on the user's machine). + +2. If you are shipping a Windows executable as described above, you either need to + ensure that your users have ``python3.dll`` on their PATH (which is not the + default behaviour of the installer) or you should bundle your application with + the embedded distribution. + +3. The suggested launcher above uses the Python embedding API. This means that in + your application, ``sys.executable`` will be your application, and *not* a + conventional Python interpreter. Your code and its dependencies need to be + prepared for this possibility. For example, if your application uses the + :mod:`multiprocessing` module, it will need to call + :func:`multiprocessing.set_executable` to let the module know where to find the + standard Python interpreter. + + +The Python Zip Application Archive Format +----------------------------------------- + +Python has been able to execute zip files which contain a ``__main__.py`` file +since version 2.6. In order to be executed by Python, an application archive +simply has to be a standard zip file containing a ``__main__.py`` file which +will be run as the entry point for the application. As usual for any Python +script, the parent of the script (in this case the zip file) will be placed on +:data:`sys.path` and thus further modules can be imported from the zip file. + +The zip file format allows arbitrary data to be prepended to a zip file. The +zip application format uses this ability to prepend a standard POSIX "shebang" +line to the file (``#!/path/to/interpreter``). + +Formally, the Python zip application format is therefore: + +1. An optional shebang line, containing the characters ``b'#!'`` followed by an + interpreter name, and then a newline (``b'\n'``) character. The interpreter + name can be anything acceptable to the OS "shebang" processing, or the Python + launcher on Windows. The interpreter should be encoded in UTF-8 on Windows, + and in :func:`sys.getfilesystemencoding()` on POSIX. +2. Standard zipfile data, as generated by the :mod:`zipfile` module. The + zipfile content *must* include a file called ``__main__.py`` (which must be + in the "root" of the zipfile - i.e., it cannot be in a subdirectory). The + zipfile data can be compressed or uncompressed. + +If an application archive has a shebang line, it may have the executable bit set +on POSIX systems, to allow it to be executed directly. + +There is no requirement that the tools in this module are used to create +application archives - the module is a convenience, but archives in the above +format created by any means are acceptable to Python. + diff --git a/cpython_2/environment/repo/Doc/library/zipfile.rst b/cpython_2/environment/repo/Doc/library/zipfile.rst new file mode 100644 index 0000000000000000000000000000000000000000..7126d8bd703f62902eb400059132529bd393b8bc --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/zipfile.rst @@ -0,0 +1,870 @@ +:mod:`zipfile` --- Work with ZIP archives +========================================= + +.. module:: zipfile + :synopsis: Read and write ZIP-format archive files. + +.. moduleauthor:: James C. Ahlstrom +.. sectionauthor:: James C. Ahlstrom + +**Source code:** :source:`Lib/zipfile.py` + +-------------- + +The ZIP file format is a common archive and compression standard. This module +provides tools to create, read, write, append, and list a ZIP file. Any +advanced use of this module will require an understanding of the format, as +defined in `PKZIP Application Note`_. + +This module does not currently handle multi-disk ZIP files. +It can handle ZIP files that use the ZIP64 extensions +(that is ZIP files that are more than 4 GiB in size). It supports +decryption of encrypted files in ZIP archives, but it currently cannot +create an encrypted file. Decryption is extremely slow as it is +implemented in native Python rather than C. + +The module defines the following items: + +.. exception:: BadZipFile + + The error raised for bad ZIP files. + + .. versionadded:: 3.2 + + +.. exception:: BadZipfile + + Alias of :exc:`BadZipFile`, for compatibility with older Python versions. + + .. deprecated:: 3.2 + + +.. exception:: LargeZipFile + + The error raised when a ZIP file would require ZIP64 functionality but that has + not been enabled. + + +.. class:: ZipFile + :noindex: + + The class for reading and writing ZIP files. See section + :ref:`zipfile-objects` for constructor details. + + +.. class:: Path + :noindex: + + A pathlib-compatible wrapper for zip files. See section + :ref:`path-objects` for details. + + .. versionadded:: 3.8 + + +.. class:: PyZipFile + :noindex: + + Class for creating ZIP archives containing Python libraries. + + +.. class:: ZipInfo(filename='NoName', date_time=(1980,1,1,0,0,0)) + + Class used to represent information about a member of an archive. Instances + of this class are returned by the :meth:`.getinfo` and :meth:`.infolist` + methods of :class:`ZipFile` objects. Most users of the :mod:`zipfile` module + will not need to create these, but only use those created by this + module. *filename* should be the full name of the archive member, and + *date_time* should be a tuple containing six fields which describe the time + of the last modification to the file; the fields are described in section + :ref:`zipinfo-objects`. + + +.. function:: is_zipfile(filename) + + Returns ``True`` if *filename* is a valid ZIP file based on its magic number, + otherwise returns ``False``. *filename* may be a file or file-like object too. + + .. versionchanged:: 3.1 + Support for file and file-like objects. + + +.. data:: ZIP_STORED + + The numeric constant for an uncompressed archive member. + + +.. data:: ZIP_DEFLATED + + The numeric constant for the usual ZIP compression method. This requires the + :mod:`zlib` module. + + +.. data:: ZIP_BZIP2 + + The numeric constant for the BZIP2 compression method. This requires the + :mod:`bz2` module. + + .. versionadded:: 3.3 + +.. data:: ZIP_LZMA + + The numeric constant for the LZMA compression method. This requires the + :mod:`lzma` module. + + .. versionadded:: 3.3 + + .. note:: + + The ZIP file format specification has included support for bzip2 compression + since 2001, and for LZMA compression since 2006. However, some tools + (including older Python releases) do not support these compression + methods, and may either refuse to process the ZIP file altogether, + or fail to extract individual files. + + +.. seealso:: + + `PKZIP Application Note`_ + Documentation on the ZIP file format by Phil Katz, the creator of the format and + algorithms used. + + `Info-ZIP Home Page `_ + Information about the Info-ZIP project's ZIP archive programs and development + libraries. + + +.. _zipfile-objects: + +ZipFile Objects +--------------- + + +.. class:: ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, \ + compresslevel=None, *, strict_timestamps=True) + + Open a ZIP file, where *file* can be a path to a file (a string), a + file-like object or a :term:`path-like object`. + + The *mode* parameter should be ``'r'`` to read an existing + file, ``'w'`` to truncate and write a new file, ``'a'`` to append to an + existing file, or ``'x'`` to exclusively create and write a new file. + If *mode* is ``'x'`` and *file* refers to an existing file, + a :exc:`FileExistsError` will be raised. + If *mode* is ``'a'`` and *file* refers to an existing ZIP + file, then additional files are added to it. If *file* does not refer to a + ZIP file, then a new ZIP archive is appended to the file. This is meant for + adding a ZIP archive to another file (such as :file:`python.exe`). If + *mode* is ``'a'`` and the file does not exist at all, it is created. + If *mode* is ``'r'`` or ``'a'``, the file should be seekable. + + *compression* is the ZIP compression method to use when writing the archive, + and should be :const:`ZIP_STORED`, :const:`ZIP_DEFLATED`, + :const:`ZIP_BZIP2` or :const:`ZIP_LZMA`; unrecognized + values will cause :exc:`NotImplementedError` to be raised. If + :const:`ZIP_DEFLATED`, :const:`ZIP_BZIP2` or :const:`ZIP_LZMA` is specified + but the corresponding module (:mod:`zlib`, :mod:`bz2` or :mod:`lzma`) is not + available, :exc:`RuntimeError` is raised. The default is :const:`ZIP_STORED`. + + If *allowZip64* is ``True`` (the default) zipfile will create ZIP files that + use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is + ``false`` :mod:`zipfile` will raise an exception when the ZIP file would + require ZIP64 extensions. + + The *compresslevel* parameter controls the compression level to use when + writing files to the archive. + When using :const:`ZIP_STORED` or :const:`ZIP_LZMA` it has no effect. + When using :const:`ZIP_DEFLATED` integers ``0`` through ``9`` are accepted + (see :class:`zlib ` for more information). + When using :const:`ZIP_BZIP2` integers ``1`` through ``9`` are accepted + (see :class:`bz2 ` for more information). + + The *strict_timestamps* argument, when set to ``False``, allows to + zip files older than 1980-01-01 at the cost of setting the + timestamp to 1980-01-01. + Similar behavior occurs with files newer than 2107-12-31, + the timestamp is also set to the limit. + + If the file is created with mode ``'w'``, ``'x'`` or ``'a'`` and then + :meth:`closed ` without adding any files to the archive, the appropriate + ZIP structures for an empty archive will be written to the file. + + ZipFile is also a context manager and therefore supports the + :keyword:`with` statement. In the example, *myzip* is closed after the + :keyword:`!with` statement's suite is finished---even if an exception occurs:: + + with ZipFile('spam.zip', 'w') as myzip: + myzip.write('eggs.txt') + + .. versionadded:: 3.2 + Added the ability to use :class:`ZipFile` as a context manager. + + .. versionchanged:: 3.3 + Added support for :mod:`bzip2 ` and :mod:`lzma` compression. + + .. versionchanged:: 3.4 + ZIP64 extensions are enabled by default. + + .. versionchanged:: 3.5 + Added support for writing to unseekable streams. + Added support for the ``'x'`` mode. + + .. versionchanged:: 3.6 + Previously, a plain :exc:`RuntimeError` was raised for unrecognized + compression values. + + .. versionchanged:: 3.6.2 + The *file* parameter accepts a :term:`path-like object`. + + .. versionchanged:: 3.7 + Add the *compresslevel* parameter. + + .. versionadded:: 3.8 + The *strict_timestamps* keyword-only argument + + +.. method:: ZipFile.close() + + Close the archive file. You must call :meth:`close` before exiting your program + or essential records will not be written. + + +.. method:: ZipFile.getinfo(name) + + Return a :class:`ZipInfo` object with information about the archive member + *name*. Calling :meth:`getinfo` for a name not currently contained in the + archive will raise a :exc:`KeyError`. + + +.. method:: ZipFile.infolist() + + Return a list containing a :class:`ZipInfo` object for each member of the + archive. The objects are in the same order as their entries in the actual ZIP + file on disk if an existing archive was opened. + + +.. method:: ZipFile.namelist() + + Return a list of archive members by name. + + +.. method:: ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False) + + Access a member of the archive as a binary file-like object. *name* + can be either the name of a file within the archive or a :class:`ZipInfo` + object. The *mode* parameter, if included, must be ``'r'`` (the default) + or ``'w'``. *pwd* is the password used to decrypt encrypted ZIP files. + + :meth:`~ZipFile.open` is also a context manager and therefore supports the + :keyword:`with` statement:: + + with ZipFile('spam.zip') as myzip: + with myzip.open('eggs.txt') as myfile: + print(myfile.read()) + + With *mode* ``'r'`` the file-like object + (``ZipExtFile``) is read-only and provides the following methods: + :meth:`~io.BufferedIOBase.read`, :meth:`~io.IOBase.readline`, + :meth:`~io.IOBase.readlines`, :meth:`~io.IOBase.seek`, + :meth:`~io.IOBase.tell`, :meth:`__iter__`, :meth:`~iterator.__next__`. + These objects can operate independently of the ZipFile. + + With ``mode='w'``, a writable file handle is returned, which supports the + :meth:`~io.BufferedIOBase.write` method. While a writable file handle is open, + attempting to read or write other files in the ZIP file will raise a + :exc:`ValueError`. + + When writing a file, if the file size is not known in advance but may exceed + 2 GiB, pass ``force_zip64=True`` to ensure that the header format is + capable of supporting large files. If the file size is known in advance, + construct a :class:`ZipInfo` object with :attr:`~ZipInfo.file_size` set, and + use that as the *name* parameter. + + .. note:: + + The :meth:`.open`, :meth:`read` and :meth:`extract` methods can take a filename + or a :class:`ZipInfo` object. You will appreciate this when trying to read a + ZIP file that contains members with duplicate names. + + .. versionchanged:: 3.6 + Removed support of ``mode='U'``. Use :class:`io.TextIOWrapper` for reading + compressed text files in :term:`universal newlines` mode. + + .. versionchanged:: 3.6 + :meth:`open` can now be used to write files into the archive with the + ``mode='w'`` option. + + .. versionchanged:: 3.6 + Calling :meth:`.open` on a closed ZipFile will raise a :exc:`ValueError`. + Previously, a :exc:`RuntimeError` was raised. + + +.. method:: ZipFile.extract(member, path=None, pwd=None) + + Extract a member from the archive to the current working directory; *member* + must be its full name or a :class:`ZipInfo` object. Its file information is + extracted as accurately as possible. *path* specifies a different directory + to extract to. *member* can be a filename or a :class:`ZipInfo` object. + *pwd* is the password used for encrypted files. + + Returns the normalized path created (a directory or new file). + + .. note:: + + If a member filename is an absolute path, a drive/UNC sharepoint and + leading (back)slashes will be stripped, e.g.: ``///foo/bar`` becomes + ``foo/bar`` on Unix, and ``C:\foo\bar`` becomes ``foo\bar`` on Windows. + And all ``".."`` components in a member filename will be removed, e.g.: + ``../../foo../../ba..r`` becomes ``foo../ba..r``. On Windows illegal + characters (``:``, ``<``, ``>``, ``|``, ``"``, ``?``, and ``*``) + replaced by underscore (``_``). + + .. versionchanged:: 3.6 + Calling :meth:`extract` on a closed ZipFile will raise a + :exc:`ValueError`. Previously, a :exc:`RuntimeError` was raised. + + .. versionchanged:: 3.6.2 + The *path* parameter accepts a :term:`path-like object`. + + +.. method:: ZipFile.extractall(path=None, members=None, pwd=None) + + 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. + + .. warning:: + + Never extract archives from untrusted sources without prior inspection. + It is possible that files are created outside of *path*, e.g. members + that have absolute filenames starting with ``"/"`` or filenames with two + dots ``".."``. This module attempts to prevent that. + See :meth:`extract` note. + + .. versionchanged:: 3.6 + Calling :meth:`extractall` on a closed ZipFile will raise a + :exc:`ValueError`. Previously, a :exc:`RuntimeError` was raised. + + .. versionchanged:: 3.6.2 + The *path* parameter accepts a :term:`path-like object`. + + +.. method:: ZipFile.printdir() + + Print a table of contents for the archive to ``sys.stdout``. + + +.. method:: ZipFile.setpassword(pwd) + + Set *pwd* as default password to extract encrypted files. + + +.. method:: ZipFile.read(name, pwd=None) + + Return the bytes of the file *name* in the archive. *name* is the name of the + file in the archive, or a :class:`ZipInfo` object. The archive must be open for + read or append. *pwd* is the password used for encrypted files and, if specified, + it will override the default password set with :meth:`setpassword`. Calling + :meth:`read` on a ZipFile that uses a compression method other than + :const:`ZIP_STORED`, :const:`ZIP_DEFLATED`, :const:`ZIP_BZIP2` or + :const:`ZIP_LZMA` will raise a :exc:`NotImplementedError`. An error will also + be raised if the corresponding compression module is not available. + + .. versionchanged:: 3.6 + Calling :meth:`read` on a closed ZipFile will raise a :exc:`ValueError`. + Previously, a :exc:`RuntimeError` was raised. + + +.. method:: ZipFile.testzip() + + Read all the files in the archive and check their CRC's and file headers. + Return the name of the first bad file, or else return ``None``. + + .. versionchanged:: 3.6 + Calling :meth:`testzip` on a closed ZipFile will raise a + :exc:`ValueError`. Previously, a :exc:`RuntimeError` was raised. + + +.. method:: ZipFile.write(filename, arcname=None, compress_type=None, \ + compresslevel=None) + + Write the file named *filename* to the archive, giving it the archive name + *arcname* (by default, this will be the same as *filename*, but without a drive + letter and with leading path separators removed). If given, *compress_type* + overrides the value given for the *compression* parameter to the constructor for + the new entry. Similarly, *compresslevel* will override the constructor if + given. + The archive must be open with mode ``'w'``, ``'x'`` or ``'a'``. + + .. note:: + + Archive names should be relative to the archive root, that is, they should not + start with a path separator. + + .. note:: + + If ``arcname`` (or ``filename``, if ``arcname`` is not given) contains a null + byte, the name of the file in the archive will be truncated at the null byte. + + .. versionchanged:: 3.6 + Calling :meth:`write` on a ZipFile created with mode ``'r'`` or + a closed ZipFile will raise a :exc:`ValueError`. Previously, + a :exc:`RuntimeError` was raised. + + +.. method:: ZipFile.writestr(zinfo_or_arcname, data, compress_type=None, \ + compresslevel=None) + + Write a file into the archive. The contents is *data*, which may be either + a :class:`str` or a :class:`bytes` instance; if it is a :class:`str`, + it is encoded as UTF-8 first. *zinfo_or_arcname* is either the file + name it will be given in the archive, or a :class:`ZipInfo` instance. If it's + an instance, at least the filename, date, and time must be given. If it's a + name, the date and time is set to the current date and time. + The archive must be opened with mode ``'w'``, ``'x'`` or ``'a'``. + + If given, *compress_type* overrides the value given for the *compression* + parameter to the constructor for the new entry, or in the *zinfo_or_arcname* + (if that is a :class:`ZipInfo` instance). Similarly, *compresslevel* will + override the constructor if given. + + .. note:: + + When passing a :class:`ZipInfo` instance as the *zinfo_or_arcname* 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`. + + .. versionchanged:: 3.2 + The *compress_type* argument. + + .. versionchanged:: 3.6 + Calling :meth:`writestr` on a ZipFile created with mode ``'r'`` or + a closed ZipFile will raise a :exc:`ValueError`. Previously, + a :exc:`RuntimeError` was raised. + + +The following data attributes are also available: + +.. attribute:: ZipFile.filename + + Name of the ZIP file. + +.. attribute:: ZipFile.debug + + The level of debug output to use. This may be set from ``0`` (the default, no + output) to ``3`` (the most output). Debugging information is written to + ``sys.stdout``. + +.. attribute:: ZipFile.comment + + The comment associated with the ZIP file as a :class:`bytes` object. + If assigning a comment to a + :class:`ZipFile` instance created with mode ``'w'``, ``'x'`` or ``'a'``, + it should be no longer than 65535 bytes. Comments longer than this will be + truncated. + + +.. _path-objects: + +Path Objects +------------ + +.. class:: Path(root, at='') + + Construct a Path object from a ``root`` zipfile (which may be a + :class:`ZipFile` instance or ``file`` suitable for passing to + the :class:`ZipFile` constructor). + + ``at`` specifies the location of this Path within the zipfile, + e.g. 'dir/file.txt', 'dir/', or ''. Defaults to the empty string, + indicating the root. + +Path objects expose the following features of :mod:`pathlib.Path` +objects: + +Path objects are traversable using the ``/`` operator. + +.. attribute:: Path.name + + The final path component. + +.. method:: Path.open(mode='r', *, pwd, **) + + Invoke :meth:`ZipFile.open` on the current path. + Allows opening for read or write, text or binary + through supported modes: 'r', 'w', 'rb', 'wb'. + Positional and keyword arguments are passed through to + :class:`io.TextIOWrapper` when opened as text and + ignored otherwise. + ``pwd`` is the ``pwd`` parameter to + :meth:`ZipFile.open`. + + .. versionchanged:: 3.9 + Added support for text and binary modes for open. Default + mode is now text. + +.. method:: Path.iterdir() + + Enumerate the children of the current directory. + +.. method:: Path.is_dir() + + Return ``True`` if the current context references a directory. + +.. method:: Path.is_file() + + Return ``True`` if the current context references a file. + +.. method:: Path.exists() + + Return ``True`` if the current context references a file or + directory in the zip file. + +.. method:: Path.read_text(*, **) + + Read the current file as unicode text. Positional and + keyword arguments are passed through to + :class:`io.TextIOWrapper` (except ``buffer``, which is + implied by the context). + +.. method:: Path.read_bytes() + + Read the current file as bytes. + + +.. _pyzipfile-objects: + +PyZipFile Objects +----------------- + +The :class:`PyZipFile` constructor takes the same parameters as the +:class:`ZipFile` constructor, and one additional parameter, *optimize*. + +.. class:: PyZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, \ + optimize=-1) + + .. versionadded:: 3.2 + The *optimize* parameter. + + .. versionchanged:: 3.4 + ZIP64 extensions are enabled by default. + + Instances have one method in addition to those of :class:`ZipFile` objects: + + .. method:: PyZipFile.writepy(pathname, basename='', filterfunc=None) + + Search for files :file:`\*.py` and add the corresponding file to the + archive. + + If the *optimize* parameter to :class:`PyZipFile` was not given or ``-1``, + the corresponding file is a :file:`\*.pyc` file, compiling if necessary. + + If the *optimize* parameter to :class:`PyZipFile` was ``0``, ``1`` or + ``2``, only files with that optimization level (see :func:`compile`) are + added to the archive, compiling if necessary. + + If *pathname* is a file, the filename must end with :file:`.py`, and + just the (corresponding :file:`\*.pyc`) file is added at the top level + (no path information). If *pathname* is a file that does not end with + :file:`.py`, a :exc:`RuntimeError` will be raised. If it is a directory, + and the directory is not a package directory, then all the files + :file:`\*.pyc` are added at the top level. If the directory is a + package directory, then all :file:`\*.pyc` are added under the package + name as a file path, and if any subdirectories are package directories, + all of these are added recursively in sorted order. + + *basename* is intended for internal use only. + + *filterfunc*, if given, must be a function taking a single string + argument. It will be passed each path (including each individual full + file path) before it is added to the archive. If *filterfunc* returns a + false value, the path will not be added, and if it is a directory its + contents will be ignored. For example, if our test files are all either + in ``test`` directories or start with the string ``test_``, we can use a + *filterfunc* to exclude them:: + + >>> zf = PyZipFile('myprog.zip') + >>> def notests(s): + ... fn = os.path.basename(s) + ... return (not (fn == 'test' or fn.startswith('test_'))) + >>> zf.writepy('myprog', filterfunc=notests) + + The :meth:`writepy` method makes archives with file names like + this:: + + string.pyc # Top level name + test/__init__.pyc # Package directory + test/testall.pyc # Module test.testall + test/bogus/__init__.pyc # Subpackage directory + test/bogus/myfile.pyc # Submodule test.bogus.myfile + + .. versionadded:: 3.4 + The *filterfunc* parameter. + + .. versionchanged:: 3.6.2 + The *pathname* parameter accepts a :term:`path-like object`. + + .. versionchanged:: 3.7 + Recursion sorts directory entries. + + +.. _zipinfo-objects: + +ZipInfo Objects +--------------- + +Instances of the :class:`ZipInfo` class are returned by the :meth:`.getinfo` and +:meth:`.infolist` methods of :class:`ZipFile` objects. Each object stores +information about a single member of the ZIP archive. + +There is one classmethod to make a :class:`ZipInfo` instance for a filesystem +file: + +.. classmethod:: ZipInfo.from_file(filename, arcname=None, *, \ + strict_timestamps=True) + + Construct a :class:`ZipInfo` instance for a file on the filesystem, in + preparation for adding it to a zip file. + + *filename* should be the path to a file or directory on the filesystem. + + If *arcname* is specified, it is used as the name within the archive. + If *arcname* is not specified, the name will be the same as *filename*, but + with any drive letter and leading path separators removed. + + The *strict_timestamps* argument, when set to ``False``, allows to + zip files older than 1980-01-01 at the cost of setting the + timestamp to 1980-01-01. + Similar behavior occurs with files newer than 2107-12-31, + the timestamp is also set to the limit. + + .. versionadded:: 3.6 + + .. versionchanged:: 3.6.2 + The *filename* parameter accepts a :term:`path-like object`. + + .. versionadded:: 3.8 + The *strict_timestamps* keyword-only argument + + +Instances have the following methods and attributes: + +.. method:: ZipInfo.is_dir() + + Return ``True`` if this archive member is a directory. + + This uses the entry's name: directories should always end with ``/``. + + .. versionadded:: 3.6 + + +.. attribute:: ZipInfo.filename + + Name of the file in the archive. + + +.. attribute:: ZipInfo.date_time + + The time and date of the last modification to the archive member. This is a + tuple of six values: + + +-------+--------------------------+ + | Index | Value | + +=======+==========================+ + | ``0`` | Year (>= 1980) | + +-------+--------------------------+ + | ``1`` | Month (one-based) | + +-------+--------------------------+ + | ``2`` | Day of month (one-based) | + +-------+--------------------------+ + | ``3`` | Hours (zero-based) | + +-------+--------------------------+ + | ``4`` | Minutes (zero-based) | + +-------+--------------------------+ + | ``5`` | Seconds (zero-based) | + +-------+--------------------------+ + + .. note:: + + The ZIP file format does not support timestamps before 1980. + + +.. attribute:: ZipInfo.compress_type + + Type of compression for the archive member. + + +.. attribute:: ZipInfo.comment + + Comment for the individual archive member as a :class:`bytes` object. + + +.. attribute:: ZipInfo.extra + + Expansion field data. The `PKZIP Application Note`_ contains + some comments on the internal structure of the data contained in this + :class:`bytes` object. + + +.. attribute:: ZipInfo.create_system + + System which created ZIP archive. + + +.. attribute:: ZipInfo.create_version + + PKZIP version which created ZIP archive. + + +.. attribute:: ZipInfo.extract_version + + PKZIP version needed to extract archive. + + +.. attribute:: ZipInfo.reserved + + Must be zero. + + +.. attribute:: ZipInfo.flag_bits + + ZIP flag bits. + + +.. attribute:: ZipInfo.volume + + Volume number of file header. + + +.. attribute:: ZipInfo.internal_attr + + Internal attributes. + + +.. attribute:: ZipInfo.external_attr + + External file attributes. + + +.. attribute:: ZipInfo.header_offset + + Byte offset to the file header. + + +.. attribute:: ZipInfo.CRC + + CRC-32 of the uncompressed file. + + +.. attribute:: ZipInfo.compress_size + + Size of the compressed data. + + +.. attribute:: ZipInfo.file_size + + Size of the uncompressed file. + + +.. _zipfile-commandline: +.. program:: zipfile + +Command-Line Interface +---------------------- + +The :mod:`zipfile` module provides a simple command-line interface to interact +with ZIP archives. + +If you want to create a new ZIP archive, specify its name after the :option:`-c` +option and then list the filename(s) that should be included: + +.. code-block:: shell-session + + $ python -m zipfile -c monty.zip spam.txt eggs.txt + +Passing a directory is also acceptable: + +.. code-block:: shell-session + + $ python -m zipfile -c monty.zip life-of-brian_1979/ + +If you want to extract a ZIP archive into the specified directory, use +the :option:`-e` option: + +.. code-block:: shell-session + + $ python -m zipfile -e monty.zip target-dir/ + +For a list of the files in a ZIP archive, use the :option:`-l` option: + +.. code-block:: shell-session + + $ python -m zipfile -l monty.zip + + +Command-line options +~~~~~~~~~~~~~~~~~~~~ + +.. cmdoption:: -l + --list + + List files in a zipfile. + +.. cmdoption:: -c ... + --create ... + + Create zipfile from source files. + +.. cmdoption:: -e + --extract + + Extract zipfile into target directory. + +.. cmdoption:: -t + --test + + Test whether the zipfile is valid or not. + +Decompression pitfalls +---------------------- + +The extraction in zipfile module might fail due to some pitfalls listed below. + +From file itself +~~~~~~~~~~~~~~~~ + +Decompression may fail due to incorrect password / CRC checksum / ZIP format or +unsupported compression method / decryption. + +File System limitations +~~~~~~~~~~~~~~~~~~~~~~~ + +Exceeding limitations on different file systems can cause decompression failed. +Such as allowable characters in the directory entries, length of the file name, +length of the pathname, size of a single file, and number of files, etc. + +Resources limitations +~~~~~~~~~~~~~~~~~~~~~ + +The lack of memory or disk volume would lead to decompression +failed. For example, decompression bombs (aka `ZIP bomb`_) +apply to zipfile library that can cause disk volume exhaustion. + +Interruption +~~~~~~~~~~~~ + +Interruption during the decompression, such as pressing control-C or killing the +decompression process may result in incomplete decompression of the archive. + +Default behaviors of extraction +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Not knowing the default extraction behaviors +can cause unexpected decompression results. +For example, when extracting the same archive twice, +it overwrites files without asking. + + +.. _ZIP bomb: https://en.wikipedia.org/wiki/Zip_bomb +.. _PKZIP Application Note: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT diff --git a/cpython_2/environment/repo/Doc/library/zipimport.rst b/cpython_2/environment/repo/Doc/library/zipimport.rst new file mode 100644 index 0000000000000000000000000000000000000000..8ac3fb16bdb90d1eb7675d9ea84d3e1cde801d9d --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/zipimport.rst @@ -0,0 +1,170 @@ +:mod:`zipimport` --- Import modules from Zip archives +===================================================== + +.. module:: zipimport + :synopsis: Support for importing Python modules from ZIP archives. + +.. moduleauthor:: Just van Rossum + +**Source code:** :source:`Lib/zipimport.py` + +-------------- + +This module adds the ability to import Python modules (:file:`\*.py`, +:file:`\*.pyc`) and packages from ZIP-format archives. It is usually not +needed to use the :mod:`zipimport` module explicitly; it is automatically used +by the built-in :keyword:`import` mechanism for :data:`sys.path` items that are paths +to ZIP archives. + +Typically, :data:`sys.path` is a list of directory names as strings. This module +also allows an item of :data:`sys.path` to be a string naming a ZIP file archive. +The ZIP archive can contain a subdirectory structure to support package imports, +and a path within the archive can be specified to only import from a +subdirectory. For example, the path :file:`example.zip/lib/` would only +import from the :file:`lib/` subdirectory within the archive. + +Any files may be present in the ZIP archive, but only files :file:`.py` and +:file:`.pyc` are available for import. ZIP import of dynamic modules +(:file:`.pyd`, :file:`.so`) is disallowed. Note that if an archive only contains +:file:`.py` files, Python will not attempt to modify the archive by adding the +corresponding :file:`.pyc` file, meaning that if a ZIP archive +doesn't contain :file:`.pyc` files, importing may be rather slow. + +.. versionchanged:: 3.8 + Previously, ZIP archives with an archive comment were not supported. + +.. seealso:: + + `PKZIP Application Note `_ + Documentation on the ZIP file format by Phil Katz, the creator of the format and + algorithms used. + + :pep:`273` - Import Modules from Zip Archives + Written by James C. Ahlstrom, who also provided an implementation. Python 2.3 + follows the specification in :pep:`273`, but uses an implementation written by Just + van Rossum that uses the import hooks described in :pep:`302`. + + :pep:`302` - New Import Hooks + The PEP to add the import hooks that help this module work. + + +This module defines an exception: + +.. exception:: ZipImportError + + Exception raised by zipimporter objects. It's a subclass of :exc:`ImportError`, + so it can be caught as :exc:`ImportError`, too. + + +.. _zipimporter-objects: + +zipimporter Objects +------------------- + +:class:`zipimporter` is the class for importing ZIP files. + +.. class:: zipimporter(archivepath) + + Create a new zipimporter instance. *archivepath* must be a path to a ZIP + file, or to a specific path within a ZIP file. For example, an *archivepath* + of :file:`foo/bar.zip/lib` will look for modules in the :file:`lib` directory + inside the ZIP file :file:`foo/bar.zip` (provided that it exists). + + :exc:`ZipImportError` is raised if *archivepath* doesn't point to a valid ZIP + archive. + + .. method:: find_module(fullname[, path]) + + Search for a module specified by *fullname*. *fullname* must be the fully + qualified (dotted) module name. It returns the zipimporter instance itself + if the module was found, or :const:`None` if it wasn't. The optional + *path* argument is ignored---it's there for compatibility with the + importer protocol. + + + .. method:: get_code(fullname) + + Return the code object for the specified module. Raise + :exc:`ZipImportError` if the module couldn't be found. + + + .. method:: get_data(pathname) + + Return the data associated with *pathname*. Raise :exc:`OSError` if the + file wasn't found. + + .. versionchanged:: 3.3 + :exc:`IOError` used to be raised instead of :exc:`OSError`. + + + .. method:: get_filename(fullname) + + Return the value ``__file__`` would be set to if the specified module + was imported. Raise :exc:`ZipImportError` if the module couldn't be + found. + + .. versionadded:: 3.1 + + + .. method:: get_source(fullname) + + Return the source code for the specified module. Raise + :exc:`ZipImportError` if the module couldn't be found, return + :const:`None` if the archive does contain the module, but has no source + for it. + + + .. method:: is_package(fullname) + + Return ``True`` if the module specified by *fullname* is a package. Raise + :exc:`ZipImportError` if the module couldn't be found. + + + .. method:: load_module(fullname) + + Load the module specified by *fullname*. *fullname* must be the fully + qualified (dotted) module name. It returns the imported module, or raises + :exc:`ZipImportError` if it wasn't found. + + + .. attribute:: archive + + The file name of the importer's associated ZIP file, without a possible + subpath. + + + .. attribute:: prefix + + The subpath within the ZIP file where modules are searched. This is the + empty string for zipimporter objects which point to the root of the ZIP + file. + + The :attr:`archive` and :attr:`prefix` attributes, when combined with a + slash, equal the original *archivepath* argument given to the + :class:`zipimporter` constructor. + + +.. _zipimport-examples: + +Examples +-------- + +Here is an example that imports a module from a ZIP archive - note that the +:mod:`zipimport` module is not explicitly used. + +.. code-block:: shell-session + + $ unzip -l example.zip + Archive: example.zip + Length Date Time Name + -------- ---- ---- ---- + 8467 11-26-02 22:30 jwzthreading.py + -------- ------- + 8467 1 file + $ ./python + Python 2.3 (#1, Aug 1 2003, 19:54:32) + >>> import sys + >>> sys.path.insert(0, 'example.zip') # Add .zip file to front of path + >>> import jwzthreading + >>> jwzthreading.__file__ + 'example.zip/jwzthreading.py' diff --git a/cpython_2/environment/repo/Doc/library/zlib.rst b/cpython_2/environment/repo/Doc/library/zlib.rst new file mode 100644 index 0000000000000000000000000000000000000000..ec60ea24db662709f0745715e91cf3c738885164 --- /dev/null +++ b/cpython_2/environment/repo/Doc/library/zlib.rst @@ -0,0 +1,339 @@ +:mod:`zlib` --- Compression compatible with :program:`gzip` +=========================================================== + +.. module:: zlib + :synopsis: Low-level interface to compression and decompression routines + compatible with gzip. + +-------------- + +For applications that require data compression, the functions in this module +allow compression and decompression, using the zlib library. The zlib library +has its own home page at https://www.zlib.net. There are known +incompatibilities between the Python module and versions of the zlib library +earlier than 1.1.3; 1.1.3 has a `security vulnerability `_, so we recommend using +1.1.4 or later. + +zlib's functions have many options and often need to be used in a particular +order. This documentation doesn't attempt to cover all of the permutations; +consult the zlib manual at http://www.zlib.net/manual.html for authoritative +information. + +For reading and writing ``.gz`` files see the :mod:`gzip` module. + +The available exception and functions in this module are: + + +.. exception:: error + + Exception raised on compression and decompression errors. + + +.. function:: adler32(data[, value]) + + Computes an Adler-32 checksum of *data*. (An Adler-32 checksum is almost as + reliable as a CRC32 but can be computed much more quickly.) The result + is an unsigned 32-bit integer. If *value* is present, it is used as + the starting value of the checksum; otherwise, a default value of 1 + is used. Passing in *value* allows computing a running checksum over the + concatenation of several inputs. The algorithm is not cryptographically + strong, and should not be used for authentication or digital signatures. Since + the algorithm is designed for use as a checksum algorithm, it is not suitable + for use as a general hash algorithm. + + .. versionchanged:: 3.0 + Always returns an unsigned value. + To generate the same numeric value across all Python versions and + platforms, use ``adler32(data) & 0xffffffff``. + + +.. function:: compress(data, /, level=-1) + + Compresses the bytes in *data*, returning a bytes object containing compressed data. + *level* is an integer from ``0`` to ``9`` or ``-1`` controlling the level of compression; + ``1`` (Z_BEST_SPEED) is fastest and produces the least compression, ``9`` (Z_BEST_COMPRESSION) + is slowest and produces the most. ``0`` (Z_NO_COMPRESSION) is no compression. + The default value is ``-1`` (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default + compromise between speed and compression (currently equivalent to level 6). + Raises the :exc:`error` exception if any error occurs. + + .. versionchanged:: 3.6 + *level* can now be used as a keyword parameter. + + +.. function:: compressobj(level=-1, method=DEFLATED, wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=Z_DEFAULT_STRATEGY[, zdict]) + + Returns a compression object, to be used for compressing data streams that won't + fit into memory at once. + + *level* is the compression level -- an integer from ``0`` to ``9`` or ``-1``. + A value of ``1`` (Z_BEST_SPEED) is fastest and produces the least compression, + while a value of ``9`` (Z_BEST_COMPRESSION) is slowest and produces the most. + ``0`` (Z_NO_COMPRESSION) is no compression. The default value is ``-1`` (Z_DEFAULT_COMPRESSION). + Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression + (currently equivalent to level 6). + + *method* is the compression algorithm. Currently, the only supported value is + :const:`DEFLATED`. + + The *wbits* argument controls the size of the history buffer (or the + "window size") used when compressing data, and whether a header and + trailer is included in the output. It can take several ranges of values, + defaulting to ``15`` (MAX_WBITS): + + * +9 to +15: The base-two logarithm of the window size, which + therefore ranges between 512 and 32768. Larger values produce + better compression at the expense of greater memory usage. The + resulting output will include a zlib-specific header and trailer. + + * −9 to −15: Uses the absolute value of *wbits* as the + window size logarithm, while producing a raw output stream with no + header or trailing checksum. + + * +25 to +31 = 16 + (9 to 15): Uses the low 4 bits of the value as the + window size logarithm, while including a basic :program:`gzip` header + and trailing checksum in the output. + + The *memLevel* argument controls the amount of memory used for the + internal compression state. Valid values range from ``1`` to ``9``. + Higher values use more memory, but are faster and produce smaller output. + + *strategy* is used to tune the compression algorithm. Possible values are + :const:`Z_DEFAULT_STRATEGY`, :const:`Z_FILTERED`, :const:`Z_HUFFMAN_ONLY`, + :const:`Z_RLE` (zlib 1.2.0.1) and :const:`Z_FIXED` (zlib 1.2.2.2). + + *zdict* is a predefined compression dictionary. This is a sequence of bytes + (such as a :class:`bytes` object) containing subsequences that are expected + to occur frequently in the data that is to be compressed. Those subsequences + that are expected to be most common should come at the end of the dictionary. + + .. versionchanged:: 3.3 + Added the *zdict* parameter and keyword argument support. + + +.. function:: crc32(data[, value]) + + .. index:: + single: Cyclic Redundancy Check + single: checksum; Cyclic Redundancy Check + + Computes a CRC (Cyclic Redundancy Check) checksum of *data*. The + result is an unsigned 32-bit integer. If *value* is present, it is used + as the starting value of the checksum; otherwise, a default value of 0 + is used. Passing in *value* allows computing a running checksum over the + concatenation of several inputs. The algorithm is not cryptographically + strong, and should not be used for authentication or digital signatures. Since + the algorithm is designed for use as a checksum algorithm, it is not suitable + for use as a general hash algorithm. + + .. versionchanged:: 3.0 + Always returns an unsigned value. + To generate the same numeric value across all Python versions and + platforms, use ``crc32(data) & 0xffffffff``. + + +.. function:: decompress(data, /, wbits=MAX_WBITS, bufsize=DEF_BUF_SIZE) + + Decompresses the bytes in *data*, returning a bytes object containing the + uncompressed data. The *wbits* parameter depends on + the format of *data*, and is discussed further below. + If *bufsize* is given, it is used as the initial size of the output + buffer. Raises the :exc:`error` exception if any error occurs. + + .. _decompress-wbits: + + The *wbits* parameter controls the size of the history buffer + (or "window size"), and what header and trailer format is expected. + It is similar to the parameter for :func:`compressobj`, but accepts + more ranges of values: + + * +8 to +15: The base-two logarithm of the window size. The input + must include a zlib header and trailer. + + * 0: Automatically determine the window size from the zlib header. + Only supported since zlib 1.2.3.5. + + * −8 to −15: Uses the absolute value of *wbits* as the window size + logarithm. The input must be a raw stream with no header or trailer. + + * +24 to +31 = 16 + (8 to 15): Uses the low 4 bits of the value as + the window size logarithm. The input must include a gzip header and + trailer. + + * +40 to +47 = 32 + (8 to 15): Uses the low 4 bits of the value as + the window size logarithm, and automatically accepts either + the zlib or gzip format. + + When decompressing a stream, the window size must not be smaller + than the size originally used to compress the stream; using a too-small + value may result in an :exc:`error` exception. The default *wbits* value + corresponds to the largest window size and requires a zlib header and + trailer to be included. + + *bufsize* is the initial size of the buffer used to hold decompressed data. If + more space is required, the buffer size will be increased as needed, so you + don't have to get this value exactly right; tuning it will only save a few calls + to :c:func:`malloc`. + + .. versionchanged:: 3.6 + *wbits* and *bufsize* can be used as keyword arguments. + +.. function:: decompressobj(wbits=MAX_WBITS[, zdict]) + + Returns a decompression object, to be used for decompressing data streams that + won't fit into memory at once. + + The *wbits* parameter controls the size of the history buffer (or the + "window size"), and what header and trailer format is expected. It has + the same meaning as `described for decompress() <#decompress-wbits>`__. + + The *zdict* parameter specifies a predefined compression dictionary. If + provided, this must be the same dictionary as was used by the compressor that + produced the data that is to be decompressed. + + .. note:: + + If *zdict* is a mutable object (such as a :class:`bytearray`), you must not + modify its contents between the call to :func:`decompressobj` and the first + call to the decompressor's ``decompress()`` method. + + .. versionchanged:: 3.3 + Added the *zdict* parameter. + + +Compression objects support the following methods: + + +.. method:: Compress.compress(data) + + Compress *data*, returning a bytes object containing compressed data for at least + part of the data in *data*. This data should be concatenated to the output + produced by any preceding calls to the :meth:`compress` method. Some input may + be kept in internal buffers for later processing. + + +.. method:: Compress.flush([mode]) + + All pending input is processed, and a bytes object containing the remaining compressed + output is returned. *mode* can be selected from the constants + :const:`Z_NO_FLUSH`, :const:`Z_PARTIAL_FLUSH`, :const:`Z_SYNC_FLUSH`, + :const:`Z_FULL_FLUSH`, :const:`Z_BLOCK` (zlib 1.2.3.4), or :const:`Z_FINISH`, + defaulting to :const:`Z_FINISH`. Except :const:`Z_FINISH`, all constants + allow compressing further bytestrings of data, while :const:`Z_FINISH` finishes the + compressed stream and prevents compressing any more data. After calling :meth:`flush` + with *mode* set to :const:`Z_FINISH`, the :meth:`compress` method cannot be called again; + the only realistic action is to delete the object. + + +.. method:: Compress.copy() + + Returns a copy of the compression object. This can be used to efficiently + compress a set of data that share a common initial prefix. + + +.. versionchanged:: 3.8 + Added :func:`copy.copy` and :func:`copy.deepcopy` support to compression + objects. + + +Decompression objects support the following methods and attributes: + + +.. attribute:: Decompress.unused_data + + A bytes object which contains any bytes past the end of the compressed data. That is, + this remains ``b""`` until the last byte that contains compression data is + available. If the whole bytestring turned out to contain compressed data, this is + ``b""``, an empty bytes object. + + +.. attribute:: Decompress.unconsumed_tail + + A bytes object that contains any data that was not consumed by the last + :meth:`decompress` call because it exceeded the limit for the uncompressed data + buffer. This data has not yet been seen by the zlib machinery, so you must feed + it (possibly with further data concatenated to it) back to a subsequent + :meth:`decompress` method call in order to get correct output. + + +.. attribute:: Decompress.eof + + A boolean indicating whether the end of the compressed data stream has been + reached. + + This makes it possible to distinguish between a properly-formed compressed + stream, and an incomplete or truncated one. + + .. versionadded:: 3.3 + + +.. method:: Decompress.decompress(data, max_length=0) + + Decompress *data*, returning a bytes object containing the uncompressed data + corresponding to at least part of the data in *string*. This data should be + concatenated to the output produced by any preceding calls to the + :meth:`decompress` method. Some of the input data may be preserved in internal + buffers for later processing. + + If the optional parameter *max_length* is non-zero then the return value will be + no longer than *max_length*. This may mean that not all of the compressed input + can be processed; and unconsumed data will be stored in the attribute + :attr:`unconsumed_tail`. This bytestring must be passed to a subsequent call to + :meth:`decompress` if decompression is to continue. If *max_length* is zero + then the whole input is decompressed, and :attr:`unconsumed_tail` is empty. + + .. versionchanged:: 3.6 + *max_length* can be used as a keyword argument. + + +.. method:: Decompress.flush([length]) + + All pending input is processed, and a bytes object containing the remaining + uncompressed output is returned. After calling :meth:`flush`, the + :meth:`decompress` method cannot be called again; the only realistic action is + to delete the object. + + The optional parameter *length* sets the initial size of the output buffer. + + +.. method:: Decompress.copy() + + Returns a copy of the decompression object. This can be used to save the state + of the decompressor midway through the data stream in order to speed up random + seeks into the stream at a future point. + + +.. versionchanged:: 3.8 + Added :func:`copy.copy` and :func:`copy.deepcopy` support to decompression + objects. + + +Information about the version of the zlib library in use is available through +the following constants: + + +.. data:: ZLIB_VERSION + + The version string of the zlib library that was used for building the module. + This may be different from the zlib library actually used at runtime, which + is available as :const:`ZLIB_RUNTIME_VERSION`. + + +.. data:: ZLIB_RUNTIME_VERSION + + The version string of the zlib library actually loaded by the interpreter. + + .. versionadded:: 3.3 + + +.. seealso:: + + Module :mod:`gzip` + Reading and writing :program:`gzip`\ -format files. + + http://www.zlib.net + The zlib library home page. + + http://www.zlib.net/manual.html + The zlib manual explains the semantics and usage of the library's many + functions. diff --git a/cpython_2/environment/repo/Doc/license.rst b/cpython_2/environment/repo/Doc/license.rst new file mode 100644 index 0000000000000000000000000000000000000000..472a5cf3d88b3409c838cff7e26ec7436fb96e4b --- /dev/null +++ b/cpython_2/environment/repo/Doc/license.rst @@ -0,0 +1,952 @@ +.. highlight:: none + +.. _history-and-license: + +******************* +History and License +******************* + + +History of the software +======================= + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl/) in the Netherlands as a +successor of a language called ABC. Guido remains Python's principal author, +although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for National +Research Initiatives (CNRI, see https://www.cnri.reston.va.us/) in Reston, +Virginia where he released several versions of the software. + +In May 2000, Guido and the Python core development team moved to BeOpen.com to +form the BeOpen PythonLabs team. In October of the same year, the PythonLabs +team moved to Digital Creations (now Zope Corporation; see +https://www.zope.org/). In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization created +specifically to own Python-related Intellectual Property. Zope Corporation is a +sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org/ for the Open +Source Definition). Historically, most, but not all, Python releases have also +been GPL-compatible; the table below summarizes the various releases. + ++----------------+--------------+------------+------------+-----------------+ +| Release | Derived from | Year | Owner | GPL compatible? | ++================+==============+============+============+=================+ +| 0.9.0 thru 1.2 | n/a | 1991-1995 | CWI | yes | ++----------------+--------------+------------+------------+-----------------+ +| 1.3 thru 1.5.2 | 1.2 | 1995-1999 | CNRI | yes | ++----------------+--------------+------------+------------+-----------------+ +| 1.6 | 1.5.2 | 2000 | CNRI | no | ++----------------+--------------+------------+------------+-----------------+ +| 2.0 | 1.6 | 2000 | BeOpen.com | no | ++----------------+--------------+------------+------------+-----------------+ +| 1.6.1 | 1.6 | 2001 | CNRI | no | ++----------------+--------------+------------+------------+-----------------+ +| 2.1 | 2.0+1.6.1 | 2001 | PSF | no | ++----------------+--------------+------------+------------+-----------------+ +| 2.0.1 | 2.0+1.6.1 | 2001 | PSF | yes | ++----------------+--------------+------------+------------+-----------------+ +| 2.1.1 | 2.1+2.0.1 | 2001 | PSF | yes | ++----------------+--------------+------------+------------+-----------------+ +| 2.1.2 | 2.1.1 | 2002 | PSF | yes | ++----------------+--------------+------------+------------+-----------------+ +| 2.1.3 | 2.1.2 | 2002 | PSF | yes | ++----------------+--------------+------------+------------+-----------------+ +| 2.2 and above | 2.1.1 | 2001-now | PSF | yes | ++----------------+--------------+------------+------------+-----------------+ + +.. note:: + + GPL-compatible doesn't mean that we're distributing Python under the GPL. All + Python licenses, unlike the GPL, let you distribute a modified version without + making your changes open source. The GPL-compatible licenses make it possible to + combine Python with other software that is released under the GPL; the others + don't. + +Thanks to the many outside volunteers who have worked under Guido's direction to +make these releases possible. + + +Terms and conditions for accessing or otherwise using Python +============================================================ + + +PSF LICENSE AGREEMENT FOR PYTHON |release| +------------------------------------------ + +.. parsed-literal:: + + 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and + the Individual or Organization ("Licensee") accessing and otherwise using Python + |release| software in source or binary form and its associated documentation. + + 2. Subject to the terms and conditions of this License Agreement, PSF hereby + grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, + analyze, test, perform and/or display publicly, prepare derivative works, + distribute, and otherwise use Python |release| alone or in any derivative + version, provided, however, that PSF's License Agreement and PSF's notice of + copyright, i.e., "Copyright © 2001-2020 Python Software Foundation; All Rights + Reserved" are retained in Python |release| alone or in any derivative version + prepared by Licensee. + + 3. In the event Licensee prepares a derivative work that is based on or + incorporates Python |release| or any part thereof, and wants to make the + derivative work available to others as provided herein, then Licensee hereby + agrees to include in any such work a brief summary of the changes made to Python + |release|. + + 4. PSF is making Python |release| available to Licensee on an "AS IS" basis. + PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF + EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR + WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE + USE OF PYTHON |release| WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + + 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON |release| + FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF + MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON |release|, OR ANY DERIVATIVE + THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + + 6. This License Agreement will automatically terminate upon a material breach of + its terms and conditions. + + 7. Nothing in this License Agreement shall be deemed to create any relationship + of agency, partnership, or joint venture between PSF and Licensee. This License + Agreement does not grant permission to use PSF trademarks or trade name in a + trademark sense to endorse or promote products or services of Licensee, or any + third party. + + 8. By copying, installing or otherwise using Python |release|, Licensee agrees + to be bound by the terms and conditions of this License Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +.. parsed-literal:: + + 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at + 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization + ("Licensee") accessing and otherwise using this software in source or binary + form and its associated documentation ("the Software"). + + 2. Subject to the terms and conditions of this BeOpen Python License Agreement, + BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license + to reproduce, analyze, test, perform and/or display publicly, prepare derivative + works, distribute, and otherwise use the Software alone or in any derivative + version, provided, however, that the BeOpen Python License is retained in the + Software, alone or in any derivative version prepared by Licensee. + + 3. BeOpen is making the Software available to Licensee on an "AS IS" basis. + BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF + EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR + WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE + USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + + 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR + ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, + MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF + ADVISED OF THE POSSIBILITY THEREOF. + + 5. This License Agreement will automatically terminate upon a material breach of + its terms and conditions. + + 6. This License Agreement shall be governed by and interpreted in all respects + by the law of the State of California, excluding conflict of law provisions. + Nothing in this License Agreement shall be deemed to create any relationship of + agency, partnership, or joint venture between BeOpen and Licensee. This License + Agreement does not grant permission to use BeOpen trademarks or trade names in a + trademark sense to endorse or promote products or services of Licensee, or any + third party. As an exception, the "BeOpen Python" logos available at + http://www.pythonlabs.com/logos.html may be used according to the permissions + granted on that web page. + + 7. By copying, installing or otherwise using the software, Licensee agrees to be + bound by the terms and conditions of this License Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +.. parsed-literal:: + + 1. This LICENSE AGREEMENT is between the Corporation for National Research + Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 + ("CNRI"), and the Individual or Organization ("Licensee") accessing and + otherwise using Python 1.6.1 software in source or binary form and its + associated documentation. + + 2. Subject to the terms and conditions of this License Agreement, CNRI hereby + grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, + analyze, test, perform and/or display publicly, prepare derivative works, + distribute, and otherwise use Python 1.6.1 alone or in any derivative version, + provided, however, that CNRI's License Agreement and CNRI's notice of copyright, + i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All + Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version + prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, + Licensee may substitute the following text (omitting the quotes): "Python 1.6.1 + is made available subject to the terms and conditions in CNRI's License + Agreement. This Agreement together with Python 1.6.1 may be located on the + Internet using the following unique, persistent identifier (known as a handle): + 1895.22/1013. This Agreement may also be obtained from a proxy server on the + Internet using the following URL: http://hdl.handle.net/1895.22/1013." + + 3. In the event Licensee prepares a derivative work that is based on or + incorporates Python 1.6.1 or any part thereof, and wants to make the derivative + work available to others as provided herein, then Licensee hereby agrees to + include in any such work a brief summary of the changes made to Python 1.6.1. + + 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI + MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, + BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY + OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF + PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + + 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR + ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF + MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE + THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + + 6. This License Agreement will automatically terminate upon a material breach of + its terms and conditions. + + 7. This License Agreement shall be governed by the federal intellectual property + law of the United States, including without limitation the federal copyright + law, and, to the extent such U.S. federal law does not apply, by the law of the + Commonwealth of Virginia, excluding Virginia's conflict of law provisions. + Notwithstanding the foregoing, with regard to derivative works based on Python + 1.6.1 that incorporate non-separable material that was previously distributed + under the GNU General Public License (GPL), the law of the Commonwealth of + Virginia shall govern this License Agreement only as to issues arising under or + with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in + this License Agreement shall be deemed to create any relationship of agency, + partnership, or joint venture between CNRI and Licensee. This License Agreement + does not grant permission to use CNRI trademarks or trade name in a trademark + sense to endorse or promote products or services of Licensee, or any third + party. + + 8. By clicking on the "ACCEPT" button where indicated, or by copying, installing + or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and + conditions of this License Agreement. + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +.. parsed-literal:: + + Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The + Netherlands. All rights reserved. + + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee is hereby granted, provided that + the above copyright notice appear in all copies and that both that copyright + notice and this permission notice appear in supporting documentation, and that + the name of Stichting Mathematisch Centrum or CWI not be used in advertising or + publicity pertaining to distribution of the software without specific, written + prior permission. + + STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT + OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + SOFTWARE. + + +Licenses and Acknowledgements for Incorporated Software +======================================================= + +This section is an incomplete, but growing list of licenses and acknowledgements +for third-party software incorporated in the Python distribution. + + +Mersenne Twister +---------------- + +The :mod:`_random` module includes code based on a download from +http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html. The following are +the verbatim comments from the original code:: + + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. + + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + Any feedback is very welcome. + http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html + email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) + + +Sockets +------- + +The :mod:`socket` module uses the functions, :func:`getaddrinfo`, and +:func:`getnameinfo`, which are coded in separate source files from the WIDE +Project, http://www.wide.ad.jp/. :: + + Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the project nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + +Asynchronous socket services +---------------------------- + +The :mod:`asynchat` and :mod:`asyncore` modules contain the following notice:: + + Copyright 1996 by Sam Rushing + + All Rights Reserved + + Permission to use, copy, modify, and distribute this software and + its documentation for any purpose and without fee is hereby + granted, provided that the above copyright notice appear in all + copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of Sam + Rushing not be used in advertising or publicity pertaining to + distribution of the software without specific, written prior + permission. + + SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN + NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR + CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +Cookie management +----------------- + +The :mod:`http.cookies` module contains the following notice:: + + Copyright 2000 by Timothy O'Malley + + All Rights Reserved + + Permission to use, copy, modify, and distribute this software + and its documentation for any purpose and without fee is hereby + granted, provided that the above copyright notice appear in all + copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Timothy O'Malley not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR + ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + + +Execution tracing +----------------- + +The :mod:`trace` module contains the following notice:: + + portions copyright 2001, Autonomous Zones Industries, Inc., all rights... + err... reserved and offered to the public under the terms of the + Python 2.2 license. + Author: Zooko O'Whielacronx + http://zooko.com/ + mailto:zooko@zooko.com + + Copyright 2000, Mojam Media, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1999, Bioreason, Inc., all rights reserved. + Author: Andrew Dalke + + Copyright 1995-1997, Automatrix, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved. + + + Permission to use, copy, modify, and distribute this Python software and + its associated documentation for any purpose without fee is hereby + granted, provided that the above copyright notice appears in all copies, + and that both that copyright notice and this permission notice appear in + supporting documentation, and that the name of neither Automatrix, + Bioreason or Mojam Media be used in advertising or publicity pertaining to + distribution of the software without specific, written prior permission. + + +UUencode and UUdecode functions +------------------------------- + +The :mod:`uu` module contains the following notice:: + + Copyright 1994 by Lance Ellinghouse + Cathedral City, California Republic, United States of America. + All Rights Reserved + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee is hereby granted, + provided that the above copyright notice appear in all copies and that + both that copyright notice and this permission notice appear in + supporting documentation, and that the name of Lance Ellinghouse + not be used in advertising or publicity pertaining to distribution + of the software without specific, written prior permission. + LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO + THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE + FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + Modified by Jack Jansen, CWI, July 1995: + - Use binascii module to do the actual line-by-line conversion + between ascii and binary. This results in a 1000-fold speedup. The C + version is still 5 times faster, though. + - Arguments more compliant with Python standard + + +XML Remote Procedure Calls +-------------------------- + +The :mod:`xmlrpc.client` module contains the following notice:: + + The XML-RPC client interface is + + Copyright (c) 1999-2002 by Secret Labs AB + Copyright (c) 1999-2002 by Fredrik Lundh + + By obtaining, using, and/or copying this software and/or its + associated documentation, you agree that you have read, understood, + and will comply with the following terms and conditions: + + Permission to use, copy, modify, and distribute this software and + its associated documentation for any purpose and without fee is + hereby granted, provided that the above copyright notice appears in + all copies, and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Secret Labs AB or the author not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD + TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- + ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR + BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY + DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + OF THIS SOFTWARE. + + +test_epoll +---------- + +The :mod:`test_epoll` module contains the following notice:: + + Copyright (c) 2001-2006 Twisted Matrix Laboratories. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Select kqueue +------------- + +The :mod:`select` module contains the following notice for the kqueue +interface:: + + Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + +SipHash24 +--------- + +The file :file:`Python/pyhash.c` contains Marek Majkowski' implementation of +Dan Bernstein's SipHash24 algorithm. It contains the following note:: + + + Copyright (c) 2013 Marek Majkowski + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + + Original location: + https://github.com/majek/csiphash/ + + Solution inspired by code from: + Samuel Neves (supercop/crypto_auth/siphash24/little) + djb (supercop/crypto_auth/siphash24/little2) + Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c) + + +strtod and dtoa +--------------- + +The file :file:`Python/dtoa.c`, which supplies C functions dtoa and +strtod for conversion of C doubles to and from strings, is derived +from the file of the same name by David M. Gay, currently available +from http://www.netlib.org/fp/. The original file, as retrieved on +March 16, 2009, contains the following copyright and licensing +notice:: + + /**************************************************************** + * + * The author of this software is David M. Gay. + * + * Copyright (c) 1991, 2000, 2001 by Lucent Technologies. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose without fee is hereby granted, provided that this entire notice + * is included in all copies of any software which is or includes a copy + * or modification of this software and in all copies of the supporting + * documentation for such software. + * + * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED + * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY + * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY + * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. + * + ***************************************************************/ + + +OpenSSL +------- + +The modules :mod:`hashlib`, :mod:`posix`, :mod:`ssl`, :mod:`crypt` use +the OpenSSL library for added performance if made available by the +operating system. Additionally, the Windows and Mac OS X installers for +Python may include a copy of the OpenSSL libraries, so we include a copy +of the OpenSSL license here:: + + + LICENSE ISSUES + ============== + + The OpenSSL toolkit stays under a dual license, i.e. both the conditions of + the OpenSSL License and the original SSLeay license apply to the toolkit. + See below for the actual license texts. Actually both licenses are BSD-style + Open Source licenses. In case of any license issues related to OpenSSL + please contact openssl-core@openssl.org. + + OpenSSL License + --------------- + + /* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + Original SSLeay License + ----------------------- + + /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + + +expat +----- + +The :mod:`pyexpat` extension is built using an included copy of the expat +sources unless the build is configured ``--with-system-expat``:: + + Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd + and Clark Cooper + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +libffi +------ + +The :mod:`_ctypes` extension is built using an included copy of the libffi +sources unless the build is configured ``--with-system-libffi``:: + + Copyright (c) 1996-2008 Red Hat, Inc and others. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + +zlib +---- + +The :mod:`zlib` extension is built using an included copy of the zlib +sources if the zlib version found on the system is too old to be +used for the build:: + + Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + +cfuhash +------- + +The implementation of the hash table used by the :mod:`tracemalloc` is based +on the cfuhash project:: + + Copyright (c) 2005 Don Owens + All rights reserved. + + This code is released under the BSD license: + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the author nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + OF THE POSSIBILITY OF SUCH DAMAGE. + + +libmpdec +-------- + +The :mod:`_decimal` module is built using an included copy of the libmpdec +library unless the build is configured ``--with-system-libmpdec``:: + + Copyright (c) 2008-2016 Stefan Krah. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + +W3C C14N test suite +------------------- + +The C14N 2.0 test suite in the :mod:`test` package +(``Lib/test/xmltestdata/c14n-20/``) was retrieved from the W3C website at +https://www.w3.org/TR/xml-c14n2-testcases/ and is distributed under the +3-clause BSD license: + + Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang), + All Rights Reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of works must retain the original copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the original copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the W3C nor the names of its contributors may be + used to endorse or promote products derived from this work without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/cpython_2/environment/repo/Doc/make.bat b/cpython_2/environment/repo/Doc/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..a2f64ffddbf5342c25431b4d1cfe888043460f64 --- /dev/null +++ b/cpython_2/environment/repo/Doc/make.bat @@ -0,0 +1,179 @@ +@echo off +setlocal + +pushd %~dp0 + +set this=%~n0 + +call ..\PCbuild\find_python.bat %PYTHON% + +if not defined PYTHON set PYTHON=py + +if not defined SPHINXBUILD ( + %PYTHON% -c "import sphinx" > nul 2> nul + if errorlevel 1 ( + echo Installing sphinx with %PYTHON% + %PYTHON% -m pip install sphinx + if errorlevel 1 exit /B + ) + set SPHINXBUILD=%PYTHON% -c "import sphinx.cmd.build, sys; sys.exit(sphinx.cmd.build.main())" +) + +%PYTHON% -c "import python_docs_theme" > nul 2> nul +if errorlevel 1 ( + echo Installing python-docs-theme with %PYTHON% + %PYTHON% -m pip install python-docs-theme + if errorlevel 1 exit /B +) + +if not defined BLURB ( + %PYTHON% -c "import blurb" > nul 2> nul + if errorlevel 1 ( + echo Installing blurb with %PYTHON% + %PYTHON% -m pip install blurb + if errorlevel 1 exit /B + ) + set BLURB=%PYTHON% -m blurb +) + +if "%1" NEQ "htmlhelp" goto :skiphhcsearch +if exist "%HTMLHELP%" goto :skiphhcsearch + +rem Search for HHC in likely places +set HTMLHELP= +where hhc /q && set "HTMLHELP=hhc" && goto :skiphhcsearch +where /R ..\externals hhc > "%TEMP%\hhc.loc" 2> nul && set /P HTMLHELP= < "%TEMP%\hhc.loc" & del "%TEMP%\hhc.loc" +if not exist "%HTMLHELP%" where /R "%ProgramFiles(x86)%" hhc > "%TEMP%\hhc.loc" 2> nul && set /P HTMLHELP= < "%TEMP%\hhc.loc" & del "%TEMP%\hhc.loc" +if not exist "%HTMLHELP%" where /R "%ProgramFiles%" hhc > "%TEMP%\hhc.loc" 2> nul && set /P HTMLHELP= < "%TEMP%\hhc.loc" & del "%TEMP%\hhc.loc" +if not exist "%HTMLHELP%" ( + echo. + echo.The HTML Help Workshop was not found. Set the HTMLHELP variable + echo.to the path to hhc.exe or download and install it from + echo.http://msdn.microsoft.com/en-us/library/ms669985 + exit /B 1 +) +:skiphhcsearch + +if not defined DISTVERSION for /f "usebackq" %%v in (`%PYTHON% tools/extensions/patchlevel.py`) do set DISTVERSION=%%v + +if not defined BUILDDIR set BUILDDIR=build + +rem Targets that don't require sphinx-build +if "%1" EQU "" goto help +if "%1" EQU "help" goto help +if "%1" EQU "check" goto check +if "%1" EQU "serve" goto serve +if "%1" == "clean" ( + rmdir /q /s "%BUILDDIR%" + goto end +) + +%SPHINXBUILD% >nul 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + popd + exit /B 1 +) + +rem Targets that do require sphinx-build and have their own label +if "%1" EQU "htmlview" goto htmlview + +rem Everything else +goto build + +:help +echo.usage: %this% BUILDER [filename ...] +echo. +echo.Call %this% with the desired Sphinx builder as the first argument, e.g. +echo.``%this% html`` or ``%this% doctest``. Interesting targets that are +echo.always available include: +echo. +echo. Provided by Sphinx: +echo. html, htmlhelp, latex, text +echo. suspicious, linkcheck, changes, doctest +echo. Provided by this script: +echo. clean, check, serve, htmlview +echo. +echo.All arguments past the first one are passed through to sphinx-build as +echo.filenames to build or are ignored. See README.rst in this directory or +echo.the documentation for your version of Sphinx for more exhaustive lists +echo.of available targets and descriptions of each. +echo. +echo.This script assumes that the SPHINXBUILD environment variable contains +echo.a legitimate command for calling sphinx-build, or that sphinx-build is +echo.on your PATH if SPHINXBUILD is not set. Options for sphinx-build can +echo.be passed by setting the SPHINXOPTS environment variable. +goto end + +:build +if not exist "%BUILDDIR%" mkdir "%BUILDDIR%" + +rem PY_MISC_NEWS_DIR is also used by our Sphinx extension in tools/extensions/pyspecific.py +if not defined PY_MISC_NEWS_DIR set PY_MISC_NEWS_DIR=%BUILDDIR%\%1 +if not exist "%PY_MISC_NEWS_DIR%" mkdir "%PY_MISC_NEWS_DIR%" +if exist ..\Misc\NEWS ( + echo.Copying Misc\NEWS to %PY_MISC_NEWS_DIR%\NEWS + copy ..\Misc\NEWS "%PY_MISC_NEWS_DIR%\NEWS" > nul +) else if exist ..\Misc\NEWS.D ( + if defined BLURB ( + echo.Merging Misc/NEWS with %BLURB% + %BLURB% merge -f "%PY_MISC_NEWS_DIR%\NEWS" + ) else ( + echo.No Misc/NEWS file and Blurb is not available. + exit /B 1 + ) +) + +if defined PAPER ( + set SPHINXOPTS=-D latex_elements.papersize=%PAPER% %SPHINXOPTS% +) +if "%1" EQU "htmlhelp" ( + set SPHINXOPTS=-D html_theme_options.body_max_width=none %SPHINXOPTS% +) +cmd /S /C "%SPHINXBUILD% %SPHINXOPTS% -b%1 -dbuild\doctrees . "%BUILDDIR%\%1" %2 %3 %4 %5 %6 %7 %8 %9" + +if "%1" EQU "htmlhelp" ( + "%HTMLHELP%" "%BUILDDIR%\htmlhelp\python%DISTVERSION:.=%.hhp" + rem hhc.exe seems to always exit with code 1, reset to 0 for less than 2 + if not errorlevel 2 cmd /C exit /b 0 +) + +echo. +if errorlevel 1 ( + echo.Build failed (exit code %ERRORLEVEL%^), check for error messages + echo.above. Any output will be found in %BUILDDIR%\%1 +) else ( + echo.Build succeeded. All output should be in %BUILDDIR%\%1 +) +goto end + +:htmlview +if NOT "%2" EQU "" ( + echo.Can't specify filenames to build with htmlview target, ignoring. +) +cmd /C %this% html + +if EXIST "%BUILDDIR%\html\index.html" ( + echo.Opening "%BUILDDIR%\html\index.html" in the default web browser... + start "" "%BUILDDIR%\html\index.html" +) + +goto end + +:check +cmd /S /C "%PYTHON% tools\rstlint.py -i tools" +goto end + +:serve +cmd /S /C "%PYTHON% ..\Tools\scripts\serve.py "%BUILDDIR%\html"" +goto end + +:end +popd diff --git a/cpython_2/environment/repo/Doc/myfile.bz2 b/cpython_2/environment/repo/Doc/myfile.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..33afacec6589dd935a718c5af24a83f02fd81519 --- /dev/null +++ b/cpython_2/environment/repo/Doc/myfile.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25df866deee0a826796261bf689db6742d4241b2a5f2b878c34267c845612901 +size 331 diff --git a/cpython_2/environment/repo/Doc/reference/compound_stmts.rst b/cpython_2/environment/repo/Doc/reference/compound_stmts.rst new file mode 100644 index 0000000000000000000000000000000000000000..c14e7c79fe14cfb87395ff281ac9d02a775e3d8a --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/compound_stmts.rst @@ -0,0 +1,897 @@ +.. _compound: + +******************* +Compound statements +******************* + +.. index:: pair: compound; statement + +Compound statements contain (groups of) other statements; they affect or control +the execution of those other statements in some way. In general, compound +statements span multiple lines, although in simple incarnations a whole compound +statement may be contained in one line. + +The :keyword:`if`, :keyword:`while` and :keyword:`for` statements implement +traditional control flow constructs. :keyword:`try` specifies exception +handlers and/or cleanup code for a group of statements, while the +:keyword:`with` statement allows the execution of initialization and +finalization code around a block of code. Function and class definitions are +also syntactically compound statements. + +.. index:: + single: clause + single: suite + single: ; (semicolon) + +A compound statement consists of one or more 'clauses.' A clause consists of a +header and a 'suite.' The clause headers of a particular compound statement are +all at the same indentation level. Each clause header begins with a uniquely +identifying keyword and ends with a colon. A suite is a group of statements +controlled by a clause. A suite can be one or more semicolon-separated simple +statements on the same line as the header, following the header's colon, or it +can be one or more indented statements on subsequent lines. Only the latter +form of a suite can contain nested compound statements; the following is illegal, +mostly because it wouldn't be clear to which :keyword:`if` clause a following +:keyword:`else` clause would belong:: + + if test1: if test2: print(x) + +Also note that the semicolon binds tighter than the colon in this context, so +that in the following example, either all or none of the :func:`print` calls are +executed:: + + if x < y < z: print(x); print(y); print(z) + +Summarizing: + +.. productionlist:: + compound_stmt: `if_stmt` + : | `while_stmt` + : | `for_stmt` + : | `try_stmt` + : | `with_stmt` + : | `funcdef` + : | `classdef` + : | `async_with_stmt` + : | `async_for_stmt` + : | `async_funcdef` + suite: `stmt_list` NEWLINE | NEWLINE INDENT `statement`+ DEDENT + statement: `stmt_list` NEWLINE | `compound_stmt` + stmt_list: `simple_stmt` (";" `simple_stmt`)* [";"] + +.. index:: + single: NEWLINE token + single: DEDENT token + pair: dangling; else + +Note that statements always end in a ``NEWLINE`` possibly followed by a +``DEDENT``. Also note that optional continuation clauses always begin with a +keyword that cannot start a statement, thus there are no ambiguities (the +'dangling :keyword:`else`' problem is solved in Python by requiring nested +:keyword:`if` statements to be indented). + +The formatting of the grammar rules in the following sections places each clause +on a separate line for clarity. + + +.. _if: +.. _elif: +.. _else: + +The :keyword:`!if` statement +============================ + +.. index:: + ! statement: if + keyword: elif + keyword: else + single: : (colon); compound statement + +The :keyword:`if` statement is used for conditional execution: + +.. productionlist:: + if_stmt: "if" `assignment_expression` ":" `suite` + : ("elif" `assignment_expression` ":" `suite`)* + : ["else" ":" `suite`] + +It selects exactly one of the suites by evaluating the expressions one by one +until one is found to be true (see section :ref:`booleans` for the definition of +true and false); then that suite is executed (and no other part of the +:keyword:`if` statement is executed or evaluated). If all expressions are +false, the suite of the :keyword:`else` clause, if present, is executed. + + +.. _while: + +The :keyword:`!while` statement +=============================== + +.. index:: + ! statement: while + keyword: else + pair: loop; statement + single: : (colon); compound statement + +The :keyword:`while` statement is used for repeated execution as long as an +expression is true: + +.. productionlist:: + while_stmt: "while" `assignment_expression` ":" `suite` + : ["else" ":" `suite`] + +This repeatedly tests the expression and, if it is true, executes the first +suite; if the expression is false (which may be the first time it is tested) the +suite of the :keyword:`!else` clause, if present, is executed and the loop +terminates. + +.. index:: + statement: break + statement: continue + +A :keyword:`break` statement executed in the first suite terminates the loop +without executing the :keyword:`!else` clause's suite. A :keyword:`continue` +statement executed in the first suite skips the rest of the suite and goes back +to testing the expression. + + +.. _for: + +The :keyword:`!for` statement +============================= + +.. index:: + ! statement: for + keyword: in + keyword: else + pair: target; list + pair: loop; statement + object: sequence + single: : (colon); compound statement + +The :keyword:`for` statement is used to iterate over the elements of a sequence +(such as a string, tuple or list) or other iterable object: + +.. productionlist:: + for_stmt: "for" `target_list` "in" `expression_list` ":" `suite` + : ["else" ":" `suite`] + +The expression list is evaluated once; it should yield an iterable object. An +iterator is created for the result of the ``expression_list``. The suite is +then executed once for each item provided by the iterator, in the order returned +by the iterator. Each item in turn is assigned to the target list using the +standard rules for assignments (see :ref:`assignment`), and then the suite is +executed. When the items are exhausted (which is immediately when the sequence +is empty or an iterator raises a :exc:`StopIteration` exception), the suite in +the :keyword:`!else` clause, if present, is executed, and the loop terminates. + +.. index:: + statement: break + statement: continue + +A :keyword:`break` statement executed in the first suite terminates the loop +without executing the :keyword:`!else` clause's suite. A :keyword:`continue` +statement executed in the first suite skips the rest of the suite and continues +with the next item, or with the :keyword:`!else` clause if there is no next +item. + +The for-loop makes assignments to the variables in the target list. +This overwrites all previous assignments to those variables including +those made in the suite of the for-loop:: + + for i in range(10): + print(i) + i = 5 # this will not affect the for-loop + # because i will be overwritten with the next + # index in the range + + +.. index:: + builtin: range + +Names in the target list are not deleted when the loop is finished, but if the +sequence is empty, they will not have been assigned to at all by the loop. Hint: +the built-in function :func:`range` returns an iterator of integers suitable to +emulate the effect of Pascal's ``for i := a to b do``; e.g., ``list(range(3))`` +returns the list ``[0, 1, 2]``. + +.. note:: + + .. index:: + single: loop; over mutable sequence + single: mutable sequence; loop over + + There is a subtlety when the sequence is being modified by the loop (this can + only occur for mutable sequences, e.g. lists). An internal counter is used + to keep track of which item is used next, and this is incremented on each + iteration. When this counter has reached the length of the sequence the loop + terminates. This means that if the suite deletes the current (or a previous) + item from the sequence, the next item will be skipped (since it gets the + index of the current item which has already been treated). Likewise, if the + suite inserts an item in the sequence before the current item, the current + item will be treated again the next time through the loop. This can lead to + nasty bugs that can be avoided by making a temporary copy using a slice of + the whole sequence, e.g., :: + + for x in a[:]: + if x < 0: a.remove(x) + + +.. _try: +.. _except: +.. _finally: + +The :keyword:`!try` statement +============================= + +.. index:: + ! statement: try + keyword: except + keyword: finally + keyword: else + keyword: as + single: : (colon); compound statement + +The :keyword:`try` statement specifies exception handlers and/or cleanup code +for a group of statements: + +.. productionlist:: + try_stmt: `try1_stmt` | `try2_stmt` + try1_stmt: "try" ":" `suite` + : ("except" [`expression` ["as" `identifier`]] ":" `suite`)+ + : ["else" ":" `suite`] + : ["finally" ":" `suite`] + try2_stmt: "try" ":" `suite` + : "finally" ":" `suite` + + +The :keyword:`except` clause(s) specify one or more exception handlers. When no +exception occurs in the :keyword:`try` clause, no exception handler is executed. +When an exception occurs in the :keyword:`!try` suite, a search for an exception +handler is started. This search inspects the except clauses in turn until one +is found that matches the exception. An expression-less except clause, if +present, must be last; it matches any exception. For an except clause with an +expression, that expression is evaluated, and the clause matches the exception +if the resulting object is "compatible" with the exception. An object is +compatible with an exception if it is the class or a base class of the exception +object or a tuple containing an item compatible with the exception. + +If no except clause matches the exception, the search for an exception handler +continues in the surrounding code and on the invocation stack. [#]_ + +If the evaluation of an expression in the header of an except clause raises an +exception, the original search for a handler is canceled and a search starts for +the new exception in the surrounding code and on the call stack (it is treated +as if the entire :keyword:`try` statement raised the exception). + +.. index:: single: as; except clause + +When a matching except clause is found, the exception is assigned to the target +specified after the :keyword:`!as` keyword in that except clause, if present, and +the except clause's suite is executed. All except clauses must have an +executable block. When the end of this block is reached, execution continues +normally after the entire try statement. (This means that if two nested +handlers exist for the same exception, and the exception occurs in the try +clause of the inner handler, the outer handler will not handle the exception.) + +When an exception has been assigned using ``as target``, it is cleared at the +end of the except clause. This is as if :: + + except E as N: + foo + +was translated to :: + + except E as N: + try: + foo + finally: + del N + +This means the exception must be assigned to a different name to be able to +refer to it after the except clause. Exceptions are cleared because with the +traceback attached to them, they form a reference cycle with the stack frame, +keeping all locals in that frame alive until the next garbage collection occurs. + +.. index:: + module: sys + object: traceback + +Before an except clause's suite is executed, details about the exception are +stored in the :mod:`sys` module and can be accessed via :func:`sys.exc_info`. +:func:`sys.exc_info` returns a 3-tuple consisting of the exception class, the +exception instance and a traceback object (see section :ref:`types`) identifying +the point in the program where the exception occurred. :func:`sys.exc_info` +values are restored to their previous values (before the call) when returning +from a function that handled an exception. + +.. index:: + keyword: else + statement: return + statement: break + statement: continue + +The optional :keyword:`!else` clause is executed if the control flow leaves the +:keyword:`try` suite, no exception was raised, and no :keyword:`return`, +:keyword:`continue`, or :keyword:`break` statement was executed. Exceptions in +the :keyword:`!else` clause are not handled by the preceding :keyword:`except` +clauses. + +.. index:: keyword: finally + +If :keyword:`finally` is present, it specifies a 'cleanup' handler. The +:keyword:`try` clause is executed, including any :keyword:`except` and +:keyword:`!else` clauses. If an exception occurs in any of the clauses and is +not handled, the exception is temporarily saved. The :keyword:`!finally` clause +is executed. If there is a saved exception it is re-raised at the end of the +:keyword:`!finally` clause. If the :keyword:`!finally` clause raises another +exception, the saved exception is set as the context of the new exception. +If the :keyword:`!finally` clause executes a :keyword:`return`, :keyword:`break` +or :keyword:`continue` statement, the saved exception is discarded:: + + >>> def f(): + ... try: + ... 1/0 + ... finally: + ... return 42 + ... + >>> f() + 42 + +The exception information is not available to the program during execution of +the :keyword:`finally` clause. + +.. index:: + statement: return + statement: break + statement: continue + +When a :keyword:`return`, :keyword:`break` or :keyword:`continue` statement is +executed in the :keyword:`try` suite of a :keyword:`!try`...\ :keyword:`!finally` +statement, the :keyword:`finally` clause is also executed 'on the way out.' + +The return value of a function is determined by the last :keyword:`return` +statement executed. Since the :keyword:`finally` clause always executes, a +:keyword:`!return` statement executed in the :keyword:`!finally` clause will +always be the last one executed:: + + >>> def foo(): + ... try: + ... return 'try' + ... finally: + ... return 'finally' + ... + >>> foo() + 'finally' + +Additional information on exceptions can be found in section :ref:`exceptions`, +and information on using the :keyword:`raise` statement to generate exceptions +may be found in section :ref:`raise`. + +.. versionchanged:: 3.8 + Prior to Python 3.8, a :keyword:`continue` statement was illegal in the + :keyword:`finally` clause due to a problem with the implementation. + + +.. _with: +.. _as: + +The :keyword:`!with` statement +============================== + +.. index:: + ! statement: with + keyword: as + single: as; with statement + single: , (comma); with statement + single: : (colon); compound statement + +The :keyword:`with` statement is used to wrap the execution of a block with +methods defined by a context manager (see section :ref:`context-managers`). +This allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` +usage patterns to be encapsulated for convenient reuse. + +.. productionlist:: + with_stmt: "with" `with_item` ("," `with_item`)* ":" `suite` + with_item: `expression` ["as" `target`] + +The execution of the :keyword:`with` statement with one "item" proceeds as follows: + +#. The context expression (the expression given in the :token:`with_item`) is + evaluated to obtain a context manager. + +#. The context manager's :meth:`__enter__` is loaded for later use. + +#. The context manager's :meth:`__exit__` is loaded for later use. + +#. The context manager's :meth:`__enter__` method is invoked. + +#. If a target was included in the :keyword:`with` statement, the return value + from :meth:`__enter__` is assigned to it. + + .. note:: + + The :keyword:`with` statement guarantees that if the :meth:`__enter__` + method returns without an error, then :meth:`__exit__` will always be + called. Thus, if an error occurs during the assignment to the target list, + it will be treated the same as an error occurring within the suite would + be. See step 6 below. + +#. The suite is executed. + +#. The context manager's :meth:`__exit__` method is invoked. If an exception + caused the suite to be exited, its type, value, and traceback are passed as + arguments to :meth:`__exit__`. Otherwise, three :const:`None` arguments are + supplied. + + If the suite was exited due to an exception, and the return value from the + :meth:`__exit__` method was false, the exception is reraised. If the return + value was true, the exception is suppressed, and execution continues with the + statement following the :keyword:`with` statement. + + If the suite was exited for any reason other than an exception, the return + value from :meth:`__exit__` is ignored, and execution proceeds at the normal + location for the kind of exit that was taken. + +The following code:: + + with EXPRESSION as TARGET: + SUITE + +is semantically equivalent to:: + + manager = (EXPRESSION) + enter = type(manager).__enter__ + exit = type(manager).__exit__ + value = enter(manager) + hit_except = False + + try: + TARGET = value + SUITE + except: + hit_except = True + if not exit(manager, *sys.exc_info()): + raise + finally: + if not hit_except: + exit(manager, None, None, None) + +With more than one item, the context managers are processed as if multiple +:keyword:`with` statements were nested:: + + with A() as a, B() as b: + SUITE + +is semantically equivalent to:: + + with A() as a: + with B() as b: + SUITE + +.. versionchanged:: 3.1 + Support for multiple context expressions. + +.. seealso:: + + :pep:`343` - The "with" statement + The specification, background, and examples for the Python :keyword:`with` + statement. + + +.. index:: + single: parameter; function definition + +.. _function: +.. _def: + +Function definitions +==================== + +.. index:: + statement: def + pair: function; definition + pair: function; name + pair: name; binding + object: user-defined function + object: function + pair: function; name + pair: name; binding + single: () (parentheses); function definition + single: , (comma); parameter list + single: : (colon); compound statement + +A function definition defines a user-defined function object (see section +:ref:`types`): + +.. productionlist:: + funcdef: [`decorators`] "def" `funcname` "(" [`parameter_list`] ")" + : ["->" `expression`] ":" `suite` + decorators: `decorator`+ + decorator: "@" `assignment_expression` NEWLINE + dotted_name: `identifier` ("." `identifier`)* + parameter_list: `defparameter` ("," `defparameter`)* "," "/" ["," [`parameter_list_no_posonly`]] + : | `parameter_list_no_posonly` + parameter_list_no_posonly: `defparameter` ("," `defparameter`)* ["," [`parameter_list_starargs`]] + : | `parameter_list_starargs` + parameter_list_starargs: "*" [`parameter`] ("," `defparameter`)* ["," ["**" `parameter` [","]]] + : | "**" `parameter` [","] + parameter: `identifier` [":" `expression`] + defparameter: `parameter` ["=" `expression`] + funcname: `identifier` + + +A function definition is an executable statement. Its execution binds the +function name in the current local namespace to a function object (a wrapper +around the executable code for the function). This function object contains a +reference to the current global namespace as the global namespace to be used +when the function is called. + +The function definition does not execute the function body; this gets executed +only when the function is called. [#]_ + +.. index:: + single: @ (at); function definition + +A function definition may be wrapped by one or more :term:`decorator` expressions. +Decorator expressions are evaluated when the function is defined, in the scope +that contains the function definition. The result must be a callable, which is +invoked with the function object as the only argument. The returned value is +bound to the function name instead of the function object. Multiple decorators +are applied in nested fashion. For example, the following code :: + + @f1(arg) + @f2 + def func(): pass + +is roughly equivalent to :: + + def func(): pass + func = f1(arg)(f2(func)) + +except that the original function is not temporarily bound to the name ``func``. + +.. versionchanged:: 3.9 + Functions may be decorated with any valid :token:`assignment_expression`. + Previously, the grammar was much more restrictive; see :pep:`614` for + details. + +.. index:: + triple: default; parameter; value + single: argument; function definition + single: = (equals); function definition + +When one or more :term:`parameters ` have the form *parameter* ``=`` +*expression*, the function is said to have "default parameter values." For a +parameter with a default value, the corresponding :term:`argument` may be +omitted from a call, in which +case the parameter's default value is substituted. If a parameter has a default +value, all following parameters up until the "``*``" must also have a default +value --- this is a syntactic restriction that is not expressed by the grammar. + +**Default parameter values are evaluated from left to right when the function +definition is executed.** This means that the expression is evaluated once, when +the function is defined, and that the same "pre-computed" value is used for each +call. This is especially important to understand when a default parameter is a +mutable object, such as a list or a dictionary: if the function modifies the +object (e.g. by appending an item to a list), the default value is in effect +modified. This is generally not what was intended. A way around this is to use +``None`` as the default, and explicitly test for it in the body of the function, +e.g.:: + + def whats_on_the_telly(penguin=None): + if penguin is None: + penguin = [] + penguin.append("property of the zoo") + return penguin + +.. index:: + single: * (asterisk); function definition + single: **; function definition + +Function call semantics are described in more detail in section :ref:`calls`. A +function call always assigns values to all parameters mentioned in the parameter +list, either from position arguments, from keyword arguments, or from default +values. If the form "``*identifier``" is present, it is initialized to a tuple +receiving any excess positional parameters, defaulting to the empty tuple. +If the form "``**identifier``" is present, it is initialized to a new +ordered mapping receiving any excess keyword arguments, defaulting to a +new empty mapping of the same type. Parameters after "``*``" or +"``*identifier``" are keyword-only parameters and may only be passed +used keyword arguments. + +.. index:: + pair: function; annotations + single: ->; function annotations + single: : (colon); function annotations + +Parameters may have an :term:`annotation ` of the form "``: expression``" +following the parameter name. Any parameter may have an annotation, even those of the form +``*identifier`` or ``**identifier``. Functions may have "return" annotation of +the form "``-> expression``" after the parameter list. These annotations can be +any valid Python expression. The presence of annotations does not change the +semantics of a function. The annotation values are available as values of +a dictionary keyed by the parameters' names in the :attr:`__annotations__` +attribute of the function object. If the ``annotations`` import from +:mod:`__future__` is used, annotations are preserved as strings at runtime which +enables postponed evaluation. Otherwise, they are evaluated when the function +definition is executed. In this case annotations may be evaluated in +a different order than they appear in the source code. + +.. index:: pair: lambda; expression + +It is also possible to create anonymous functions (functions not bound to a +name), for immediate use in expressions. This uses lambda expressions, described in +section :ref:`lambda`. Note that the lambda expression is merely a shorthand for a +simplified function definition; a function defined in a ":keyword:`def`" +statement can be passed around or assigned to another name just like a function +defined by a lambda expression. The ":keyword:`!def`" form is actually more powerful +since it allows the execution of multiple statements and annotations. + +**Programmer's note:** Functions are first-class objects. A "``def``" statement +executed inside a function definition defines a local function that can be +returned or passed around. Free variables used in the nested function can +access the local variables of the function containing the def. See section +:ref:`naming` for details. + +.. seealso:: + + :pep:`3107` - Function Annotations + The original specification for function annotations. + + :pep:`484` - Type Hints + Definition of a standard meaning for annotations: type hints. + + :pep:`526` - Syntax for Variable Annotations + Ability to type hint variable declarations, including class + variables and instance variables + + :pep:`563` - Postponed Evaluation of Annotations + Support for forward references within annotations by preserving + annotations in a string form at runtime instead of eager evaluation. + + +.. _class: + +Class definitions +================= + +.. index:: + object: class + statement: class + pair: class; definition + pair: class; name + pair: name; binding + pair: execution; frame + single: inheritance + single: docstring + single: () (parentheses); class definition + single: , (comma); expression list + single: : (colon); compound statement + +A class definition defines a class object (see section :ref:`types`): + +.. productionlist:: + classdef: [`decorators`] "class" `classname` [`inheritance`] ":" `suite` + inheritance: "(" [`argument_list`] ")" + classname: `identifier` + +A class definition is an executable statement. The inheritance list usually +gives a list of base classes (see :ref:`metaclasses` for more advanced uses), so +each item in the list should evaluate to a class object which allows +subclassing. Classes without an inheritance list inherit, by default, from the +base class :class:`object`; hence, :: + + class Foo: + pass + +is equivalent to :: + + class Foo(object): + pass + +The class's suite is then executed in a new execution frame (see :ref:`naming`), +using a newly created local namespace and the original global namespace. +(Usually, the suite contains mostly function definitions.) When the class's +suite finishes execution, its execution frame is discarded but its local +namespace is saved. [#]_ A class object is then created using the inheritance +list for the base classes and the saved local namespace for the attribute +dictionary. The class name is bound to this class object in the original local +namespace. + +The order in which attributes are defined in the class body is preserved +in the new class's ``__dict__``. Note that this is reliable only right +after the class is created and only for classes that were defined using +the definition syntax. + +Class creation can be customized heavily using :ref:`metaclasses `. + +.. index:: + single: @ (at); class definition + +Classes can also be decorated: just like when decorating functions, :: + + @f1(arg) + @f2 + class Foo: pass + +is roughly equivalent to :: + + class Foo: pass + Foo = f1(arg)(f2(Foo)) + +The evaluation rules for the decorator expressions are the same as for function +decorators. The result is then bound to the class name. + +.. versionchanged:: 3.9 + Classes may be decorated with any valid :token:`assignment_expression`. + Previously, the grammar was much more restrictive; see :pep:`614` for + details. + +**Programmer's note:** Variables defined in the class definition are class +attributes; they are shared by instances. Instance attributes can be set in a +method with ``self.name = value``. Both class and instance attributes are +accessible through the notation "``self.name``", and an instance attribute hides +a class attribute with the same name when accessed in this way. Class +attributes can be used as defaults for instance attributes, but using mutable +values there can lead to unexpected results. :ref:`Descriptors ` +can be used to create instance variables with different implementation details. + + +.. seealso:: + + :pep:`3115` - Metaclasses in Python 3000 + The proposal that changed the declaration of metaclasses to the current + syntax, and the semantics for how classes with metaclasses are + constructed. + + :pep:`3129` - Class Decorators + The proposal that added class decorators. Function and method decorators + were introduced in :pep:`318`. + + +.. _async: + +Coroutines +========== + +.. versionadded:: 3.5 + +.. index:: statement: async def +.. _`async def`: + +Coroutine function definition +----------------------------- + +.. productionlist:: + async_funcdef: [`decorators`] "async" "def" `funcname` "(" [`parameter_list`] ")" + : ["->" `expression`] ":" `suite` + +.. index:: + keyword: async + keyword: await + +Execution of Python coroutines can be suspended and resumed at many points +(see :term:`coroutine`). Inside the body of a coroutine function, ``await`` and +``async`` identifiers become reserved keywords; :keyword:`await` expressions, +:keyword:`async for` and :keyword:`async with` can only be used in +coroutine function bodies. + +Functions defined with ``async def`` syntax are always coroutine functions, +even if they do not contain ``await`` or ``async`` keywords. + +It is a :exc:`SyntaxError` to use a ``yield from`` expression inside the body +of a coroutine function. + +An example of a coroutine function:: + + async def func(param1, param2): + do_stuff() + await some_coroutine() + + +.. index:: statement: async for +.. _`async for`: + +The :keyword:`!async for` statement +----------------------------------- + +.. productionlist:: + async_for_stmt: "async" `for_stmt` + +An :term:`asynchronous iterable` is able to call asynchronous code in its +*iter* implementation, and :term:`asynchronous iterator` can call asynchronous +code in its *next* method. + +The ``async for`` statement allows convenient iteration over asynchronous +iterators. + +The following code:: + + async for TARGET in ITER: + SUITE + else: + SUITE2 + +Is semantically equivalent to:: + + iter = (ITER) + iter = type(iter).__aiter__(iter) + running = True + + while running: + try: + TARGET = await type(iter).__anext__(iter) + except StopAsyncIteration: + running = False + else: + SUITE + else: + SUITE2 + +See also :meth:`__aiter__` and :meth:`__anext__` for details. + +It is a :exc:`SyntaxError` to use an ``async for`` statement outside the +body of a coroutine function. + + +.. index:: statement: async with +.. _`async with`: + +The :keyword:`!async with` statement +------------------------------------ + +.. productionlist:: + async_with_stmt: "async" `with_stmt` + +An :term:`asynchronous context manager` is a :term:`context manager` that is +able to suspend execution in its *enter* and *exit* methods. + +The following code:: + + async with EXPRESSION as TARGET: + SUITE + +is semantically equivalent to:: + + manager = (EXPRESSION) + aenter = type(manager).__aenter__ + aexit = type(manager).__aexit__ + value = await aenter(manager) + hit_except = False + + try: + TARGET = value + SUITE + except: + hit_except = True + if not await aexit(manager, *sys.exc_info()): + raise + finally: + if not hit_except: + await aexit(manager, None, None, None) + +See also :meth:`__aenter__` and :meth:`__aexit__` for details. + +It is a :exc:`SyntaxError` to use an ``async with`` statement outside the +body of a coroutine function. + +.. seealso:: + + :pep:`492` - Coroutines with async and await syntax + The proposal that made coroutines a proper standalone concept in Python, + and added supporting syntax. + + +.. rubric:: Footnotes + +.. [#] The exception is propagated to the invocation stack unless + there is a :keyword:`finally` clause which happens to raise another + exception. That new exception causes the old one to be lost. + +.. [#] A string literal appearing as the first statement in the function body is + transformed into the function's ``__doc__`` attribute and therefore the + function's :term:`docstring`. + +.. [#] A string literal appearing as the first statement in the class body is + transformed into the namespace's ``__doc__`` item and therefore the class's + :term:`docstring`. diff --git a/cpython_2/environment/repo/Doc/reference/datamodel.rst b/cpython_2/environment/repo/Doc/reference/datamodel.rst new file mode 100644 index 0000000000000000000000000000000000000000..c5a7f046992dd11041e14ebadb6d0529dc031267 --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/datamodel.rst @@ -0,0 +1,2776 @@ + +.. _datamodel: + +********** +Data model +********** + + +.. _objects: + +Objects, values and types +========================= + +.. index:: + single: object + single: data + +:dfn:`Objects` are Python's abstraction for data. All data in a Python program +is represented by objects or by relations between objects. (In a sense, and in +conformance to Von Neumann's model of a "stored program computer", code is also +represented by objects.) + +.. index:: + builtin: id + builtin: type + single: identity of an object + single: value of an object + single: type of an object + single: mutable object + single: immutable object + +.. XXX it *is* now possible in some cases to change an object's + type, under certain controlled conditions + +Every object has an identity, a type and a value. An object's *identity* never +changes once it has been created; you may think of it as the object's address in +memory. The ':keyword:`is`' operator compares the identity of two objects; the +:func:`id` function returns an integer representing its identity. + +.. impl-detail:: + + For CPython, ``id(x)`` is the memory address where ``x`` is stored. + +An object's type determines the operations that the object supports (e.g., "does +it have a length?") and also defines the possible values for objects of that +type. The :func:`type` function returns an object's type (which is an object +itself). Like its identity, an object's :dfn:`type` is also unchangeable. +[#]_ + +The *value* of some objects can change. Objects whose value can +change are said to be *mutable*; objects whose value is unchangeable once they +are created are called *immutable*. (The value of an immutable container object +that contains a reference to a mutable object can change when the latter's value +is changed; however the container is still considered immutable, because the +collection of objects it contains cannot be changed. So, immutability is not +strictly the same as having an unchangeable value, it is more subtle.) An +object's mutability is determined by its type; for instance, numbers, strings +and tuples are immutable, while dictionaries and lists are mutable. + +.. index:: + single: garbage collection + single: reference counting + single: unreachable object + +Objects are never explicitly destroyed; however, when they become unreachable +they may be garbage-collected. An implementation is allowed to postpone garbage +collection or omit it altogether --- it is a matter of implementation quality +how garbage collection is implemented, as long as no objects are collected that +are still reachable. + +.. impl-detail:: + + CPython currently uses a reference-counting scheme with (optional) delayed + detection of cyclically linked garbage, which collects most objects as soon + as they become unreachable, but is not guaranteed to collect garbage + containing circular references. See the documentation of the :mod:`gc` + module for information on controlling the collection of cyclic garbage. + Other implementations act differently and CPython may change. + Do not depend on immediate finalization of objects when they become + unreachable (so you should always close files explicitly). + +Note that the use of the implementation's tracing or debugging facilities may +keep objects alive that would normally be collectable. Also note that catching +an exception with a ':keyword:`try`...\ :keyword:`except`' statement may keep +objects alive. + +Some objects contain references to "external" resources such as open files or +windows. It is understood that these resources are freed when the object is +garbage-collected, but since garbage collection is not guaranteed to happen, +such objects also provide an explicit way to release the external resource, +usually a :meth:`close` method. Programs are strongly recommended to explicitly +close such objects. The ':keyword:`try`...\ :keyword:`finally`' statement +and the ':keyword:`with`' statement provide convenient ways to do this. + +.. index:: single: container + +Some objects contain references to other objects; these are called *containers*. +Examples of containers are tuples, lists and dictionaries. The references are +part of a container's value. In most cases, when we talk about the value of a +container, we imply the values, not the identities of the contained objects; +however, when we talk about the mutability of a container, only the identities +of the immediately contained objects are implied. So, if an immutable container +(like a tuple) contains a reference to a mutable object, its value changes if +that mutable object is changed. + +Types affect almost all aspects of object behavior. Even the importance of +object identity is affected in some sense: for immutable types, operations that +compute new values may actually return a reference to any existing object with +the same type and value, while for mutable objects this is not allowed. E.g., +after ``a = 1; b = 1``, ``a`` and ``b`` may or may not refer to the same object +with the value one, depending on the implementation, but after ``c = []; d = +[]``, ``c`` and ``d`` are guaranteed to refer to two different, unique, newly +created empty lists. (Note that ``c = d = []`` assigns the same object to both +``c`` and ``d``.) + + +.. _types: + +The standard type hierarchy +=========================== + +.. index:: + single: type + pair: data; type + pair: type; hierarchy + pair: extension; module + pair: C; language + +Below is a list of the types that are built into Python. Extension modules +(written in C, Java, or other languages, depending on the implementation) can +define additional types. Future versions of Python may add types to the type +hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.), +although such additions will often be provided via the standard library instead. + +.. index:: + single: attribute + pair: special; attribute + triple: generic; special; attribute + +Some of the type descriptions below contain a paragraph listing 'special +attributes.' These are attributes that provide access to the implementation and +are not intended for general use. Their definition may change in the future. + +None + .. index:: object: None + + This type has a single value. There is a single object with this value. This + object is accessed through the built-in name ``None``. It is used to signify the + absence of a value in many situations, e.g., it is returned from functions that + don't explicitly return anything. Its truth value is false. + +NotImplemented + .. index:: object: NotImplemented + + This type has a single value. There is a single object with this value. This + object is accessed through the built-in name ``NotImplemented``. Numeric methods + and rich comparison methods should return this value if they do not implement the + operation for the operands provided. (The interpreter will then try the + reflected operation, or some other fallback, depending on the operator.) It + should not be evaluated in a boolean context. + + See + :ref:`implementing-the-arithmetic-operations` + for more details. + + .. versionchanged:: 3.9 + Evaluating ``NotImplemented`` in a boolean context is deprecated. While + it currently evaluates as true, it will emit a :exc:`DeprecationWarning`. + It will raise a :exc:`TypeError` in a future version of Python. + + +Ellipsis + .. index:: + object: Ellipsis + single: ...; ellipsis literal + + This type has a single value. There is a single object with this value. This + object is accessed through the literal ``...`` or the built-in name + ``Ellipsis``. Its truth value is true. + +:class:`numbers.Number` + .. index:: object: numeric + + These are created by numeric literals and returned as results by arithmetic + operators and arithmetic built-in functions. Numeric objects are immutable; + once created their value never changes. Python numbers are of course strongly + related to mathematical numbers, but subject to the limitations of numerical + representation in computers. + + Python distinguishes between integers, floating point numbers, and complex + numbers: + + :class:`numbers.Integral` + .. index:: object: integer + + These represent elements from the mathematical set of integers (positive and + negative). + + There are two types of integers: + + Integers (:class:`int`) + + These represent numbers in an unlimited range, subject to available (virtual) + memory only. For the purpose of shift and mask operations, a binary + representation is assumed, and negative numbers are represented in a variant of + 2's complement which gives the illusion of an infinite string of sign bits + extending to the left. + + Booleans (:class:`bool`) + .. index:: + object: Boolean + single: False + single: True + + These represent the truth values False and True. The two objects representing + the values ``False`` and ``True`` are the only Boolean objects. The Boolean type is a + subtype of the integer type, and Boolean values behave like the values 0 and 1, + respectively, in almost all contexts, the exception being that when converted to + a string, the strings ``"False"`` or ``"True"`` are returned, respectively. + + .. index:: pair: integer; representation + + The rules for integer representation are intended to give the most meaningful + interpretation of shift and mask operations involving negative integers. + + :class:`numbers.Real` (:class:`float`) + .. index:: + object: floating point + pair: floating point; number + pair: C; language + pair: Java; language + + These represent machine-level double precision floating point numbers. You are + at the mercy of the underlying machine architecture (and C or Java + implementation) for the accepted range and handling of overflow. Python does not + support single-precision floating point numbers; the savings in processor and + memory usage that are usually the reason for using these are dwarfed by the + overhead of using objects in Python, so there is no reason to complicate the + language with two kinds of floating point numbers. + + :class:`numbers.Complex` (:class:`complex`) + .. index:: + object: complex + pair: complex; number + + These represent complex numbers as a pair of machine-level double precision + floating point numbers. The same caveats apply as for floating point numbers. + The real and imaginary parts of a complex number ``z`` can be retrieved through + the read-only attributes ``z.real`` and ``z.imag``. + +Sequences + .. index:: + builtin: len + object: sequence + single: index operation + single: item selection + single: subscription + + These represent finite ordered sets indexed by non-negative numbers. The + built-in function :func:`len` returns the number of items of a sequence. When + the length of a sequence is *n*, the index set contains the numbers 0, 1, + ..., *n*-1. Item *i* of sequence *a* is selected by ``a[i]``. + + .. index:: single: slicing + + Sequences also support slicing: ``a[i:j]`` selects all items with index *k* such + that *i* ``<=`` *k* ``<`` *j*. When used as an expression, a slice is a + sequence of the same type. This implies that the index set is renumbered so + that it starts at 0. + + Some sequences also support "extended slicing" with a third "step" parameter: + ``a[i:j:k]`` selects all items of *a* with index *x* where ``x = i + n*k``, *n* + ``>=`` ``0`` and *i* ``<=`` *x* ``<`` *j*. + + Sequences are distinguished according to their mutability: + + Immutable sequences + .. index:: + object: immutable sequence + object: immutable + + An object of an immutable sequence type cannot change once it is created. (If + the object contains references to other objects, these other objects may be + mutable and may be changed; however, the collection of objects directly + referenced by an immutable object cannot change.) + + The following types are immutable sequences: + + .. index:: + single: string; immutable sequences + + Strings + .. index:: + builtin: chr + builtin: ord + single: character + single: integer + single: Unicode + + A string is a sequence of values that represent Unicode code points. + All the code points in the range ``U+0000 - U+10FFFF`` can be + represented in a string. Python doesn't have a :c:type:`char` type; + instead, every code point in the string is represented as a string + object with length ``1``. The built-in function :func:`ord` + converts a code point from its string form to an integer in the + range ``0 - 10FFFF``; :func:`chr` converts an integer in the range + ``0 - 10FFFF`` to the corresponding length ``1`` string object. + :meth:`str.encode` can be used to convert a :class:`str` to + :class:`bytes` using the given text encoding, and + :meth:`bytes.decode` can be used to achieve the opposite. + + Tuples + .. index:: + object: tuple + pair: singleton; tuple + pair: empty; tuple + + The items of a tuple are arbitrary Python objects. Tuples of two or + more items are formed by comma-separated lists of expressions. A tuple + of one item (a 'singleton') can be formed by affixing a comma to an + expression (an expression by itself does not create a tuple, since + parentheses must be usable for grouping of expressions). An empty + tuple can be formed by an empty pair of parentheses. + + Bytes + .. index:: bytes, byte + + A bytes object is an immutable array. The items are 8-bit bytes, + represented by integers in the range 0 <= x < 256. Bytes literals + (like ``b'abc'``) and the built-in :func:`bytes()` constructor + can be used to create bytes objects. Also, bytes objects can be + decoded to strings via the :meth:`~bytes.decode` method. + + Mutable sequences + .. index:: + object: mutable sequence + object: mutable + pair: assignment; statement + single: subscription + single: slicing + + Mutable sequences can be changed after they are created. The subscription and + slicing notations can be used as the target of assignment and :keyword:`del` + (delete) statements. + + There are currently two intrinsic mutable sequence types: + + Lists + .. index:: object: list + + The items of a list are arbitrary Python objects. Lists are formed by + placing a comma-separated list of expressions in square brackets. (Note + that there are no special cases needed to form lists of length 0 or 1.) + + Byte Arrays + .. index:: bytearray + + A bytearray object is a mutable array. They are created by the built-in + :func:`bytearray` constructor. Aside from being mutable + (and hence unhashable), byte arrays otherwise provide the same interface + and functionality as immutable :class:`bytes` objects. + + .. index:: module: array + + The extension module :mod:`array` provides an additional example of a + mutable sequence type, as does the :mod:`collections` module. + +Set types + .. index:: + builtin: len + object: set type + + These represent unordered, finite sets of unique, immutable objects. As such, + they cannot be indexed by any subscript. However, they can be iterated over, and + the built-in function :func:`len` returns the number of items in a set. Common + uses for sets are fast membership testing, removing duplicates from a sequence, + and computing mathematical operations such as intersection, union, difference, + and symmetric difference. + + For set elements, the same immutability rules apply as for dictionary keys. Note + that numeric types obey the normal rules for numeric comparison: if two numbers + compare equal (e.g., ``1`` and ``1.0``), only one of them can be contained in a + set. + + There are currently two intrinsic set types: + + Sets + .. index:: object: set + + These represent a mutable set. They are created by the built-in :func:`set` + constructor and can be modified afterwards by several methods, such as + :meth:`~set.add`. + + Frozen sets + .. index:: object: frozenset + + These represent an immutable set. They are created by the built-in + :func:`frozenset` constructor. As a frozenset is immutable and + :term:`hashable`, it can be used again as an element of another set, or as + a dictionary key. + +Mappings + .. index:: + builtin: len + single: subscription + object: mapping + + These represent finite sets of objects indexed by arbitrary index sets. The + subscript notation ``a[k]`` selects the item indexed by ``k`` from the mapping + ``a``; this can be used in expressions and as the target of assignments or + :keyword:`del` statements. The built-in function :func:`len` returns the number + of items in a mapping. + + There is currently a single intrinsic mapping type: + + Dictionaries + .. index:: object: dictionary + + These represent finite sets of objects indexed by nearly arbitrary values. The + only types of values not acceptable as keys are values containing lists or + dictionaries or other mutable types that are compared by value rather than by + object identity, the reason being that the efficient implementation of + dictionaries requires a key's hash value to remain constant. Numeric types used + for keys obey the normal rules for numeric comparison: if two numbers compare + equal (e.g., ``1`` and ``1.0``) then they can be used interchangeably to index + the same dictionary entry. + + Dictionaries preserve insertion order, meaning that keys will be produced + in the same order they were added sequentially over the dictionary. + Replacing an existing key does not change the order, however removing a key + and re-inserting it will add it to the end instead of keeping its old place. + + Dictionaries are mutable; they can be created by the ``{...}`` notation (see + section :ref:`dict`). + + .. index:: + module: dbm.ndbm + module: dbm.gnu + + The extension modules :mod:`dbm.ndbm` and :mod:`dbm.gnu` provide + additional examples of mapping types, as does the :mod:`collections` + module. + + .. versionchanged:: 3.7 + Dictionaries did not preserve insertion order in versions of Python before 3.6. + In CPython 3.6, insertion order was preserved, but it was considered + an implementation detail at that time rather than a language guarantee. + +Callable types + .. index:: + object: callable + pair: function; call + single: invocation + pair: function; argument + + These are the types to which the function call operation (see section + :ref:`calls`) can be applied: + + User-defined functions + .. index:: + pair: user-defined; function + object: function + object: user-defined function + + A user-defined function object is created by a function definition (see + section :ref:`function`). It should be called with an argument list + containing the same number of items as the function's formal parameter + list. + + Special attributes: + + .. tabularcolumns:: |l|L|l| + + .. index:: + single: __doc__ (function attribute) + single: __name__ (function attribute) + single: __module__ (function attribute) + single: __dict__ (function attribute) + single: __defaults__ (function attribute) + single: __closure__ (function attribute) + single: __code__ (function attribute) + single: __globals__ (function attribute) + single: __annotations__ (function attribute) + single: __kwdefaults__ (function attribute) + pair: global; namespace + + +-------------------------+-------------------------------+-----------+ + | Attribute | Meaning | | + +=========================+===============================+===========+ + | :attr:`__doc__` | The function's documentation | Writable | + | | string, or ``None`` if | | + | | unavailable; not inherited by | | + | | subclasses. | | + +-------------------------+-------------------------------+-----------+ + | :attr:`~definition.\ | The function's name. | Writable | + | __name__` | | | + +-------------------------+-------------------------------+-----------+ + | :attr:`~definition.\ | The function's | Writable | + | __qualname__` | :term:`qualified name`. | | + | | | | + | | .. versionadded:: 3.3 | | + +-------------------------+-------------------------------+-----------+ + | :attr:`__module__` | The name of the module the | Writable | + | | function was defined in, or | | + | | ``None`` if unavailable. | | + +-------------------------+-------------------------------+-----------+ + | :attr:`__defaults__` | A tuple containing default | Writable | + | | argument values for those | | + | | arguments that have defaults, | | + | | or ``None`` if no arguments | | + | | have a default value. | | + +-------------------------+-------------------------------+-----------+ + | :attr:`__code__` | The code object representing | Writable | + | | the compiled function body. | | + +-------------------------+-------------------------------+-----------+ + | :attr:`__globals__` | A reference to the dictionary | Read-only | + | | that holds the function's | | + | | global variables --- the | | + | | global namespace of the | | + | | module in which the function | | + | | was defined. | | + +-------------------------+-------------------------------+-----------+ + | :attr:`~object.__dict__`| The namespace supporting | Writable | + | | arbitrary function | | + | | attributes. | | + +-------------------------+-------------------------------+-----------+ + | :attr:`__closure__` | ``None`` or a tuple of cells | Read-only | + | | that contain bindings for the | | + | | function's free variables. | | + | | See below for information on | | + | | the ``cell_contents`` | | + | | attribute. | | + +-------------------------+-------------------------------+-----------+ + | :attr:`__annotations__` | A dict containing annotations | Writable | + | | of parameters. The keys of | | + | | the dict are the parameter | | + | | names, and ``'return'`` for | | + | | the return annotation, if | | + | | provided. | | + +-------------------------+-------------------------------+-----------+ + | :attr:`__kwdefaults__` | A dict containing defaults | Writable | + | | for keyword-only parameters. | | + +-------------------------+-------------------------------+-----------+ + + Most of the attributes labelled "Writable" check the type of the assigned value. + + Function objects also support getting and setting arbitrary attributes, which + can be used, for example, to attach metadata to functions. Regular attribute + dot-notation is used to get and set such attributes. *Note that the current + implementation only supports function attributes on user-defined functions. + Function attributes on built-in functions may be supported in the future.* + + A cell object has the attribute ``cell_contents``. This can be used to get + the value of the cell, as well as set the value. + + Additional information about a function's definition can be retrieved from its + code object; see the description of internal types below. The + :data:`cell ` type can be accessed in the :mod:`types` + module. + + Instance methods + .. index:: + object: method + object: user-defined method + pair: user-defined; method + + An instance method object combines a class, a class instance and any + callable object (normally a user-defined function). + + .. index:: + single: __func__ (method attribute) + single: __self__ (method attribute) + single: __doc__ (method attribute) + single: __name__ (method attribute) + single: __module__ (method attribute) + + Special read-only attributes: :attr:`__self__` is the class instance object, + :attr:`__func__` is the function object; :attr:`__doc__` is the method's + documentation (same as ``__func__.__doc__``); :attr:`~definition.__name__` is the + method name (same as ``__func__.__name__``); :attr:`__module__` is the + name of the module the method was defined in, or ``None`` if unavailable. + + Methods also support accessing (but not setting) the arbitrary function + attributes on the underlying function object. + + User-defined method objects may be created when getting an attribute of a + class (perhaps via an instance of that class), if that attribute is a + user-defined function object or a class method object. + + When an instance method object is created by retrieving a user-defined + function object from a class via one of its instances, its + :attr:`__self__` attribute is the instance, and the method object is said + to be bound. The new method's :attr:`__func__` attribute is the original + function object. + + When an instance method object is created by retrieving a class method + object from a class or instance, its :attr:`__self__` attribute is the + class itself, and its :attr:`__func__` attribute is the function object + underlying the class method. + + When an instance method object is called, the underlying function + (:attr:`__func__`) is called, inserting the class instance + (:attr:`__self__`) in front of the argument list. For instance, when + :class:`C` is a class which contains a definition for a function + :meth:`f`, and ``x`` is an instance of :class:`C`, calling ``x.f(1)`` is + equivalent to calling ``C.f(x, 1)``. + + When an instance method object is derived from a class method object, the + "class instance" stored in :attr:`__self__` will actually be the class + itself, so that calling either ``x.f(1)`` or ``C.f(1)`` is equivalent to + calling ``f(C,1)`` where ``f`` is the underlying function. + + Note that the transformation from function object to instance method + object happens each time the attribute is retrieved from the instance. In + some cases, a fruitful optimization is to assign the attribute to a local + variable and call that local variable. Also notice that this + transformation only happens for user-defined functions; other callable + objects (and all non-callable objects) are retrieved without + transformation. It is also important to note that user-defined functions + which are attributes of a class instance are not converted to bound + methods; this *only* happens when the function is an attribute of the + class. + + Generator functions + .. index:: + single: generator; function + single: generator; iterator + + A function or method which uses the :keyword:`yield` statement (see section + :ref:`yield`) is called a :dfn:`generator function`. Such a function, when + called, always returns an iterator object which can be used to execute the + body of the function: calling the iterator's :meth:`iterator.__next__` + method will cause the function to execute until it provides a value + using the :keyword:`!yield` statement. When the function executes a + :keyword:`return` statement or falls off the end, a :exc:`StopIteration` + exception is raised and the iterator will have reached the end of the set of + values to be returned. + + Coroutine functions + .. index:: + single: coroutine; function + + A function or method which is defined using :keyword:`async def` is called + a :dfn:`coroutine function`. Such a function, when called, returns a + :term:`coroutine` object. It may contain :keyword:`await` expressions, + as well as :keyword:`async with` and :keyword:`async for` statements. See + also the :ref:`coroutine-objects` section. + + Asynchronous generator functions + .. index:: + single: asynchronous generator; function + single: asynchronous generator; asynchronous iterator + + A function or method which is defined using :keyword:`async def` and + which uses the :keyword:`yield` statement is called a + :dfn:`asynchronous generator function`. Such a function, when called, + returns an asynchronous iterator object which can be used in an + :keyword:`async for` statement to execute the body of the function. + + Calling the asynchronous iterator's :meth:`aiterator.__anext__` method + will return an :term:`awaitable` which when awaited + will execute until it provides a value using the :keyword:`yield` + expression. When the function executes an empty :keyword:`return` + statement or falls off the end, a :exc:`StopAsyncIteration` exception + is raised and the asynchronous iterator will have reached the end of + the set of values to be yielded. + + Built-in functions + .. index:: + object: built-in function + object: function + pair: C; language + + A built-in function object is a wrapper around a C function. Examples of + built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a + standard built-in module). The number and type of the arguments are + determined by the C function. Special read-only attributes: + :attr:`__doc__` is the function's documentation string, or ``None`` if + unavailable; :attr:`~definition.__name__` is the function's name; :attr:`__self__` is + set to ``None`` (but see the next item); :attr:`__module__` is the name of + the module the function was defined in or ``None`` if unavailable. + + Built-in methods + .. index:: + object: built-in method + object: method + pair: built-in; method + + This is really a different disguise of a built-in function, this time containing + an object passed to the C function as an implicit extra argument. An example of + a built-in method is ``alist.append()``, assuming *alist* is a list object. In + this case, the special read-only attribute :attr:`__self__` is set to the object + denoted by *alist*. + + Classes + Classes are callable. These objects normally act as factories for new + instances of themselves, but variations are possible for class types that + override :meth:`__new__`. The arguments of the call are passed to + :meth:`__new__` and, in the typical case, to :meth:`__init__` to + initialize the new instance. + + Class Instances + Instances of arbitrary classes can be made callable by defining a + :meth:`__call__` method in their class. + + +Modules + .. index:: + statement: import + object: module + + Modules are a basic organizational unit of Python code, and are created by + the :ref:`import system ` as invoked either by the + :keyword:`import` statement, or by calling + functions such as :func:`importlib.import_module` and built-in + :func:`__import__`. A module object has a namespace implemented by a + dictionary object (this is the dictionary referenced by the ``__globals__`` + attribute of functions defined in the module). Attribute references are + translated to lookups in this dictionary, e.g., ``m.x`` is equivalent to + ``m.__dict__["x"]``. A module object does not contain the code object used + to initialize the module (since it isn't needed once the initialization is + done). + + Attribute assignment updates the module's namespace dictionary, e.g., + ``m.x = 1`` is equivalent to ``m.__dict__["x"] = 1``. + + .. index:: + single: __name__ (module attribute) + single: __doc__ (module attribute) + single: __file__ (module attribute) + single: __annotations__ (module attribute) + pair: module; namespace + + Predefined (writable) attributes: :attr:`__name__` is the module's name; + :attr:`__doc__` is the module's documentation string, or ``None`` if + unavailable; :attr:`__annotations__` (optional) is a dictionary containing + :term:`variable annotations ` collected during module + body execution; :attr:`__file__` is the pathname of the file from which the + module was loaded, if it was loaded from a file. The :attr:`__file__` + attribute may be missing for certain types of modules, such as C modules + that are statically linked into the interpreter; for extension modules + loaded dynamically from a shared library, it is the pathname of the shared + library file. + + .. index:: single: __dict__ (module attribute) + + Special read-only attribute: :attr:`~object.__dict__` is the module's + namespace as a dictionary object. + + .. impl-detail:: + + Because of the way CPython clears module dictionaries, the module + dictionary will be cleared when the module falls out of scope even if the + dictionary still has live references. To avoid this, copy the dictionary + or keep the module around while using its dictionary directly. + +Custom classes + Custom class types are typically created by class definitions (see section + :ref:`class`). A class has a namespace implemented by a dictionary object. + Class attribute references are translated to lookups in this dictionary, e.g., + ``C.x`` is translated to ``C.__dict__["x"]`` (although there are a number of + hooks which allow for other means of locating attributes). When the attribute + name is not found there, the attribute search continues in the base classes. + This search of the base classes uses the C3 method resolution order which + behaves correctly even in the presence of 'diamond' inheritance structures + where there are multiple inheritance paths leading back to a common ancestor. + Additional details on the C3 MRO used by Python can be found in the + documentation accompanying the 2.3 release at + https://www.python.org/download/releases/2.3/mro/. + + .. XXX: Could we add that MRO doc as an appendix to the language ref? + + .. index:: + object: class + object: class instance + object: instance + pair: class object; call + single: container + object: dictionary + pair: class; attribute + + When a class attribute reference (for class :class:`C`, say) would yield a + class method object, it is transformed into an instance method object whose + :attr:`__self__` attribute is :class:`C`. When it would yield a static + method object, it is transformed into the object wrapped by the static method + object. See section :ref:`descriptors` for another way in which attributes + retrieved from a class may differ from those actually contained in its + :attr:`~object.__dict__`. + + .. index:: triple: class; attribute; assignment + + Class attribute assignments update the class's dictionary, never the dictionary + of a base class. + + .. index:: pair: class object; call + + A class object can be called (see above) to yield a class instance (see below). + + .. index:: + single: __name__ (class attribute) + single: __module__ (class attribute) + single: __dict__ (class attribute) + single: __bases__ (class attribute) + single: __doc__ (class attribute) + single: __annotations__ (class attribute) + + Special attributes: :attr:`~definition.__name__` is the class name; :attr:`__module__` is + the module name in which the class was defined; :attr:`~object.__dict__` is the + dictionary containing the class's namespace; :attr:`~class.__bases__` is a + tuple containing the base classes, in the order of their occurrence in the + base class list; :attr:`__doc__` is the class's documentation string, + or ``None`` if undefined; :attr:`__annotations__` (optional) is a dictionary + containing :term:`variable annotations ` collected during + class body execution. + +Class instances + .. index:: + object: class instance + object: instance + pair: class; instance + pair: class instance; attribute + + A class instance is created by calling a class object (see above). A class + instance has a namespace implemented as a dictionary which is the first place + in which attribute references are searched. When an attribute is not found + there, and the instance's class has an attribute by that name, the search + continues with the class attributes. If a class attribute is found that is a + user-defined function object, it is transformed into an instance method + object whose :attr:`__self__` attribute is the instance. Static method and + class method objects are also transformed; see above under "Classes". See + section :ref:`descriptors` for another way in which attributes of a class + retrieved via its instances may differ from the objects actually stored in + the class's :attr:`~object.__dict__`. If no class attribute is found, and the + object's class has a :meth:`__getattr__` method, that is called to satisfy + the lookup. + + .. index:: triple: class instance; attribute; assignment + + Attribute assignments and deletions update the instance's dictionary, never a + class's dictionary. If the class has a :meth:`__setattr__` or + :meth:`__delattr__` method, this is called instead of updating the instance + dictionary directly. + + .. index:: + object: numeric + object: sequence + object: mapping + + Class instances can pretend to be numbers, sequences, or mappings if they have + methods with certain special names. See section :ref:`specialnames`. + + .. index:: + single: __dict__ (instance attribute) + single: __class__ (instance attribute) + + Special attributes: :attr:`~object.__dict__` is the attribute dictionary; + :attr:`~instance.__class__` is the instance's class. + +I/O objects (also known as file objects) + .. index:: + builtin: open + module: io + single: popen() (in module os) + single: makefile() (socket method) + single: sys.stdin + single: sys.stdout + single: sys.stderr + single: stdio + single: stdin (in module sys) + single: stdout (in module sys) + single: stderr (in module sys) + + A :term:`file object` represents an open file. Various shortcuts are + available to create file objects: the :func:`open` built-in function, and + also :func:`os.popen`, :func:`os.fdopen`, and the + :meth:`~socket.socket.makefile` method of socket objects (and perhaps by + other functions or methods provided by extension modules). + + The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are + initialized to file objects corresponding to the interpreter's standard + input, output and error streams; they are all open in text mode and + therefore follow the interface defined by the :class:`io.TextIOBase` + abstract class. + +Internal types + .. index:: + single: internal type + single: types, internal + + A few types used internally by the interpreter are exposed to the user. Their + definitions may change with future versions of the interpreter, but they are + mentioned here for completeness. + + .. index:: bytecode, object; code, code object + + Code objects + Code objects represent *byte-compiled* executable Python code, or :term:`bytecode`. + The difference between a code object and a function object is that the function + object contains an explicit reference to the function's globals (the module in + which it was defined), while a code object contains no context; also the default + argument values are stored in the function object, not in the code object + (because they represent values calculated at run-time). Unlike function + objects, code objects are immutable and contain no references (directly or + indirectly) to mutable objects. + + .. index:: + single: co_argcount (code object attribute) + single: co_posonlyargcount (code object attribute) + single: co_kwonlyargcount (code object attribute) + single: co_code (code object attribute) + single: co_consts (code object attribute) + single: co_filename (code object attribute) + single: co_firstlineno (code object attribute) + single: co_flags (code object attribute) + single: co_lnotab (code object attribute) + single: co_name (code object attribute) + single: co_names (code object attribute) + single: co_nlocals (code object attribute) + single: co_stacksize (code object attribute) + single: co_varnames (code object attribute) + single: co_cellvars (code object attribute) + single: co_freevars (code object attribute) + + Special read-only attributes: :attr:`co_name` gives the function name; + :attr:`co_argcount` is the total number of positional arguments + (including positional-only arguments and arguments with default values); + :attr:`co_posonlyargcount` is the number of positional-only arguments + (including arguments with default values); :attr:`co_kwonlyargcount` is + the number of keyword-only arguments (including arguments with default + values); :attr:`co_nlocals` is the number of local variables used by the + function (including arguments); :attr:`co_varnames` is a tuple containing + the names of the local variables (starting with the argument names); + :attr:`co_cellvars` is a tuple containing the names of local variables + that are referenced by nested functions; :attr:`co_freevars` is a tuple + containing the names of free variables; :attr:`co_code` is a string + representing the sequence of bytecode instructions; :attr:`co_consts` is + a tuple containing the literals used by the bytecode; :attr:`co_names` is + a tuple containing the names used by the bytecode; :attr:`co_filename` is + the filename from which the code was compiled; :attr:`co_firstlineno` is + the first line number of the function; :attr:`co_lnotab` is a string + encoding the mapping from bytecode offsets to line numbers (for details + see the source code of the interpreter); :attr:`co_stacksize` is the + required stack size; :attr:`co_flags` is an integer encoding a number + of flags for the interpreter. + + .. index:: object: generator + + The following flag bits are defined for :attr:`co_flags`: bit ``0x04`` is set if + the function uses the ``*arguments`` syntax to accept an arbitrary number of + positional arguments; bit ``0x08`` is set if the function uses the + ``**keywords`` syntax to accept arbitrary keyword arguments; bit ``0x20`` is set + if the function is a generator. + + Future feature declarations (``from __future__ import division``) also use bits + in :attr:`co_flags` to indicate whether a code object was compiled with a + particular feature enabled: bit ``0x2000`` is set if the function was compiled + with future division enabled; bits ``0x10`` and ``0x1000`` were used in earlier + versions of Python. + + Other bits in :attr:`co_flags` are reserved for internal use. + + .. index:: single: documentation string + + If a code object represents a function, the first item in :attr:`co_consts` is + the documentation string of the function, or ``None`` if undefined. + + .. _frame-objects: + + Frame objects + .. index:: object: frame + + Frame objects represent execution frames. They may occur in traceback objects + (see below), and are also passed to registered trace functions. + + .. index:: + single: f_back (frame attribute) + single: f_code (frame attribute) + single: f_globals (frame attribute) + single: f_locals (frame attribute) + single: f_lasti (frame attribute) + single: f_builtins (frame attribute) + + Special read-only attributes: :attr:`f_back` is to the previous stack frame + (towards the caller), or ``None`` if this is the bottom stack frame; + :attr:`f_code` is the code object being executed in this frame; :attr:`f_locals` + is the dictionary used to look up local variables; :attr:`f_globals` is used for + global variables; :attr:`f_builtins` is used for built-in (intrinsic) names; + :attr:`f_lasti` gives the precise instruction (this is an index into the + bytecode string of the code object). + + .. index:: + single: f_trace (frame attribute) + single: f_trace_lines (frame attribute) + single: f_trace_opcodes (frame attribute) + single: f_lineno (frame attribute) + + Special writable attributes: :attr:`f_trace`, if not ``None``, is a function + called for various events during code execution (this is used by the debugger). + Normally an event is triggered for each new source line - this can be + disabled by setting :attr:`f_trace_lines` to :const:`False`. + + Implementations *may* allow per-opcode events to be requested by setting + :attr:`f_trace_opcodes` to :const:`True`. Note that this may lead to + undefined interpreter behaviour if exceptions raised by the trace + function escape to the function being traced. + + :attr:`f_lineno` is the current line number of the frame --- writing to this + from within a trace function jumps to the given line (only for the bottom-most + frame). A debugger can implement a Jump command (aka Set Next Statement) + by writing to f_lineno. + + Frame objects support one method: + + .. method:: frame.clear() + + This method clears all references to local variables held by the + frame. Also, if the frame belonged to a generator, the generator + is finalized. This helps break reference cycles involving frame + objects (for example when catching an exception and storing its + traceback for later use). + + :exc:`RuntimeError` is raised if the frame is currently executing. + + .. versionadded:: 3.4 + + .. _traceback-objects: + + Traceback objects + .. index:: + object: traceback + pair: stack; trace + pair: exception; handler + pair: execution; stack + single: exc_info (in module sys) + single: last_traceback (in module sys) + single: sys.exc_info + single: sys.last_traceback + + Traceback objects represent a stack trace of an exception. A traceback object + is implicitly created when an exception occurs, and may also be explicitly + created by calling :class:`types.TracebackType`. + + For implicitly created tracebacks, when the search for an exception handler + unwinds the execution stack, at each unwound level a traceback object is + inserted in front of the current traceback. When an exception handler is + entered, the stack trace is made available to the program. (See section + :ref:`try`.) It is accessible as the third item of the + tuple returned by ``sys.exc_info()``, and as the ``__traceback__`` attribute + of the caught exception. + + When the program contains no suitable + handler, the stack trace is written (nicely formatted) to the standard error + stream; if the interpreter is interactive, it is also made available to the user + as ``sys.last_traceback``. + + For explicitly created tracebacks, it is up to the creator of the traceback + to determine how the ``tb_next`` attributes should be linked to form a + full stack trace. + + .. index:: + single: tb_frame (traceback attribute) + single: tb_lineno (traceback attribute) + single: tb_lasti (traceback attribute) + statement: try + + Special read-only attributes: + :attr:`tb_frame` points to the execution frame of the current level; + :attr:`tb_lineno` gives the line number where the exception occurred; + :attr:`tb_lasti` indicates the precise instruction. + The line number and last instruction in the traceback may differ from the + line number of its frame object if the exception occurred in a + :keyword:`try` statement with no matching except clause or with a + finally clause. + + .. index:: + single: tb_next (traceback attribute) + + Special writable attribute: :attr:`tb_next` is the next level in the stack + trace (towards the frame where the exception occurred), or ``None`` if + there is no next level. + + .. versionchanged:: 3.7 + Traceback objects can now be explicitly instantiated from Python code, + and the ``tb_next`` attribute of existing instances can be updated. + + Slice objects + .. index:: builtin: slice + + Slice objects are used to represent slices for :meth:`__getitem__` + methods. They are also created by the built-in :func:`slice` function. + + .. index:: + single: start (slice object attribute) + single: stop (slice object attribute) + single: step (slice object attribute) + + Special read-only attributes: :attr:`~slice.start` is the lower bound; + :attr:`~slice.stop` is the upper bound; :attr:`~slice.step` is the step + value; each is ``None`` if omitted. These attributes can have any type. + + Slice objects support one method: + + .. method:: slice.indices(self, length) + + This method takes a single integer argument *length* and computes + information about the slice that the slice object would describe if + applied to a sequence of *length* items. It returns a tuple of three + integers; respectively these are the *start* and *stop* indices and the + *step* or stride length of the slice. Missing or out-of-bounds indices + are handled in a manner consistent with regular slices. + + Static method objects + Static method objects provide a way of defeating the transformation of function + objects to method objects described above. A static method object is a wrapper + around any other object, usually a user-defined method object. When a static + method object is retrieved from a class or a class instance, the object actually + returned is the wrapped object, which is not subject to any further + transformation. Static method objects are not themselves callable, although the + objects they wrap usually are. Static method objects are created by the built-in + :func:`staticmethod` constructor. + + Class method objects + A class method object, like a static method object, is a wrapper around another + object that alters the way in which that object is retrieved from classes and + class instances. The behaviour of class method objects upon such retrieval is + described above, under "User-defined methods". Class method objects are created + by the built-in :func:`classmethod` constructor. + + +.. _specialnames: + +Special method names +==================== + +.. index:: + pair: operator; overloading + single: __getitem__() (mapping object method) + +A class can implement certain operations that are invoked by special syntax +(such as arithmetic operations or subscripting and slicing) by defining methods +with special names. This is Python's approach to :dfn:`operator overloading`, +allowing classes to define their own behavior with respect to language +operators. For instance, if a class defines a method named :meth:`__getitem__`, +and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent +to ``type(x).__getitem__(x, i)``. Except where mentioned, attempts to execute an +operation raise an exception when no appropriate method is defined (typically +:exc:`AttributeError` or :exc:`TypeError`). + +Setting a special method to ``None`` indicates that the corresponding +operation is not available. For example, if a class sets +:meth:`__iter__` to ``None``, the class is not iterable, so calling +:func:`iter` on its instances will raise a :exc:`TypeError` (without +falling back to :meth:`__getitem__`). [#]_ + +When implementing a class that emulates any built-in type, it is important that +the emulation only be implemented to the degree that it makes sense for the +object being modelled. For example, some sequences may work well with retrieval +of individual elements, but extracting a slice may not make sense. (One example +of this is the :class:`~xml.dom.NodeList` interface in the W3C's Document +Object Model.) + + +.. _customization: + +Basic customization +------------------- + +.. method:: object.__new__(cls[, ...]) + + .. index:: pair: subclassing; immutable types + + Called to create a new instance of class *cls*. :meth:`__new__` is a static + method (special-cased so you need not declare it as such) that takes the class + of which an instance was requested as its first argument. The remaining + arguments are those passed to the object constructor expression (the call to the + class). The return value of :meth:`__new__` should be the new object instance + (usually an instance of *cls*). + + Typical implementations create a new instance of the class by invoking the + superclass's :meth:`__new__` method using ``super().__new__(cls[, ...])`` + with appropriate arguments and then modifying the newly-created instance + as necessary before returning it. + + If :meth:`__new__` is invoked during object construction and it returns an + instance or subclass of *cls*, then the new instance’s :meth:`__init__` method + will be invoked like ``__init__(self[, ...])``, where *self* is the new instance + and the remaining arguments are the same as were passed to the object constructor. + + If :meth:`__new__` does not return an instance of *cls*, then the new instance's + :meth:`__init__` method will not be invoked. + + :meth:`__new__` is intended mainly to allow subclasses of immutable types (like + int, str, or tuple) to customize instance creation. It is also commonly + overridden in custom metaclasses in order to customize class creation. + + +.. method:: object.__init__(self[, ...]) + + .. index:: pair: class; constructor + + Called after the instance has been created (by :meth:`__new__`), but before + it is returned to the caller. The arguments are those passed to the + class constructor expression. If a base class has an :meth:`__init__` + method, the derived class's :meth:`__init__` method, if any, must explicitly + call it to ensure proper initialization of the base class part of the + instance; for example: ``super().__init__([args...])``. + + Because :meth:`__new__` and :meth:`__init__` work together in constructing + objects (:meth:`__new__` to create it, and :meth:`__init__` to customize it), + no non-``None`` value may be returned by :meth:`__init__`; doing so will + cause a :exc:`TypeError` to be raised at runtime. + + +.. method:: object.__del__(self) + + .. index:: + single: destructor + single: finalizer + statement: del + + Called when the instance is about to be destroyed. This is also called a + finalizer or (improperly) a destructor. If a base class has a + :meth:`__del__` method, the derived class's :meth:`__del__` method, + if any, must explicitly call it to ensure proper deletion of the base + class part of the instance. + + It is possible (though not recommended!) for the :meth:`__del__` method + to postpone destruction of the instance by creating a new reference to + it. This is called object *resurrection*. It is implementation-dependent + whether :meth:`__del__` is called a second time when a resurrected object + is about to be destroyed; the current :term:`CPython` implementation + only calls it once. + + It is not guaranteed that :meth:`__del__` methods are called for objects + that still exist when the interpreter exits. + + .. note:: + + ``del x`` doesn't directly call ``x.__del__()`` --- the former decrements + the reference count for ``x`` by one, and the latter is only called when + ``x``'s reference count reaches zero. + + .. impl-detail:: + It is possible for a reference cycle to prevent the reference count + of an object from going to zero. In this case, the cycle will be + later detected and deleted by the :term:`cyclic garbage collector + `. A common cause of reference cycles is when + an exception has been caught in a local variable. The frame's + locals then reference the exception, which references its own + traceback, which references the locals of all frames caught in the + traceback. + + .. seealso:: + Documentation for the :mod:`gc` module. + + .. warning:: + + Due to the precarious circumstances under which :meth:`__del__` methods are + invoked, exceptions that occur during their execution are ignored, and a warning + is printed to ``sys.stderr`` instead. In particular: + + * :meth:`__del__` can be invoked when arbitrary code is being executed, + including from any arbitrary thread. If :meth:`__del__` needs to take + a lock or invoke any other blocking resource, it may deadlock as + the resource may already be taken by the code that gets interrupted + to execute :meth:`__del__`. + + * :meth:`__del__` can be executed during interpreter shutdown. As a + consequence, the global variables it needs to access (including other + modules) may already have been deleted or set to ``None``. Python + guarantees that globals whose name begins with a single underscore + are deleted from their module before other globals are deleted; if + no other references to such globals exist, this may help in assuring + that imported modules are still available at the time when the + :meth:`__del__` method is called. + + + .. index:: + single: repr() (built-in function); __repr__() (object method) + +.. method:: object.__repr__(self) + + Called by the :func:`repr` built-in function to compute the "official" string + representation of an object. If at all possible, this should look like a + valid Python expression that could be used to recreate an object with the + same value (given an appropriate environment). If this is not possible, a + string of the form ``<...some useful description...>`` should be returned. + The return value must be a string object. If a class defines :meth:`__repr__` + but not :meth:`__str__`, then :meth:`__repr__` is also used when an + "informal" string representation of instances of that class is required. + + This is typically used for debugging, so it is important that the representation + is information-rich and unambiguous. + + .. index:: + single: string; __str__() (object method) + single: format() (built-in function); __str__() (object method) + single: print() (built-in function); __str__() (object method) + + +.. method:: object.__str__(self) + + Called by :func:`str(object) ` and the built-in functions + :func:`format` and :func:`print` to compute the "informal" or nicely + printable string representation of an object. The return value must be a + :ref:`string ` object. + + This method differs from :meth:`object.__repr__` in that there is no + expectation that :meth:`__str__` return a valid Python expression: a more + convenient or concise representation can be used. + + The default implementation defined by the built-in type :class:`object` + calls :meth:`object.__repr__`. + + .. XXX what about subclasses of string? + + +.. method:: object.__bytes__(self) + + .. index:: builtin: bytes + + Called by :ref:`bytes ` to compute a byte-string representation + of an object. This should return a :class:`bytes` object. + + .. index:: + single: string; __format__() (object method) + pair: string; conversion + builtin: print + + +.. method:: object.__format__(self, format_spec) + + Called by the :func:`format` built-in function, + and by extension, evaluation of :ref:`formatted string literals + ` and the :meth:`str.format` method, to produce a "formatted" + string representation of an object. The *format_spec* argument is + a string that contains a description of the formatting options desired. + The interpretation of the *format_spec* argument is up to the type + 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. + + .. versionchanged:: 3.4 + The __format__ method of ``object`` itself raises a :exc:`TypeError` + if passed any non-empty string. + + .. versionchanged:: 3.7 + ``object.__format__(x, '')`` is now equivalent to ``str(x)`` rather + than ``format(str(x), '')``. + + +.. _richcmpfuncs: +.. method:: object.__lt__(self, other) + object.__le__(self, other) + object.__eq__(self, other) + object.__ne__(self, other) + object.__gt__(self, other) + object.__ge__(self, other) + + .. index:: + single: comparisons + + These are the so-called "rich comparison" methods. The correspondence between + operator symbols and method names is as follows: ``xy`` calls ``x.__gt__(y)``, and ``x>=y`` calls + ``x.__ge__(y)``. + + A rich comparison method may return the singleton ``NotImplemented`` if it does + not implement the operation for a given pair of arguments. By convention, + ``False`` and ``True`` are returned for a successful comparison. However, these + methods can return any value, so if the comparison operator is used in a Boolean + context (e.g., in the condition of an ``if`` statement), Python will call + :func:`bool` on the value to determine if the result is true or false. + + By default, :meth:`__ne__` delegates to :meth:`__eq__` and + inverts the result unless it is ``NotImplemented``. There are no other + implied relationships among the comparison operators, for example, + the truth of ``(x.__hash__``. + + If a class that does not override :meth:`__eq__` wishes to suppress hash + support, it should include ``__hash__ = None`` in the class definition. + A class which defines its own :meth:`__hash__` that explicitly raises + a :exc:`TypeError` would be incorrectly identified as hashable by + an ``isinstance(obj, collections.abc.Hashable)`` call. + + + .. note:: + + By default, the :meth:`__hash__` values of str and bytes objects are + "salted" with an unpredictable random value. Although they + remain constant within an individual Python process, they are not + predictable between repeated invocations of Python. + + This is intended to provide protection against a denial-of-service caused + by carefully-chosen inputs that exploit the worst case performance of a + dict insertion, O(n^2) complexity. See + http://www.ocert.org/advisories/ocert-2011-003.html for details. + + Changing hash values affects the iteration order of sets. + Python has never made guarantees about this ordering + (and it typically varies between 32-bit and 64-bit builds). + + See also :envvar:`PYTHONHASHSEED`. + + .. versionchanged:: 3.3 + Hash randomization is enabled by default. + + +.. method:: object.__bool__(self) + + .. index:: single: __len__() (mapping object method) + + Called to implement truth value testing and the built-in operation + ``bool()``; should return ``False`` or ``True``. When this method is not + defined, :meth:`__len__` is called, if it is defined, and the object is + considered true if its result is nonzero. If a class defines neither + :meth:`__len__` nor :meth:`__bool__`, all its instances are considered + true. + + +.. _attribute-access: + +Customizing attribute access +---------------------------- + +The following methods can be defined to customize the meaning of attribute +access (use of, assignment to, or deletion of ``x.name``) for class instances. + +.. XXX explain how descriptors interfere here! + + +.. method:: object.__getattr__(self, name) + + Called when the default attribute access fails with an :exc:`AttributeError` + (either :meth:`__getattribute__` raises an :exc:`AttributeError` because + *name* is not an instance attribute or an attribute in the class tree + for ``self``; or :meth:`__get__` of a *name* property raises + :exc:`AttributeError`). This method should either return the (computed) + attribute value or raise an :exc:`AttributeError` exception. + + Note that if the attribute is found through the normal mechanism, + :meth:`__getattr__` is not called. (This is an intentional asymmetry between + :meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency + reasons and because otherwise :meth:`__getattr__` would have no way to access + other attributes of the instance. Note that at least for instance variables, + you can fake total control by not inserting any values in the instance attribute + dictionary (but instead inserting them in another object). See the + :meth:`__getattribute__` method below for a way to actually get total control + over attribute access. + + +.. method:: object.__getattribute__(self, name) + + Called unconditionally to implement attribute accesses for instances of the + class. If the class also defines :meth:`__getattr__`, the latter will not be + called unless :meth:`__getattribute__` either calls it explicitly or raises an + :exc:`AttributeError`. This method should return the (computed) attribute value + or raise an :exc:`AttributeError` exception. In order to avoid infinite + recursion in this method, its implementation should always call the base class + method with the same name to access any attributes it needs, for example, + ``object.__getattribute__(self, name)``. + + .. note:: + + This method may still be bypassed when looking up special methods as the + result of implicit invocation via language syntax or built-in functions. + See :ref:`special-lookup`. + + +.. method:: object.__setattr__(self, name, value) + + Called when an attribute assignment is attempted. This is called instead of + the normal mechanism (i.e. store the value in the instance dictionary). + *name* is the attribute name, *value* is the value to be assigned to it. + + If :meth:`__setattr__` wants to assign to an instance attribute, it should + call the base class method with the same name, for example, + ``object.__setattr__(self, name, value)``. + + +.. method:: object.__delattr__(self, name) + + Like :meth:`__setattr__` but for attribute deletion instead of assignment. This + should only be implemented if ``del obj.name`` is meaningful for the object. + + +.. method:: object.__dir__(self) + + Called when :func:`dir` is called on the object. A sequence must be + returned. :func:`dir` converts the returned sequence to a list and sorts it. + + +Customizing module attribute access +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. index:: + single: __getattr__ (module attribute) + single: __dir__ (module attribute) + single: __class__ (module attribute) + +Special names ``__getattr__`` and ``__dir__`` can be also used to customize +access to module attributes. The ``__getattr__`` function at the module level +should accept one argument which is the name of an attribute and return the +computed value or raise an :exc:`AttributeError`. If an attribute is +not found on a module object through the normal lookup, i.e. +:meth:`object.__getattribute__`, then ``__getattr__`` is searched in +the module ``__dict__`` before raising an :exc:`AttributeError`. If found, +it is called with the attribute name and the result is returned. + +The ``__dir__`` function should accept no arguments, and return a sequence of +strings that represents the names accessible on module. If present, this +function overrides the standard :func:`dir` search on a module. + +For a more fine grained customization of the module behavior (setting +attributes, properties, etc.), one can set the ``__class__`` attribute of +a module object to a subclass of :class:`types.ModuleType`. For example:: + + import sys + from types import ModuleType + + class VerboseModule(ModuleType): + def __repr__(self): + return f'Verbose {self.__name__}' + + def __setattr__(self, attr, value): + print(f'Setting {attr}...') + super().__setattr__(attr, value) + + sys.modules[__name__].__class__ = VerboseModule + +.. note:: + Defining module ``__getattr__`` and setting module ``__class__`` only + affect lookups made using the attribute access syntax -- directly accessing + the module globals (whether by code within the module, or via a reference + to the module's globals dictionary) is unaffected. + +.. versionchanged:: 3.5 + ``__class__`` module attribute is now writable. + +.. versionadded:: 3.7 + ``__getattr__`` and ``__dir__`` module attributes. + +.. seealso:: + + :pep:`562` - Module __getattr__ and __dir__ + Describes the ``__getattr__`` and ``__dir__`` functions on modules. + + +.. _descriptors: + +Implementing Descriptors +^^^^^^^^^^^^^^^^^^^^^^^^ + +The following methods only apply when an instance of the class containing the +method (a so-called *descriptor* class) appears in an *owner* class (the +descriptor must be in either the owner's class dictionary or in the class +dictionary for one of its parents). In the examples below, "the attribute" +refers to the attribute whose name is the key of the property in the owner +class' :attr:`~object.__dict__`. + + +.. method:: object.__get__(self, instance, owner=None) + + Called to get the attribute of the owner class (class attribute access) or + of an instance of that class (instance attribute access). The optional + *owner* argument is the owner class, while *instance* is the instance that + the attribute was accessed through, or ``None`` when the attribute is + accessed through the *owner*. + + This method should return the computed attribute value or raise an + :exc:`AttributeError` exception. + + :PEP:`252` specifies that :meth:`__get__` is callable with one or two + arguments. Python's own built-in descriptors support this specification; + however, it is likely that some third-party tools have descriptors + that require both arguments. Python's own :meth:`__getattribute__` + implementation always passes in both arguments whether they are required + or not. + +.. method:: object.__set__(self, instance, value) + + Called to set the attribute on an instance *instance* of the owner class to a + new value, *value*. + + Note, adding :meth:`__set__` or :meth:`__delete__` changes the kind of + descriptor to a "data descriptor". See :ref:`descriptor-invocation` for + more details. + +.. method:: object.__delete__(self, instance) + + Called to delete the attribute on an instance *instance* of the owner class. + + +.. method:: object.__set_name__(self, owner, name) + + Called at the time the owning class *owner* is created. The + descriptor has been assigned to *name*. + + .. note:: + + :meth:`__set_name__` is only called implicitly as part of the + :class:`type` constructor, so it will need to be called explicitly with + the appropriate parameters when a descriptor is added to a class after + initial creation:: + + class A: + pass + descr = custom_descriptor() + A.attr = descr + descr.__set_name__(A, 'attr') + + See :ref:`class-object-creation` for more details. + + .. versionadded:: 3.6 + +The attribute :attr:`__objclass__` is interpreted by the :mod:`inspect` module +as specifying the class where this object was defined (setting this +appropriately can assist in runtime introspection of dynamic class attributes). +For callables, it may indicate that an instance of the given type (or a +subclass) is expected or required as the first positional argument (for example, +CPython sets this attribute for unbound methods that are implemented in C). + + +.. _descriptor-invocation: + +Invoking Descriptors +^^^^^^^^^^^^^^^^^^^^ + +In general, a descriptor is an object attribute with "binding behavior", one +whose attribute access has been overridden by methods in the descriptor +protocol: :meth:`__get__`, :meth:`__set__`, and :meth:`__delete__`. If any of +those methods are defined for an object, it is said to be a descriptor. + +The default behavior for attribute access is to get, set, or delete the +attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain +starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and +continuing through the base classes of ``type(a)`` excluding metaclasses. + +However, if the looked-up value is an object defining one of the descriptor +methods, then Python may override the default behavior and invoke the descriptor +method instead. Where this occurs in the precedence chain depends on which +descriptor methods were defined and how they were called. + +The starting point for descriptor invocation is a binding, ``a.x``. How the +arguments are assembled depends on ``a``: + +Direct Call + The simplest and least common call is when user code directly invokes a + descriptor method: ``x.__get__(a)``. + +Instance Binding + If binding to an object instance, ``a.x`` is transformed into the call: + ``type(a).__dict__['x'].__get__(a, type(a))``. + +Class Binding + If binding to a class, ``A.x`` is transformed into the call: + ``A.__dict__['x'].__get__(None, A)``. + +Super Binding + If ``a`` is an instance of :class:`super`, then the binding ``super(B, obj).m()`` + searches ``obj.__class__.__mro__`` for the base class ``A`` + immediately preceding ``B`` and then invokes the descriptor with the call: + ``A.__dict__['m'].__get__(obj, obj.__class__)``. + +For instance bindings, the precedence of descriptor invocation depends on the +which descriptor methods are defined. A descriptor can define any combination +of :meth:`__get__`, :meth:`__set__` and :meth:`__delete__`. If it does not +define :meth:`__get__`, then accessing the attribute will return the descriptor +object itself unless there is a value in the object's instance dictionary. If +the descriptor defines :meth:`__set__` and/or :meth:`__delete__`, it is a data +descriptor; if it defines neither, it is a non-data descriptor. Normally, data +descriptors define both :meth:`__get__` and :meth:`__set__`, while non-data +descriptors have just the :meth:`__get__` method. Data descriptors with +:meth:`__get__` and :meth:`__set__` (and/or :meth:`__delete__`) defined always override a redefinition in an +instance dictionary. In contrast, non-data descriptors can be overridden by +instances. + +Python methods (including :func:`staticmethod` and :func:`classmethod`) are +implemented as non-data descriptors. Accordingly, instances can redefine and +override methods. This allows individual instances to acquire behaviors that +differ from other instances of the same class. + +The :func:`property` function is implemented as a data descriptor. Accordingly, +instances cannot override the behavior of a property. + + +.. _slots: + +__slots__ +^^^^^^^^^ + +*__slots__* allow us to explicitly declare data members (like +properties) and deny the creation of *__dict__* and *__weakref__* +(unless explicitly declared in *__slots__* or available in a parent.) + +The space saved over using *__dict__* can be significant. +Attribute lookup speed can be significantly improved as well. + +.. data:: object.__slots__ + + This class variable can be assigned a string, iterable, or sequence of + strings with variable names used by instances. *__slots__* reserves space + for the declared variables and prevents the automatic creation of *__dict__* + and *__weakref__* for each instance. + + +Notes on using *__slots__* +"""""""""""""""""""""""""" + +* When inheriting from a class without *__slots__*, the *__dict__* and + *__weakref__* attribute of the instances will always be accessible. + +* Without a *__dict__* variable, instances cannot be assigned new variables not + listed in the *__slots__* definition. Attempts to assign to an unlisted + variable name raises :exc:`AttributeError`. If dynamic assignment of new + variables is desired, then add ``'__dict__'`` to the sequence of strings in + the *__slots__* declaration. + +* Without a *__weakref__* variable for each instance, classes defining + *__slots__* do not support weak references to its instances. If weak reference + support is needed, then add ``'__weakref__'`` to the sequence of strings in the + *__slots__* declaration. + +* *__slots__* are implemented at the class level by creating descriptors + (:ref:`descriptors`) for each variable name. As a result, class attributes + cannot be used to set default values for instance variables defined by + *__slots__*; otherwise, the class attribute would overwrite the descriptor + assignment. + +* The action of a *__slots__* declaration is not limited to the class + where it is defined. *__slots__* declared in parents are available in + child classes. However, child subclasses will get a *__dict__* and + *__weakref__* unless they also define *__slots__* (which should only + contain names of any *additional* slots). + +* If a class defines a slot also defined in a base class, the instance variable + defined by the base class slot is inaccessible (except by retrieving its + descriptor directly from the base class). This renders the meaning of the + program undefined. In the future, a check may be added to prevent this. + +* Nonempty *__slots__* does not work for classes derived from "variable-length" + built-in types such as :class:`int`, :class:`bytes` and :class:`tuple`. + +* Any non-string iterable may be assigned to *__slots__*. Mappings may also be + used; however, in the future, special meaning may be assigned to the values + corresponding to each key. + +* *__class__* assignment works only if both classes have the same *__slots__*. + +* Multiple inheritance with multiple slotted parent classes can be used, + but only one parent is allowed to have attributes created by slots + (the other bases must have empty slot layouts) - violations raise + :exc:`TypeError`. + +* If an iterator is used for *__slots__* then a descriptor is created for each + of the iterator's values. However, the *__slots__* attribute will be an empty + iterator. + +.. _class-customization: + +Customizing class creation +-------------------------- + +Whenever a class inherits from another class, *__init_subclass__* is +called on that class. This way, it is possible to write classes which +change the behavior of subclasses. This is closely related to class +decorators, but where class decorators only affect the specific class they're +applied to, ``__init_subclass__`` solely applies to future subclasses of the +class defining the method. + +.. classmethod:: object.__init_subclass__(cls) + + This method is called whenever the containing class is subclassed. + *cls* is then the new subclass. If defined as a normal instance method, + this method is implicitly converted to a class method. + + Keyword arguments which are given to a new class are passed to + the parent's class ``__init_subclass__``. For compatibility with + other classes using ``__init_subclass__``, one should take out the + needed keyword arguments and pass the others over to the base + class, as in:: + + class Philosopher: + def __init_subclass__(cls, /, default_name, **kwargs): + super().__init_subclass__(**kwargs) + cls.default_name = default_name + + class AustralianPhilosopher(Philosopher, default_name="Bruce"): + pass + + The default implementation ``object.__init_subclass__`` does + nothing, but raises an error if it is called with any arguments. + + .. note:: + + The metaclass hint ``metaclass`` is consumed by the rest of the type + machinery, and is never passed to ``__init_subclass__`` implementations. + The actual metaclass (rather than the explicit hint) can be accessed as + ``type(cls)``. + + .. versionadded:: 3.6 + + +.. _metaclasses: + +Metaclasses +^^^^^^^^^^^ + +.. index:: + single: metaclass + builtin: type + single: = (equals); class definition + +By default, classes are constructed using :func:`type`. The class body is +executed in a new namespace and the class name is bound locally to the +result of ``type(name, bases, namespace)``. + +The class creation process can be customized by passing the ``metaclass`` +keyword argument in the class definition line, or by inheriting from an +existing class that included such an argument. In the following example, +both ``MyClass`` and ``MySubclass`` are instances of ``Meta``:: + + class Meta(type): + pass + + class MyClass(metaclass=Meta): + pass + + class MySubclass(MyClass): + pass + +Any other keyword arguments that are specified in the class definition are +passed through to all metaclass operations described below. + +When a class definition is executed, the following steps occur: + +* MRO entries are resolved; +* the appropriate metaclass is determined; +* the class namespace is prepared; +* the class body is executed; +* the class object is created. + + +Resolving MRO entries +^^^^^^^^^^^^^^^^^^^^^ + +If a base that appears in class definition is not an instance of :class:`type`, +then an ``__mro_entries__`` method is searched on it. If found, it is called +with the original bases tuple. This method must return a tuple of classes that +will be used instead of this base. The tuple may be empty, in such case +the original base is ignored. + +.. seealso:: + + :pep:`560` - Core support for typing module and generic types + + +Determining the appropriate metaclass +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. index:: + single: metaclass hint + +The appropriate metaclass for a class definition is determined as follows: + +* if no bases and no explicit metaclass are given, then :func:`type` is used; +* if an explicit metaclass is given and it is *not* an instance of + :func:`type`, then it is used directly as the metaclass; +* if an instance of :func:`type` is given as the explicit metaclass, or + bases are defined, then the most derived metaclass is used. + +The most derived metaclass is selected from the explicitly specified +metaclass (if any) and the metaclasses (i.e. ``type(cls)``) of all specified +base classes. The most derived metaclass is one which is a subtype of *all* +of these candidate metaclasses. If none of the candidate metaclasses meets +that criterion, then the class definition will fail with ``TypeError``. + + +.. _prepare: + +Preparing the class namespace +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. index:: + single: __prepare__ (metaclass method) + +Once the appropriate metaclass has been identified, then the class namespace +is prepared. If the metaclass has a ``__prepare__`` attribute, it is called +as ``namespace = metaclass.__prepare__(name, bases, **kwds)`` (where the +additional keyword arguments, if any, come from the class definition). The +``__prepare__`` method should be implemented as a :func:`classmethod`. The +namespace returned by ``__prepare__`` is passed in to ``__new__``, but when +the final class object is created the namespace is copied into a new ``dict``. + +If the metaclass has no ``__prepare__`` attribute, then the class namespace +is initialised as an empty ordered mapping. + +.. seealso:: + + :pep:`3115` - Metaclasses in Python 3000 + Introduced the ``__prepare__`` namespace hook + + +Executing the class body +^^^^^^^^^^^^^^^^^^^^^^^^ + +.. index:: + single: class; body + +The class body is executed (approximately) as +``exec(body, globals(), namespace)``. The key difference from a normal +call to :func:`exec` is that lexical scoping allows the class body (including +any methods) to reference names from the current and outer scopes when the +class definition occurs inside a function. + +However, even when the class definition occurs inside the function, methods +defined inside the class still cannot see names defined at the class scope. +Class variables must be accessed through the first parameter of instance or +class methods, or through the implicit lexically scoped ``__class__`` reference +described in the next section. + +.. _class-object-creation: + +Creating the class object +^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. index:: + single: __class__ (method cell) + single: __classcell__ (class namespace entry) + + +Once the class namespace has been populated by executing the class body, +the class object is created by calling +``metaclass(name, bases, namespace, **kwds)`` (the additional keywords +passed here are the same as those passed to ``__prepare__``). + +This class object is the one that will be referenced by the zero-argument +form of :func:`super`. ``__class__`` is an implicit closure reference +created by the compiler if any methods in a class body refer to either +``__class__`` or ``super``. This allows the zero argument form of +:func:`super` to correctly identify the class being defined based on +lexical scoping, while the class or instance that was used to make the +current call is identified based on the first argument passed to the method. + +.. impl-detail:: + + In CPython 3.6 and later, the ``__class__`` cell is passed to the metaclass + as a ``__classcell__`` entry in the class namespace. If present, this must + be propagated up to the ``type.__new__`` call in order for the class to be + initialised correctly. + Failing to do so will result in a :exc:`RuntimeError` in Python 3.8. + +When using the default metaclass :class:`type`, or any metaclass that ultimately +calls ``type.__new__``, the following additional customisation steps are +invoked after creating the class object: + +* first, ``type.__new__`` collects all of the descriptors in the class + namespace that define a :meth:`~object.__set_name__` method; +* second, all of these ``__set_name__`` methods are called with the class + being defined and the assigned name of that particular descriptor; +* finally, the :meth:`~object.__init_subclass__` hook is called on the + immediate parent of the new class in its method resolution order. + +After the class object is created, it is passed to the class decorators +included in the class definition (if any) and the resulting object is bound +in the local namespace as the defined class. + +When a new class is created by ``type.__new__``, the object provided as the +namespace parameter is copied to a new ordered mapping and the original +object is discarded. The new copy is wrapped in a read-only proxy, which +becomes the :attr:`~object.__dict__` attribute of the class object. + +.. seealso:: + + :pep:`3135` - New super + Describes the implicit ``__class__`` closure reference + + +Uses for metaclasses +^^^^^^^^^^^^^^^^^^^^ + +The potential uses for metaclasses are boundless. Some ideas that have been +explored include enum, logging, interface checking, automatic delegation, +automatic property creation, proxies, frameworks, and automatic resource +locking/synchronization. + + +Customizing instance and subclass checks +---------------------------------------- + +The following methods are used to override the default behavior of the +:func:`isinstance` and :func:`issubclass` built-in functions. + +In particular, the metaclass :class:`abc.ABCMeta` implements these methods in +order to allow the addition of Abstract Base Classes (ABCs) as "virtual base +classes" to any class or type (including built-in types), including other +ABCs. + +.. method:: class.__instancecheck__(self, instance) + + Return true if *instance* should be considered a (direct or indirect) + instance of *class*. If defined, called to implement ``isinstance(instance, + class)``. + + +.. method:: class.__subclasscheck__(self, subclass) + + Return true if *subclass* should be considered a (direct or indirect) + subclass of *class*. If defined, called to implement ``issubclass(subclass, + class)``. + + +Note that these methods are looked up on the type (metaclass) of a class. They +cannot be defined as class methods in the actual class. This is consistent with +the lookup of special methods that are called on instances, only in this +case the instance is itself a class. + +.. seealso:: + + :pep:`3119` - Introducing Abstract Base Classes + Includes the specification for customizing :func:`isinstance` and + :func:`issubclass` behavior through :meth:`~class.__instancecheck__` and + :meth:`~class.__subclasscheck__`, with motivation for this functionality + in the context of adding Abstract Base Classes (see the :mod:`abc` + module) to the language. + + +Emulating generic types +----------------------- + +One can implement the generic class syntax as specified by :pep:`484` +(for example ``List[int]``) by defining a special method: + +.. classmethod:: object.__class_getitem__(cls, key) + + Return an object representing the specialization of a generic class + by type arguments found in *key*. + +This method is looked up on the class object itself, and when defined in +the class body, this method is implicitly a class method. Note, this +mechanism is primarily reserved for use with static type hints, other usage +is discouraged. + +.. seealso:: + + :pep:`560` - Core support for typing module and generic types + + +.. _callable-types: + +Emulating callable objects +-------------------------- + + +.. method:: object.__call__(self[, args...]) + + .. index:: pair: call; instance + + Called when the instance is "called" as a function; if this method is defined, + ``x(arg1, arg2, ...)`` is a shorthand for ``x.__call__(arg1, arg2, ...)``. + + +.. _sequence-types: + +Emulating container types +------------------------- + +The following methods can be defined to implement container objects. Containers +usually are sequences (such as lists or tuples) or mappings (like dictionaries), +but can represent other containers as well. The first set of methods is used +either to emulate a sequence or to emulate a mapping; the difference is that for +a sequence, the allowable keys should be the integers *k* for which ``0 <= k < +N`` where *N* is the length of the sequence, or slice objects, which define a +range of items. It is also recommended that mappings provide the methods +:meth:`keys`, :meth:`values`, :meth:`items`, :meth:`get`, :meth:`clear`, +:meth:`setdefault`, :meth:`pop`, :meth:`popitem`, :meth:`!copy`, and +:meth:`update` behaving similar to those for Python's standard dictionary +objects. The :mod:`collections.abc` module provides a +:class:`~collections.abc.MutableMapping` +abstract base class to help create those methods from a base set of +:meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__`, and :meth:`keys`. +Mutable sequences should provide methods :meth:`append`, :meth:`count`, +:meth:`index`, :meth:`extend`, :meth:`insert`, :meth:`pop`, :meth:`remove`, +:meth:`reverse` and :meth:`sort`, like Python standard list objects. Finally, +sequence types should implement addition (meaning concatenation) and +multiplication (meaning repetition) by defining the methods :meth:`__add__`, +:meth:`__radd__`, :meth:`__iadd__`, :meth:`__mul__`, :meth:`__rmul__` and +:meth:`__imul__` described below; they should not define other numerical +operators. It is recommended that both mappings and sequences implement the +:meth:`__contains__` method to allow efficient use of the ``in`` operator; for +mappings, ``in`` should search the mapping's keys; for sequences, it should +search through the values. It is further recommended that both mappings and +sequences implement the :meth:`__iter__` method to allow efficient iteration +through the container; for mappings, :meth:`__iter__` should iterate +through the object's keys; for sequences, it should iterate through the values. + +.. method:: object.__len__(self) + + .. index:: + builtin: len + single: __bool__() (object method) + + Called to implement the built-in function :func:`len`. Should return the length + of the object, an integer ``>=`` 0. Also, an object that doesn't define a + :meth:`__bool__` method and whose :meth:`__len__` method returns zero is + considered to be false in a Boolean context. + + .. impl-detail:: + + In CPython, the length is required to be at most :attr:`sys.maxsize`. + If the length is larger than :attr:`!sys.maxsize` some features (such as + :func:`len`) may raise :exc:`OverflowError`. To prevent raising + :exc:`!OverflowError` by truth value testing, an object must define a + :meth:`__bool__` method. + + +.. method:: object.__length_hint__(self) + + Called to implement :func:`operator.length_hint`. Should return an estimated + length for the object (which may be greater or less than the actual length). + The length must be an integer ``>=`` 0. The return value may also be + :const:`NotImplemented`, which is treated the same as if the + ``__length_hint__`` method didn't exist at all. This method is purely an + optimization and is never required for correctness. + + .. versionadded:: 3.4 + + +.. index:: object: slice + +.. note:: + + Slicing is done exclusively with the following three methods. A call like :: + + a[1:2] = b + + is translated to :: + + a[slice(1, 2, None)] = b + + and so forth. Missing slice items are always filled in with ``None``. + + +.. method:: object.__getitem__(self, key) + + Called to implement evaluation of ``self[key]``. For sequence types, the + accepted keys should be integers and slice objects. Note that the special + interpretation of negative indexes (if the class wishes to emulate a sequence + type) is up to the :meth:`__getitem__` method. If *key* is of an inappropriate + type, :exc:`TypeError` may be raised; if of a value outside the set of indexes + for the sequence (after any special interpretation of negative values), + :exc:`IndexError` should be raised. For mapping types, if *key* is missing (not + in the container), :exc:`KeyError` should be raised. + + .. note:: + + :keyword:`for` loops expect that an :exc:`IndexError` will be raised for illegal + indexes to allow proper detection of the end of the sequence. + + +.. method:: object.__setitem__(self, key, value) + + Called to implement assignment to ``self[key]``. Same note as for + :meth:`__getitem__`. This should only be implemented for mappings if the + objects support changes to the values for keys, or if new keys can be added, or + for sequences if elements can be replaced. The same exceptions should be raised + for improper *key* values as for the :meth:`__getitem__` method. + + +.. method:: object.__delitem__(self, key) + + Called to implement deletion of ``self[key]``. Same note as for + :meth:`__getitem__`. This should only be implemented for mappings if the + objects support removal of keys, or for sequences if elements can be removed + from the sequence. The same exceptions should be raised for improper *key* + values as for the :meth:`__getitem__` method. + + +.. method:: object.__missing__(self, key) + + Called by :class:`dict`\ .\ :meth:`__getitem__` to implement ``self[key]`` for dict subclasses + when key is not in the dictionary. + + +.. method:: object.__iter__(self) + + This method is called when an iterator is required for a container. This method + should return a new iterator object that can iterate over all the objects in the + container. For mappings, it should iterate over the keys of the container. + + Iterator objects also need to implement this method; they are required to return + themselves. For more information on iterator objects, see :ref:`typeiter`. + + +.. method:: object.__reversed__(self) + + Called (if present) by the :func:`reversed` built-in to implement + reverse iteration. It should return a new iterator object that iterates + over all the objects in the container in reverse order. + + If the :meth:`__reversed__` method is not provided, the :func:`reversed` + built-in will fall back to using the sequence protocol (:meth:`__len__` and + :meth:`__getitem__`). Objects that support the sequence protocol should + only provide :meth:`__reversed__` if they can provide an implementation + that is more efficient than the one provided by :func:`reversed`. + + +The membership test operators (:keyword:`in` and :keyword:`not in`) are normally +implemented as an iteration through a container. However, container objects can +supply the following special method with a more efficient implementation, which +also does not require the object be iterable. + +.. method:: object.__contains__(self, item) + + Called to implement membership test operators. Should return true if *item* + is in *self*, false otherwise. For mapping objects, this should consider the + keys of the mapping rather than the values or the key-item pairs. + + For objects that don't define :meth:`__contains__`, the membership test first + tries iteration via :meth:`__iter__`, then the old sequence iteration + protocol via :meth:`__getitem__`, see :ref:`this section in the language + reference `. + + +.. _numeric-types: + +Emulating numeric types +----------------------- + +The following methods can be defined to emulate numeric objects. Methods +corresponding to operations that are not supported by the particular kind of +number implemented (e.g., bitwise operations for non-integral numbers) should be +left undefined. + + +.. method:: object.__add__(self, other) + object.__sub__(self, other) + object.__mul__(self, other) + object.__matmul__(self, other) + object.__truediv__(self, other) + object.__floordiv__(self, other) + object.__mod__(self, other) + object.__divmod__(self, other) + object.__pow__(self, other[, modulo]) + object.__lshift__(self, other) + object.__rshift__(self, other) + object.__and__(self, other) + object.__xor__(self, other) + object.__or__(self, other) + + .. index:: + builtin: divmod + builtin: pow + builtin: pow + + These methods are called to implement the binary arithmetic operations + (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, + :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For instance, to + evaluate the expression ``x + y``, where *x* is an instance of a class that + has an :meth:`__add__` method, ``x.__add__(y)`` is called. The + :meth:`__divmod__` method should be the equivalent to using + :meth:`__floordiv__` and :meth:`__mod__`; it should not be related to + :meth:`__truediv__`. Note that :meth:`__pow__` should be defined to accept + an optional third argument if the ternary version of the built-in :func:`pow` + function is to be supported. + + If one of those methods does not support the operation with the supplied + arguments, it should return ``NotImplemented``. + + +.. method:: object.__radd__(self, other) + object.__rsub__(self, other) + object.__rmul__(self, other) + object.__rmatmul__(self, other) + object.__rtruediv__(self, other) + object.__rfloordiv__(self, other) + object.__rmod__(self, other) + object.__rdivmod__(self, other) + object.__rpow__(self, other[, modulo]) + object.__rlshift__(self, other) + object.__rrshift__(self, other) + object.__rand__(self, other) + object.__rxor__(self, other) + object.__ror__(self, other) + + .. index:: + builtin: divmod + builtin: pow + + These methods are called to implement the binary arithmetic operations + (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, + :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with reflected + (swapped) operands. These functions are only called if the left operand does + not support the corresponding operation [#]_ and the operands are of different + types. [#]_ For instance, to evaluate the expression ``x - y``, where *y* is + an instance of a class that has an :meth:`__rsub__` method, ``y.__rsub__(x)`` + is called if ``x.__sub__(y)`` returns *NotImplemented*. + + .. index:: builtin: pow + + Note that ternary :func:`pow` will not try calling :meth:`__rpow__` (the + coercion rules would become too complicated). + + .. note:: + + If the right operand's type is a subclass of the left operand's type and that + subclass provides the reflected method for the operation, this method will be + called before the left operand's non-reflected method. This behavior allows + subclasses to override their ancestors' operations. + + +.. method:: object.__iadd__(self, other) + object.__isub__(self, other) + object.__imul__(self, other) + object.__imatmul__(self, other) + object.__itruediv__(self, other) + object.__ifloordiv__(self, other) + object.__imod__(self, other) + object.__ipow__(self, other[, modulo]) + object.__ilshift__(self, other) + object.__irshift__(self, other) + object.__iand__(self, other) + object.__ixor__(self, other) + object.__ior__(self, other) + + These methods are called to implement the augmented arithmetic assignments + (``+=``, ``-=``, ``*=``, ``@=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, + ``>>=``, ``&=``, ``^=``, ``|=``). These methods should attempt to do the + operation in-place (modifying *self*) and return the result (which could be, + but does not have to be, *self*). If a specific method is not defined, the + augmented assignment falls back to the normal methods. For instance, if *x* + is an instance of a class with an :meth:`__iadd__` method, ``x += y`` is + equivalent to ``x = x.__iadd__(y)`` . Otherwise, ``x.__add__(y)`` and + ``y.__radd__(x)`` are considered, as with the evaluation of ``x + y``. In + certain situations, augmented assignment can result in unexpected errors (see + :ref:`faq-augmented-assignment-tuple-error`), but this behavior is in fact + part of the data model. + + +.. method:: object.__neg__(self) + object.__pos__(self) + object.__abs__(self) + object.__invert__(self) + + .. index:: builtin: abs + + Called to implement the unary arithmetic operations (``-``, ``+``, :func:`abs` + and ``~``). + + +.. method:: object.__complex__(self) + object.__int__(self) + object.__float__(self) + + .. index:: + builtin: complex + builtin: int + builtin: float + + Called to implement the built-in functions :func:`complex`, + :func:`int` and :func:`float`. Should return a value + of the appropriate type. + + +.. method:: object.__index__(self) + + Called to implement :func:`operator.index`, and whenever Python needs to + losslessly convert the numeric object to an integer object (such as in + slicing, or in the built-in :func:`bin`, :func:`hex` and :func:`oct` + functions). Presence of this method indicates that the numeric object is + an integer type. Must return an integer. + + If :meth:`__int__`, :meth:`__float__` and :meth:`__complex__` are not + defined then corresponding built-in functions :func:`int`, :func:`float` + and :func:`complex` fall back to :meth:`__index__`. + + +.. method:: object.__round__(self, [,ndigits]) + object.__trunc__(self) + object.__floor__(self) + object.__ceil__(self) + + .. index:: builtin: round + + Called to implement the built-in function :func:`round` and :mod:`math` + functions :func:`~math.trunc`, :func:`~math.floor` and :func:`~math.ceil`. + Unless *ndigits* is passed to :meth:`!__round__` all these methods should + return the value of the object truncated to an :class:`~numbers.Integral` + (typically an :class:`int`). + + If :meth:`__int__` is not defined then the built-in function :func:`int` + falls back to :meth:`__trunc__`. + + +.. _context-managers: + +With Statement Context Managers +------------------------------- + +A :dfn:`context manager` is an object that defines the runtime context to be +established when executing a :keyword:`with` statement. The context manager +handles the entry into, and the exit from, the desired runtime context for the +execution of the block of code. Context managers are normally invoked using the +:keyword:`!with` statement (described in section :ref:`with`), but can also be +used by directly invoking their methods. + +.. index:: + statement: with + single: context manager + +Typical uses of context managers include saving and restoring various kinds of +global state, locking and unlocking resources, closing opened files, etc. + +For more information on context managers, see :ref:`typecontextmanager`. + + +.. method:: object.__enter__(self) + + Enter the runtime context related to this object. The :keyword:`with` statement + will bind this method's return value to the target(s) specified in the + :keyword:`!as` clause of the statement, if any. + + +.. method:: object.__exit__(self, exc_type, exc_value, traceback) + + Exit the runtime context related to this object. The parameters describe the + exception that caused the context to be exited. If the context was exited + without an exception, all three arguments will be :const:`None`. + + If an exception is supplied, and the method wishes to suppress the exception + (i.e., prevent it from being propagated), it should return a true value. + Otherwise, the exception will be processed normally upon exit from this method. + + Note that :meth:`__exit__` methods should not reraise the passed-in exception; + this is the caller's responsibility. + + +.. seealso:: + + :pep:`343` - The "with" statement + The specification, background, and examples for the Python :keyword:`with` + statement. + + +.. _special-lookup: + +Special method lookup +--------------------- + +For custom classes, implicit invocations of special methods are only guaranteed +to work correctly if defined on an object's type, not in the object's instance +dictionary. That behaviour is the reason why the following code raises an +exception:: + + >>> class C: + ... pass + ... + >>> c = C() + >>> c.__len__ = lambda: 5 + >>> len(c) + Traceback (most recent call last): + File "", line 1, in + TypeError: object of type 'C' has no len() + +The rationale behind this behaviour lies with a number of special methods such +as :meth:`__hash__` and :meth:`__repr__` that are implemented by all objects, +including type objects. If the implicit lookup of these methods used the +conventional lookup process, they would fail when invoked on the type object +itself:: + + >>> 1 .__hash__() == hash(1) + True + >>> int.__hash__() == hash(int) + Traceback (most recent call last): + File "", line 1, in + TypeError: descriptor '__hash__' of 'int' object needs an argument + +Incorrectly attempting to invoke an unbound method of a class in this way is +sometimes referred to as 'metaclass confusion', and is avoided by bypassing +the instance when looking up special methods:: + + >>> type(1).__hash__(1) == hash(1) + True + >>> type(int).__hash__(int) == hash(int) + True + +In addition to bypassing any instance attributes in the interest of +correctness, implicit special method lookup generally also bypasses the +:meth:`__getattribute__` method even of the object's metaclass:: + + >>> class Meta(type): + ... def __getattribute__(*args): + ... print("Metaclass getattribute invoked") + ... return type.__getattribute__(*args) + ... + >>> class C(object, metaclass=Meta): + ... def __len__(self): + ... return 10 + ... def __getattribute__(*args): + ... print("Class getattribute invoked") + ... return object.__getattribute__(*args) + ... + >>> c = C() + >>> c.__len__() # Explicit lookup via instance + Class getattribute invoked + 10 + >>> type(c).__len__(c) # Explicit lookup via type + Metaclass getattribute invoked + 10 + >>> len(c) # Implicit lookup + 10 + +Bypassing the :meth:`__getattribute__` machinery in this fashion +provides significant scope for speed optimisations within the +interpreter, at the cost of some flexibility in the handling of +special methods (the special method *must* be set on the class +object itself in order to be consistently invoked by the interpreter). + + +.. index:: + single: coroutine + +Coroutines +========== + + +Awaitable Objects +----------------- + +An :term:`awaitable` object generally implements an :meth:`__await__` method. +:term:`Coroutine` objects returned from :keyword:`async def` functions +are awaitable. + +.. note:: + + The :term:`generator iterator` objects returned from generators + decorated with :func:`types.coroutine` or :func:`asyncio.coroutine` + are also awaitable, but they do not implement :meth:`__await__`. + +.. method:: object.__await__(self) + + Must return an :term:`iterator`. Should be used to implement + :term:`awaitable` objects. For instance, :class:`asyncio.Future` implements + this method to be compatible with the :keyword:`await` expression. + +.. versionadded:: 3.5 + +.. seealso:: :pep:`492` for additional information about awaitable objects. + + +.. _coroutine-objects: + +Coroutine Objects +----------------- + +:term:`Coroutine` objects are :term:`awaitable` objects. +A coroutine's execution can be controlled by calling :meth:`__await__` and +iterating over the result. When the coroutine has finished executing and +returns, the iterator raises :exc:`StopIteration`, and the exception's +:attr:`~StopIteration.value` attribute holds the return value. If the +coroutine raises an exception, it is propagated by the iterator. Coroutines +should not directly raise unhandled :exc:`StopIteration` exceptions. + +Coroutines also have the methods listed below, which are analogous to +those of generators (see :ref:`generator-methods`). However, unlike +generators, coroutines do not directly support iteration. + +.. versionchanged:: 3.5.2 + It is a :exc:`RuntimeError` to await on a coroutine more than once. + + +.. method:: coroutine.send(value) + + Starts or resumes execution of the coroutine. If *value* is ``None``, + this is equivalent to advancing the iterator returned by + :meth:`__await__`. If *value* is not ``None``, this method delegates + to the :meth:`~generator.send` method of the iterator that caused + the coroutine to suspend. The result (return value, + :exc:`StopIteration`, or other exception) is the same as when + iterating over the :meth:`__await__` return value, described above. + +.. method:: coroutine.throw(type[, value[, traceback]]) + + Raises the specified exception in the coroutine. This method delegates + to the :meth:`~generator.throw` method of the iterator that caused + the coroutine to suspend, if it has such a method. Otherwise, + the exception is raised at the suspension point. The result + (return value, :exc:`StopIteration`, or other exception) is the same as + when iterating over the :meth:`__await__` return value, described + above. If the exception is not caught in the coroutine, it propagates + back to the caller. + +.. method:: coroutine.close() + + Causes the coroutine to clean itself up and exit. If the coroutine + is suspended, this method first delegates to the :meth:`~generator.close` + method of the iterator that caused the coroutine to suspend, if it + has such a method. Then it raises :exc:`GeneratorExit` at the + suspension point, causing the coroutine to immediately clean itself up. + Finally, the coroutine is marked as having finished executing, even if + it was never started. + + Coroutine objects are automatically closed using the above process when + they are about to be destroyed. + +.. _async-iterators: + +Asynchronous Iterators +---------------------- + +An *asynchronous iterator* can call asynchronous code in +its ``__anext__`` method. + +Asynchronous iterators can be used in an :keyword:`async for` statement. + +.. method:: object.__aiter__(self) + + Must return an *asynchronous iterator* object. + +.. method:: object.__anext__(self) + + Must return an *awaitable* resulting in a next value of the iterator. Should + raise a :exc:`StopAsyncIteration` error when the iteration is over. + +An example of an asynchronous iterable object:: + + class Reader: + async def readline(self): + ... + + def __aiter__(self): + return self + + async def __anext__(self): + val = await self.readline() + if val == b'': + raise StopAsyncIteration + return val + +.. versionadded:: 3.5 + +.. versionchanged:: 3.7 + Prior to Python 3.7, ``__aiter__`` could return an *awaitable* + that would resolve to an + :term:`asynchronous iterator `. + + Starting with Python 3.7, ``__aiter__`` must return an + asynchronous iterator object. Returning anything else + will result in a :exc:`TypeError` error. + + +.. _async-context-managers: + +Asynchronous Context Managers +----------------------------- + +An *asynchronous context manager* is a *context manager* that is able to +suspend execution in its ``__aenter__`` and ``__aexit__`` methods. + +Asynchronous context managers can be used in an :keyword:`async with` statement. + +.. method:: object.__aenter__(self) + + Semantically similar to :meth:`__enter__`, the only + difference being that it must return an *awaitable*. + +.. method:: object.__aexit__(self, exc_type, exc_value, traceback) + + Semantically similar to :meth:`__exit__`, the only + difference being that it must return an *awaitable*. + +An example of an asynchronous context manager class:: + + class AsyncContextManager: + async def __aenter__(self): + await log('entering context') + + async def __aexit__(self, exc_type, exc, tb): + await log('exiting context') + +.. versionadded:: 3.5 + + +.. rubric:: Footnotes + +.. [#] It *is* possible in some cases to change an object's type, under certain + controlled conditions. It generally isn't a good idea though, since it can + lead to some very strange behaviour if it is handled incorrectly. + +.. [#] The :meth:`__hash__`, :meth:`__iter__`, :meth:`__reversed__`, and + :meth:`__contains__` methods have special handling for this; others + will still raise a :exc:`TypeError`, but may do so by relying on + the behavior that ``None`` is not callable. + +.. [#] "Does not support" here means that the class has no such method, or + the method returns ``NotImplemented``. Do not set the method to + ``None`` if you want to force fallback to the right operand's reflected + method—that will instead have the opposite effect of explicitly + *blocking* such fallback. + +.. [#] For operands of the same type, it is assumed that if the non-reflected method + (such as :meth:`__add__`) fails the operation is not supported, which is why the + reflected method is not called. diff --git a/cpython_2/environment/repo/Doc/reference/executionmodel.rst b/cpython_2/environment/repo/Doc/reference/executionmodel.rst new file mode 100644 index 0000000000000000000000000000000000000000..55ac01b6a844dcef91ea7358fbfe9781ee4cc63a --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/executionmodel.rst @@ -0,0 +1,268 @@ + +.. _execmodel: + +*************** +Execution model +*************** + +.. index:: + single: execution model + pair: code; block + +.. _prog_structure: + +Structure of a program +====================== + +.. index:: block + +A Python program is constructed from code blocks. +A :dfn:`block` is a piece of Python program text that is executed as a unit. +The following are blocks: a module, a function body, and a class definition. +Each command typed interactively is a block. A script file (a file given as +standard input to the interpreter or specified as a command line argument to the +interpreter) is a code block. A script command (a command specified on the +interpreter command line with the :option:`-c` option) is a code block. +A module run as a top level script (as module ``__main__``) from the command +line using a :option:`-m` argument is also a code block. The string +argument passed to the built-in functions :func:`eval` and :func:`exec` is a +code block. + +.. index:: pair: execution; frame + +A code block is executed in an :dfn:`execution frame`. A frame contains some +administrative information (used for debugging) and determines where and how +execution continues after the code block's execution has completed. + +.. _naming: + +Naming and binding +================== + +.. index:: + single: namespace + single: scope + +.. _bind_names: + +Binding of names +---------------- + +.. index:: + single: name + pair: binding; name + +:dfn:`Names` refer to objects. Names are introduced by name binding operations. + +.. index:: single: from; import statement + +The following constructs bind names: formal parameters to functions, +:keyword:`import` statements, class and function definitions (these bind the +class or function name in the defining block), and targets that are identifiers +if occurring in an assignment, :keyword:`for` loop header, or after +:keyword:`!as` in a :keyword:`with` statement or :keyword:`except` clause. +The :keyword:`!import` statement +of the form ``from ... import *`` binds all names defined in the imported +module, except those beginning with an underscore. This form may only be used +at the module level. + +A target occurring in a :keyword:`del` statement is also considered bound for +this purpose (though the actual semantics are to unbind the name). + +Each assignment or import statement occurs within a block defined by a class or +function definition or at the module level (the top-level code block). + +.. index:: pair: free; variable + +If a name is bound in a block, it is a local variable of that block, unless +declared as :keyword:`nonlocal` or :keyword:`global`. If a name is bound at +the module level, it is a global variable. (The variables of the module code +block are local and global.) If a variable is used in a code block but not +defined there, it is a :dfn:`free variable`. + +Each occurrence of a name in the program text refers to the :dfn:`binding` of +that name established by the following name resolution rules. + +.. _resolve_names: + +Resolution of names +------------------- + +.. index:: scope + +A :dfn:`scope` defines the visibility of a name within a block. If a local +variable is defined in a block, its scope includes that block. If the +definition occurs in a function block, the scope extends to any blocks contained +within the defining one, unless a contained block introduces a different binding +for the name. + +.. index:: single: environment + +When a name is used in a code block, it is resolved using the nearest enclosing +scope. The set of all such scopes visible to a code block is called the block's +:dfn:`environment`. + +.. index:: + single: NameError (built-in exception) + single: UnboundLocalError + +When a name is not found at all, a :exc:`NameError` exception is raised. +If the current scope is a function scope, and the name refers to a local +variable that has not yet been bound to a value at the point where the name is +used, an :exc:`UnboundLocalError` exception is raised. +:exc:`UnboundLocalError` is a subclass of :exc:`NameError`. + +If a name binding operation occurs anywhere within a code block, all uses of the +name within the block are treated as references to the current block. This can +lead to errors when a name is used within a block before it is bound. This rule +is subtle. Python lacks declarations and allows name binding operations to +occur anywhere within a code block. The local variables of a code block can be +determined by scanning the entire text of the block for name binding operations. + +If the :keyword:`global` statement occurs within a block, all uses of the name +specified in the statement refer to the binding of that name in the top-level +namespace. Names are resolved in the top-level namespace by searching the +global namespace, i.e. the namespace of the module containing the code block, +and the builtins namespace, the namespace of the module :mod:`builtins`. The +global namespace is searched first. If the name is not found there, the +builtins namespace is searched. The :keyword:`!global` statement must precede +all uses of the name. + +The :keyword:`global` statement has the same scope as a name binding operation +in the same block. If the nearest enclosing scope for a free variable contains +a global statement, the free variable is treated as a global. + +.. XXX say more about "nonlocal" semantics here + +The :keyword:`nonlocal` statement causes corresponding names to refer +to previously bound variables in the nearest enclosing function scope. +:exc:`SyntaxError` is raised at compile time if the given name does not +exist in any enclosing function scope. + +.. index:: module: __main__ + +The namespace for a module is automatically created the first time a module is +imported. The main module for a script is always called :mod:`__main__`. + +Class definition blocks and arguments to :func:`exec` and :func:`eval` are +special in the context of name resolution. +A class definition is an executable statement that may use and define names. +These references follow the normal rules for name resolution with an exception +that unbound local variables are looked up in the global namespace. +The namespace of the class definition becomes the attribute dictionary of +the class. The scope of names defined in a class block is limited to the +class block; it does not extend to the code blocks of methods -- this includes +comprehensions and generator expressions since they are implemented using a +function scope. This means that the following will fail:: + + class A: + a = 42 + b = list(a + i for i in range(10)) + +.. _restrict_exec: + +Builtins and restricted execution +--------------------------------- + +.. index:: pair: restricted; execution + +.. impl-detail:: + + Users should not touch ``__builtins__``; it is strictly an implementation + detail. Users wanting to override values in the builtins namespace should + :keyword:`import` the :mod:`builtins` module and modify its + attributes appropriately. + +The builtins namespace associated with the execution of a code block +is actually found by looking up the name ``__builtins__`` in its +global namespace; this should be a dictionary or a module (in the +latter case the module's dictionary is used). By default, when in the +:mod:`__main__` module, ``__builtins__`` is the built-in module +:mod:`builtins`; when in any other module, ``__builtins__`` is an +alias for the dictionary of the :mod:`builtins` module itself. + + +.. _dynamic-features: + +Interaction with dynamic features +--------------------------------- + +Name resolution of free variables occurs at runtime, not at compile time. +This means that the following code will print 42:: + + i = 10 + def f(): + print(i) + i = 42 + f() + +.. XXX from * also invalid with relative imports (at least currently) + +The :func:`eval` and :func:`exec` functions do not have access to the full +environment for resolving names. Names may be resolved in the local and global +namespaces of the caller. Free variables are not resolved in the nearest +enclosing namespace, but in the global namespace. [#]_ The :func:`exec` and +:func:`eval` functions have optional arguments to override the global and local +namespace. If only one namespace is specified, it is used for both. + + +.. _exceptions: + +Exceptions +========== + +.. index:: single: exception + +.. index:: + single: raise an exception + single: handle an exception + single: exception handler + single: errors + single: error handling + +Exceptions are a means of breaking out of the normal flow of control of a code +block in order to handle errors or other exceptional conditions. An exception +is *raised* at the point where the error is detected; it may be *handled* by the +surrounding code block or by any code block that directly or indirectly invoked +the code block where the error occurred. + +The Python interpreter raises an exception when it detects a run-time error +(such as division by zero). A Python program can also explicitly raise an +exception with the :keyword:`raise` statement. Exception handlers are specified +with the :keyword:`try` ... :keyword:`except` statement. The :keyword:`finally` +clause of such a statement can be used to specify cleanup code which does not +handle the exception, but is executed whether an exception occurred or not in +the preceding code. + +.. index:: single: termination model + +Python uses the "termination" model of error handling: an exception handler can +find out what happened and continue execution at an outer level, but it cannot +repair the cause of the error and retry the failing operation (except by +re-entering the offending piece of code from the top). + +.. index:: single: SystemExit (built-in exception) + +When an exception is not handled at all, the interpreter terminates execution of +the program, or returns to its interactive main loop. In either case, it prints +a stack traceback, except when the exception is :exc:`SystemExit`. + +Exceptions are identified by class instances. The :keyword:`except` clause is +selected depending on the class of the instance: it must reference the class of +the instance or a base class thereof. The instance can be received by the +handler and can carry additional information about the exceptional condition. + +.. note:: + + Exception messages are not part of the Python API. Their contents may change + from one version of Python to the next without warning and should not be + relied on by code which will run under multiple versions of the interpreter. + +See also the description of the :keyword:`try` statement in section :ref:`try` +and :keyword:`raise` statement in section :ref:`raise`. + + +.. rubric:: Footnotes + +.. [#] This limitation occurs because the code that is executed by these operations + is not available at the time the module is compiled. diff --git a/cpython_2/environment/repo/Doc/reference/expressions.rst b/cpython_2/environment/repo/Doc/reference/expressions.rst new file mode 100644 index 0000000000000000000000000000000000000000..8036a491c29ab11266f3cf0cf0ab121b96fc0216 --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/expressions.rst @@ -0,0 +1,1891 @@ + +.. _expressions: + +*********** +Expressions +*********** + +.. index:: expression, BNF + +This chapter explains the meaning of the elements of expressions in Python. + +**Syntax Notes:** In this and the following chapters, extended BNF notation will +be used to describe syntax, not lexical analysis. When (one alternative of) a +syntax rule has the form + +.. productionlist:: * + name: `othername` + +and no semantics are given, the semantics of this form of ``name`` are the same +as for ``othername``. + + +.. _conversions: + +Arithmetic conversions +====================== + +.. index:: pair: arithmetic; conversion + +When a description of an arithmetic operator below uses the phrase "the numeric +arguments are converted to a common type", this means that the operator +implementation for built-in types works as follows: + +* If either argument is a complex number, the other is converted to complex; + +* otherwise, if either argument is a floating point number, the other is + converted to floating point; + +* otherwise, both must be integers and no conversion is necessary. + +Some additional rules apply for certain operators (e.g., a string as a left +argument to the '%' operator). Extensions must define their own conversion +behavior. + + +.. _atoms: + +Atoms +===== + +.. index:: atom + +Atoms are the most basic elements of expressions. The simplest atoms are +identifiers or literals. Forms enclosed in parentheses, brackets or braces are +also categorized syntactically as atoms. The syntax for atoms is: + +.. productionlist:: + atom: `identifier` | `literal` | `enclosure` + enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display` + : | `generator_expression` | `yield_atom` + + +.. _atom-identifiers: + +Identifiers (Names) +------------------- + +.. index:: name, identifier + +An identifier occurring as an atom is a name. See section :ref:`identifiers` +for lexical definition and section :ref:`naming` for documentation of naming and +binding. + +.. index:: exception: NameError + +When the name is bound to an object, evaluation of the atom yields that object. +When a name is not bound, an attempt to evaluate it raises a :exc:`NameError` +exception. + +.. index:: + pair: name; mangling + pair: private; names + +**Private name mangling:** When an identifier that textually occurs in a class +definition begins with two or more underscore characters and does not end in two +or more underscores, it is considered a :dfn:`private name` of that class. +Private names are transformed to a longer form before code is generated for +them. The transformation inserts the class name, with leading underscores +removed and a single underscore inserted, in front of the name. For example, +the identifier ``__spam`` occurring in a class named ``Ham`` will be transformed +to ``_Ham__spam``. This transformation is independent of the syntactical +context in which the identifier is used. If the transformed name is extremely +long (longer than 255 characters), implementation defined truncation may happen. +If the class name consists only of underscores, no transformation is done. + + +.. _atom-literals: + +Literals +-------- + +.. index:: single: literal + +Python supports string and bytes literals and various numeric literals: + +.. productionlist:: + literal: `stringliteral` | `bytesliteral` + : | `integer` | `floatnumber` | `imagnumber` + +Evaluation of a literal yields an object of the given type (string, bytes, +integer, floating point number, complex number) with the given value. The value +may be approximated in the case of floating point and imaginary (complex) +literals. See section :ref:`literals` for details. + +.. index:: + triple: immutable; data; type + pair: immutable; object + +All literals correspond to immutable data types, and hence the object's identity +is less important than its value. Multiple evaluations of literals with the +same value (either the same occurrence in the program text or a different +occurrence) may obtain the same object or a different object with the same +value. + + +.. _parenthesized: + +Parenthesized forms +------------------- + +.. index:: + single: parenthesized form + single: () (parentheses); tuple display + +A parenthesized form is an optional expression list enclosed in parentheses: + +.. productionlist:: + parenth_form: "(" [`starred_expression`] ")" + +A parenthesized expression list yields whatever that expression list yields: if +the list contains at least one comma, it yields a tuple; otherwise, it yields +the single expression that makes up the expression list. + +.. index:: pair: empty; tuple + +An empty pair of parentheses yields an empty tuple object. Since tuples are +immutable, the same rules as for literals apply (i.e., two occurrences of the empty +tuple may or may not yield the same object). + +.. index:: + single: comma + single: , (comma) + +Note that tuples are not formed by the parentheses, but rather by use of the +comma operator. The exception is the empty tuple, for which parentheses *are* +required --- allowing unparenthesized "nothing" in expressions would cause +ambiguities and allow common typos to pass uncaught. + + +.. _comprehensions: + +Displays for lists, sets and dictionaries +----------------------------------------- + +For constructing a list, a set or a dictionary Python provides special syntax +called "displays", each of them in two flavors: + +* either the container contents are listed explicitly, or + +* they are computed via a set of looping and filtering instructions, called a + :dfn:`comprehension`. + +.. index:: + single: for; in comprehensions + single: if; in comprehensions + single: async for; in comprehensions + +Common syntax elements for comprehensions are: + +.. productionlist:: + comprehension: `assignment_expression` `comp_for` + comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`] + comp_iter: `comp_for` | `comp_if` + comp_if: "if" `expression_nocond` [`comp_iter`] + +The comprehension consists of a single expression followed by at least one +:keyword:`!for` clause and zero or more :keyword:`!for` or :keyword:`!if` clauses. +In this case, the elements of the new container are those that would be produced +by considering each of the :keyword:`!for` or :keyword:`!if` clauses a block, +nesting from left to right, and evaluating the expression to produce an element +each time the innermost block is reached. + +However, aside from the iterable expression in the leftmost :keyword:`!for` clause, +the comprehension is executed in a separate implicitly nested scope. This ensures +that names assigned to in the target list don't "leak" into the enclosing scope. + +The iterable expression in the leftmost :keyword:`!for` clause is evaluated +directly in the enclosing scope and then passed as an argument to the implicitly +nested scope. Subsequent :keyword:`!for` clauses and any filter condition in the +leftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as +they may depend on the values obtained from the leftmost iterable. For example: +``[x*y for x in range(10) for y in range(x, x+10)]``. + +To ensure the comprehension always results in a container of the appropriate +type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly +nested scope. + +.. index:: + single: await; in comprehensions + +Since Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for` +clause may be used to iterate over a :term:`asynchronous iterator`. +A comprehension in an :keyword:`!async def` function may consist of either a +:keyword:`!for` or :keyword:`!async for` clause following the leading +expression, may contain additional :keyword:`!for` or :keyword:`!async for` +clauses, and may also use :keyword:`await` expressions. +If a comprehension contains either :keyword:`!async for` clauses +or :keyword:`!await` expressions it is called an +:dfn:`asynchronous comprehension`. An asynchronous comprehension may +suspend the execution of the coroutine function in which it appears. +See also :pep:`530`. + +.. versionadded:: 3.6 + Asynchronous comprehensions were introduced. + +.. versionchanged:: 3.8 + ``yield`` and ``yield from`` prohibited in the implicitly nested scope. + + +.. _lists: + +List displays +------------- + +.. index:: + pair: list; display + pair: list; comprehensions + pair: empty; list + object: list + single: [] (square brackets); list expression + single: , (comma); expression list + +A list display is a possibly empty series of expressions enclosed in square +brackets: + +.. productionlist:: + list_display: "[" [`starred_list` | `comprehension`] "]" + +A list display yields a new list object, the contents being specified by either +a list of expressions or a comprehension. When a comma-separated list of +expressions is supplied, its elements are evaluated from left to right and +placed into the list object in that order. When a comprehension is supplied, +the list is constructed from the elements resulting from the comprehension. + + +.. _set: + +Set displays +------------ + +.. index:: + pair: set; display + object: set + single: {} (curly brackets); set expression + single: , (comma); expression list + +A set display is denoted by curly braces and distinguishable from dictionary +displays by the lack of colons separating keys and values: + +.. productionlist:: + set_display: "{" (`starred_list` | `comprehension`) "}" + +A set display yields a new mutable set object, the contents being specified by +either a sequence of expressions or a comprehension. When a comma-separated +list of expressions is supplied, its elements are evaluated from left to right +and added to the set object. When a comprehension is supplied, the set is +constructed from the elements resulting from the comprehension. + +An empty set cannot be constructed with ``{}``; this literal constructs an empty +dictionary. + + +.. _dict: + +Dictionary displays +------------------- + +.. index:: + pair: dictionary; display + key, datum, key/datum pair + object: dictionary + single: {} (curly brackets); dictionary expression + single: : (colon); in dictionary expressions + single: , (comma); in dictionary displays + +A dictionary display is a possibly empty series of key/datum pairs enclosed in +curly braces: + +.. productionlist:: + dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}" + key_datum_list: `key_datum` ("," `key_datum`)* [","] + key_datum: `expression` ":" `expression` | "**" `or_expr` + dict_comprehension: `expression` ":" `expression` `comp_for` + +A dictionary display yields a new dictionary object. + +If a comma-separated sequence of key/datum pairs is given, they are evaluated +from left to right to define the entries of the dictionary: each key object is +used as a key into the dictionary to store the corresponding datum. This means +that you can specify the same key multiple times in the key/datum list, and the +final dictionary's value for that key will be the last one given. + +.. index:: + unpacking; dictionary + single: **; in dictionary displays + +A double asterisk ``**`` denotes :dfn:`dictionary unpacking`. +Its operand must be a :term:`mapping`. Each mapping item is added +to the new dictionary. Later values replace values already set by +earlier key/datum pairs and earlier dictionary unpackings. + +.. versionadded:: 3.5 + Unpacking into dictionary displays, originally proposed by :pep:`448`. + +A dict comprehension, in contrast to list and set comprehensions, needs two +expressions separated with a colon followed by the usual "for" and "if" clauses. +When the comprehension is run, the resulting key and value elements are inserted +in the new dictionary in the order they are produced. + +.. index:: pair: immutable; object + hashable + +Restrictions on the types of the key values are listed earlier in section +:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes +all mutable objects.) Clashes between duplicate keys are not detected; the last +datum (textually rightmost in the display) stored for a given key value +prevails. + +.. versionchanged:: 3.8 + Prior to Python 3.8, in dict comprehensions, the evaluation order of key + and value was not well-defined. In CPython, the value was evaluated before + the key. Starting with 3.8, the key is evaluated before the value, as + proposed by :pep:`572`. + + +.. _genexpr: + +Generator expressions +--------------------- + +.. index:: + pair: generator; expression + object: generator + single: () (parentheses); generator expression + +A generator expression is a compact generator notation in parentheses: + +.. productionlist:: + generator_expression: "(" `expression` `comp_for` ")" + +A generator expression yields a new generator object. Its syntax is the same as +for comprehensions, except that it is enclosed in parentheses instead of +brackets or curly braces. + +Variables used in the generator expression are evaluated lazily when the +:meth:`~generator.__next__` method is called for the generator object (in the same +fashion as normal generators). However, the iterable expression in the +leftmost :keyword:`!for` clause is immediately evaluated, so that an error +produced by it will be emitted at the point where the generator expression +is defined, rather than at the point where the first value is retrieved. +Subsequent :keyword:`!for` clauses and any filter condition in the leftmost +:keyword:`!for` clause cannot be evaluated in the enclosing scope as they may +depend on the values obtained from the leftmost iterable. For example: +``(x*y for x in range(10) for y in range(x, x+10))``. + +The parentheses can be omitted on calls with only one argument. See section +:ref:`calls` for details. + +To avoid interfering with the expected operation of the generator expression +itself, ``yield`` and ``yield from`` expressions are prohibited in the +implicitly defined generator. + +If a generator expression contains either :keyword:`!async for` +clauses or :keyword:`await` expressions it is called an +:dfn:`asynchronous generator expression`. An asynchronous generator +expression returns a new asynchronous generator object, +which is an asynchronous iterator (see :ref:`async-iterators`). + +.. versionadded:: 3.6 + Asynchronous generator expressions were introduced. + +.. versionchanged:: 3.7 + Prior to Python 3.7, asynchronous generator expressions could + only appear in :keyword:`async def` coroutines. Starting + with 3.7, any function can use asynchronous generator expressions. + +.. versionchanged:: 3.8 + ``yield`` and ``yield from`` prohibited in the implicitly nested scope. + + +.. _yieldexpr: + +Yield expressions +----------------- + +.. index:: + keyword: yield + keyword: from + pair: yield; expression + pair: generator; function + +.. productionlist:: + yield_atom: "(" `yield_expression` ")" + yield_expression: "yield" [`expression_list` | "from" `expression`] + +The yield expression is used when defining a :term:`generator` function +or an :term:`asynchronous generator` function and +thus can only be used in the body of a function definition. Using a yield +expression in a function's body causes that function to be a generator, +and using it in an :keyword:`async def` function's body causes that +coroutine function to be an asynchronous generator. For example:: + + def gen(): # defines a generator function + yield 123 + + async def agen(): # defines an asynchronous generator function + yield 123 + +Due to their side effects on the containing scope, ``yield`` expressions +are not permitted as part of the implicitly defined scopes used to +implement comprehensions and generator expressions. + +.. versionchanged:: 3.8 + Yield expressions prohibited in the implicitly nested scopes used to + implement comprehensions and generator expressions. + +Generator functions are described below, while asynchronous generator +functions are described separately in section +:ref:`asynchronous-generator-functions`. + +When a generator function is called, it returns an iterator known as a +generator. That generator then controls the execution of the generator function. +The execution starts when one of the generator's methods is called. At that +time, the execution proceeds to the first yield expression, where it is +suspended again, returning the value of :token:`expression_list` to the generator's +caller. By suspended, we mean that all local state is retained, including the +current bindings of local variables, the instruction pointer, the internal +evaluation stack, and the state of any exception handling. When the execution +is resumed by calling one of the +generator's methods, the function can proceed exactly as if the yield expression +were just another external call. The value of the yield expression after +resuming depends on the method which resumed the execution. If +:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or +the :func:`next` builtin) then the result is :const:`None`. Otherwise, if +:meth:`~generator.send` is used, then the result will be the value passed in to +that method. + +.. index:: single: coroutine + +All of this makes generator functions quite similar to coroutines; they yield +multiple times, they have more than one entry point and their execution can be +suspended. The only difference is that a generator function cannot control +where the execution should continue after it yields; the control is always +transferred to the generator's caller. + +Yield expressions are allowed anywhere in a :keyword:`try` construct. If the +generator is not resumed before it is +finalized (by reaching a zero reference count or by being garbage collected), +the generator-iterator's :meth:`~generator.close` method will be called, +allowing any pending :keyword:`finally` clauses to execute. + +.. index:: + single: from; yield from expression + +When ``yield from `` is used, it treats the supplied expression as +a subiterator. All values produced by that subiterator are passed directly +to the caller of the current generator's methods. Any values passed in with +:meth:`~generator.send` and any exceptions passed in with +:meth:`~generator.throw` are passed to the underlying iterator if it has the +appropriate methods. If this is not the case, then :meth:`~generator.send` +will raise :exc:`AttributeError` or :exc:`TypeError`, while +:meth:`~generator.throw` will just raise the passed in exception immediately. + +When the underlying iterator is complete, the :attr:`~StopIteration.value` +attribute of the raised :exc:`StopIteration` instance becomes the value of +the yield expression. It can be either set explicitly when raising +:exc:`StopIteration`, or automatically when the subiterator is a generator +(by returning a value from the subgenerator). + + .. versionchanged:: 3.3 + Added ``yield from `` to delegate control flow to a subiterator. + +The parentheses may be omitted when the yield expression is the sole expression +on the right hand side of an assignment statement. + +.. seealso:: + + :pep:`255` - Simple Generators + The proposal for adding generators and the :keyword:`yield` statement to Python. + + :pep:`342` - Coroutines via Enhanced Generators + The proposal to enhance the API and syntax of generators, making them + usable as simple coroutines. + + :pep:`380` - Syntax for Delegating to a Subgenerator + The proposal to introduce the :token:`yield_from` syntax, making delegation + to subgenerators easy. + + :pep:`525` - Asynchronous Generators + The proposal that expanded on :pep:`492` by adding generator capabilities to + coroutine functions. + +.. index:: object: generator +.. _generator-methods: + +Generator-iterator methods +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +This subsection describes the methods of a generator iterator. They can +be used to control the execution of a generator function. + +Note that calling any of the generator methods below when the generator +is already executing raises a :exc:`ValueError` exception. + +.. index:: exception: StopIteration + + +.. method:: generator.__next__() + + Starts the execution of a generator function or resumes it at the last + executed yield expression. When a generator function is resumed with a + :meth:`~generator.__next__` method, the current yield expression always + evaluates to :const:`None`. The execution then continues to the next yield + expression, where the generator is suspended again, and the value of the + :token:`expression_list` is returned to :meth:`__next__`'s caller. If the + generator exits without yielding another value, a :exc:`StopIteration` + exception is raised. + + This method is normally called implicitly, e.g. by a :keyword:`for` loop, or + by the built-in :func:`next` function. + + +.. method:: generator.send(value) + + Resumes the execution and "sends" a value into the generator function. The + *value* argument becomes the result of the current yield expression. The + :meth:`send` method returns the next value yielded by the generator, or + raises :exc:`StopIteration` if the generator exits without yielding another + value. When :meth:`send` is called to start the generator, it must be called + with :const:`None` as the argument, because there is no yield expression that + could receive the value. + + +.. method:: generator.throw(type[, value[, traceback]]) + + Raises an exception of type ``type`` at the point where the generator was paused, + and returns the next value yielded by the generator function. If the generator + exits without yielding another value, a :exc:`StopIteration` exception is + raised. If the generator function does not catch the passed-in exception, or + raises a different exception, then that exception propagates to the caller. + +.. index:: exception: GeneratorExit + + +.. method:: generator.close() + + Raises a :exc:`GeneratorExit` at the point where the generator function was + paused. If the generator function then exits gracefully, is already closed, + or raises :exc:`GeneratorExit` (by not catching the exception), close + returns to its caller. If the generator yields a value, a + :exc:`RuntimeError` is raised. If the generator raises any other exception, + it is propagated to the caller. :meth:`close` does nothing if the generator + has already exited due to an exception or normal exit. + +.. index:: single: yield; examples + +Examples +^^^^^^^^ + +Here is a simple example that demonstrates the behavior of generators and +generator functions:: + + >>> def echo(value=None): + ... print("Execution starts when 'next()' is called for the first time.") + ... try: + ... while True: + ... try: + ... value = (yield value) + ... except Exception as e: + ... value = e + ... finally: + ... print("Don't forget to clean up when 'close()' is called.") + ... + >>> generator = echo(1) + >>> print(next(generator)) + Execution starts when 'next()' is called for the first time. + 1 + >>> print(next(generator)) + None + >>> print(generator.send(2)) + 2 + >>> generator.throw(TypeError, "spam") + TypeError('spam',) + >>> generator.close() + Don't forget to clean up when 'close()' is called. + +For examples using ``yield from``, see :ref:`pep-380` in "What's New in +Python." + +.. _asynchronous-generator-functions: + +Asynchronous generator functions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The presence of a yield expression in a function or method defined using +:keyword:`async def` further defines the function as an +:term:`asynchronous generator` function. + +When an asynchronous generator function is called, it returns an +asynchronous iterator known as an asynchronous generator object. +That object then controls the execution of the generator function. +An asynchronous generator object is typically used in an +:keyword:`async for` statement in a coroutine function analogously to +how a generator object would be used in a :keyword:`for` statement. + +Calling one of the asynchronous generator's methods returns an +:term:`awaitable` object, and the execution starts when this object +is awaited on. At that time, the execution proceeds to the first yield +expression, where it is suspended again, returning the value of +:token:`expression_list` to the awaiting coroutine. As with a generator, +suspension means that all local state is retained, including the +current bindings of local variables, the instruction pointer, the internal +evaluation stack, and the state of any exception handling. When the execution +is resumed by awaiting on the next object returned by the asynchronous +generator's methods, the function can proceed exactly as if the yield +expression were just another external call. The value of the yield expression +after resuming depends on the method which resumed the execution. If +:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if +:meth:`~agen.asend` is used, then the result will be the value passed in to +that method. + +In an asynchronous generator function, yield expressions are allowed anywhere +in a :keyword:`try` construct. However, if an asynchronous generator is not +resumed before it is finalized (by reaching a zero reference count or by +being garbage collected), then a yield expression within a :keyword:`!try` +construct could result in a failure to execute pending :keyword:`finally` +clauses. In this case, it is the responsibility of the event loop or +scheduler running the asynchronous generator to call the asynchronous +generator-iterator's :meth:`~agen.aclose` method and run the resulting +coroutine object, thus allowing any pending :keyword:`!finally` clauses +to execute. + +To take care of finalization, an event loop should define +a *finalizer* function which takes an asynchronous generator-iterator +and presumably calls :meth:`~agen.aclose` and executes the coroutine. +This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`. +When first iterated over, an asynchronous generator-iterator will store the +registered *finalizer* to be called upon finalization. For a reference example +of a *finalizer* method see the implementation of +``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`. + +The expression ``yield from `` is a syntax error when used in an +asynchronous generator function. + +.. index:: object: asynchronous-generator +.. _asynchronous-generator-methods: + +Asynchronous generator-iterator methods +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +This subsection describes the methods of an asynchronous generator iterator, +which are used to control the execution of a generator function. + + +.. index:: exception: StopAsyncIteration + +.. coroutinemethod:: agen.__anext__() + + Returns an awaitable which when run starts to execute the asynchronous + generator or resumes it at the last executed yield expression. When an + asynchronous generator function is resumed with an :meth:`~agen.__anext__` + method, the current yield expression always evaluates to :const:`None` in + the returned awaitable, which when run will continue to the next yield + expression. The value of the :token:`expression_list` of the yield + expression is the value of the :exc:`StopIteration` exception raised by + the completing coroutine. If the asynchronous generator exits without + yielding another value, the awaitable instead raises a + :exc:`StopAsyncIteration` exception, signalling that the asynchronous + iteration has completed. + + This method is normally called implicitly by a :keyword:`async for` loop. + + +.. coroutinemethod:: agen.asend(value) + + Returns an awaitable which when run resumes the execution of the + asynchronous generator. As with the :meth:`~generator.send()` method for a + generator, this "sends" a value into the asynchronous generator function, + and the *value* argument becomes the result of the current yield expression. + The awaitable returned by the :meth:`asend` method will return the next + value yielded by the generator as the value of the raised + :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the + asynchronous generator exits without yielding another value. When + :meth:`asend` is called to start the asynchronous + generator, it must be called with :const:`None` as the argument, + because there is no yield expression that could receive the value. + + +.. coroutinemethod:: agen.athrow(type[, value[, traceback]]) + + Returns an awaitable that raises an exception of type ``type`` at the point + where the asynchronous generator was paused, and returns the next value + yielded by the generator function as the value of the raised + :exc:`StopIteration` exception. If the asynchronous generator exits + without yielding another value, a :exc:`StopAsyncIteration` exception is + raised by the awaitable. + If the generator function does not catch the passed-in exception, or + raises a different exception, then when the awaitable is run that exception + propagates to the caller of the awaitable. + +.. index:: exception: GeneratorExit + + +.. coroutinemethod:: agen.aclose() + + Returns an awaitable that when run will throw a :exc:`GeneratorExit` into + the asynchronous generator function at the point where it was paused. + If the asynchronous generator function then exits gracefully, is already + closed, or raises :exc:`GeneratorExit` (by not catching the exception), + then the returned awaitable will raise a :exc:`StopIteration` exception. + Any further awaitables returned by subsequent calls to the asynchronous + generator will raise a :exc:`StopAsyncIteration` exception. If the + asynchronous generator yields a value, a :exc:`RuntimeError` is raised + by the awaitable. If the asynchronous generator raises any other exception, + it is propagated to the caller of the awaitable. If the asynchronous + generator has already exited due to an exception or normal exit, then + further calls to :meth:`aclose` will return an awaitable that does nothing. + +.. _primaries: + +Primaries +========= + +.. index:: single: primary + +Primaries represent the most tightly bound operations of the language. Their +syntax is: + +.. productionlist:: + primary: `atom` | `attributeref` | `subscription` | `slicing` | `call` + + +.. _attribute-references: + +Attribute references +-------------------- + +.. index:: + pair: attribute; reference + single: . (dot); attribute reference + +An attribute reference is a primary followed by a period and a name: + +.. productionlist:: + attributeref: `primary` "." `identifier` + +.. index:: + exception: AttributeError + object: module + object: list + +The primary must evaluate to an object of a type that supports attribute +references, which most objects do. This object is then asked to produce the +attribute whose name is the identifier. This production can be customized by +overriding the :meth:`__getattr__` method. If this attribute is not available, +the exception :exc:`AttributeError` is raised. Otherwise, the type and value of +the object produced is determined by the object. Multiple evaluations of the +same attribute reference may yield different objects. + + +.. _subscriptions: + +Subscriptions +------------- + +.. index:: + single: subscription + single: [] (square brackets); subscription + +.. index:: + object: sequence + object: mapping + object: string + object: tuple + object: list + object: dictionary + pair: sequence; item + +A subscription selects an item of a sequence (string, tuple or list) or mapping +(dictionary) object: + +.. productionlist:: + subscription: `primary` "[" `expression_list` "]" + +The primary must evaluate to an object that supports subscription (lists or +dictionaries for example). User-defined objects can support subscription by +defining a :meth:`__getitem__` method. + +For built-in objects, there are two types of objects that support subscription: + +If the primary is a mapping, the expression list must evaluate to an object +whose value is one of the keys of the mapping, and the subscription selects the +value in the mapping that corresponds to that key. (The expression list is a +tuple except if it has exactly one item.) + +If the primary is a sequence, the expression list must evaluate to an integer +or a slice (as discussed in the following section). + +The formal syntax makes no special provision for negative indices in +sequences; however, built-in sequences all provide a :meth:`__getitem__` +method that interprets negative indices by adding the length of the sequence +to the index (so that ``x[-1]`` selects the last item of ``x``). The +resulting value must be a nonnegative integer less than the number of items in +the sequence, and the subscription selects the item whose index is that value +(counting from zero). Since the support for negative indices and slicing +occurs in the object's :meth:`__getitem__` method, subclasses overriding +this method will need to explicitly add that support. + +.. index:: + single: character + pair: string; item + +A string's items are characters. A character is not a separate data type but a +string of exactly one character. + + +.. _slicings: + +Slicings +-------- + +.. index:: + single: slicing + single: slice + single: : (colon); slicing + single: , (comma); slicing + +.. index:: + object: sequence + object: string + object: tuple + object: list + +A slicing selects a range of items in a sequence object (e.g., a string, tuple +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` "]" + slice_list: `slice_item` ("," `slice_item`)* [","] + slice_item: `expression` | `proper_slice` + proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ] + lower_bound: `expression` + upper_bound: `expression` + stride: `expression` + +There is ambiguity in the formal syntax here: anything that looks like an +expression list also looks like a slice list, so any subscription can be +interpreted as a slicing. Rather than further complicating the syntax, this is +disambiguated by defining that in this case the interpretation as a subscription +takes priority over the interpretation as a slicing (this is the case if the +slice list contains no proper slice). + +.. index:: + single: start (slice object attribute) + single: stop (slice object attribute) + single: step (slice object attribute) + +The semantics for a slicing are as follows. The primary is indexed (using the +same :meth:`__getitem__` method as +normal subscription) with a key that is constructed from the slice list, as +follows. If the slice list contains at least one comma, the key is a tuple +containing the conversion of the slice items; otherwise, the conversion of the +lone slice item is the key. The conversion of a slice item that is an +expression is that expression. The conversion of a proper slice is a slice +object (see section :ref:`types`) whose :attr:`~slice.start`, +:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the +expressions given as lower bound, upper bound and stride, respectively, +substituting ``None`` for missing expressions. + + +.. index:: + object: callable + single: call + single: argument; call semantics + single: () (parentheses); call + single: , (comma); argument list + single: = (equals); in function calls + +.. _calls: + +Calls +----- + +A call calls a callable object (e.g., a :term:`function`) with a possibly empty +series of :term:`arguments `: + +.. productionlist:: + call: `primary` "(" [`argument_list` [","] | `comprehension`] ")" + argument_list: `positional_arguments` ["," `starred_and_keywords`] + : ["," `keywords_arguments`] + : | `starred_and_keywords` ["," `keywords_arguments`] + : | `keywords_arguments` + positional_arguments: positional_item ("," positional_item)* + positional_item: `assignment_expression` | "*" `expression` + starred_and_keywords: ("*" `expression` | `keyword_item`) + : ("," "*" `expression` | "," `keyword_item`)* + keywords_arguments: (`keyword_item` | "**" `expression`) + : ("," `keyword_item` | "," "**" `expression`)* + keyword_item: `identifier` "=" `expression` + +An optional trailing comma may be present after the positional and keyword arguments +but does not affect the semantics. + +.. index:: + single: parameter; call semantics + +The primary must evaluate to a callable object (user-defined functions, built-in +functions, methods of built-in objects, class objects, methods of class +instances, and all objects having a :meth:`__call__` method are callable). All +argument expressions are evaluated before the call is attempted. Please refer +to section :ref:`function` for the syntax of formal :term:`parameter` lists. + +.. XXX update with kwonly args PEP + +If keyword arguments are present, they are first converted to positional +arguments, as follows. First, a list of unfilled slots is created for the +formal parameters. If there are N positional arguments, they are placed in the +first N slots. Next, for each keyword argument, the identifier is used to +determine the corresponding slot (if the identifier is the same as the first +formal parameter name, the first slot is used, and so on). If the slot is +already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of +the argument is placed in the slot, filling it (even if the expression is +``None``, it fills the slot). When all arguments have been processed, the slots +that are still unfilled are filled with the corresponding default value from the +function definition. (Default values are calculated, once, when the function is +defined; thus, a mutable object such as a list or dictionary used as default +value will be shared by all calls that don't specify an argument value for the +corresponding slot; this should usually be avoided.) If there are any unfilled +slots for which no default value is specified, a :exc:`TypeError` exception is +raised. Otherwise, the list of filled slots is used as the argument list for +the call. + +.. impl-detail:: + + An implementation may provide built-in 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 functions implemented in C that use :c:func:`PyArg_ParseTuple` to + parse their arguments. + +If there are more positional arguments than there are formal parameter slots, a +:exc:`TypeError` exception is raised, unless a formal parameter using the syntax +``*identifier`` is present; in this case, that formal parameter receives a tuple +containing the excess positional arguments (or an empty tuple if there were no +excess positional arguments). + +If any keyword argument does not correspond to a formal parameter name, a +:exc:`TypeError` exception is raised, unless a formal parameter using the syntax +``**identifier`` is present; in this case, that formal parameter receives a +dictionary containing the excess keyword arguments (using the keywords as keys +and the argument values as corresponding values), or a (new) empty dictionary if +there were no excess keyword arguments. + +.. index:: + single: * (asterisk); in function calls + single: unpacking; in function calls + +If the syntax ``*expression`` appears in the function call, ``expression`` must +evaluate to an :term:`iterable`. Elements from these iterables are +treated as if they were additional positional arguments. For the call +``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*, +this is equivalent to a call with M+4 positional arguments *x1*, *x2*, +*y1*, ..., *yM*, *x3*, *x4*. + +A consequence of this is that although the ``*expression`` syntax may appear +*after* explicit keyword arguments, it is processed *before* the +keyword arguments (and any ``**expression`` arguments -- see below). So:: + + >>> def f(a, b): + ... print(a, b) + ... + >>> f(b=1, *(2,)) + 2 1 + >>> f(a=1, *(2,)) + Traceback (most recent call last): + File "", line 1, in + TypeError: f() got multiple values for keyword argument 'a' + >>> f(1, *(2,)) + 1 2 + +It is unusual for both keyword arguments and the ``*expression`` syntax to be +used in the same call, so in practice this confusion does not arise. + +.. index:: + single: **; in function calls + +If the syntax ``**expression`` appears in the function call, ``expression`` must +evaluate to a :term:`mapping`, the contents of which are treated as +additional keyword arguments. If a keyword is already present +(as an explicit keyword argument, or from another unpacking), +a :exc:`TypeError` exception is raised. + +Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be +used as positional argument slots or as keyword argument names. + +.. versionchanged:: 3.5 + Function calls accept any number of ``*`` and ``**`` unpackings, + positional arguments may follow iterable unpackings (``*``), + and keyword arguments may follow dictionary unpackings (``**``). + Originally proposed by :pep:`448`. + +A call always returns some value, possibly ``None``, unless it raises an +exception. How this value is computed depends on the type of the callable +object. + +If it is--- + +a user-defined function: + .. index:: + pair: function; call + triple: user-defined; function; call + object: user-defined function + object: function + + The code block for the function is executed, passing it the argument list. The + first thing the code block will do is bind the formal parameters to the + arguments; this is described in section :ref:`function`. When the code block + executes a :keyword:`return` statement, this specifies the return value of the + function call. + +a built-in function or method: + .. index:: + pair: function; call + pair: built-in function; call + pair: method; call + pair: built-in method; call + object: built-in method + object: built-in function + object: method + object: function + + The result is up to the interpreter; see :ref:`built-in-funcs` for the + descriptions of built-in functions and methods. + +a class object: + .. index:: + object: class + pair: class object; call + + A new instance of that class is returned. + +a class instance method: + .. index:: + object: class instance + object: instance + pair: class instance; call + + The corresponding user-defined function is called, with an argument list that is + one longer than the argument list of the call: the instance becomes the first + argument. + +a class instance: + .. index:: + pair: instance; call + single: __call__() (object method) + + The class must define a :meth:`__call__` method; the effect is then the same as + if that method was called. + + +.. index:: keyword: await +.. _await: + +Await expression +================ + +Suspend the execution of :term:`coroutine` on an :term:`awaitable` object. +Can only be used inside a :term:`coroutine function`. + +.. productionlist:: + await_expr: "await" `primary` + +.. versionadded:: 3.5 + + +.. _power: + +The power operator +================== + +.. index:: + pair: power; operation + operator: ** + +The power operator binds more tightly than unary operators on its left; it binds +less tightly than unary operators on its right. The syntax is: + +.. productionlist:: + power: (`await_expr` | `primary`) ["**" `u_expr`] + +Thus, in an unparenthesized sequence of power and unary operators, the operators +are evaluated from right to left (this does not constrain the evaluation order +for the operands): ``-1**2`` results in ``-1``. + +The power operator has the same semantics as the built-in :func:`pow` function, +when called with two arguments: it yields its left argument raised to the power +of its right argument. The numeric arguments are first converted to a common +type, and the result is of that type. + +For int operands, the result has the same type as the operands unless the second +argument is negative; in that case, all arguments are converted to float and a +float result is delivered. For example, ``10**2`` returns ``100``, but +``10**-2`` returns ``0.01``. + +Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`. +Raising a negative number to a fractional power results in a :class:`complex` +number. (In earlier versions it raised a :exc:`ValueError`.) + + +.. _unary: + +Unary arithmetic and bitwise operations +======================================= + +.. index:: + triple: unary; arithmetic; operation + triple: unary; bitwise; operation + +All unary arithmetic and bitwise operations have the same priority: + +.. productionlist:: + u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr` + +.. index:: + single: negation + single: minus + single: operator; - (minus) + single: - (minus); unary operator + +The unary ``-`` (minus) operator yields the negation of its numeric argument. + +.. index:: + single: plus + single: operator; + (plus) + single: + (plus); unary operator + +The unary ``+`` (plus) operator yields its numeric argument unchanged. + +.. index:: + single: inversion + operator: ~ (tilde) + +The unary ``~`` (invert) operator yields the bitwise inversion of its integer +argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only +applies to integral numbers. + +.. index:: exception: TypeError + +In all three cases, if the argument does not have the proper type, a +:exc:`TypeError` exception is raised. + + +.. _binary: + +Binary arithmetic operations +============================ + +.. index:: triple: binary; arithmetic; operation + +The binary arithmetic operations have the conventional priority levels. Note +that some of these operations also apply to certain non-numeric types. Apart +from the power operator, there are only two levels, one for multiplicative +operators and one for additive operators: + +.. productionlist:: + m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` | + : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` | + : `m_expr` "%" `u_expr` + a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr` + +.. index:: + single: multiplication + operator: * (asterisk) + +The ``*`` (multiplication) operator yields the product of its arguments. The +arguments must either both be numbers, or one argument must be an integer and +the other must be a sequence. In the former case, the numbers are converted to a +common type and then multiplied together. In the latter case, sequence +repetition is performed; a negative repetition factor yields an empty sequence. + +.. index:: + single: matrix multiplication + operator: @ (at) + +The ``@`` (at) operator is intended to be used for matrix multiplication. No +builtin Python types implement this operator. + +.. versionadded:: 3.5 + +.. index:: + exception: ZeroDivisionError + single: division + operator: / (slash) + operator: // + +The ``/`` (division) and ``//`` (floor division) operators yield the quotient of +their arguments. The numeric arguments are first converted to a common type. +Division of integers yields a float, while floor division of integers results in an +integer; the result is that of mathematical division with the 'floor' function +applied to the result. Division by zero raises the :exc:`ZeroDivisionError` +exception. + +.. index:: + single: modulo + operator: % (percent) + +The ``%`` (modulo) operator yields the remainder from the division of the first +argument by the second. The numeric arguments are first converted to a common +type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The +arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34`` +(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a +result with the same sign as its second operand (or zero); the absolute value of +the result is strictly smaller than the absolute value of the second operand +[#]_. + +The floor division and modulo operators are connected by the following +identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also +connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y, +x%y)``. [#]_. + +In addition to performing the modulo operation on numbers, the ``%`` operator is +also overloaded by string objects to perform old-style string formatting (also +known as interpolation). The syntax for string formatting is described in the +Python Library Reference, section :ref:`old-string-formatting`. + +The floor division operator, the modulo operator, and the :func:`divmod` +function are not defined for complex numbers. Instead, convert to a floating +point number using the :func:`abs` function if appropriate. + +.. index:: + single: addition + single: operator; + (plus) + single: + (plus); binary operator + +The ``+`` (addition) operator yields the sum of its arguments. The arguments +must either both be numbers or both be sequences of the same type. In the +former case, the numbers are converted to a common type and then added together. +In the latter case, the sequences are concatenated. + +.. index:: + single: subtraction + single: operator; - (minus) + single: - (minus); binary operator + +The ``-`` (subtraction) operator yields the difference of its arguments. The +numeric arguments are first converted to a common type. + + +.. _shifting: + +Shifting operations +=================== + +.. index:: + pair: shifting; operation + operator: << + operator: >> + +The shifting operations have lower priority than the arithmetic operations: + +.. productionlist:: + shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr` + +These operators accept integers as arguments. They shift the first argument to +the left or right by the number of bits given by the second argument. + +.. index:: exception: ValueError + +A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left +shift by *n* bits is defined as multiplication with ``pow(2,n)``. + + +.. _bitwise: + +Binary bitwise operations +========================= + +.. index:: triple: binary; bitwise; operation + +Each of the three bitwise operations has a different priority level: + +.. productionlist:: + and_expr: `shift_expr` | `and_expr` "&" `shift_expr` + xor_expr: `and_expr` | `xor_expr` "^" `and_expr` + or_expr: `xor_expr` | `or_expr` "|" `xor_expr` + +.. index:: + pair: bitwise; and + operator: & (ampersand) + +The ``&`` operator yields the bitwise AND of its arguments, which must be +integers. + +.. index:: + pair: bitwise; xor + pair: exclusive; or + operator: ^ (caret) + +The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which +must be integers. + +.. index:: + pair: bitwise; or + pair: inclusive; or + operator: | (vertical bar) + +The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which +must be integers. + + +.. _comparisons: + +Comparisons +=========== + +.. index:: + single: comparison + pair: C; language + operator: < (less) + operator: > (greater) + operator: <= + operator: >= + operator: == + operator: != + +Unlike C, all comparison operations in Python have the same priority, which is +lower than that of any arithmetic, shifting or bitwise operation. Also unlike +C, expressions like ``a < b < c`` have the interpretation that is conventional +in mathematics: + +.. productionlist:: + comparison: `or_expr` (`comp_operator` `or_expr`)* + comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!=" + : | "is" ["not"] | ["not"] "in" + +Comparisons yield boolean values: ``True`` or ``False``. + +.. index:: pair: chaining; comparisons + +Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to +``x < y and y <= z``, except that ``y`` is evaluated only once (but in both +cases ``z`` is not evaluated at all when ``x < y`` is found to be false). + +Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ..., +*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent +to ``a op1 b and b op2 c and ... y opN z``, except that each expression is +evaluated at most once. + +Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and +*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not +pretty). + +Value comparisons +----------------- + +The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the +values of two objects. The objects do not need to have the same type. + +Chapter :ref:`objects` states that objects have a value (in addition to type +and identity). The value of an object is a rather abstract notion in Python: +For example, there is no canonical access method for an object's value. Also, +there is no requirement that the value of an object should be constructed in a +particular way, e.g. comprised of all its data attributes. Comparison operators +implement a particular notion of what the value of an object is. One can think +of them as defining the value of an object indirectly, by means of their +comparison implementation. + +Because all types are (direct or indirect) subtypes of :class:`object`, they +inherit the default comparison behavior from :class:`object`. Types can +customize their comparison behavior by implementing +:dfn:`rich comparison methods` like :meth:`__lt__`, described in +:ref:`customization`. + +The default behavior for equality comparison (``==`` and ``!=``) is based on +the identity of the objects. Hence, equality comparison of instances with the +same identity results in equality, and equality comparison of instances with +different identities results in inequality. A motivation for this default +behavior is the desire that all objects should be reflexive (i.e. ``x is y`` +implies ``x == y``). + +A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided; +an attempt raises :exc:`TypeError`. A motivation for this default behavior is +the lack of a similar invariant as for equality. + +The behavior of the default equality comparison, that instances with different +identities are always unequal, may be in contrast to what types will need that +have a sensible definition of object value and value-based equality. Such +types will need to customize their comparison behavior, and in fact, a number +of built-in types have done that. + +The following list describes the comparison behavior of the most important +built-in types. + +* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard + library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be + compared within and across their types, with the restriction that complex + numbers do not support order comparison. Within the limits of the types + involved, they compare mathematically (algorithmically) correct without loss + of precision. + + The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are + special. Any ordered comparison of a number to a not-a-number value is false. + A counter-intuitive implication is that not-a-number values are not equal to + themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and + ``x == x`` are all false, while ``x != x`` is true. This behavior is + compliant with IEEE 754. + +* ``None`` and ``NotImplemented`` are singletons. :PEP:`8` advises that + comparisons for singletons should always be done with ``is`` or ``is not``, + never the equality operators. + +* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be + compared within and across their types. They compare lexicographically using + the numeric values of their elements. + +* Strings (instances of :class:`str`) compare lexicographically using the + numerical Unicode code points (the result of the built-in function + :func:`ord`) of their characters. [#]_ + + Strings and binary sequences cannot be directly compared. + +* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can + be compared only within each of their types, with the restriction that ranges + do not support order comparison. Equality comparison across these types + results in inequality, and ordering comparison across these types raises + :exc:`TypeError`. + + Sequences compare lexicographically using comparison of corresponding + elements. The built-in containers typically assume identical objects are + equal to themselves. That lets them bypass equality tests for identical + objects to improve performance and to maintain their internal invariants. + + Lexicographical comparison between built-in collections works as follows: + + - For two collections to compare equal, they must be of the same type, have + the same length, and each pair of corresponding elements must compare + equal (for example, ``[1,2] == (1,2)`` is false because the type is not the + same). + + - Collections that support order comparison are ordered the same as their + first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same + value as ``x <= y``). If a corresponding element does not exist, the + shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is + true). + +* Mappings (instances of :class:`dict`) compare equal if and only if they have + equal `(key, value)` pairs. Equality comparison of the keys and values + enforces reflexivity. + + Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`. + +* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within + and across their types. + + They define order + comparison operators to mean subset and superset tests. Those relations do + not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}`` + are not equal, nor subsets of one another, nor supersets of one + another). Accordingly, sets are not appropriate arguments for functions + which depend on total ordering (for example, :func:`min`, :func:`max`, and + :func:`sorted` produce undefined results given a list of sets as inputs). + + Comparison of sets enforces reflexivity of its elements. + +* Most other built-in types have no comparison methods implemented, so they + inherit the default comparison behavior. + +User-defined classes that customize their comparison behavior should follow +some consistency rules, if possible: + +* Equality comparison should be reflexive. + In other words, identical objects should compare equal: + + ``x is y`` implies ``x == y`` + +* Comparison should be symmetric. + In other words, the following expressions should have the same result: + + ``x == y`` and ``y == x`` + + ``x != y`` and ``y != x`` + + ``x < y`` and ``y > x`` + + ``x <= y`` and ``y >= x`` + +* Comparison should be transitive. + The following (non-exhaustive) examples illustrate that: + + ``x > y and y > z`` implies ``x > z`` + + ``x < y and y <= z`` implies ``x < z`` + +* Inverse comparison should result in the boolean negation. + In other words, the following expressions should have the same result: + + ``x == y`` and ``not x != y`` + + ``x < y`` and ``not x >= y`` (for total ordering) + + ``x > y`` and ``not x <= y`` (for total ordering) + + The last two expressions apply to totally ordered collections (e.g. to + sequences, but not to sets or mappings). See also the + :func:`~functools.total_ordering` decorator. + +* The :func:`hash` result should be consistent with equality. + Objects that are equal should either have the same hash value, + or be marked as unhashable. + +Python does not enforce these consistency rules. In fact, the not-a-number +values are an example for not following these rules. + + +.. _in: +.. _not in: +.. _membership-test-details: + +Membership test operations +-------------------------- + +The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in +s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise. +``x not in s`` returns the negation of ``x in s``. All built-in sequences and +set types support this as well as dictionary, for which :keyword:`!in` tests +whether the dictionary has a given key. For container types such as list, tuple, +set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent +to ``any(x is e or x == e for e in y)``. + +For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a +substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are +always considered to be a substring of any other string, so ``"" in "abc"`` will +return ``True``. + +For user-defined classes which define the :meth:`__contains__` method, ``x in +y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and +``False`` otherwise. + +For user-defined classes which do not define :meth:`__contains__` but do define +:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z``, for which the +expression ``x is z or x == z`` is true, is produced while iterating over ``y``. +If an exception is raised during the iteration, it is as if :keyword:`in` raised +that exception. + +Lastly, the old-style iteration protocol is tried: if a class defines +:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative +integer index *i* such that ``x is y[i] or x == y[i]``, and no lower integer index +raises the :exc:`IndexError` exception. (If any other exception is raised, it is as +if :keyword:`in` raised that exception). + +.. index:: + operator: in + operator: not in + pair: membership; test + object: sequence + +The operator :keyword:`not in` is defined to have the inverse truth value of +:keyword:`in`. + +.. index:: + operator: is + operator: is not + pair: identity; test + + +.. _is: +.. _is not: + +Identity comparisons +-------------------- + +The operators :keyword:`is` and :keyword:`is not` test for an object's identity: ``x +is y`` is true if and only if *x* and *y* are the same object. An Object's identity +is determined using the :meth:`id` function. ``x is not y`` yields the inverse +truth value. [#]_ + + +.. _booleans: +.. _and: +.. _or: +.. _not: + +Boolean operations +================== + +.. index:: + pair: Conditional; expression + pair: Boolean; operation + +.. productionlist:: + or_test: `and_test` | `or_test` "or" `and_test` + and_test: `not_test` | `and_test` "and" `not_test` + not_test: `comparison` | "not" `not_test` + +In the context of Boolean operations, and also when expressions are used by +control flow statements, the following values are interpreted as false: +``False``, ``None``, numeric zero of all types, and empty strings and containers +(including strings, tuples, lists, dictionaries, sets and frozensets). All +other values are interpreted as true. User-defined objects can customize their +truth value by providing a :meth:`__bool__` method. + +.. index:: operator: not + +The operator :keyword:`not` yields ``True`` if its argument is false, ``False`` +otherwise. + +.. index:: operator: and + +The expression ``x and y`` first evaluates *x*; if *x* is false, its value is +returned; otherwise, *y* is evaluated and the resulting value is returned. + +.. index:: operator: or + +The expression ``x or y`` first evaluates *x*; if *x* is true, its value is +returned; otherwise, *y* is evaluated and the resulting value is returned. + +Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type +they return to ``False`` and ``True``, but rather return the last evaluated +argument. This is sometimes useful, e.g., if ``s`` is a string that should be +replaced by a default value if it is empty, the expression ``s or 'foo'`` yields +the desired value. Because :keyword:`not` has to create a new value, it +returns a boolean value regardless of the type of its argument +(for example, ``not 'foo'`` produces ``False`` rather than ``''``.) + + +Assignment expressions +====================== + +.. productionlist:: + assignment_expression: [`identifier` ":="] `expression` + +.. TODO: BPO-39868 + +See :pep:`572` for more details about assignment expressions. + + +.. _if_expr: + +Conditional expressions +======================= + +.. index:: + pair: conditional; expression + pair: ternary; operator + single: if; conditional expression + single: else; conditional expression + +.. productionlist:: + conditional_expression: `or_test` ["if" `or_test` "else" `expression`] + expression: `conditional_expression` | `lambda_expr` + expression_nocond: `or_test` | `lambda_expr_nocond` + +Conditional expressions (sometimes called a "ternary operator") have the lowest +priority of all Python operations. + +The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*. +If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is +evaluated and its value is returned. + +See :pep:`308` for more details about conditional expressions. + + +.. _lambdas: +.. _lambda: + +Lambdas +======= + +.. index:: + pair: lambda; expression + pair: lambda; form + pair: anonymous; function + single: : (colon); lambda expression + +.. productionlist:: + lambda_expr: "lambda" [`parameter_list`] ":" `expression` + lambda_expr_nocond: "lambda" [`parameter_list`] ":" `expression_nocond` + +Lambda expressions (sometimes called lambda forms) are used to create anonymous +functions. The expression ``lambda parameters: expression`` yields a function +object. The unnamed object behaves like a function object defined with: + +.. code-block:: none + + def (parameters): + return expression + +See section :ref:`function` for the syntax of parameter lists. Note that +functions created with lambda expressions cannot contain statements or +annotations. + + +.. _exprlists: + +Expression lists +================ + +.. index:: + pair: expression; list + single: , (comma); expression list + +.. productionlist:: + expression_list: `expression` ("," `expression`)* [","] + starred_list: `starred_item` ("," `starred_item`)* [","] + starred_expression: `expression` | (`starred_item` ",")* [`starred_item`] + starred_item: `assignment_expression` | "*" `or_expr` + +.. index:: object: tuple + +Except when part of a list or set display, an expression list +containing at least one comma yields a tuple. The length of +the tuple is the number of expressions in the list. The expressions are +evaluated from left to right. + +.. index:: + pair: iterable; unpacking + single: * (asterisk); in expression lists + +An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be +an :term:`iterable`. The iterable is expanded into a sequence of items, +which are included in the new tuple, list, or set, at the site of +the unpacking. + +.. versionadded:: 3.5 + Iterable unpacking in expression lists, originally proposed by :pep:`448`. + +.. index:: pair: trailing; comma + +The trailing comma is required only to create a single tuple (a.k.a. a +*singleton*); it is optional in all other cases. A single expression without a +trailing comma doesn't create a tuple, but rather yields the value of that +expression. (To create an empty tuple, use an empty pair of parentheses: +``()``.) + + +.. _evalorder: + +Evaluation order +================ + +.. index:: pair: evaluation; order + +Python evaluates expressions from left to right. Notice that while evaluating +an assignment, the right-hand side is evaluated before the left-hand side. + +In the following lines, expressions will be evaluated in the arithmetic order of +their suffixes:: + + expr1, expr2, expr3, expr4 + (expr1, expr2, expr3, expr4) + {expr1: expr2, expr3: expr4} + expr1 + expr2 * (expr3 - expr4) + expr1(expr2, expr3, *expr4, **expr5) + expr3, expr4 = expr1, expr2 + + +.. _operator-summary: + +Operator precedence +=================== + +.. index:: + pair: operator; precedence + +The following table summarizes the operator precedence in Python, from lowest +precedence (least binding) to highest precedence (most binding). Operators in +the same box have the same precedence. Unless the syntax is explicitly given, +operators are binary. Operators in the same box group left to right (except for +exponentiation, which groups from right to left). + +Note that comparisons, membership tests, and identity tests, all have the same +precedence and have a left-to-right chaining feature as described in the +:ref:`comparisons` section. + + ++-----------------------------------------------+-------------------------------------+ +| Operator | Description | ++===============================================+=====================================+ +| ``:=`` | Assignment expression | ++-----------------------------------------------+-------------------------------------+ +| :keyword:`lambda` | Lambda expression | ++-----------------------------------------------+-------------------------------------+ +| :keyword:`if ` -- :keyword:`!else` | Conditional expression | ++-----------------------------------------------+-------------------------------------+ +| :keyword:`or` | Boolean OR | ++-----------------------------------------------+-------------------------------------+ +| :keyword:`and` | Boolean AND | ++-----------------------------------------------+-------------------------------------+ +| :keyword:`not` ``x`` | Boolean NOT | ++-----------------------------------------------+-------------------------------------+ +| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership | +| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests | +| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | | ++-----------------------------------------------+-------------------------------------+ +| ``|`` | Bitwise OR | ++-----------------------------------------------+-------------------------------------+ +| ``^`` | Bitwise XOR | ++-----------------------------------------------+-------------------------------------+ +| ``&`` | Bitwise AND | ++-----------------------------------------------+-------------------------------------+ +| ``<<``, ``>>`` | Shifts | ++-----------------------------------------------+-------------------------------------+ +| ``+``, ``-`` | Addition and subtraction | ++-----------------------------------------------+-------------------------------------+ +| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix | +| | multiplication, division, floor | +| | division, remainder [#]_ | ++-----------------------------------------------+-------------------------------------+ +| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT | ++-----------------------------------------------+-------------------------------------+ +| ``**`` | Exponentiation [#]_ | ++-----------------------------------------------+-------------------------------------+ +| :keyword:`await` ``x`` | Await expression | ++-----------------------------------------------+-------------------------------------+ +| ``x[index]``, ``x[index:index]``, | Subscription, slicing, | +| ``x(arguments...)``, ``x.attribute`` | call, attribute reference | ++-----------------------------------------------+-------------------------------------+ +| ``(expressions...)``, | Binding or parenthesized | +| | expression, | +| ``[expressions...]``, | list display, | +| ``{key: value...}``, | dictionary display, | +| ``{expressions...}`` | set display | ++-----------------------------------------------+-------------------------------------+ + + +.. rubric:: Footnotes + +.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be + true numerically due to roundoff. For example, and assuming a platform on which + a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 % + 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 + + 1e100``, which is numerically exactly equal to ``1e100``. The function + :func:`math.fmod` returns a result whose sign matches the sign of the + first argument instead, and so returns ``-1e-100`` in this case. Which approach + is more appropriate depends on the application. + +.. [#] If x is very close to an exact integer multiple of y, it's possible for + ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such + cases, Python returns the latter result, in order to preserve that + ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. + +.. [#] The Unicode standard distinguishes between :dfn:`code points` + (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A"). + While most abstract characters in Unicode are only represented using one + code point, there is a number of abstract characters that can in addition be + represented using a sequence of more than one code point. For example, the + abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented + as a single :dfn:`precomposed character` at code position U+00C7, or as a + sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL + LETTER C), followed by a :dfn:`combining character` at code position U+0327 + (COMBINING CEDILLA). + + The comparison operators on strings compare at the level of Unicode code + points. This may be counter-intuitive to humans. For example, + ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings + represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA". + + To compare strings at the level of abstract characters (that is, in a way + intuitive to humans), use :func:`unicodedata.normalize`. + +.. [#] 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. + +.. [#] The ``%`` operator is also used for string formatting; the same + precedence applies. + +.. [#] The power operator ``**`` binds less tightly than an arithmetic or + bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. diff --git a/cpython_2/environment/repo/Doc/reference/grammar.rst b/cpython_2/environment/repo/Doc/reference/grammar.rst new file mode 100644 index 0000000000000000000000000000000000000000..83d0f8532c636662139e5178700ee6d52be68f6e --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/grammar.rst @@ -0,0 +1,7 @@ +Full Grammar specification +========================== + +This is the full Python grammar, as it is read by the parser generator and used +to parse Python source files: + +.. literalinclude:: ../../Grammar/Grammar diff --git a/cpython_2/environment/repo/Doc/reference/import.rst b/cpython_2/environment/repo/Doc/reference/import.rst new file mode 100644 index 0000000000000000000000000000000000000000..4c36e15dc0606351c4fb78ca16936f4772145ac8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/import.rst @@ -0,0 +1,1074 @@ + +.. _importsystem: + +***************** +The import system +***************** + +.. index:: single: import machinery + +Python code in one :term:`module` gains access to the code in another module +by the process of :term:`importing` it. The :keyword:`import` statement is +the most common way of invoking the import machinery, but it is not the only +way. Functions such as :func:`importlib.import_module` and built-in +:func:`__import__` can also be used to invoke the import machinery. + +The :keyword:`import` statement combines two operations; it searches for the +named module, then it binds the results of that search to a name in the local +scope. The search operation of the :keyword:`!import` statement is defined as +a call to the :func:`__import__` function, with the appropriate arguments. +The return value of :func:`__import__` is used to perform the name +binding operation of the :keyword:`!import` statement. See the +:keyword:`!import` statement for the exact details of that name binding +operation. + +A direct call to :func:`__import__` performs only the module search and, if +found, the module creation operation. While certain side-effects may occur, +such as the importing of parent packages, and the updating of various caches +(including :data:`sys.modules`), only the :keyword:`import` statement performs +a name binding operation. + +When an :keyword:`import` statement is executed, the standard builtin +:func:`__import__` function is called. Other mechanisms for invoking the +import system (such as :func:`importlib.import_module`) may choose to bypass +:func:`__import__` and use their own solutions to implement import semantics. + +When a module is first imported, Python searches for the module and if found, +it creates a module object [#fnmo]_, initializing it. If the named module +cannot be found, a :exc:`ModuleNotFoundError` is raised. Python implements various +strategies to search for the named module when the import machinery is +invoked. These strategies can be modified and extended by using various hooks +described in the sections below. + +.. versionchanged:: 3.3 + The import system has been updated to fully implement the second phase + of :pep:`302`. There is no longer any implicit import machinery - the full + import system is exposed through :data:`sys.meta_path`. In addition, + native namespace package support has been implemented (see :pep:`420`). + + +:mod:`importlib` +================ + +The :mod:`importlib` module provides a rich API for interacting with the +import system. For example :func:`importlib.import_module` provides a +recommended, simpler API than built-in :func:`__import__` for invoking the +import machinery. Refer to the :mod:`importlib` library documentation for +additional detail. + + + +Packages +======== + +.. index:: + single: package + +Python has only one type of module object, and all modules are of this type, +regardless of whether the module is implemented in Python, C, or something +else. To help organize modules and provide a naming hierarchy, Python has a +concept of :term:`packages `. + +You can think of packages as the directories on a file system and modules as +files within directories, but don't take this analogy too literally since +packages and modules need not originate from the file system. For the +purposes of this documentation, we'll use this convenient analogy of +directories and files. Like file system directories, packages are organized +hierarchically, and packages may themselves contain subpackages, as well as +regular modules. + +It's important to keep in mind that all packages are modules, but not all +modules are packages. Or put another way, packages are just a special kind of +module. Specifically, any module that contains a ``__path__`` attribute is +considered a package. + +All modules have a name. Subpackage names are separated from their parent +package name by a dot, akin to Python's standard attribute access syntax. Thus +you might have a module called :mod:`sys` and a package called :mod:`email`, +which in turn has a subpackage called :mod:`email.mime` and a module within +that subpackage called :mod:`email.mime.text`. + + +Regular packages +---------------- + +.. index:: + pair: package; regular + +Python defines two types of packages, :term:`regular packages ` and :term:`namespace packages `. Regular +packages are traditional packages as they existed in Python 3.2 and earlier. +A regular package is typically implemented as a directory containing an +``__init__.py`` file. When a regular package is imported, this +``__init__.py`` file is implicitly executed, and the objects it defines are +bound to names in the package's namespace. The ``__init__.py`` file can +contain the same Python code that any other module can contain, and Python +will add some additional attributes to the module when it is imported. + +For example, the following file system layout defines a top level ``parent`` +package with three subpackages:: + + parent/ + __init__.py + one/ + __init__.py + two/ + __init__.py + three/ + __init__.py + +Importing ``parent.one`` will implicitly execute ``parent/__init__.py`` and +``parent/one/__init__.py``. Subsequent imports of ``parent.two`` or +``parent.three`` will execute ``parent/two/__init__.py`` and +``parent/three/__init__.py`` respectively. + + +Namespace packages +------------------ + +.. index:: + pair: package; namespace + pair: package; portion + +A namespace package is a composite of various :term:`portions `, +where each portion contributes a subpackage to the parent package. Portions +may reside in different locations on the file system. Portions may also be +found in zip files, on the network, or anywhere else that Python searches +during import. Namespace packages may or may not correspond directly to +objects on the file system; they may be virtual modules that have no concrete +representation. + +Namespace packages do not use an ordinary list for their ``__path__`` +attribute. They instead use a custom iterable type which will automatically +perform a new search for package portions on the next import attempt within +that package if the path of their parent package (or :data:`sys.path` for a +top level package) changes. + +With namespace packages, there is no ``parent/__init__.py`` file. In fact, +there may be multiple ``parent`` directories found during import search, where +each one is provided by a different portion. Thus ``parent/one`` may not be +physically located next to ``parent/two``. In this case, Python will create a +namespace package for the top-level ``parent`` package whenever it or one of +its subpackages is imported. + +See also :pep:`420` for the namespace package specification. + + +Searching +========= + +To begin the search, Python needs the :term:`fully qualified ` +name of the module (or package, but for the purposes of this discussion, the +difference is immaterial) being imported. This name may come from various +arguments to the :keyword:`import` statement, or from the parameters to the +:func:`importlib.import_module` or :func:`__import__` functions. + +This name will be used in various phases of the import search, and it may be +the dotted path to a submodule, e.g. ``foo.bar.baz``. In this case, Python +first tries to import ``foo``, then ``foo.bar``, and finally ``foo.bar.baz``. +If any of the intermediate imports fail, a :exc:`ModuleNotFoundError` is raised. + + +The module cache +---------------- + +.. index:: + single: sys.modules + +The first place checked during import search is :data:`sys.modules`. This +mapping serves as a cache of all modules that have been previously imported, +including the intermediate paths. So if ``foo.bar.baz`` was previously +imported, :data:`sys.modules` will contain entries for ``foo``, ``foo.bar``, +and ``foo.bar.baz``. Each key will have as its value the corresponding module +object. + +During import, the module name is looked up in :data:`sys.modules` and if +present, the associated value is the module satisfying the import, and the +process completes. However, if the value is ``None``, then a +:exc:`ModuleNotFoundError` is raised. If the module name is missing, Python will +continue searching for the module. + +:data:`sys.modules` is writable. Deleting a key may not destroy the +associated module (as other modules may hold references to it), +but it will invalidate the cache entry for the named module, causing +Python to search anew for the named module upon its next +import. The key can also be assigned to ``None``, forcing the next import +of the module to result in a :exc:`ModuleNotFoundError`. + +Beware though, as if you keep a reference to the module object, +invalidate its cache entry in :data:`sys.modules`, and then re-import the +named module, the two module objects will *not* be the same. By contrast, +:func:`importlib.reload` will reuse the *same* module object, and simply +reinitialise the module contents by rerunning the module's code. + + +.. _finders-and-loaders: + +Finders and loaders +------------------- + +.. index:: + single: finder + single: loader + single: module spec + +If the named module is not found in :data:`sys.modules`, then Python's import +protocol is invoked to find and load the module. This protocol consists of +two conceptual objects, :term:`finders ` and :term:`loaders `. +A finder's job is to determine whether it can find the named module using +whatever strategy it knows about. Objects that implement both of these +interfaces are referred to as :term:`importers ` - they return +themselves when they find that they can load the requested module. + +Python includes a number of default finders and importers. The first one +knows how to locate built-in modules, and the second knows how to locate +frozen modules. A third default finder searches an :term:`import path` +for modules. The :term:`import path` is a list of locations that may +name file system paths or zip files. It can also be extended to search +for any locatable resource, such as those identified by URLs. + +The import machinery is extensible, so new finders can be added to extend the +range and scope of module searching. + +Finders do not actually load modules. If they can find the named module, they +return a :dfn:`module spec`, an encapsulation of the module's import-related +information, which the import machinery then uses when loading the module. + +The following sections describe the protocol for finders and loaders in more +detail, including how you can create and register new ones to extend the +import machinery. + +.. versionchanged:: 3.4 + In previous versions of Python, finders returned :term:`loaders ` + directly, whereas now they return module specs which *contain* loaders. + Loaders are still used during import but have fewer responsibilities. + +Import hooks +------------ + +.. index:: + single: import hooks + single: meta hooks + single: path hooks + pair: hooks; import + pair: hooks; meta + pair: hooks; path + +The import machinery is designed to be extensible; the primary mechanism for +this are the *import hooks*. There are two types of import hooks: *meta +hooks* and *import path hooks*. + +Meta hooks are called at the start of import processing, before any other +import processing has occurred, other than :data:`sys.modules` cache look up. +This allows meta hooks to override :data:`sys.path` processing, frozen +modules, or even built-in modules. Meta hooks are registered by adding new +finder objects to :data:`sys.meta_path`, as described below. + +Import path hooks are called as part of :data:`sys.path` (or +``package.__path__``) processing, at the point where their associated path +item is encountered. Import path hooks are registered by adding new callables +to :data:`sys.path_hooks` as described below. + + +The meta path +------------- + +.. index:: + single: sys.meta_path + pair: finder; find_spec + +When the named module is not found in :data:`sys.modules`, Python next +searches :data:`sys.meta_path`, which contains a list of meta path finder +objects. These finders are queried in order to see if they know how to handle +the named module. Meta path finders must implement a method called +:meth:`~importlib.abc.MetaPathFinder.find_spec()` which takes three arguments: +a name, an import path, and (optionally) a target module. The meta path +finder can use any strategy it wants to determine whether it can handle +the named module or not. + +If the meta path finder knows how to handle the named module, it returns a +spec object. If it cannot handle the named module, it returns ``None``. If +:data:`sys.meta_path` processing reaches the end of its list without returning +a spec, then a :exc:`ModuleNotFoundError` is raised. Any other exceptions +raised are simply propagated up, aborting the import process. + +The :meth:`~importlib.abc.MetaPathFinder.find_spec()` method of meta path +finders is called with two or three arguments. The first is the fully +qualified name of the module being imported, for example ``foo.bar.baz``. +The second argument is the path entries to use for the module search. For +top-level modules, the second argument is ``None``, but for submodules or +subpackages, the second argument is the value of the parent package's +``__path__`` attribute. If the appropriate ``__path__`` attribute cannot +be accessed, a :exc:`ModuleNotFoundError` is raised. The third argument +is an existing module object that will be the target of loading later. +The import system passes in a target module only during reload. + +The meta path may be traversed multiple times for a single import request. +For example, assuming none of the modules involved has already been cached, +importing ``foo.bar.baz`` will first perform a top level import, calling +``mpf.find_spec("foo", None, None)`` on each meta path finder (``mpf``). After +``foo`` has been imported, ``foo.bar`` will be imported by traversing the +meta path a second time, calling +``mpf.find_spec("foo.bar", foo.__path__, None)``. Once ``foo.bar`` has been +imported, the final traversal will call +``mpf.find_spec("foo.bar.baz", foo.bar.__path__, None)``. + +Some meta path finders only support top level imports. These importers will +always return ``None`` when anything other than ``None`` is passed as the +second argument. + +Python's default :data:`sys.meta_path` has three meta path finders, one that +knows how to import built-in modules, one that knows how to import frozen +modules, and one that knows how to import modules from an :term:`import path` +(i.e. the :term:`path based finder`). + +.. versionchanged:: 3.4 + The :meth:`~importlib.abc.MetaPathFinder.find_spec` method of meta path + finders replaced :meth:`~importlib.abc.MetaPathFinder.find_module`, which + is now deprecated. While it will continue to work without change, the + import machinery will try it only if the finder does not implement + ``find_spec()``. + + +Loading +======= + +If and when a module spec is found, the import machinery will use it (and +the loader it contains) when loading the module. Here is an approximation +of what happens during the loading portion of import:: + + module = None + if spec.loader is not None and hasattr(spec.loader, 'create_module'): + # It is assumed 'exec_module' will also be defined on the loader. + module = spec.loader.create_module(spec) + if module is None: + module = ModuleType(spec.name) + # The import-related module attributes get set here: + _init_module_attrs(spec, module) + + if spec.loader is None: + # unsupported + raise ImportError + if spec.origin is None and spec.submodule_search_locations is not None: + # namespace package + sys.modules[spec.name] = module + elif not hasattr(spec.loader, 'exec_module'): + module = spec.loader.load_module(spec.name) + # Set __loader__ and __package__ if missing. + else: + sys.modules[spec.name] = module + try: + spec.loader.exec_module(module) + except BaseException: + try: + del sys.modules[spec.name] + except KeyError: + pass + raise + return sys.modules[spec.name] + +Note the following details: + + * If there is an existing module object with the given name in + :data:`sys.modules`, import will have already returned it. + + * The module will exist in :data:`sys.modules` before the loader + executes the module code. This is crucial because the module code may + (directly or indirectly) import itself; adding it to :data:`sys.modules` + beforehand prevents unbounded recursion in the worst case and multiple + loading in the best. + + * If loading fails, the failing module -- and only the failing module -- + gets removed from :data:`sys.modules`. Any module already in the + :data:`sys.modules` cache, and any module that was successfully loaded + as a side-effect, must remain in the cache. This contrasts with + reloading where even the failing module is left in :data:`sys.modules`. + + * After the module is created but before execution, the import machinery + sets the import-related module attributes ("_init_module_attrs" in + the pseudo-code example above), as summarized in a + :ref:`later section `. + + * Module execution is the key moment of loading in which the module's + namespace gets populated. Execution is entirely delegated to the + loader, which gets to decide what gets populated and how. + + * The module created during loading and passed to exec_module() may + not be the one returned at the end of import [#fnlo]_. + +.. versionchanged:: 3.4 + The import system has taken over the boilerplate responsibilities of + loaders. These were previously performed by the + :meth:`importlib.abc.Loader.load_module` method. + +Loaders +------- + +Module loaders provide the critical function of loading: module execution. +The import machinery calls the :meth:`importlib.abc.Loader.exec_module` +method with a single argument, the module object to execute. Any value +returned from :meth:`~importlib.abc.Loader.exec_module` is ignored. + +Loaders must satisfy the following requirements: + + * If the module is a Python module (as opposed to a built-in module or a + dynamically loaded extension), the loader should execute the module's code + in the module's global name space (``module.__dict__``). + + * If the loader cannot execute the module, it should raise an + :exc:`ImportError`, although any other exception raised during + :meth:`~importlib.abc.Loader.exec_module` will be propagated. + +In many cases, the finder and loader can be the same object; in such cases the +:meth:`~importlib.abc.MetaPathFinder.find_spec` method would just return a +spec with the loader set to ``self``. + +Module loaders may opt in to creating the module object during loading +by implementing a :meth:`~importlib.abc.Loader.create_module` method. +It takes one argument, the module spec, and returns the new module object +to use during loading. ``create_module()`` does not need to set any attributes +on the module object. If the method returns ``None``, the +import machinery will create the new module itself. + +.. versionadded:: 3.4 + The :meth:`~importlib.abc.Loader.create_module` method of loaders. + +.. versionchanged:: 3.4 + The :meth:`~importlib.abc.Loader.load_module` method was replaced by + :meth:`~importlib.abc.Loader.exec_module` and the import + machinery assumed all the boilerplate responsibilities of loading. + + For compatibility with existing loaders, the import machinery will use + the ``load_module()`` method of loaders if it exists and the loader does + not also implement ``exec_module()``. However, ``load_module()`` has been + deprecated and loaders should implement ``exec_module()`` instead. + + The ``load_module()`` method must implement all the boilerplate loading + functionality described above in addition to executing the module. All + the same constraints apply, with some additional clarification: + + * If there is an existing module object with the given name in + :data:`sys.modules`, the loader must use that existing module. + (Otherwise, :func:`importlib.reload` will not work correctly.) If the + named module does not exist in :data:`sys.modules`, the loader + must create a new module object and add it to :data:`sys.modules`. + + * The module *must* exist in :data:`sys.modules` before the loader + executes the module code, to prevent unbounded recursion or multiple + loading. + + * If loading fails, the loader must remove any modules it has inserted + into :data:`sys.modules`, but it must remove **only** the failing + module(s), and only if the loader itself has loaded the module(s) + explicitly. + +.. versionchanged:: 3.5 + A :exc:`DeprecationWarning` is raised when ``exec_module()`` is defined but + ``create_module()`` is not. + +.. versionchanged:: 3.6 + An :exc:`ImportError` is raised when ``exec_module()`` is defined but + ``create_module()`` is not. + +Submodules +---------- + +When a submodule is loaded using any mechanism (e.g. ``importlib`` APIs, the +``import`` or ``import-from`` statements, or built-in ``__import__()``) a +binding is placed in the parent module's namespace to the submodule object. +For example, if package ``spam`` has a submodule ``foo``, after importing +``spam.foo``, ``spam`` will have an attribute ``foo`` which is bound to the +submodule. Let's say you have the following directory structure:: + + spam/ + __init__.py + foo.py + bar.py + +and ``spam/__init__.py`` has the following lines in it:: + + from .foo import Foo + from .bar import Bar + +then executing the following puts a name binding to ``foo`` and ``bar`` in the +``spam`` module:: + + >>> import spam + >>> spam.foo + + >>> spam.bar + + +Given Python's familiar name binding rules this might seem surprising, but +it's actually a fundamental feature of the import system. The invariant +holding is that if you have ``sys.modules['spam']`` and +``sys.modules['spam.foo']`` (as you would after the above import), the latter +must appear as the ``foo`` attribute of the former. + +Module spec +----------- + +The import machinery uses a variety of information about each module +during import, especially before loading. Most of the information is +common to all modules. The purpose of a module's spec is to encapsulate +this import-related information on a per-module basis. + +Using a spec during import allows state to be transferred between import +system components, e.g. between the finder that creates the module spec +and the loader that executes it. Most importantly, it allows the +import machinery to perform the boilerplate operations of loading, +whereas without a module spec the loader had that responsibility. + +The module's spec is exposed as the ``__spec__`` attribute on a module object. +See :class:`~importlib.machinery.ModuleSpec` for details on the contents of +the module spec. + +.. versionadded:: 3.4 + +.. _import-mod-attrs: + +Import-related module attributes +-------------------------------- + +The import machinery fills in these attributes on each module object +during loading, based on the module's spec, before the loader executes +the module. + +.. attribute:: __name__ + + The ``__name__`` attribute must be set to the fully-qualified name of + the module. This name is used to uniquely identify the module in + the import system. + +.. attribute:: __loader__ + + The ``__loader__`` attribute must be set to the loader object that + the import machinery used when loading the module. This is mostly + for introspection, but can be used for additional loader-specific + functionality, for example getting data associated with a loader. + +.. attribute:: __package__ + + The module's ``__package__`` attribute must be set. Its value must + be a string, but it can be the same value as its ``__name__``. When + the module is a package, its ``__package__`` value should be set to + its ``__name__``. When the module is not a package, ``__package__`` + should be set to the empty string for top-level modules, or for + submodules, to the parent package's name. See :pep:`366` for further + details. + + This attribute is used instead of ``__name__`` to calculate explicit + relative imports for main modules, as defined in :pep:`366`. It is + expected to have the same value as ``__spec__.parent``. + + .. versionchanged:: 3.6 + The value of ``__package__`` is expected to be the same as + ``__spec__.parent``. + +.. attribute:: __spec__ + + The ``__spec__`` attribute must be set to the module spec that was + used when importing the module. Setting ``__spec__`` + appropriately applies equally to :ref:`modules initialized during + interpreter startup `. The one exception is ``__main__``, + where ``__spec__`` is :ref:`set to None in some cases `. + + When ``__package__`` is not defined, ``__spec__.parent`` is used as + a fallback. + + .. versionadded:: 3.4 + + .. versionchanged:: 3.6 + ``__spec__.parent`` is used as a fallback when ``__package__`` is + not defined. + +.. attribute:: __path__ + + If the module is a package (either regular or namespace), the module + object's ``__path__`` attribute must be set. The value must be + iterable, but may be empty if ``__path__`` has no further significance. + If ``__path__`` is not empty, it must produce strings when iterated + over. More details on the semantics of ``__path__`` are given + :ref:`below `. + + Non-package modules should not have a ``__path__`` attribute. + +.. attribute:: __file__ +.. attribute:: __cached__ + + ``__file__`` is optional. If set, this attribute's value must be a + string. The import system may opt to leave ``__file__`` unset if it + has no semantic meaning (e.g. a module loaded from a database). + + If ``__file__`` is set, it may also be appropriate to set the + ``__cached__`` attribute which is the path to any compiled version of + the code (e.g. byte-compiled file). The file does not need to exist + to set this attribute; the path can simply point to where the + compiled file would exist (see :pep:`3147`). + + It is also appropriate to set ``__cached__`` when ``__file__`` is not + set. However, that scenario is quite atypical. Ultimately, the + loader is what makes use of ``__file__`` and/or ``__cached__``. So + if a loader can load from a cached module but otherwise does not load + from a file, that atypical scenario may be appropriate. + +.. _package-path-rules: + +module.__path__ +--------------- + +By definition, if a module has a ``__path__`` attribute, it is a package. + +A package's ``__path__`` attribute is used during imports of its subpackages. +Within the import machinery, it functions much the same as :data:`sys.path`, +i.e. providing a list of locations to search for modules during import. +However, ``__path__`` is typically much more constrained than +:data:`sys.path`. + +``__path__`` must be an iterable of strings, but it may be empty. +The same rules used for :data:`sys.path` also apply to a package's +``__path__``, and :data:`sys.path_hooks` (described below) are +consulted when traversing a package's ``__path__``. + +A package's ``__init__.py`` file may set or alter the package's ``__path__`` +attribute, and this was typically the way namespace packages were implemented +prior to :pep:`420`. With the adoption of :pep:`420`, namespace packages no +longer need to supply ``__init__.py`` files containing only ``__path__`` +manipulation code; the import machinery automatically sets ``__path__`` +correctly for the namespace package. + +Module reprs +------------ + +By default, all modules have a usable repr, however depending on the +attributes set above, and in the module's spec, you can more explicitly +control the repr of module objects. + +If the module has a spec (``__spec__``), the import machinery will try +to generate a repr from it. If that fails or there is no spec, the import +system will craft a default repr using whatever information is available +on the module. It will try to use the ``module.__name__``, +``module.__file__``, and ``module.__loader__`` as input into the repr, +with defaults for whatever information is missing. + +Here are the exact rules used: + + * If the module has a ``__spec__`` attribute, the information in the spec + is used to generate the repr. The "name", "loader", "origin", and + "has_location" attributes are consulted. + + * If the module has a ``__file__`` attribute, this is used as part of the + module's repr. + + * If the module has no ``__file__`` but does have a ``__loader__`` that is not + ``None``, then the loader's repr is used as part of the module's repr. + + * Otherwise, just use the module's ``__name__`` in the repr. + +.. versionchanged:: 3.4 + Use of :meth:`loader.module_repr() ` + has been deprecated and the module spec is now used by the import + machinery to generate a module repr. + + For backward compatibility with Python 3.3, the module repr will be + generated by calling the loader's + :meth:`~importlib.abc.Loader.module_repr` method, if defined, before + trying either approach described above. However, the method is deprecated. + +.. _pyc-invalidation: + +Cached bytecode invalidation +---------------------------- + +Before Python loads cached bytecode from ``.pyc`` file, it checks whether the +cache is up-to-date with the source ``.py`` file. By default, Python does this +by storing the source's last-modified timestamp and size in the cache file when +writing it. At runtime, the import system then validates the cache file by +checking the stored metadata in the cache file against the source's +metadata. + +Python also supports "hash-based" cache files, which store a hash of the source +file's contents rather than its metadata. There are two variants of hash-based +``.pyc`` files: checked and unchecked. For checked hash-based ``.pyc`` files, +Python validates the cache file by hashing the source file and comparing the +resulting hash with the hash in the cache file. If a checked hash-based cache +file is found to be invalid, Python regenerates it and writes a new checked +hash-based cache file. For unchecked hash-based ``.pyc`` files, Python simply +assumes the cache file is valid if it exists. Hash-based ``.pyc`` files +validation behavior may be overridden with the :option:`--check-hash-based-pycs` +flag. + +.. versionchanged:: 3.7 + Added hash-based ``.pyc`` files. Previously, Python only supported + timestamp-based invalidation of bytecode caches. + + +The Path Based Finder +===================== + +.. index:: + single: path based finder + +As mentioned previously, Python comes with several default meta path finders. +One of these, called the :term:`path based finder` +(:class:`~importlib.machinery.PathFinder`), searches an :term:`import path`, +which contains a list of :term:`path entries `. Each path +entry names a location to search for modules. + +The path based finder itself doesn't know how to import anything. Instead, it +traverses the individual path entries, associating each of them with a +path entry finder that knows how to handle that particular kind of path. + +The default set of path entry finders implement all the semantics for finding +modules on the file system, handling special file types such as Python source +code (``.py`` files), Python byte code (``.pyc`` files) and +shared libraries (e.g. ``.so`` files). When supported by the :mod:`zipimport` +module in the standard library, the default path entry finders also handle +loading all of these file types (other than shared libraries) from zipfiles. + +Path entries need not be limited to file system locations. They can refer to +URLs, database queries, or any other location that can be specified as a +string. + +The path based finder provides additional hooks and protocols so that you +can extend and customize the types of searchable path entries. For example, +if you wanted to support path entries as network URLs, you could write a hook +that implements HTTP semantics to find modules on the web. This hook (a +callable) would return a :term:`path entry finder` supporting the protocol +described below, which was then used to get a loader for the module from the +web. + +A word of warning: this section and the previous both use the term *finder*, +distinguishing between them by using the terms :term:`meta path finder` and +:term:`path entry finder`. These two types of finders are very similar, +support similar protocols, and function in similar ways during the import +process, but it's important to keep in mind that they are subtly different. +In particular, meta path finders operate at the beginning of the import +process, as keyed off the :data:`sys.meta_path` traversal. + +By contrast, path entry finders are in a sense an implementation detail +of the path based finder, and in fact, if the path based finder were to be +removed from :data:`sys.meta_path`, none of the path entry finder semantics +would be invoked. + + +Path entry finders +------------------ + +.. index:: + single: sys.path + single: sys.path_hooks + single: sys.path_importer_cache + single: PYTHONPATH + +The :term:`path based finder` is responsible for finding and loading +Python modules and packages whose location is specified with a string +:term:`path entry`. Most path entries name locations in the file system, +but they need not be limited to this. + +As a meta path finder, the :term:`path based finder` implements the +:meth:`~importlib.abc.MetaPathFinder.find_spec` protocol previously +described, however it exposes additional hooks that can be used to +customize how modules are found and loaded from the :term:`import path`. + +Three variables are used by the :term:`path based finder`, :data:`sys.path`, +:data:`sys.path_hooks` and :data:`sys.path_importer_cache`. The ``__path__`` +attributes on package objects are also used. These provide additional ways +that the import machinery can be customized. + +:data:`sys.path` contains a list of strings providing search locations for +modules and packages. It is initialized from the :data:`PYTHONPATH` +environment variable and various other installation- and +implementation-specific defaults. Entries in :data:`sys.path` can name +directories on the file system, zip files, and potentially other "locations" +(see the :mod:`site` module) that should be searched for modules, such as +URLs, or database queries. Only strings and bytes should be present on +:data:`sys.path`; all other data types are ignored. The encoding of bytes +entries is determined by the individual :term:`path entry finders `. + +The :term:`path based finder` is a :term:`meta path finder`, so the import +machinery begins the :term:`import path` search by calling the path +based finder's :meth:`~importlib.machinery.PathFinder.find_spec` method as +described previously. When the ``path`` argument to +:meth:`~importlib.machinery.PathFinder.find_spec` is given, it will be a +list of string paths to traverse - typically a package's ``__path__`` +attribute for an import within that package. If the ``path`` argument is +``None``, this indicates a top level import and :data:`sys.path` is used. + +The path based finder iterates over every entry in the search path, and +for each of these, looks for an appropriate :term:`path entry finder` +(:class:`~importlib.abc.PathEntryFinder`) for the +path entry. Because this can be an expensive operation (e.g. there may be +`stat()` call overheads for this search), the path based finder maintains +a cache mapping path entries to path entry finders. This cache is maintained +in :data:`sys.path_importer_cache` (despite the name, this cache actually +stores finder objects rather than being limited to :term:`importer` objects). +In this way, the expensive search for a particular :term:`path entry` +location's :term:`path entry finder` need only be done once. User code is +free to remove cache entries from :data:`sys.path_importer_cache` forcing +the path based finder to perform the path entry search again [#fnpic]_. + +If the path entry is not present in the cache, the path based finder iterates +over every callable in :data:`sys.path_hooks`. Each of the :term:`path entry +hooks ` in this list is called with a single argument, the +path entry to be searched. This callable may either return a :term:`path +entry finder` that can handle the path entry, or it may raise +:exc:`ImportError`. An :exc:`ImportError` is used by the path based finder to +signal that the hook cannot find a :term:`path entry finder` +for that :term:`path entry`. The +exception is ignored and :term:`import path` iteration continues. The hook +should expect either a string or bytes object; the encoding of bytes objects +is up to the hook (e.g. it may be a file system encoding, UTF-8, or something +else), and if the hook cannot decode the argument, it should raise +:exc:`ImportError`. + +If :data:`sys.path_hooks` iteration ends with no :term:`path entry finder` +being returned, then the path based finder's +:meth:`~importlib.machinery.PathFinder.find_spec` method will store ``None`` +in :data:`sys.path_importer_cache` (to indicate that there is no finder for +this path entry) and return ``None``, indicating that this +:term:`meta path finder` could not find the module. + +If a :term:`path entry finder` *is* returned by one of the :term:`path entry +hook` callables on :data:`sys.path_hooks`, then the following protocol is used +to ask the finder for a module spec, which is then used when loading the +module. + +The current working directory -- denoted by an empty string -- is handled +slightly differently from other entries on :data:`sys.path`. First, if the +current working directory is found to not exist, no value is stored in +:data:`sys.path_importer_cache`. Second, the value for the current working +directory is looked up fresh for each module lookup. Third, the path used for +:data:`sys.path_importer_cache` and returned by +:meth:`importlib.machinery.PathFinder.find_spec` will be the actual current +working directory and not the empty string. + +Path entry finder protocol +-------------------------- + +In order to support imports of modules and initialized packages and also to +contribute portions to namespace packages, path entry finders must implement +the :meth:`~importlib.abc.PathEntryFinder.find_spec` method. + +:meth:`~importlib.abc.PathEntryFinder.find_spec` takes two arguments: the +fully qualified name of the module being imported, and the (optional) target +module. ``find_spec()`` returns a fully populated spec for the module. +This spec will always have "loader" set (with one exception). + +To indicate to the import machinery that the spec represents a namespace +:term:`portion`, the path entry finder sets "loader" on the spec to +``None`` and "submodule_search_locations" to a list containing the +portion. + +.. versionchanged:: 3.4 + :meth:`~importlib.abc.PathEntryFinder.find_spec` replaced + :meth:`~importlib.abc.PathEntryFinder.find_loader` and + :meth:`~importlib.abc.PathEntryFinder.find_module`, both of which + are now deprecated, but will be used if ``find_spec()`` is not defined. + + Older path entry finders may implement one of these two deprecated methods + instead of ``find_spec()``. The methods are still respected for the + sake of backward compatibility. However, if ``find_spec()`` is + implemented on the path entry finder, the legacy methods are ignored. + + :meth:`~importlib.abc.PathEntryFinder.find_loader` takes one argument, the + fully qualified name of the module being imported. ``find_loader()`` + returns a 2-tuple where the first item is the loader and the second item + is a namespace :term:`portion`. When the first item (i.e. the loader) is + ``None``, this means that while the path entry finder does not have a + loader for the named module, it knows that the path entry contributes to + a namespace portion for the named module. This will almost always be the + case where Python is asked to import a namespace package that has no + physical presence on the file system. When a path entry finder returns + ``None`` for the loader, the second item of the 2-tuple return value must + be a sequence, although it can be empty. + + If ``find_loader()`` returns a non-``None`` loader value, the portion is + ignored and the loader is returned from the path based finder, terminating + the search through the path entries. + + For backwards compatibility with other implementations of the import + protocol, many path entry finders also support the same, + traditional ``find_module()`` method that meta path finders support. + However path entry finder ``find_module()`` methods are never called + with a ``path`` argument (they are expected to record the appropriate + path information from the initial call to the path hook). + + The ``find_module()`` method on path entry finders is deprecated, + as it does not allow the path entry finder to contribute portions to + namespace packages. If both ``find_loader()`` and ``find_module()`` + exist on a path entry finder, the import system will always call + ``find_loader()`` in preference to ``find_module()``. + + +Replacing the standard import system +==================================== + +The most reliable mechanism for replacing the entire import system is to +delete the default contents of :data:`sys.meta_path`, replacing them +entirely with a custom meta path hook. + +If it is acceptable to only alter the behaviour of import statements +without affecting other APIs that access the import system, then replacing +the builtin :func:`__import__` function may be sufficient. This technique +may also be employed at the module level to only alter the behaviour of +import statements within that module. + +To selectively prevent the import of some modules from a hook early on the +meta path (rather than disabling the standard import system entirely), +it is sufficient to raise :exc:`ModuleNotFoundError` directly from +:meth:`~importlib.abc.MetaPathFinder.find_spec` instead of returning +``None``. The latter indicates that the meta path search should continue, +while raising an exception terminates it immediately. + +.. _relativeimports: + +Package Relative Imports +======================== + +Relative imports use leading dots. A single leading dot indicates a relative +import, starting with the current package. Two or more leading dots indicate a +relative import to the parent(s) of the current package, one level per dot +after the first. For example, given the following package layout:: + + package/ + __init__.py + subpackage1/ + __init__.py + moduleX.py + moduleY.py + subpackage2/ + __init__.py + moduleZ.py + moduleA.py + +In either ``subpackage1/moduleX.py`` or ``subpackage1/__init__.py``, +the following are valid relative imports:: + + from .moduleY import spam + from .moduleY import spam as ham + from . import moduleY + from ..subpackage1 import moduleY + from ..subpackage2.moduleZ import eggs + from ..moduleA import foo + +Absolute imports may use either the ``import <>`` or ``from <> import <>`` +syntax, but relative imports may only use the second form; the reason +for this is that:: + + import XXX.YYY.ZZZ + +should expose ``XXX.YYY.ZZZ`` as a usable expression, but .moduleY is +not a valid expression. + + +Special considerations for __main__ +=================================== + +The :mod:`__main__` module is a special case relative to Python's import +system. As noted :ref:`elsewhere `, the ``__main__`` module +is directly initialized at interpreter startup, much like :mod:`sys` and +:mod:`builtins`. However, unlike those two, it doesn't strictly +qualify as a built-in module. This is because the manner in which +``__main__`` is initialized depends on the flags and other options with +which the interpreter is invoked. + +.. _main_spec: + +__main__.__spec__ +----------------- + +Depending on how :mod:`__main__` is initialized, ``__main__.__spec__`` +gets set appropriately or to ``None``. + +When Python is started with the :option:`-m` option, ``__spec__`` is set +to the module spec of the corresponding module or package. ``__spec__`` is +also populated when the ``__main__`` module is loaded as part of executing a +directory, zipfile or other :data:`sys.path` entry. + +In :ref:`the remaining cases ` +``__main__.__spec__`` is set to ``None``, as the code used to populate the +:mod:`__main__` does not correspond directly with an importable module: + +- interactive prompt +- :option:`-c` option +- running from stdin +- running directly from a source or bytecode file + +Note that ``__main__.__spec__`` is always ``None`` in the last case, +*even if* the file could technically be imported directly as a module +instead. Use the :option:`-m` switch if valid module metadata is desired +in :mod:`__main__`. + +Note also that even when ``__main__`` corresponds with an importable module +and ``__main__.__spec__`` is set accordingly, they're still considered +*distinct* modules. This is due to the fact that blocks guarded by +``if __name__ == "__main__":`` checks only execute when the module is used +to populate the ``__main__`` namespace, and not during normal import. + + +Open issues +=========== + +XXX It would be really nice to have a diagram. + +XXX * (import_machinery.rst) how about a section devoted just to the +attributes of modules and packages, perhaps expanding upon or supplanting the +related entries in the data model reference page? + +XXX runpy, pkgutil, et al in the library manual should all get "See Also" +links at the top pointing to the new import system section. + +XXX Add more explanation regarding the different ways in which +``__main__`` is initialized? + +XXX Add more info on ``__main__`` quirks/pitfalls (i.e. copy from +:pep:`395`). + + +References +========== + +The import machinery has evolved considerably since Python's early days. The +original `specification for packages +`_ is still available to read, +although some details have changed since the writing of that document. + +The original specification for :data:`sys.meta_path` was :pep:`302`, with +subsequent extension in :pep:`420`. + +:pep:`420` introduced :term:`namespace packages ` for +Python 3.3. :pep:`420` also introduced the :meth:`find_loader` protocol as an +alternative to :meth:`find_module`. + +:pep:`366` describes the addition of the ``__package__`` attribute for +explicit relative imports in main modules. + +:pep:`328` introduced absolute and explicit relative imports and initially +proposed ``__name__`` for semantics :pep:`366` would eventually specify for +``__package__``. + +:pep:`338` defines executing modules as scripts. + +:pep:`451` adds the encapsulation of per-module import state in spec +objects. It also off-loads most of the boilerplate responsibilities of +loaders back onto the import machinery. These changes allow the +deprecation of several APIs in the import system and also addition of new +methods to finders and loaders. + +.. rubric:: Footnotes + +.. [#fnmo] See :class:`types.ModuleType`. + +.. [#fnlo] The importlib implementation avoids using the return value + directly. Instead, it gets the module object by looking the module name up + in :data:`sys.modules`. The indirect effect of this is that an imported + module may replace itself in :data:`sys.modules`. This is + implementation-specific behavior that is not guaranteed to work in other + Python implementations. + +.. [#fnpic] In legacy code, it is possible to find instances of + :class:`imp.NullImporter` in the :data:`sys.path_importer_cache`. It + is recommended that code be changed to use ``None`` instead. See + :ref:`portingpythoncode` for more details. diff --git a/cpython_2/environment/repo/Doc/reference/index.rst b/cpython_2/environment/repo/Doc/reference/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..a66673b17246d7be0376f12120cabd9c15e67b2d --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/index.rst @@ -0,0 +1,29 @@ +.. _reference-index: + +################################# + The Python Language Reference +################################# + +This reference manual describes the syntax and "core semantics" of the +language. It is terse, but attempts to be exact and complete. The semantics of +non-essential built-in object types and of the built-in functions and modules +are described in :ref:`library-index`. For an informal introduction to the +language, see :ref:`tutorial-index`. For C or C++ programmers, two additional +manuals exist: :ref:`extending-index` describes the high-level picture of how to +write a Python extension module, and the :ref:`c-api-index` describes the +interfaces available to C/C++ programmers in detail. + +.. toctree:: + :maxdepth: 2 + :numbered: + + introduction.rst + lexical_analysis.rst + datamodel.rst + executionmodel.rst + import.rst + expressions.rst + simple_stmts.rst + compound_stmts.rst + toplevel_components.rst + grammar.rst diff --git a/cpython_2/environment/repo/Doc/reference/introduction.rst b/cpython_2/environment/repo/Doc/reference/introduction.rst new file mode 100644 index 0000000000000000000000000000000000000000..bb7e3906dba6072a83bbeeda437de40dba2d06b0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/introduction.rst @@ -0,0 +1,132 @@ + +.. _introduction: + +************ +Introduction +************ + +This reference manual describes the Python programming language. It is not +intended as a tutorial. + +While I am trying to be as precise as possible, I chose to use English rather +than formal specifications for everything except syntax and lexical analysis. +This should make the document more understandable to the average reader, but +will leave room for ambiguities. Consequently, if you were coming from Mars and +tried to re-implement Python from this document alone, you might have to guess +things and in fact you would probably end up implementing quite a different +language. On the other hand, if you are using Python and wonder what the precise +rules about a particular area of the language are, you should definitely be able +to find them here. If you would like to see a more formal definition of the +language, maybe you could volunteer your time --- or invent a cloning machine +:-). + +It is dangerous to add too many implementation details to a language reference +document --- the implementation may change, and other implementations of the +same language may work differently. On the other hand, CPython is the one +Python implementation in widespread use (although alternate implementations +continue to gain support), and its particular quirks are sometimes worth being +mentioned, especially where the implementation imposes additional limitations. +Therefore, you'll find short "implementation notes" sprinkled throughout the +text. + +Every Python implementation comes with a number of built-in and standard +modules. These are documented in :ref:`library-index`. A few built-in modules +are mentioned when they interact in a significant way with the language +definition. + + +.. _implementations: + +Alternate Implementations +========================= + +Though there is one Python implementation which is by far the most popular, +there are some alternate implementations which are of particular interest to +different audiences. + +Known implementations include: + +CPython + This is the original and most-maintained implementation of Python, written in C. + New language features generally appear here first. + +Jython + Python implemented in Java. This implementation can be used as a scripting + language for Java applications, or can be used to create applications using the + Java class libraries. It is also often used to create tests for Java libraries. + More information can be found at `the Jython website `_. + +Python for .NET + This implementation actually uses the CPython implementation, but is a managed + .NET application and makes .NET libraries available. It was created by Brian + Lloyd. For more information, see the `Python for .NET home page + `_. + +IronPython + An alternate Python for .NET. Unlike Python.NET, this is a complete Python + implementation that generates IL, and compiles Python code directly to .NET + assemblies. It was created by Jim Hugunin, the original creator of Jython. For + more information, see `the IronPython website `_. + +PyPy + An implementation of Python written completely in Python. It supports several + advanced features not found in other implementations like stackless support + and a Just in Time compiler. One of the goals of the project is to encourage + experimentation with the language itself by making it easier to modify the + interpreter (since it is written in Python). Additional information is + available on `the PyPy project's home page `_. + +Each of these implementations varies in some way from the language as documented +in this manual, or introduces specific information beyond what's covered in the +standard Python documentation. Please refer to the implementation-specific +documentation to determine what else you need to know about the specific +implementation you're using. + + +.. _notation: + +Notation +======== + +.. index:: BNF, grammar, syntax, notation + +The descriptions of lexical analysis and syntax use a modified BNF grammar +notation. This uses the following style of definition: + +.. productionlist:: * + name: `lc_letter` (`lc_letter` | "_")* + lc_letter: "a"..."z" + +The first line says that a ``name`` is an ``lc_letter`` followed by a sequence +of zero or more ``lc_letter``\ s and underscores. An ``lc_letter`` in turn is +any of the single characters ``'a'`` through ``'z'``. (This rule is actually +adhered to for the names defined in lexical and grammar rules in this document.) + +Each rule begins with a name (which is the name defined by the rule) and +``::=``. A vertical bar (``|``) is used to separate alternatives; it is the +least binding operator in this notation. A star (``*``) means zero or more +repetitions of the preceding item; likewise, a plus (``+``) means one or more +repetitions, and a phrase enclosed in square brackets (``[ ]``) means zero or +one occurrences (in other words, the enclosed phrase is optional). The ``*`` +and ``+`` operators bind as tightly as possible; parentheses are used for +grouping. Literal strings are enclosed in quotes. White space is only +meaningful to separate tokens. Rules are normally contained on a single line; +rules with many alternatives may be formatted alternatively with each line after +the first beginning with a vertical bar. + +.. index:: lexical definitions, ASCII + +In lexical definitions (as the example above), two more conventions are used: +Two literal characters separated by three dots mean a choice of any single +character in the given (inclusive) range of ASCII characters. A phrase between +angular brackets (``<...>``) gives an informal description of the symbol +defined; e.g., this could be used to describe the notion of 'control character' +if needed. + +Even though the notation used is almost the same, there is a big difference +between the meaning of lexical and syntactic definitions: a lexical definition +operates on the individual characters of the input source, while a syntax +definition operates on the stream of tokens generated by the lexical analysis. +All uses of BNF in the next chapter ("Lexical Analysis") are lexical +definitions; uses in subsequent chapters are syntactic definitions. + diff --git a/cpython_2/environment/repo/Doc/reference/lexical_analysis.rst b/cpython_2/environment/repo/Doc/reference/lexical_analysis.rst new file mode 100644 index 0000000000000000000000000000000000000000..3f420817eefea29126356740419690057b102ab8 --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/lexical_analysis.rst @@ -0,0 +1,937 @@ + +.. _lexical: + +**************** +Lexical analysis +**************** + +.. index:: lexical analysis, parser, token + +A Python program is read by a *parser*. Input to the parser is a stream of +*tokens*, generated by the *lexical analyzer*. This chapter describes how the +lexical analyzer breaks a file into tokens. + +Python reads program text as Unicode code points; the encoding of a source file +can be given by an encoding declaration and defaults to UTF-8, see :pep:`3120` +for details. If the source file cannot be decoded, a :exc:`SyntaxError` is +raised. + + +.. _line-structure: + +Line structure +============== + +.. index:: line structure + +A Python program is divided into a number of *logical lines*. + + +.. _logical-lines: + +Logical lines +------------- + +.. index:: logical line, physical line, line joining, NEWLINE token + +The end of a logical line is represented by the token NEWLINE. Statements +cannot cross logical line boundaries except where NEWLINE is allowed by the +syntax (e.g., between statements in compound statements). A logical line is +constructed from one or more *physical lines* by following the explicit or +implicit *line joining* rules. + + +.. _physical-lines: + +Physical lines +-------------- + +A physical line is a sequence of characters terminated by an end-of-line +sequence. In source files and strings, any of the standard platform line +termination sequences can be used - the Unix form using ASCII LF (linefeed), +the Windows form using the ASCII sequence CR LF (return followed by linefeed), +or the old Macintosh form using the ASCII CR (return) character. All of these +forms can be used equally, regardless of platform. The end of input also serves +as an implicit terminator for the final physical line. + +When embedding Python, source code strings should be passed to Python APIs using +the standard C conventions for newline characters (the ``\n`` character, +representing ASCII LF, is the line terminator). + + +.. _comments: + +Comments +-------- + +.. index:: comment, hash character + single: # (hash); comment + +A comment starts with a hash character (``#``) that is not part of a string +literal, and ends at the end of the physical line. A comment signifies the end +of the logical line unless the implicit line joining rules are invoked. Comments +are ignored by the syntax. + + +.. _encodings: + +Encoding declarations +--------------------- + +.. index:: source character set, encoding declarations (source file) + single: # (hash); source encoding declaration + +If a comment in the first or second line of the Python script matches the +regular expression ``coding[=:]\s*([-\w.]+)``, this comment is processed as an +encoding declaration; the first group of this expression names the encoding of +the source code file. The encoding declaration must appear on a line of its +own. If it is the second line, the first line must also be a comment-only line. +The recommended forms of an encoding expression are :: + + # -*- coding: -*- + +which is recognized also by GNU Emacs, and :: + + # vim:fileencoding= + +which is recognized by Bram Moolenaar's VIM. + +If no encoding declaration is found, the default encoding is UTF-8. In +addition, if the first bytes of the file are the UTF-8 byte-order mark +(``b'\xef\xbb\xbf'``), the declared file encoding is UTF-8 (this is supported, +among others, by Microsoft's :program:`notepad`). + +If an encoding is declared, the encoding name must be recognized by Python. The +encoding is used for all lexical analysis, including string literals, comments +and identifiers. + +.. XXX there should be a list of supported encodings. + + +.. _explicit-joining: + +Explicit line joining +--------------------- + +.. index:: physical line, line joining, line continuation, backslash character + +Two or more physical lines may be joined into logical lines using backslash +characters (``\``), as follows: when a physical line ends in a backslash that is +not part of a string literal or comment, it is joined with the following forming +a single logical line, deleting the backslash and the following end-of-line +character. For example:: + + if 1900 < year < 2100 and 1 <= month <= 12 \ + and 1 <= day <= 31 and 0 <= hour < 24 \ + and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date + return 1 + +A line ending in a backslash cannot carry a comment. A backslash does not +continue a comment. A backslash does not continue a token except for string +literals (i.e., tokens other than string literals cannot be split across +physical lines using a backslash). A backslash is illegal elsewhere on a line +outside a string literal. + + +.. _implicit-joining: + +Implicit line joining +--------------------- + +Expressions in parentheses, square brackets or curly braces can be split over +more than one physical line without using backslashes. For example:: + + month_names = ['Januari', 'Februari', 'Maart', # These are the + 'April', 'Mei', 'Juni', # Dutch names + 'Juli', 'Augustus', 'September', # for the months + 'Oktober', 'November', 'December'] # of the year + +Implicitly continued lines can carry comments. The indentation of the +continuation lines is not important. Blank continuation lines are allowed. +There is no NEWLINE token between implicit continuation lines. Implicitly +continued lines can also occur within triple-quoted strings (see below); in that +case they cannot carry comments. + + +.. _blank-lines: + +Blank lines +----------- + +.. index:: single: blank line + +A logical line that contains only spaces, tabs, formfeeds and possibly a +comment, is ignored (i.e., no NEWLINE token is generated). During interactive +input of statements, handling of a blank line may differ depending on the +implementation of the read-eval-print loop. In the standard interactive +interpreter, an entirely blank logical line (i.e. one containing not even +whitespace or a comment) terminates a multi-line statement. + + +.. _indentation: + +Indentation +----------- + +.. index:: indentation, leading whitespace, space, tab, grouping, statement grouping + +Leading whitespace (spaces and tabs) at the beginning of a logical line is used +to compute the indentation level of the line, which in turn is used to determine +the grouping of statements. + +Tabs are replaced (from left to right) by one to eight spaces such that the +total number of characters up to and including the replacement is a multiple of +eight (this is intended to be the same rule as used by Unix). The total number +of spaces preceding the first non-blank character then determines the line's +indentation. Indentation cannot be split over multiple physical lines using +backslashes; the whitespace up to the first backslash determines the +indentation. + +Indentation is rejected as inconsistent if a source file mixes tabs and spaces +in a way that makes the meaning dependent on the worth of a tab in spaces; a +:exc:`TabError` is raised in that case. + +**Cross-platform compatibility note:** because of the nature of text editors on +non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the +indentation in a single source file. It should also be noted that different +platforms may explicitly limit the maximum indentation level. + +A formfeed character may be present at the start of the line; it will be ignored +for the indentation calculations above. Formfeed characters occurring elsewhere +in the leading whitespace have an undefined effect (for instance, they may reset +the space count to zero). + +.. index:: INDENT token, DEDENT token + +The indentation levels of consecutive lines are used to generate INDENT and +DEDENT tokens, using a stack, as follows. + +Before the first line of the file is read, a single zero is pushed on the stack; +this will never be popped off again. The numbers pushed on the stack will +always be strictly increasing from bottom to top. At the beginning of each +logical line, the line's indentation level is compared to the top of the stack. +If it is equal, nothing happens. If it is larger, it is pushed on the stack, and +one INDENT token is generated. If it is smaller, it *must* be one of the +numbers occurring on the stack; all numbers on the stack that are larger are +popped off, and for each number popped off a DEDENT token is generated. At the +end of the file, a DEDENT token is generated for each number remaining on the +stack that is larger than zero. + +Here is an example of a correctly (though confusingly) indented piece of Python +code:: + + def perm(l): + # Compute the list of all permutations of l + if len(l) <= 1: + return [l] + r = [] + for i in range(len(l)): + s = l[:i] + l[i+1:] + p = perm(s) + for x in p: + r.append(l[i:i+1] + x) + return r + +The following example shows various indentation errors:: + + def perm(l): # error: first line indented + for i in range(len(l)): # error: not indented + s = l[:i] + l[i+1:] + p = perm(l[:i] + l[i+1:]) # error: unexpected indent + for x in p: + r.append(l[i:i+1] + x) + return r # error: inconsistent dedent + +(Actually, the first three errors are detected by the parser; only the last +error is found by the lexical analyzer --- the indentation of ``return r`` does +not match a level popped off the stack.) + + +.. _whitespace: + +Whitespace between tokens +------------------------- + +Except at the beginning of a logical line or in string literals, the whitespace +characters space, tab and formfeed can be used interchangeably to separate +tokens. Whitespace is needed between two tokens only if their concatenation +could otherwise be interpreted as a different token (e.g., ab is one token, but +a b is two tokens). + + +.. _other-tokens: + +Other tokens +============ + +Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist: +*identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. Whitespace +characters (other than line terminators, discussed earlier) are not tokens, but +serve to delimit tokens. Where ambiguity exists, a token comprises the longest +possible string that forms a legal token, when read from left to right. + + +.. _identifiers: + +Identifiers and keywords +======================== + +.. index:: identifier, name + +Identifiers (also referred to as *names*) are described by the following lexical +definitions. + +The syntax of identifiers in Python is based on the Unicode standard annex +UAX-31, with elaboration and changes as defined below; see also :pep:`3131` for +further details. + +Within the ASCII range (U+0001..U+007F), the valid characters for identifiers +are the same as in Python 2.x: the uppercase and lowercase letters ``A`` through +``Z``, the underscore ``_`` and, except for the first character, the digits +``0`` through ``9``. + +Python 3.0 introduces additional characters from outside the ASCII range (see +:pep:`3131`). For these characters, the classification uses the version of the +Unicode Character Database as included in the :mod:`unicodedata` module. + +Identifiers are unlimited in length. Case is significant. + +.. productionlist:: + identifier: `xid_start` `xid_continue`* + id_start: + id_continue: + xid_start: + xid_continue: + +The Unicode category codes mentioned above stand for: + +* *Lu* - uppercase letters +* *Ll* - lowercase letters +* *Lt* - titlecase letters +* *Lm* - modifier letters +* *Lo* - other letters +* *Nl* - letter numbers +* *Mn* - nonspacing marks +* *Mc* - spacing combining marks +* *Nd* - decimal numbers +* *Pc* - connector punctuations +* *Other_ID_Start* - explicit list of characters in `PropList.txt + `_ to support backwards + compatibility +* *Other_ID_Continue* - likewise + +All identifiers are converted into the normal form NFKC while parsing; comparison +of identifiers is based on NFKC. + +A non-normative HTML file listing all valid identifier characters for Unicode +4.1 can be found at +https://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html. + + +.. _keywords: + +Keywords +-------- + +.. index:: + single: keyword + single: reserved word + +The following identifiers are used as reserved words, or *keywords* of the +language, and cannot be used as ordinary identifiers. They must be spelled +exactly as written here: + +.. sourcecode:: text + + False await else import pass + None break except in raise + True class finally is return + and continue for lambda try + as def from nonlocal while + assert del global not with + async elif if or yield + +.. index:: + single: _, identifiers + single: __, identifiers +.. _id-classes: + +Reserved classes of identifiers +------------------------------- + +Certain classes of identifiers (besides keywords) have special meanings. These +classes are identified by the patterns of leading and trailing underscore +characters: + +``_*`` + Not imported by ``from module import *``. The special identifier ``_`` is used + in the interactive interpreter to store the result of the last evaluation; it is + stored in the :mod:`builtins` module. When not in interactive mode, ``_`` + has no special meaning and is not defined. See section :ref:`import`. + + .. note:: + + The name ``_`` is often used in conjunction with internationalization; + refer to the documentation for the :mod:`gettext` module for more + information on this convention. + +``__*__`` + System-defined names, informally known as "dunder" names. These names are + defined by the interpreter and its implementation (including the standard library). + Current system names are discussed in the :ref:`specialnames` section and elsewhere. + More will likely be defined in future versions of Python. *Any* use of ``__*__`` names, + in any context, that does not follow explicitly documented use, is subject to + breakage without warning. + +``__*`` + Class-private names. Names in this category, when used within the context of a + class definition, are re-written to use a mangled form to help avoid name + clashes between "private" attributes of base and derived classes. See section + :ref:`atom-identifiers`. + + +.. _literals: + +Literals +======== + +.. index:: literal, constant + +Literals are notations for constant values of some built-in types. + + +.. index:: string literal, bytes literal, ASCII + single: ' (single quote); string literal + single: " (double quote); string literal + single: u'; string literal + single: u"; string literal +.. _strings: + +String and Bytes literals +------------------------- + +String literals are described by the following lexical definitions: + +.. productionlist:: + stringliteral: [`stringprefix`](`shortstring` | `longstring`) + stringprefix: "r" | "u" | "R" | "U" | "f" | "F" + : | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF" + shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"' + longstring: "'''" `longstringitem`* "'''" | '"""' `longstringitem`* '"""' + shortstringitem: `shortstringchar` | `stringescapeseq` + longstringitem: `longstringchar` | `stringescapeseq` + shortstringchar: + longstringchar: + stringescapeseq: "\" + +.. productionlist:: + bytesliteral: `bytesprefix`(`shortbytes` | `longbytes`) + bytesprefix: "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB" + shortbytes: "'" `shortbytesitem`* "'" | '"' `shortbytesitem`* '"' + longbytes: "'''" `longbytesitem`* "'''" | '"""' `longbytesitem`* '"""' + shortbytesitem: `shortbyteschar` | `bytesescapeseq` + longbytesitem: `longbyteschar` | `bytesescapeseq` + shortbyteschar: + longbyteschar: + bytesescapeseq: "\" + +One syntactic restriction not indicated by these productions is that whitespace +is not allowed between the :token:`stringprefix` or :token:`bytesprefix` and the +rest of the literal. The source character set is defined by the encoding +declaration; it is UTF-8 if no encoding declaration is given in the source file; +see section :ref:`encodings`. + +.. index:: triple-quoted string, Unicode Consortium, raw string + single: """; string literal + single: '''; string literal + +In plain English: Both types of literals can be enclosed in matching single quotes +(``'``) or double quotes (``"``). They can also be enclosed in matching groups +of three single or double quotes (these are generally referred to as +*triple-quoted strings*). The backslash (``\``) character is used to escape +characters that otherwise have a special meaning, such as newline, backslash +itself, or the quote character. + +.. index:: + single: b'; bytes literal + single: b"; bytes literal + +Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an +instance of the :class:`bytes` type instead of the :class:`str` type. They +may only contain ASCII characters; bytes with a numeric value of 128 or greater +must be expressed with escapes. + +.. index:: + single: r'; raw string literal + single: r"; raw string literal + +Both string and bytes literals may optionally be prefixed with a letter ``'r'`` +or ``'R'``; such strings are called :dfn:`raw strings` and treat backslashes as +literal characters. As a result, in string literals, ``'\U'`` and ``'\u'`` +escapes in raw strings are not treated specially. Given that Python 2.x's raw +unicode literals behave differently than Python 3.x's the ``'ur'`` syntax +is not supported. + +.. versionadded:: 3.3 + The ``'rb'`` prefix of raw bytes literals has been added as a synonym + of ``'br'``. + +.. versionadded:: 3.3 + Support for the unicode legacy literal (``u'value'``) was reintroduced + to simplify the maintenance of dual Python 2.x and 3.x codebases. + See :pep:`414` for more information. + +.. index:: + single: f'; formatted string literal + single: f"; formatted string literal + +A string literal with ``'f'`` or ``'F'`` in its prefix is a +:dfn:`formatted string literal`; see :ref:`f-strings`. The ``'f'`` may be +combined with ``'r'``, but not with ``'b'`` or ``'u'``, therefore raw +formatted strings are possible, but formatted bytes literals are not. + +In triple-quoted literals, unescaped newlines and quotes are allowed (and are +retained), except that three unescaped quotes in a row terminate the literal. (A +"quote" is the character used to open the literal, i.e. either ``'`` or ``"``.) + +.. index:: physical line, escape sequence, Standard C, C + single: \ (backslash); escape sequence + single: \\; escape sequence + single: \a; escape sequence + single: \b; escape sequence + single: \f; escape sequence + single: \n; escape sequence + single: \r; escape sequence + single: \t; escape sequence + single: \v; escape sequence + single: \x; escape sequence + single: \N; escape sequence + single: \u; escape sequence + single: \U; escape sequence + +Unless an ``'r'`` or ``'R'`` prefix is present, escape sequences in string and +bytes literals are interpreted according to rules similar to those used by +Standard C. The recognized escape sequences are: + ++-----------------+---------------------------------+-------+ +| Escape Sequence | Meaning | Notes | ++=================+=================================+=======+ +| ``\newline`` | Backslash and newline ignored | | ++-----------------+---------------------------------+-------+ +| ``\\`` | Backslash (``\``) | | ++-----------------+---------------------------------+-------+ +| ``\'`` | Single quote (``'``) | | ++-----------------+---------------------------------+-------+ +| ``\"`` | Double quote (``"``) | | ++-----------------+---------------------------------+-------+ +| ``\a`` | ASCII Bell (BEL) | | ++-----------------+---------------------------------+-------+ +| ``\b`` | ASCII Backspace (BS) | | ++-----------------+---------------------------------+-------+ +| ``\f`` | ASCII Formfeed (FF) | | ++-----------------+---------------------------------+-------+ +| ``\n`` | ASCII Linefeed (LF) | | ++-----------------+---------------------------------+-------+ +| ``\r`` | ASCII Carriage Return (CR) | | ++-----------------+---------------------------------+-------+ +| ``\t`` | ASCII Horizontal Tab (TAB) | | ++-----------------+---------------------------------+-------+ +| ``\v`` | ASCII Vertical Tab (VT) | | ++-----------------+---------------------------------+-------+ +| ``\ooo`` | Character with octal value | (1,3) | +| | *ooo* | | ++-----------------+---------------------------------+-------+ +| ``\xhh`` | Character with hex value *hh* | (2,3) | ++-----------------+---------------------------------+-------+ + +Escape sequences only recognized in string literals are: + ++-----------------+---------------------------------+-------+ +| Escape Sequence | Meaning | Notes | ++=================+=================================+=======+ +| ``\N{name}`` | Character named *name* in the | \(4) | +| | Unicode database | | ++-----------------+---------------------------------+-------+ +| ``\uxxxx`` | Character with 16-bit hex value | \(5) | +| | *xxxx* | | ++-----------------+---------------------------------+-------+ +| ``\Uxxxxxxxx`` | Character with 32-bit hex value | \(6) | +| | *xxxxxxxx* | | ++-----------------+---------------------------------+-------+ + +Notes: + +(1) + As in Standard C, up to three octal digits are accepted. + +(2) + Unlike in Standard C, exactly two hex digits are required. + +(3) + In a bytes literal, hexadecimal and octal escapes denote the byte with the + given value. In a string literal, these escapes denote a Unicode character + with the given value. + +(4) + .. versionchanged:: 3.3 + Support for name aliases [#]_ has been added. + +(5) + Exactly four hex digits are required. + +(6) + Any Unicode character can be encoded this way. Exactly eight hex digits + are required. + + +.. index:: unrecognized escape sequence + +Unlike Standard C, all unrecognized escape sequences are left in the string +unchanged, i.e., *the backslash is left in the result*. (This behavior is +useful when debugging: if an escape sequence is mistyped, the resulting output +is more easily recognized as broken.) It is also important to note that the +escape sequences only recognized in string literals fall into the category of +unrecognized escapes for bytes literals. + + .. versionchanged:: 3.6 + Unrecognized escape sequences produce a :exc:`DeprecationWarning`. In + a future Python version they will be a :exc:`SyntaxWarning` and + eventually a :exc:`SyntaxError`. + +Even in a raw literal, quotes can be escaped with a backslash, but the +backslash remains in the result; for example, ``r"\""`` is a valid string +literal consisting of two characters: a backslash and a double quote; ``r"\"`` +is not a valid string literal (even a raw string cannot end in an odd number of +backslashes). Specifically, *a raw literal cannot end in a single backslash* +(since the backslash would escape the following quote character). Note also +that a single backslash followed by a newline is interpreted as those two +characters as part of the literal, *not* as a line continuation. + + +.. _string-concatenation: + +String literal concatenation +---------------------------- + +Multiple adjacent string or bytes literals (delimited by whitespace), possibly +using different quoting conventions, are allowed, and their meaning is the same +as their concatenation. Thus, ``"hello" 'world'`` is equivalent to +``"helloworld"``. This feature can be used to reduce the number of backslashes +needed, to split long strings conveniently across long lines, or even to add +comments to parts of strings, for example:: + + re.compile("[A-Za-z_]" # letter or underscore + "[A-Za-z0-9_]*" # letter, digit or underscore + ) + +Note that this feature is defined at the syntactical level, but implemented at +compile time. The '+' operator must be used to concatenate string expressions +at run time. Also note that literal concatenation can use different quoting +styles for each component (even mixing raw strings and triple quoted strings), +and formatted string literals may be concatenated with plain string literals. + + +.. index:: + single: formatted string literal + single: interpolated string literal + single: string; formatted literal + single: string; interpolated literal + single: f-string + single: {} (curly brackets); in formatted string literal + single: ! (exclamation); in formatted string literal + single: : (colon); in formatted string literal +.. _f-strings: + +Formatted string literals +------------------------- + +.. versionadded:: 3.6 + +A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal +that is prefixed with ``'f'`` or ``'F'``. These strings may contain +replacement fields, which are expressions delimited by curly braces ``{}``. +While other string literals always have a constant value, formatted strings +are really expressions evaluated at run time. + +Escape sequences are decoded like in ordinary string literals (except when +a literal is also marked as a raw string). After decoding, the grammar +for the contents of the string is: + +.. productionlist:: + f_string: (`literal_char` | "{{" | "}}" | `replacement_field`)* + replacement_field: "{" `f_expression` ["!" `conversion`] [":" `format_spec`] "}" + f_expression: (`conditional_expression` | "*" `or_expr`) + : ("," `conditional_expression` | "," "*" `or_expr`)* [","] + : | `yield_expression` + conversion: "s" | "r" | "a" + format_spec: (`literal_char` | NULL | `replacement_field`)* + literal_char: + +The parts of the string outside curly braces are treated literally, +except that any doubled curly braces ``'{{'`` or ``'}}'`` are replaced +with the corresponding single curly brace. A single opening curly +bracket ``'{'`` marks a replacement field, which starts with a +Python expression. After the expression, there may be a conversion field, +introduced by an exclamation point ``'!'``. A format specifier may also +be appended, introduced by a colon ``':'``. A replacement field ends +with a closing curly bracket ``'}'``. + +Expressions in formatted string literals are treated like regular +Python expressions surrounded by parentheses, with a few exceptions. +An empty expression is not allowed, and both :keyword:`lambda` and +assignment expressions ``:=`` must be surrounded by explicit parentheses. +Replacement expressions can contain line breaks (e.g. in triple-quoted +strings), but they cannot contain comments. Each expression is evaluated +in the context where the formatted string literal appears, in order from +left to right. + +.. versionchanged:: 3.7 + Prior to Python 3.7, an :keyword:`await` expression and comprehensions + containing an :keyword:`async for` clause were illegal in the expressions + in formatted string literals due to a problem with the implementation. + +If a conversion is specified, the result of evaluating the expression +is converted before formatting. Conversion ``'!s'`` calls :func:`str` on +the result, ``'!r'`` calls :func:`repr`, and ``'!a'`` calls :func:`ascii`. + +The result is then formatted using the :func:`format` protocol. The +format specifier is passed to the :meth:`__format__` method of the +expression or conversion result. An empty string is passed when the +format specifier is omitted. The formatted result is then included in +the final value of the whole string. + +Top-level format specifiers may include nested replacement fields. These nested +fields may include their own conversion fields and :ref:`format specifiers +`, but may not include more deeply-nested replacement fields. The +:ref:`format specifier mini-language ` is the same as that used by +the string .format() method. + +Formatted string literals may be concatenated, but replacement fields +cannot be split across literals. + +Some examples of formatted string literals:: + + >>> name = "Fred" + >>> f"He said his name is {name!r}." + "He said his name is 'Fred'." + >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r + "He said his name is 'Fred'." + >>> width = 10 + >>> precision = 4 + >>> value = decimal.Decimal("12.34567") + >>> f"result: {value:{width}.{precision}}" # nested fields + 'result: 12.35' + >>> today = datetime(year=2017, month=1, day=27) + >>> f"{today:%B %d, %Y}" # using date format specifier + 'January 27, 2017' + >>> number = 1024 + >>> f"{number:#0x}" # using integer format specifier + '0x400' + +A consequence of sharing the same syntax as regular string literals is +that characters in the replacement fields must not conflict with the +quoting used in the outer formatted string literal:: + + f"abc {a["x"]} def" # error: outer string literal ended prematurely + f"abc {a['x']} def" # workaround: use different quoting + +Backslashes are not allowed in format expressions and will raise +an error:: + + f"newline: {ord('\n')}" # raises SyntaxError + +To include a value in which a backslash escape is required, create +a temporary variable. + + >>> newline = ord('\n') + >>> f"newline: {newline}" + 'newline: 10' + +Formatted string literals cannot be used as docstrings, even if they do not +include expressions. + +:: + + >>> def foo(): + ... f"Not a docstring" + ... + >>> foo.__doc__ is None + True + +See also :pep:`498` for the proposal that added formatted string literals, +and :meth:`str.format`, which uses a related format string mechanism. + + +.. _numbers: + +Numeric literals +---------------- + +.. index:: number, numeric literal, integer literal + floating point literal, hexadecimal literal + octal literal, binary literal, decimal literal, imaginary literal, complex literal + +There are three types of numeric literals: integers, floating point numbers, and +imaginary numbers. There are no complex literals (complex numbers can be formed +by adding a real number and an imaginary number). + +Note that numeric literals do not include a sign; a phrase like ``-1`` is +actually an expression composed of the unary operator '``-``' and the literal +``1``. + + +.. index:: + single: 0b; integer literal + single: 0o; integer literal + single: 0x; integer literal + single: _ (underscore); in numeric literal + +.. _integers: + +Integer literals +---------------- + +Integer literals are described by the following lexical definitions: + +.. productionlist:: + integer: `decinteger` | `bininteger` | `octinteger` | `hexinteger` + decinteger: `nonzerodigit` (["_"] `digit`)* | "0"+ (["_"] "0")* + bininteger: "0" ("b" | "B") (["_"] `bindigit`)+ + octinteger: "0" ("o" | "O") (["_"] `octdigit`)+ + hexinteger: "0" ("x" | "X") (["_"] `hexdigit`)+ + nonzerodigit: "1"..."9" + digit: "0"..."9" + bindigit: "0" | "1" + octdigit: "0"..."7" + hexdigit: `digit` | "a"..."f" | "A"..."F" + +There is no limit for the length of integer literals apart from what can be +stored in available memory. + +Underscores are ignored for determining the numeric value of the literal. They +can be used to group digits for enhanced readability. One underscore can occur +between digits, and after base specifiers like ``0x``. + +Note that leading zeros in a non-zero decimal number are not allowed. This is +for disambiguation with C-style octal literals, which Python used before version +3.0. + +Some examples of integer literals:: + + 7 2147483647 0o177 0b100110111 + 3 79228162514264337593543950336 0o377 0xdeadbeef + 100_000_000_000 0b_1110_0101 + +.. versionchanged:: 3.6 + Underscores are now allowed for grouping purposes in literals. + + +.. index:: + single: . (dot); in numeric literal + single: e; in numeric literal + single: _ (underscore); in numeric literal +.. _floating: + +Floating point literals +----------------------- + +Floating point literals are described by the following lexical definitions: + +.. productionlist:: + floatnumber: `pointfloat` | `exponentfloat` + pointfloat: [`digitpart`] `fraction` | `digitpart` "." + exponentfloat: (`digitpart` | `pointfloat`) `exponent` + digitpart: `digit` (["_"] `digit`)* + fraction: "." `digitpart` + exponent: ("e" | "E") ["+" | "-"] `digitpart` + +Note that the integer and exponent parts are always interpreted using radix 10. +For example, ``077e010`` is legal, and denotes the same number as ``77e10``. The +allowed range of floating point literals is implementation-dependent. As in +integer literals, underscores are supported for digit grouping. + +Some examples of floating point literals:: + + 3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93 + +.. versionchanged:: 3.6 + Underscores are now allowed for grouping purposes in literals. + + +.. index:: + single: j; in numeric literal +.. _imaginary: + +Imaginary literals +------------------ + +Imaginary literals are described by the following lexical definitions: + +.. productionlist:: + imagnumber: (`floatnumber` | `digitpart`) ("j" | "J") + +An imaginary literal yields a complex number with a real part of 0.0. Complex +numbers are represented as a pair of floating point numbers and have the same +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.14_15_93j + + +.. _operators: + +Operators +========= + +.. index:: single: operators + +The following tokens are operators: + +.. code-block:: none + + + + - * ** / // % @ + << >> & | ^ ~ := + < > <= >= == != + + +.. _delimiters: + +Delimiters +========== + +.. index:: single: delimiters + +The following tokens serve as delimiters in the grammar: + +.. code-block:: none + + ( ) [ ] { } + , : . ; @ = -> + += -= *= /= //= %= @= + &= |= ^= >>= <<= **= + +The period can also occur in floating-point and imaginary literals. A sequence +of three periods has a special meaning as an ellipsis literal. The second half +of the list, the augmented assignment operators, serve lexically as delimiters, +but also perform an operation. + +The following printing ASCII characters have special meaning as part of other +tokens or are otherwise significant to the lexical analyzer: + +.. code-block:: none + + ' " # \ + +The following printing ASCII characters are not used in Python. Their +occurrence outside string literals and comments is an unconditional error: + +.. code-block:: none + + $ ? ` + + +.. rubric:: Footnotes + +.. [#] https://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt diff --git a/cpython_2/environment/repo/Doc/reference/simple_stmts.rst b/cpython_2/environment/repo/Doc/reference/simple_stmts.rst new file mode 100644 index 0000000000000000000000000000000000000000..a8ec0fbe8b732cd5ece1d47a4df4c974dcd464c0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/simple_stmts.rst @@ -0,0 +1,1013 @@ + +.. _simple: + +***************** +Simple statements +***************** + +.. index:: pair: simple; statement + +A simple statement is comprised within a single logical line. Several simple +statements may occur on a single line separated by semicolons. The syntax for +simple statements is: + +.. productionlist:: + simple_stmt: `expression_stmt` + : | `assert_stmt` + : | `assignment_stmt` + : | `augmented_assignment_stmt` + : | `annotated_assignment_stmt` + : | `pass_stmt` + : | `del_stmt` + : | `return_stmt` + : | `yield_stmt` + : | `raise_stmt` + : | `break_stmt` + : | `continue_stmt` + : | `import_stmt` + : | `future_stmt` + : | `global_stmt` + : | `nonlocal_stmt` + + +.. _exprstmts: + +Expression statements +===================== + +.. index:: + pair: expression; statement + pair: expression; list +.. index:: pair: expression; list + +Expression statements are used (mostly interactively) to compute and write a +value, or (usually) to call a procedure (a function that returns no meaningful +result; in Python, procedures return the value ``None``). Other uses of +expression statements are allowed and occasionally useful. The syntax for an +expression statement is: + +.. productionlist:: + expression_stmt: `starred_expression` + +An expression statement evaluates the expression list (which may be a single +expression). + +.. index:: + builtin: repr + object: None + pair: string; conversion + single: output + pair: standard; output + pair: writing; values + pair: procedure; call + +In interactive mode, if the value is not ``None``, it is converted to a string +using the built-in :func:`repr` function and the resulting string is written to +standard output on a line by itself (except if the result is ``None``, so that +procedure calls do not cause any output.) + +.. _assignment: + +Assignment statements +===================== + +.. index:: + single: = (equals); assignment statement + pair: assignment; statement + pair: binding; name + pair: rebinding; name + object: mutable + pair: attribute; assignment + +Assignment statements are used to (re)bind names to values and to modify +attributes or items of mutable objects: + +.. productionlist:: + assignment_stmt: (`target_list` "=")+ (`starred_expression` | `yield_expression`) + target_list: `target` ("," `target`)* [","] + target: `identifier` + : | "(" [`target_list`] ")" + : | "[" [`target_list`] "]" + : | `attributeref` + : | `subscription` + : | `slicing` + : | "*" `target` + +(See section :ref:`primaries` for the syntax definitions for *attributeref*, +*subscription*, and *slicing*.) + +An assignment statement evaluates the expression list (remember that this can be +a single expression or a comma-separated list, the latter yielding a tuple) and +assigns the single resulting object to each of the target lists, from left to +right. + +.. index:: + single: target + pair: target; list + +Assignment is defined recursively depending on the form of the target (list). +When a target is part of a mutable object (an attribute reference, subscription +or slicing), the mutable object must ultimately perform the assignment and +decide about its validity, and may raise an exception if the assignment is +unacceptable. The rules observed by various types and the exceptions raised are +given with the definition of the object types (see section :ref:`types`). + +.. index:: triple: target; list; assignment + single: , (comma); in target list + single: * (asterisk); in assignment target list + single: [] (square brackets); in assignment target list + single: () (parentheses); in assignment target list + +Assignment of an object to a target list, optionally enclosed in parentheses or +square brackets, is recursively defined as follows. + +* If the target list is a single target with no trailing comma, + optionally in parentheses, the object is assigned to that target. + +* Else: The object must be an iterable with the same number of + items as there are targets in the target list, and the items are assigned, + from left to right, to the corresponding targets. + + * If the target list contains one target prefixed with an asterisk, called a + "starred" target: The object must be an iterable with at least as many items + as there are targets in the target list, minus one. The first items of the + iterable are assigned, from left to right, to the targets before the starred + target. The final items of the iterable are assigned to the targets after + the starred target. A list of the remaining items in the iterable is then + assigned to the starred target (the list can be empty). + + * Else: The object must be an iterable with the same number of items as there + are targets in the target list, and the items are assigned, from left to + right, to the corresponding targets. + +Assignment of an object to a single target is recursively defined as follows. + +* If the target is an identifier (name): + + * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal` + statement in the current code block: the name is bound to the object in the + current local namespace. + + * Otherwise: the name is bound to the object in the global namespace or the + outer namespace determined by :keyword:`nonlocal`, respectively. + + .. index:: single: destructor + + The name is rebound if it was already bound. This may cause the reference + count for the object previously bound to the name to reach zero, causing the + object to be deallocated and its destructor (if it has one) to be called. + + .. index:: pair: attribute; assignment + +* If the target is an attribute reference: The primary expression in the + reference is evaluated. It should yield an object with assignable attributes; + if this is not the case, :exc:`TypeError` is raised. That object is then + asked to assign the assigned object to the given attribute; if it cannot + perform the assignment, it raises an exception (usually but not necessarily + :exc:`AttributeError`). + + .. _attr-target-note: + + Note: If the object is a class instance and the attribute reference occurs on + both sides of the assignment operator, the right-hand side expression, ``a.x`` can access + either an instance attribute or (if no instance attribute exists) a class + attribute. The left-hand side target ``a.x`` is always set as an instance attribute, + creating it if necessary. Thus, the two occurrences of ``a.x`` do not + necessarily refer to the same attribute: if the right-hand side expression refers to a + class attribute, the left-hand side creates a new instance attribute as the target of the + assignment:: + + class Cls: + x = 3 # class variable + inst = Cls() + inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3 + + This description does not necessarily apply to descriptor attributes, such as + properties created with :func:`property`. + + .. index:: + pair: subscription; assignment + object: mutable + +* If the target is a subscription: The primary expression in the reference is + evaluated. It should yield either a mutable sequence object (such as a list) + or a mapping object (such as a dictionary). Next, the subscript expression is + evaluated. + + .. index:: + object: sequence + object: list + + If the primary is a mutable sequence object (such as a list), the subscript + must yield an integer. If it is negative, the sequence's length is added to + it. The resulting value must be a nonnegative integer less than the + sequence's length, and the sequence is asked to assign the assigned object to + its item with that index. If the index is out of range, :exc:`IndexError` is + raised (assignment to a subscripted sequence cannot add new items to a list). + + .. index:: + object: mapping + object: dictionary + + If the primary is a mapping object (such as a dictionary), the subscript must + have a type compatible with the mapping's key type, and the mapping is then + asked to create a key/datum pair which maps the subscript to the assigned + object. This can either replace an existing key/value pair with the same key + value, or insert a new key/value pair (if no key with the same value existed). + + For user-defined objects, the :meth:`__setitem__` method is called with + appropriate arguments. + + .. index:: pair: slicing; assignment + +* If the target is a slicing: The primary expression in the reference is + evaluated. It should yield a mutable sequence object (such as a list). The + assigned object should be a sequence object of the same type. Next, the lower + and upper bound expressions are evaluated, insofar they are present; defaults + are zero and the sequence's length. The bounds should evaluate to integers. + If either bound is negative, the sequence's length is added to it. The + resulting bounds are clipped to lie between zero and the sequence's length, + inclusive. Finally, the sequence object is asked to replace the slice with + the items of the assigned sequence. The length of the slice may be different + from the length of the assigned sequence, thus changing the length of the + target sequence, if the target sequence allows it. + +.. impl-detail:: + + In the current implementation, the syntax for targets is taken to be the same + as for expressions, and invalid syntax is rejected during the code generation + phase, causing less detailed error messages. + +Although the definition of assignment implies that overlaps between the +left-hand side and the right-hand side are 'simultaneous' (for example ``a, b = +b, a`` swaps two variables), overlaps *within* the collection of assigned-to +variables occur left-to-right, sometimes resulting in confusion. For instance, +the following program prints ``[0, 2]``:: + + x = [0, 1] + i = 0 + i, x[i] = 1, 2 # i is updated, then x[i] is updated + print(x) + + +.. seealso:: + + :pep:`3132` - Extended Iterable Unpacking + The specification for the ``*target`` feature. + + +.. _augassign: + +Augmented assignment statements +------------------------------- + +.. index:: + pair: augmented; assignment + single: statement; assignment, augmented + single: +=; augmented assignment + single: -=; augmented assignment + single: *=; augmented assignment + single: /=; augmented assignment + single: %=; augmented assignment + single: &=; augmented assignment + single: ^=; augmented assignment + single: |=; augmented assignment + single: **=; augmented assignment + single: //=; augmented assignment + single: >>=; augmented assignment + single: <<=; augmented assignment + +Augmented assignment is the combination, in a single statement, of a binary +operation and an assignment statement: + +.. productionlist:: + augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`) + augtarget: `identifier` | `attributeref` | `subscription` | `slicing` + augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**=" + : | ">>=" | "<<=" | "&=" | "^=" | "|=" + +(See section :ref:`primaries` for the syntax definitions of the last three +symbols.) + +An augmented assignment evaluates the target (which, unlike normal assignment +statements, cannot be an unpacking) and the expression list, performs the binary +operation specific to the type of assignment on the two operands, and assigns +the result to the original target. The target is only evaluated once. + +An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x + +1`` to achieve a similar, but not exactly equal effect. In the augmented +version, ``x`` is only evaluated once. Also, when possible, the actual operation +is performed *in-place*, meaning that rather than creating a new object and +assigning that to the target, the old object is modified instead. + +Unlike normal assignments, augmented assignments evaluate the left-hand side +*before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first +looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and +lastly, it writes the result back to ``a[i]``. + +With the exception of assigning to tuples and multiple targets in a single +statement, the assignment done by augmented assignment statements is handled the +same way as normal assignments. Similarly, with the exception of the possible +*in-place* behavior, the binary operation performed by augmented assignment is +the same as the normal binary operations. + +For targets which are attribute references, the same :ref:`caveat about class +and instance attributes ` applies as for regular assignments. + + +.. _annassign: + +Annotated assignment statements +------------------------------- + +.. index:: + pair: annotated; assignment + single: statement; assignment, annotated + single: : (colon); annotated variable + +:term:`Annotation ` assignment is the combination, in a single +statement, of a variable or attribute annotation and an optional assignment statement: + +.. productionlist:: + annotated_assignment_stmt: `augtarget` ":" `expression` + : ["=" (`starred_expression` | `yield_expression`)] + +The difference from normal :ref:`assignment` is that only single target is allowed. + +For simple names as assignment targets, if in class or module scope, +the annotations are evaluated and stored in a special class or module +attribute :attr:`__annotations__` +that is a dictionary mapping from variable names (mangled if private) to +evaluated annotations. This attribute is writable and is automatically +created at the start of class or module body execution, if annotations +are found statically. + +For expressions as assignment targets, the annotations are evaluated if +in class or module scope, but not stored. + +If a name is annotated in a function scope, then this name is local for +that scope. Annotations are never evaluated and stored in function scopes. + +If the right hand side is present, an annotated +assignment performs the actual assignment before evaluating annotations +(where applicable). If the right hand side is not present for an expression +target, then the interpreter evaluates the target except for the last +:meth:`__setitem__` or :meth:`__setattr__` call. + +.. seealso:: + + :pep:`526` - Syntax for Variable Annotations + The proposal that added syntax for annotating the types of variables + (including class variables and instance variables), instead of expressing + them through comments. + + :pep:`484` - Type hints + The proposal that added the :mod:`typing` module to provide a standard + syntax for type annotations that can be used in static analysis tools and + IDEs. + +.. versionchanged:: 3.8 + Now annotated assignments allow same expressions in the right hand side as + the regular assignments. Previously, some expressions (like un-parenthesized + tuple expressions) caused a syntax error. + + +.. _assert: + +The :keyword:`!assert` statement +================================ + +.. index:: + ! statement: assert + pair: debugging; assertions + single: , (comma); expression list + +Assert statements are a convenient way to insert debugging assertions into a +program: + +.. productionlist:: + assert_stmt: "assert" `expression` ["," `expression`] + +The simple form, ``assert expression``, is equivalent to :: + + if __debug__: + if not expression: raise AssertionError + +The extended form, ``assert expression1, expression2``, is equivalent to :: + + if __debug__: + if not expression1: raise AssertionError(expression2) + +.. index:: + single: __debug__ + exception: AssertionError + +These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to +the built-in variables with those names. In the current implementation, the +built-in variable :const:`__debug__` is ``True`` under normal circumstances, +``False`` when optimization is requested (command line option :option:`-O`). The current +code generator emits no code for an assert statement when optimization is +requested at compile time. Note that it is unnecessary to include the source +code for the expression that failed in the error message; it will be displayed +as part of the stack trace. + +Assignments to :const:`__debug__` are illegal. The value for the built-in variable +is determined when the interpreter starts. + + +.. _pass: + +The :keyword:`!pass` statement +============================== + +.. index:: + statement: pass + pair: null; operation + pair: null; operation + +.. productionlist:: + pass_stmt: "pass" + +:keyword:`pass` is a null operation --- when it is executed, nothing happens. +It is useful as a placeholder when a statement is required syntactically, but no +code needs to be executed, for example:: + + def f(arg): pass # a function that does nothing (yet) + + class C: pass # a class with no methods (yet) + + +.. _del: + +The :keyword:`!del` statement +============================= + +.. index:: + ! statement: del + pair: deletion; target + triple: deletion; target; list + +.. productionlist:: + del_stmt: "del" `target_list` + +Deletion is recursively defined very similar to the way assignment is defined. +Rather than spelling it out in full details, here are some hints. + +Deletion of a target list recursively deletes each target, from left to right. + +.. index:: + statement: global + pair: unbinding; name + +Deletion of a name removes the binding of that name from the local or global +namespace, depending on whether the name occurs in a :keyword:`global` statement +in the same code block. If the name is unbound, a :exc:`NameError` exception +will be raised. + +.. index:: pair: attribute; deletion + +Deletion of attribute references, subscriptions and slicings is passed to the +primary object involved; deletion of a slicing is in general equivalent to +assignment of an empty slice of the right type (but even this is determined by +the sliced object). + +.. versionchanged:: 3.2 + Previously it was illegal to delete a name from the local namespace if it + occurs as a free variable in a nested block. + + +.. _return: + +The :keyword:`!return` statement +================================ + +.. index:: + ! statement: return + pair: function; definition + pair: class; definition + +.. productionlist:: + return_stmt: "return" [`expression_list`] + +:keyword:`return` may only occur syntactically nested in a function definition, +not within a nested class definition. + +If an expression list is present, it is evaluated, else ``None`` is substituted. + +:keyword:`return` leaves the current function call with the expression list (or +``None``) as return value. + +.. index:: keyword: finally + +When :keyword:`return` passes control out of a :keyword:`try` statement with a +:keyword:`finally` clause, that :keyword:`!finally` clause is executed before +really leaving the function. + +In a generator function, the :keyword:`return` statement indicates that the +generator is done and will cause :exc:`StopIteration` to be raised. The returned +value (if any) is used as an argument to construct :exc:`StopIteration` and +becomes the :attr:`StopIteration.value` attribute. + +In an asynchronous generator function, an empty :keyword:`return` statement +indicates that the asynchronous generator is done and will cause +:exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`!return` +statement is a syntax error in an asynchronous generator function. + +.. _yield: + +The :keyword:`!yield` statement +=============================== + +.. index:: + statement: yield + single: generator; function + single: generator; iterator + single: function; generator + exception: StopIteration + +.. productionlist:: + yield_stmt: `yield_expression` + +A :keyword:`yield` statement is semantically equivalent to a :ref:`yield +expression `. The yield statement can be used to omit the parentheses +that would otherwise be required in the equivalent yield expression +statement. For example, the yield statements :: + + yield + yield from + +are equivalent to the yield expression statements :: + + (yield ) + (yield from ) + +Yield expressions and statements are only used when defining a :term:`generator` +function, and are only used in the body of the generator function. Using yield +in a function definition is sufficient to cause that definition to create a +generator function instead of a normal function. + +For full details of :keyword:`yield` semantics, refer to the +:ref:`yieldexpr` section. + +.. _raise: + +The :keyword:`!raise` statement +=============================== + +.. index:: + ! statement: raise + single: exception + pair: raising; exception + single: __traceback__ (exception attribute) + +.. productionlist:: + raise_stmt: "raise" [`expression` ["from" `expression`]] + +If no expressions are present, :keyword:`raise` re-raises the last exception +that was active in the current scope. If no exception is active in the current +scope, a :exc:`RuntimeError` exception is raised indicating that this is an +error. + +Otherwise, :keyword:`raise` evaluates the first expression as the exception +object. It must be either a subclass or an instance of :class:`BaseException`. +If it is a class, the exception instance will be obtained when needed by +instantiating the class with no arguments. + +The :dfn:`type` of the exception is the exception instance's class, the +:dfn:`value` is the instance itself. + +.. index:: object: traceback + +A traceback object is normally created automatically when an exception is raised +and attached to it as the :attr:`__traceback__` attribute, which is writable. +You can create an exception and set your own traceback in one step using the +:meth:`with_traceback` exception method (which returns the same exception +instance, with its traceback set to its argument), like so:: + + raise Exception("foo occurred").with_traceback(tracebackobj) + +.. 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 +writable). If the raised exception is not handled, both exceptions will be +printed:: + + >>> try: + ... print(1 / 0) + ... except Exception as exc: + ... raise RuntimeError("Something bad happened") from exc + ... + Traceback (most recent call last): + File "", line 2, in + ZeroDivisionError: division by zero + + The above exception was the direct cause of the following exception: + + Traceback (most recent call last): + File "", line 4, in + RuntimeError: Something bad happened + +A similar mechanism works implicitly if an exception is raised inside an +exception handler or a :keyword:`finally` clause: the previous exception is then +attached as the new exception's :attr:`__context__` attribute:: + + >>> try: + ... print(1 / 0) + ... except: + ... raise RuntimeError("Something bad happened") + ... + Traceback (most recent call last): + File "", line 2, in + ZeroDivisionError: division by zero + + During handling of the above exception, another exception occurred: + + Traceback (most recent call last): + File "", line 4, in + RuntimeError: Something bad happened + +Exception chaining can be explicitly suppressed by specifying :const:`None` in +the ``from`` clause:: + + >>> try: + ... print(1 / 0) + ... except: + ... raise RuntimeError("Something bad happened") from None + ... + Traceback (most recent call last): + File "", line 4, in + RuntimeError: Something bad happened + +Additional information on exceptions can be found in section :ref:`exceptions`, +and information about handling exceptions is in section :ref:`try`. + +.. versionchanged:: 3.3 + :const:`None` is now permitted as ``Y`` in ``raise X from Y``. + +.. versionadded:: 3.3 + The ``__suppress_context__`` attribute to suppress automatic display of the + exception context. + +.. _break: + +The :keyword:`!break` statement +=============================== + +.. index:: + ! statement: break + statement: for + statement: while + pair: loop; statement + +.. productionlist:: + break_stmt: "break" + +:keyword:`break` may only occur syntactically nested in a :keyword:`for` or +:keyword:`while` loop, but not nested in a function or class definition within +that loop. + +.. index:: keyword: else + pair: loop control; target + +It terminates the nearest enclosing loop, skipping the optional :keyword:`!else` +clause if the loop has one. + +If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control +target keeps its current value. + +.. index:: keyword: finally + +When :keyword:`break` passes control out of a :keyword:`try` statement with a +:keyword:`finally` clause, that :keyword:`!finally` clause is executed before +really leaving the loop. + + +.. _continue: + +The :keyword:`!continue` statement +================================== + +.. index:: + ! statement: continue + statement: for + statement: while + pair: loop; statement + keyword: finally + +.. productionlist:: + continue_stmt: "continue" + +:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or +:keyword:`while` loop, but not nested in a function or class definition within +that loop. It continues with the next cycle of the nearest enclosing loop. + +When :keyword:`continue` passes control out of a :keyword:`try` statement with a +:keyword:`finally` clause, that :keyword:`!finally` clause is executed before +really starting the next loop cycle. + + +.. _import: +.. _from: + +The :keyword:`!import` statement +================================ + +.. index:: + ! statement: import + single: module; importing + pair: name; binding + keyword: from + keyword: as + exception: ImportError + single: , (comma); import statement + +.. productionlist:: + import_stmt: "import" `module` ["as" `identifier`] ("," `module` ["as" `identifier`])* + : | "from" `relative_module` "import" `identifier` ["as" `identifier`] + : ("," `identifier` ["as" `identifier`])* + : | "from" `relative_module` "import" "(" `identifier` ["as" `identifier`] + : ("," `identifier` ["as" `identifier`])* [","] ")" + : | "from" `module` "import" "*" + module: (`identifier` ".")* `identifier` + relative_module: "."* `module` | "."+ + +The basic import statement (no :keyword:`from` clause) is executed in two +steps: + +#. find a module, loading and initializing it if necessary +#. define a name or names in the local namespace for the scope where + the :keyword:`import` statement occurs. + +When the statement contains multiple clauses (separated by +commas) the two steps are carried out separately for each clause, just +as though the clauses had been separated out into individual import +statements. + +The details of the first step, finding and loading modules are described in +greater detail in the section on the :ref:`import system `, +which also describes the various types of packages and modules that can +be imported, as well as all the hooks that can be used to customize +the import system. Note that failures in this step may indicate either +that the module could not be located, *or* that an error occurred while +initializing the module, which includes execution of the module's code. + +If the requested module is retrieved successfully, it will be made +available in the local namespace in one of three ways: + +.. index:: single: as; import statement + +* If the module name is followed by :keyword:`!as`, then the name + following :keyword:`!as` is bound directly to the imported module. +* If no other name is specified, and the module being imported is a top + level module, the module's name is bound in the local namespace as a + reference to the imported module +* If the module being imported is *not* a top level module, then the name + of the top level package that contains the module is bound in the local + namespace as a reference to the top level package. The imported module + must be accessed using its full qualified name rather than directly + + +.. index:: + pair: name; binding + single: from; import statement + +The :keyword:`from` form uses a slightly more complex process: + +#. find the module specified in the :keyword:`from` clause, loading and + initializing it if necessary; +#. for each of the identifiers specified in the :keyword:`import` clauses: + + #. check if the imported module has an attribute by that name + #. if not, attempt to import a submodule with that name and then + check the imported module again for that attribute + #. if the attribute is not found, :exc:`ImportError` is raised. + #. otherwise, a reference to that value is stored in the local namespace, + using the name in the :keyword:`!as` clause if it is present, + otherwise using the attribute name + +Examples:: + + import foo # foo imported and bound locally + import foo.bar.baz # foo.bar.baz imported, foo bound locally + import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb + from foo.bar import baz # foo.bar.baz imported and bound as baz + from foo import attr # foo imported and foo.attr bound as attr + +.. index:: single: * (asterisk); import statement + +If the list of identifiers is replaced by a star (``'*'``), all public +names defined in the module are bound in the local namespace for the scope +where the :keyword:`import` statement occurs. + +.. index:: single: __all__ (optional module attribute) + +The *public names* defined by a module are determined by checking the module's +namespace for a variable named ``__all__``; if defined, it must be a sequence +of strings which are names defined or imported by that module. The names +given in ``__all__`` are all considered public and are required to exist. If +``__all__`` is not defined, the set of public names includes all names found +in the module's namespace which do not begin with an underscore character +(``'_'``). ``__all__`` should contain the entire public API. It is intended +to avoid accidentally exporting items that are not part of the API (such as +library modules which were imported and used within the module). + +The wild card form of import --- ``from module import *`` --- is only allowed at +the module level. Attempting to use it in class or function definitions will +raise a :exc:`SyntaxError`. + +.. index:: + single: relative; import + +When specifying what module to import you do not have to specify the absolute +name of the module. When a module or package is contained within another +package it is possible to make a relative import within the same top package +without having to mention the package name. By using leading dots in the +specified module or package after :keyword:`from` you can specify how high to +traverse up the current package hierarchy without specifying exact names. One +leading dot means the current package where the module making the import +exists. Two dots means up one package level. Three dots is up two levels, etc. +So if you execute ``from . import mod`` from a module in the ``pkg`` package +then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2 +import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``. +The specification for relative imports is contained in +the :ref:`relativeimports` section. + +:func:`importlib.import_module` is provided to support applications that +determine dynamically the modules to be loaded. + +.. audit-event:: import module,filename,sys.path,sys.meta_path,sys.path_hooks import + +.. _future: + +Future statements +----------------- + +.. index:: + pair: future; statement + single: __future__; future statement + +A :dfn:`future statement` is a directive to the compiler that a particular +module should be compiled using syntax or semantics that will be available in a +specified future release of Python where the feature becomes standard. + +The future statement is intended to ease migration to future versions of Python +that introduce incompatible changes to the language. It allows use of the new +features on a per-module basis before the release in which the feature becomes +standard. + +.. productionlist:: * + future_stmt: "from" "__future__" "import" `feature` ["as" `identifier`] + : ("," `feature` ["as" `identifier`])* + : | "from" "__future__" "import" "(" `feature` ["as" `identifier`] + : ("," `feature` ["as" `identifier`])* [","] ")" + feature: `identifier` + +A future statement must appear near the top of the module. The only lines that +can appear before a future statement are: + +* the module docstring (if any), +* comments, +* blank lines, and +* other future statements. + +The only feature in Python 3.7 that requires using the future statement is +``annotations``. + +All historical features enabled by the future statement are still recognized +by Python 3. The list includes ``absolute_import``, ``division``, +``generators``, ``generator_stop``, ``unicode_literals``, +``print_function``, ``nested_scopes`` and ``with_statement``. They are +all redundant because they are always enabled, and only kept for +backwards compatibility. + +A future statement is recognized and treated specially at compile time: Changes +to the semantics of core constructs are often implemented by generating +different code. It may even be the case that a new feature introduces new +incompatible syntax (such as a new reserved word), in which case the compiler +may need to parse the module differently. Such decisions cannot be pushed off +until runtime. + +For any given release, the compiler knows which feature names have been defined, +and raises a compile-time error if a future statement contains a feature not +known to it. + +The direct runtime semantics are the same as for any import statement: there is +a standard module :mod:`__future__`, described later, and it will be imported in +the usual way at the time the future statement is executed. + +The interesting runtime semantics depend on the specific feature enabled by the +future statement. + +Note that there is nothing special about the statement:: + + import __future__ [as name] + +That is not a future statement; it's an ordinary import statement with no +special semantics or syntax restrictions. + +Code compiled by calls to the built-in functions :func:`exec` and :func:`compile` +that occur in a module :mod:`M` containing a future statement will, by default, +use the new syntax or semantics associated with the future statement. This can +be controlled by optional arguments to :func:`compile` --- see the documentation +of that function for details. + +A future statement typed at an interactive interpreter prompt will take effect +for the rest of the interpreter session. If an interpreter is started with the +:option:`-i` option, is passed a script name to execute, and the script includes +a future statement, it will be in effect in the interactive session started +after the script is executed. + +.. seealso:: + + :pep:`236` - Back to the __future__ + The original proposal for the __future__ mechanism. + + +.. _global: + +The :keyword:`!global` statement +================================ + +.. index:: + ! statement: global + triple: global; name; binding + single: , (comma); identifier list + +.. productionlist:: + global_stmt: "global" `identifier` ("," `identifier`)* + +The :keyword:`global` statement is a declaration which holds for the entire +current code block. It means that the listed identifiers are to be interpreted +as globals. It would be impossible to assign to a global variable without +:keyword:`!global`, although free variables may refer to globals without being +declared global. + +Names listed in a :keyword:`global` statement must not be used in the same code +block textually preceding that :keyword:`!global` statement. + +Names listed in a :keyword:`global` statement must not be defined as formal +parameters or in a :keyword:`for` loop control target, :keyword:`class` +definition, function definition, :keyword:`import` statement, or variable +annotation. + +.. impl-detail:: + + The current implementation does not enforce some of these restrictions, but + programs should not abuse this freedom, as future implementations may enforce + them or silently change the meaning of the program. + +.. index:: + builtin: exec + builtin: eval + builtin: compile + +**Programmer's note:** :keyword:`global` is a directive to the parser. It +applies only to code parsed at the same time as the :keyword:`!global` statement. +In particular, a :keyword:`!global` statement contained in a string or code +object supplied to the built-in :func:`exec` function does not affect the code +block *containing* the function call, and code contained in such a string is +unaffected by :keyword:`!global` statements in the code containing the function +call. The same applies to the :func:`eval` and :func:`compile` functions. + + +.. _nonlocal: + +The :keyword:`!nonlocal` statement +================================== + +.. index:: statement: nonlocal + single: , (comma); identifier list + +.. productionlist:: + nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)* + +.. XXX add when implemented + : ["=" (`target_list` "=")+ starred_expression] + : | "nonlocal" identifier augop expression_list + +The :keyword:`nonlocal` statement causes the listed identifiers to refer to +previously bound variables in the nearest enclosing scope excluding globals. +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. + +.. XXX not implemented + The :keyword:`nonlocal` statement may prepend an assignment or augmented + assignment, but not an expression. + +Names listed in a :keyword:`nonlocal` statement, unlike those listed in a +:keyword:`global` statement, must refer to pre-existing bindings in an +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 +pre-existing bindings in the local scope. + +.. seealso:: + + :pep:`3104` - Access to Names in Outer Scopes + The specification for the :keyword:`nonlocal` statement. diff --git a/cpython_2/environment/repo/Doc/reference/toplevel_components.rst b/cpython_2/environment/repo/Doc/reference/toplevel_components.rst new file mode 100644 index 0000000000000000000000000000000000000000..d5ffb37b2e58cde69f65d4ea134b521e2c4edb08 --- /dev/null +++ b/cpython_2/environment/repo/Doc/reference/toplevel_components.rst @@ -0,0 +1,107 @@ + +.. _top-level: + +******************** +Top-level components +******************** + +.. index:: single: interpreter + +The Python interpreter can get its input from a number of sources: from a script +passed to it as standard input or as program argument, typed in interactively, +from a module source file, etc. This chapter gives the syntax used in these +cases. + + +.. _programs: + +Complete Python programs +======================== + +.. index:: single: program + +.. index:: + module: sys + module: __main__ + module: builtins + +While a language specification need not prescribe how the language interpreter +is invoked, it is useful to have a notion of a complete Python program. A +complete Python program is executed in a minimally initialized environment: all +built-in and standard modules are available, but none have been initialized, +except for :mod:`sys` (various system services), :mod:`builtins` (built-in +functions, exceptions and ``None``) and :mod:`__main__`. The latter is used to +provide the local and global namespace for execution of the complete program. + +The syntax for a complete Python program is that for file input, described in +the next section. + +.. index:: + single: interactive mode + module: __main__ + +The interpreter may also be invoked in interactive mode; in this case, it does +not read and execute a complete program but reads and executes one statement +(possibly compound) at a time. The initial environment is identical to that of +a complete program; each statement is executed in the namespace of +:mod:`__main__`. + +.. index:: + single: UNIX + single: Windows + single: command line + single: standard input + +A complete program can be passed to the interpreter +in three forms: with the :option:`-c` *string* command line option, as a file +passed as the first command line argument, or as standard input. If the file +or standard input is a tty device, the interpreter enters interactive mode; +otherwise, it executes the file as a complete program. + + +.. _file-input: + +File input +========== + +All input read from non-interactive files has the same form: + +.. productionlist:: + file_input: (NEWLINE | `statement`)* + +This syntax is used in the following situations: + +* when parsing a complete Python program (from a file or from a string); + +* when parsing a module; + +* when parsing a string passed to the :func:`exec` function; + + +.. _interactive: + +Interactive input +================= + +Input in interactive mode is parsed using the following grammar: + +.. productionlist:: + interactive_input: [`stmt_list`] NEWLINE | `compound_stmt` NEWLINE + +Note that a (top-level) compound statement must be followed by a blank line in +interactive mode; this is needed to help the parser detect the end of the input. + + +.. _expression-input: + +Expression input +================ + +.. index:: single: input +.. index:: builtin: eval + +:func:`eval` is used for expression input. It ignores leading whitespace. The +string argument to :func:`eval` must have the following form: + +.. productionlist:: + eval_input: `expression_list` NEWLINE* diff --git a/cpython_2/environment/repo/Doc/requirements.txt b/cpython_2/environment/repo/Doc/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..198446b350ff2d36ac385c85e3435cf3e7703b70 --- /dev/null +++ b/cpython_2/environment/repo/Doc/requirements.txt @@ -0,0 +1,5 @@ +# Requirements for docs build on netlify +# Pin sphinx to version specified in .travis.yml +sphinx==2.2.0 +blurb +python-docs-theme diff --git a/cpython_2/environment/repo/Doc/runtime.txt b/cpython_2/environment/repo/Doc/runtime.txt new file mode 100644 index 0000000000000000000000000000000000000000..548d71365f0ec73769cdca035854598aa03d5485 --- /dev/null +++ b/cpython_2/environment/repo/Doc/runtime.txt @@ -0,0 +1 @@ +3.7 \ No newline at end of file diff --git a/cpython_2/environment/repo/Doc/tools/extensions/asdl_highlight.py b/cpython_2/environment/repo/Doc/tools/extensions/asdl_highlight.py new file mode 100644 index 0000000000000000000000000000000000000000..7d2ef011c1b76678b4eb82d665f96c712089e357 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/extensions/asdl_highlight.py @@ -0,0 +1,51 @@ +import os +import sys +sys.path.append(os.path.abspath("../Parser/")) + +from pygments.lexer import RegexLexer, bygroups, include, words +from pygments.token import (Comment, Generic, Keyword, Name, Operator, + Punctuation, Text) + +from asdl import builtin_types +from sphinx.highlighting import lexers + +class ASDLLexer(RegexLexer): + name = "ASDL" + aliases = ["asdl"] + filenames = ["*.asdl"] + _name = r"([^\W\d]\w*)" + _text_ws = r"(\s*)" + + tokens = { + "ws": [ + (r"\n", Text), + (r"\s+", Text), + (r"--.*?$", Comment.Singleline), + ], + "root": [ + include("ws"), + ( + r"(module)" + _text_ws + _name, + bygroups(Keyword, Text, Name.Tag), + ), + ( + r"(\w+)(\*\s|\?\s|\s)(\w+)", + bygroups(Name.Builtin.Pseudo, Operator, Name), + ), + (words(builtin_types), Name.Builtin), + (r"attributes", Name.Builtin), + ( + _name + _text_ws + "(=)", + bygroups(Name, Text, Operator), + ), + (_name, Name.Class), + (r"\|", Operator), + (r"{|}|\(|\)", Punctuation), + (r".", Text), + ], + } + + +def setup(app): + lexers["asdl"] = ASDLLexer() + return {'version': '1.0', 'parallel_read_safe': True} diff --git a/cpython_2/environment/repo/Doc/tools/extensions/c_annotations.py b/cpython_2/environment/repo/Doc/tools/extensions/c_annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..fa8244a8fd318e9b68cb3178f5e2eba51788f51c --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/extensions/c_annotations.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +""" + c_annotations.py + ~~~~~~~~~~~~~~~~ + + Supports annotations for C API elements: + + * reference count annotations for C API functions. Based on + refcount.py and anno-api.py in the old Python documentation tools. + + * stable API annotations + + Usage: Set the `refcount_file` config value to the path to the reference + count data file. + + :copyright: Copyright 2007-2014 by Georg Brandl. + :license: Python license. +""" + +from os import path +from docutils import nodes +from docutils.parsers.rst import directives + +from sphinx import addnodes +from sphinx.domains.c import CObject + + +class RCEntry: + def __init__(self, name): + self.name = name + self.args = [] + self.result_type = '' + self.result_refs = None + + +class Annotations(dict): + @classmethod + def fromfile(cls, filename): + d = cls() + fp = open(filename, 'r') + try: + for line in fp: + line = line.strip() + if line[:1] in ("", "#"): + # blank lines and comments + continue + parts = line.split(":", 4) + if len(parts) != 5: + raise ValueError("Wrong field count in %r" % line) + function, type, arg, refcount, comment = parts + # Get the entry, creating it if needed: + try: + entry = d[function] + except KeyError: + entry = d[function] = RCEntry(function) + if not refcount or refcount == "null": + refcount = None + else: + refcount = int(refcount) + # Update the entry with the new parameter or the result + # information. + if arg: + entry.args.append((arg, type, refcount)) + else: + entry.result_type = type + entry.result_refs = refcount + finally: + fp.close() + return d + + def add_annotations(self, app, doctree): + for node in doctree.traverse(addnodes.desc_content): + par = node.parent + if par['domain'] != 'c': + continue + if par['stableabi']: + node.insert(0, nodes.emphasis(' Part of the stable ABI.', + ' Part of the stable ABI.', + classes=['stableabi'])) + if par['objtype'] != 'function': + continue + if not par[0].has_key('names') or not par[0]['names']: + continue + name = par[0]['names'][0] + if name.startswith("c."): + name = name[2:] + entry = self.get(name) + if not entry: + continue + elif not entry.result_type.endswith("Object*"): + continue + if entry.result_refs is None: + rc = 'Return value: Always NULL.' + elif entry.result_refs: + rc = 'Return value: New reference.' + else: + rc = 'Return value: Borrowed reference.' + node.insert(0, nodes.emphasis(rc, rc, classes=['refcount'])) + + +def init_annotations(app): + refcounts = Annotations.fromfile( + path.join(app.srcdir, app.config.refcount_file)) + app.connect('doctree-read', refcounts.add_annotations) + + +def setup(app): + app.add_config_value('refcount_file', '', True) + app.connect('builder-inited', init_annotations) + + # monkey-patch C object... + CObject.option_spec = { + 'noindex': directives.flag, + 'stableabi': directives.flag, + } + old_handle_signature = CObject.handle_signature + def new_handle_signature(self, sig, signode): + signode.parent['stableabi'] = 'stableabi' in self.options + return old_handle_signature(self, sig, signode) + CObject.handle_signature = new_handle_signature + return {'version': '1.0', 'parallel_read_safe': True} diff --git a/cpython_2/environment/repo/Doc/tools/extensions/escape4chm.py b/cpython_2/environment/repo/Doc/tools/extensions/escape4chm.py new file mode 100644 index 0000000000000000000000000000000000000000..e999971625173412e22997b4bf27e7a792eecd8f --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/extensions/escape4chm.py @@ -0,0 +1,57 @@ +""" +Escape the `body` part of .chm source file to 7-bit ASCII, to fix visual +effect on some MBCS Windows systems. + +https://bugs.python.org/issue32174 +""" + +import re +from html.entities import codepoint2name + +from sphinx.util.logging import getLogger + +# escape the characters which codepoint > 0x7F +def _process(string): + def escape(matchobj): + codepoint = ord(matchobj.group(0)) + + name = codepoint2name.get(codepoint) + if name is None: + return '&#%d;' % codepoint + else: + return '&%s;' % name + + return re.sub(r'[^\x00-\x7F]', escape, string) + +def escape_for_chm(app, pagename, templatename, context, doctree): + # only works for .chm output + if getattr(app.builder, 'name', '') != 'htmlhelp': + return + + # escape the `body` part to 7-bit ASCII + body = context.get('body') + if body is not None: + context['body'] = _process(body) + +def fixup_keywords(app, exception): + # only works for .chm output + if getattr(app.builder, 'name', '') != 'htmlhelp' or exception: + return + + getLogger(__name__).info('fixing HTML escapes in keywords file...') + outdir = app.builder.outdir + outname = app.builder.config.htmlhelp_basename + with app.builder.open_file(outdir, outname + '.hhk', 'r') as f: + index = f.read() + with app.builder.open_file(outdir, outname + '.hhk', 'w') as f: + f.write(index.replace(''', ''')) + +def setup(app): + # `html-page-context` event emitted when the HTML builder has + # created a context dictionary to render a template with. + app.connect('html-page-context', escape_for_chm) + # `build-finished` event emitted when all the files have been + # output. + app.connect('build-finished', fixup_keywords) + + return {'version': '1.0', 'parallel_read_safe': True} diff --git a/cpython_2/environment/repo/Doc/tools/extensions/patchlevel.py b/cpython_2/environment/repo/Doc/tools/extensions/patchlevel.py new file mode 100644 index 0000000000000000000000000000000000000000..617f28c2527ddff98eb308addf2addf17779be23 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/extensions/patchlevel.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +""" + patchlevel.py + ~~~~~~~~~~~~~ + + Extract version info from Include/patchlevel.h. + Adapted from Doc/tools/getversioninfo. + + :copyright: 2007-2008 by Georg Brandl. + :license: Python license. +""" + +from __future__ import print_function + +import os +import re +import sys + +def get_header_version_info(srcdir): + patchlevel_h = os.path.join(srcdir, '..', 'Include', 'patchlevel.h') + + # This won't pick out all #defines, but it will pick up the ones we + # care about. + rx = re.compile(r'\s*#define\s+([a-zA-Z][a-zA-Z_0-9]*)\s+([a-zA-Z_0-9]+)') + + d = {} + with open(patchlevel_h) as f: + for line in f: + m = rx.match(line) + if m is not None: + name, value = m.group(1, 2) + d[name] = value + + release = version = '%s.%s' % (d['PY_MAJOR_VERSION'], d['PY_MINOR_VERSION']) + micro = int(d['PY_MICRO_VERSION']) + release += '.' + str(micro) + + level = d['PY_RELEASE_LEVEL'] + suffixes = { + 'PY_RELEASE_LEVEL_ALPHA': 'a', + 'PY_RELEASE_LEVEL_BETA': 'b', + 'PY_RELEASE_LEVEL_GAMMA': 'rc', + } + if level != 'PY_RELEASE_LEVEL_FINAL': + release += suffixes[level] + str(int(d['PY_RELEASE_SERIAL'])) + return version, release + + +def get_sys_version_info(): + major, minor, micro, level, serial = sys.version_info + release = version = '%s.%s' % (major, minor) + release += '.%s' % micro + if level != 'final': + release += '%s%s' % (level[0], serial) + return version, release + + +def get_version_info(): + try: + return get_header_version_info('.') + except (IOError, OSError): + version, release = get_sys_version_info() + print('Can\'t get version info from Include/patchlevel.h, ' \ + 'using version of this interpreter (%s).' % release, file=sys.stderr) + return version, release + +if __name__ == '__main__': + print(get_header_version_info('.')[1]) diff --git a/cpython_2/environment/repo/Doc/tools/extensions/pyspecific.py b/cpython_2/environment/repo/Doc/tools/extensions/pyspecific.py new file mode 100644 index 0000000000000000000000000000000000000000..bc51555fa0512b4a1e4e4bdb051bf923a6cfd645 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/extensions/pyspecific.py @@ -0,0 +1,583 @@ +# -*- coding: utf-8 -*- +""" + pyspecific.py + ~~~~~~~~~~~~~ + + Sphinx extension with Python doc-specific markup. + + :copyright: 2008-2014 by Georg Brandl. + :license: Python license. +""" + +import re +import io +from os import getenv, path +from time import asctime +from pprint import pformat +from docutils.io import StringOutput +from docutils.parsers.rst import Directive +from docutils.utils import new_document + +from docutils import nodes, utils + +from sphinx import addnodes +from sphinx.builders import Builder +try: + from sphinx.errors import NoUri +except ImportError: + from sphinx.environment import NoUri +from sphinx.locale import translators +from sphinx.util import status_iterator, logging +from sphinx.util.nodes import split_explicit_title +from sphinx.writers.text import TextWriter, TextTranslator +from sphinx.writers.latex import LaTeXTranslator +from sphinx.domains.python import PyModulelevel, PyClassmember + +# Support for checking for suspicious markup + +import suspicious + + +ISSUE_URI = 'https://bugs.python.org/issue%s' +SOURCE_URI = 'https://github.com/python/cpython/tree/master/%s' + +# monkey-patch reST parser to disable alphabetic and roman enumerated lists +from docutils.parsers.rst.states import Body +Body.enum.converters['loweralpha'] = \ + Body.enum.converters['upperalpha'] = \ + Body.enum.converters['lowerroman'] = \ + Body.enum.converters['upperroman'] = lambda x: None + + +# Support for marking up and linking to bugs.python.org issues + +def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): + issue = utils.unescape(text) + text = 'bpo-' + issue + refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue) + return [refnode], [] + + +# Support for linking to Python source files easily + +def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): + has_t, title, target = split_explicit_title(text) + title = utils.unescape(title) + target = utils.unescape(target) + refnode = nodes.reference(title, title, refuri=SOURCE_URI % target) + return [refnode], [] + + +# Support for marking up implementation details + +class ImplementationDetail(Directive): + + has_content = True + required_arguments = 0 + optional_arguments = 1 + final_argument_whitespace = True + + # This text is copied to templates/dummy.html + label_text = 'CPython implementation detail:' + + def run(self): + pnode = nodes.compound(classes=['impl-detail']) + label = translators['sphinx'].gettext(self.label_text) + content = self.content + add_text = nodes.strong(label, label) + if self.arguments: + n, m = self.state.inline_text(self.arguments[0], self.lineno) + pnode.append(nodes.paragraph('', '', *(n + m))) + self.state.nested_parse(content, self.content_offset, pnode) + if pnode.children and isinstance(pnode[0], nodes.paragraph): + content = nodes.inline(pnode[0].rawsource, translatable=True) + content.source = pnode[0].source + content.line = pnode[0].line + content += pnode[0].children + pnode[0].replace_self(nodes.paragraph('', '', content, + translatable=False)) + pnode[0].insert(0, add_text) + pnode[0].insert(1, nodes.Text(' ')) + else: + pnode.insert(0, nodes.paragraph('', '', add_text)) + return [pnode] + + +# Support for documenting platform availability + +class Availability(Directive): + + has_content = False + required_arguments = 1 + optional_arguments = 0 + final_argument_whitespace = True + + def run(self): + availability_ref = ':ref:`Availability `: ' + pnode = nodes.paragraph(availability_ref + self.arguments[0], + classes=["availability"],) + n, m = self.state.inline_text(availability_ref, self.lineno) + pnode.extend(n + m) + n, m = self.state.inline_text(self.arguments[0], self.lineno) + pnode.extend(n + m) + return [pnode] + + +# Support for documenting audit event + +class AuditEvent(Directive): + + has_content = True + required_arguments = 1 + optional_arguments = 2 + final_argument_whitespace = True + + _label = [ + "Raises an :ref:`auditing event ` {name} with no arguments.", + "Raises an :ref:`auditing event ` {name} with argument {args}.", + "Raises an :ref:`auditing event ` {name} with arguments {args}.", + ] + + @property + def logger(self): + cls = type(self) + return logging.getLogger(cls.__module__ + "." + cls.__name__) + + def run(self): + name = self.arguments[0] + if len(self.arguments) >= 2 and self.arguments[1]: + args = (a.strip() for a in self.arguments[1].strip("'\"").split(",")) + args = [a for a in args if a] + else: + args = [] + + label = translators['sphinx'].gettext(self._label[min(2, len(args))]) + text = label.format(name="``{}``".format(name), + args=", ".join("``{}``".format(a) for a in args if a)) + + env = self.state.document.settings.env + if not hasattr(env, 'all_audit_events'): + env.all_audit_events = {} + + new_info = { + 'source': [], + 'args': args + } + info = env.all_audit_events.setdefault(name, new_info) + if info is not new_info: + if not self._do_args_match(info['args'], new_info['args']): + self.logger.warn( + "Mismatched arguments for audit-event {}: {!r} != {!r}" + .format(name, info['args'], new_info['args']) + ) + + ids = [] + try: + target = self.arguments[2].strip("\"'") + except (IndexError, TypeError): + target = None + if not target: + target = "audit_event_{}_{}".format( + re.sub(r'\W', '_', name), + len(info['source']), + ) + ids.append(target) + + info['source'].append((env.docname, target)) + + pnode = nodes.paragraph(text, classes=["audit-hook"], ids=ids) + if self.content: + self.state.nested_parse(self.content, self.content_offset, pnode) + else: + n, m = self.state.inline_text(text, self.lineno) + pnode.extend(n + m) + + return [pnode] + + # This list of sets are allowable synonyms for event argument names. + # If two names are in the same set, they are treated as equal for the + # purposes of warning. This won't help if number of arguments is + # different! + _SYNONYMS = [ + {"file", "path", "fd"}, + ] + + def _do_args_match(self, args1, args2): + if args1 == args2: + return True + if len(args1) != len(args2): + return False + for a1, a2 in zip(args1, args2): + if a1 == a2: + continue + if any(a1 in s and a2 in s for s in self._SYNONYMS): + continue + return False + return True + + +class audit_event_list(nodes.General, nodes.Element): + pass + + +class AuditEventListDirective(Directive): + + def run(self): + return [audit_event_list('')] + + +# Support for documenting decorators + +class PyDecoratorMixin(object): + def handle_signature(self, sig, signode): + ret = super(PyDecoratorMixin, self).handle_signature(sig, signode) + signode.insert(0, addnodes.desc_addname('@', '@')) + return ret + + def needs_arglist(self): + return False + + +class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel): + def run(self): + # a decorator function is a function after all + self.name = 'py:function' + return PyModulelevel.run(self) + + +class PyDecoratorMethod(PyDecoratorMixin, PyClassmember): + def run(self): + self.name = 'py:method' + return PyClassmember.run(self) + + +class PyCoroutineMixin(object): + def handle_signature(self, sig, signode): + ret = super(PyCoroutineMixin, self).handle_signature(sig, signode) + signode.insert(0, addnodes.desc_annotation('coroutine ', 'coroutine ')) + return ret + + +class PyAwaitableMixin(object): + def handle_signature(self, sig, signode): + ret = super(PyAwaitableMixin, self).handle_signature(sig, signode) + signode.insert(0, addnodes.desc_annotation('awaitable ', 'awaitable ')) + return ret + + +class PyCoroutineFunction(PyCoroutineMixin, PyModulelevel): + def run(self): + self.name = 'py:function' + return PyModulelevel.run(self) + + +class PyCoroutineMethod(PyCoroutineMixin, PyClassmember): + def run(self): + self.name = 'py:method' + return PyClassmember.run(self) + + +class PyAwaitableFunction(PyAwaitableMixin, PyClassmember): + def run(self): + self.name = 'py:function' + return PyClassmember.run(self) + + +class PyAwaitableMethod(PyAwaitableMixin, PyClassmember): + def run(self): + self.name = 'py:method' + return PyClassmember.run(self) + + +class PyAbstractMethod(PyClassmember): + + def handle_signature(self, sig, signode): + ret = super(PyAbstractMethod, self).handle_signature(sig, signode) + signode.insert(0, addnodes.desc_annotation('abstractmethod ', + 'abstractmethod ')) + return ret + + def run(self): + self.name = 'py:method' + return PyClassmember.run(self) + + +# Support for documenting version of removal in deprecations + +class DeprecatedRemoved(Directive): + has_content = True + required_arguments = 2 + optional_arguments = 1 + final_argument_whitespace = True + option_spec = {} + + _label = 'Deprecated since version {deprecated}, will be removed in version {removed}' + + def run(self): + node = addnodes.versionmodified() + node.document = self.state.document + node['type'] = 'deprecated-removed' + version = (self.arguments[0], self.arguments[1]) + node['version'] = version + label = translators['sphinx'].gettext(self._label) + text = label.format(deprecated=self.arguments[0], removed=self.arguments[1]) + if len(self.arguments) == 3: + inodes, messages = self.state.inline_text(self.arguments[2], + self.lineno+1) + para = nodes.paragraph(self.arguments[2], '', *inodes, translatable=False) + node.append(para) + else: + messages = [] + if self.content: + self.state.nested_parse(self.content, self.content_offset, node) + if len(node): + if isinstance(node[0], nodes.paragraph) and node[0].rawsource: + content = nodes.inline(node[0].rawsource, translatable=True) + content.source = node[0].source + content.line = node[0].line + content += node[0].children + node[0].replace_self(nodes.paragraph('', '', content, translatable=False)) + node[0].insert(0, nodes.inline('', '%s: ' % text, + classes=['versionmodified'])) + else: + para = nodes.paragraph('', '', + nodes.inline('', '%s.' % text, + classes=['versionmodified']), + translatable=False) + node.append(para) + env = self.state.document.settings.env + env.get_domain('changeset').note_changeset(node) + return [node] + messages + + +# Support for including Misc/NEWS + +issue_re = re.compile('(?:[Ii]ssue #|bpo-)([0-9]+)') +whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$") + + +class MiscNews(Directive): + has_content = False + required_arguments = 1 + optional_arguments = 0 + final_argument_whitespace = False + option_spec = {} + + def run(self): + fname = self.arguments[0] + source = self.state_machine.input_lines.source( + self.lineno - self.state_machine.input_offset - 1) + source_dir = getenv('PY_MISC_NEWS_DIR') + if not source_dir: + source_dir = path.dirname(path.abspath(source)) + fpath = path.join(source_dir, fname) + self.state.document.settings.record_dependencies.add(fpath) + try: + with io.open(fpath, encoding='utf-8') as fp: + content = fp.read() + except Exception: + text = 'The NEWS file is not available.' + node = nodes.strong(text, text) + return [node] + content = issue_re.sub(r'`bpo-\1 `__', + content) + content = whatsnew_re.sub(r'\1', content) + # remove first 3 lines as they are the main heading + lines = ['.. default-role:: obj', ''] + content.splitlines()[3:] + self.state_machine.insert_input(lines, fname) + return [] + + +# Support for building "topic help" for pydoc + +pydoc_topic_labels = [ + 'assert', 'assignment', 'async', 'atom-identifiers', 'atom-literals', + 'attribute-access', 'attribute-references', 'augassign', 'await', + 'binary', 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object', + 'bltin-null-object', 'bltin-type-objects', 'booleans', + 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound', + 'context-managers', 'continue', 'conversions', 'customization', 'debugger', + 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel', + 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global', + 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers', + 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types', + 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return', + 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames', + 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types', + 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules', + 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield' +] + + +class PydocTopicsBuilder(Builder): + name = 'pydoc-topics' + + default_translator_class = TextTranslator + + def init(self): + self.topics = {} + self.secnumbers = {} + + def get_outdated_docs(self): + return 'all pydoc topics' + + def get_target_uri(self, docname, typ=None): + return '' # no URIs + + def write(self, *ignored): + writer = TextWriter(self) + for label in status_iterator(pydoc_topic_labels, + 'building topics... ', + length=len(pydoc_topic_labels)): + if label not in self.env.domaindata['std']['labels']: + self.env.logger.warn('label %r not in documentation' % label) + continue + docname, labelid, sectname = self.env.domaindata['std']['labels'][label] + doctree = self.env.get_and_resolve_doctree(docname, self) + document = new_document('
') + document.append(doctree.ids[labelid]) + destination = StringOutput(encoding='utf-8') + writer.write(document, destination) + self.topics[label] = writer.output + + def finish(self): + f = open(path.join(self.outdir, 'topics.py'), 'wb') + try: + f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8')) + f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8')) + f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8')) + finally: + f.close() + + +# Support for documenting Opcodes + +opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?') + + +def parse_opcode_signature(env, sig, signode): + """Transform an opcode signature into RST nodes.""" + m = opcode_sig_re.match(sig) + if m is None: + raise ValueError + opname, arglist = m.groups() + signode += addnodes.desc_name(opname, opname) + if arglist is not None: + paramlist = addnodes.desc_parameterlist() + signode += paramlist + paramlist += addnodes.desc_parameter(arglist, arglist) + return opname.strip() + + +# Support for documenting pdb commands + +pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)') + +# later... +# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers +# [.,:]+ | # punctuation +# [\[\]()] | # parens +# \s+ # whitespace +# ''', re.X) + + +def parse_pdb_command(env, sig, signode): + """Transform a pdb command signature into RST nodes.""" + m = pdbcmd_sig_re.match(sig) + if m is None: + raise ValueError + name, args = m.groups() + fullname = name.replace('(', '').replace(')', '') + signode += addnodes.desc_name(name, name) + if args: + signode += addnodes.desc_addname(' '+args, ' '+args) + return fullname + + +def process_audit_events(app, doctree, fromdocname): + for node in doctree.traverse(audit_event_list): + break + else: + return + + env = app.builder.env + + table = nodes.table(cols=3) + group = nodes.tgroup( + '', + nodes.colspec(colwidth=30), + nodes.colspec(colwidth=55), + nodes.colspec(colwidth=15), + cols=3, + ) + head = nodes.thead() + body = nodes.tbody() + + table += group + group += head + group += body + + row = nodes.row() + row += nodes.entry('', nodes.paragraph('', nodes.Text('Audit event'))) + row += nodes.entry('', nodes.paragraph('', nodes.Text('Arguments'))) + row += nodes.entry('', nodes.paragraph('', nodes.Text('References'))) + head += row + + for name in sorted(getattr(env, "all_audit_events", ())): + audit_event = env.all_audit_events[name] + + row = nodes.row() + node = nodes.paragraph('', nodes.Text(name)) + row += nodes.entry('', node) + + node = nodes.paragraph() + for i, a in enumerate(audit_event['args']): + if i: + node += nodes.Text(", ") + node += nodes.literal(a, nodes.Text(a)) + row += nodes.entry('', node) + + node = nodes.paragraph() + backlinks = enumerate(sorted(set(audit_event['source'])), start=1) + for i, (doc, label) in backlinks: + if isinstance(label, str): + ref = nodes.reference("", nodes.Text("[{}]".format(i)), internal=True) + try: + ref['refuri'] = "{}#{}".format( + app.builder.get_relative_uri(fromdocname, doc), + label, + ) + except NoUri: + continue + node += ref + row += nodes.entry('', node) + + body += row + + for node in doctree.traverse(audit_event_list): + node.replace_self(table) + + +def setup(app): + app.add_role('issue', issue_role) + app.add_role('source', source_role) + app.add_directive('impl-detail', ImplementationDetail) + app.add_directive('availability', Availability) + app.add_directive('audit-event', AuditEvent) + app.add_directive('audit-event-table', AuditEventListDirective) + app.add_directive('deprecated-removed', DeprecatedRemoved) + app.add_builder(PydocTopicsBuilder) + app.add_builder(suspicious.CheckSuspiciousMarkupBuilder) + app.add_object_type('opcode', 'opcode', '%s (opcode)', parse_opcode_signature) + app.add_object_type('pdbcommand', 'pdbcmd', '%s (pdb command)', parse_pdb_command) + app.add_object_type('2to3fixer', '2to3fixer', '%s (2to3 fixer)') + app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction) + app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod) + app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction) + app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod) + app.add_directive_to_domain('py', 'awaitablefunction', PyAwaitableFunction) + app.add_directive_to_domain('py', 'awaitablemethod', PyAwaitableMethod) + app.add_directive_to_domain('py', 'abstractmethod', PyAbstractMethod) + app.add_directive('miscnews', MiscNews) + app.connect('doctree-resolved', process_audit_events) + return {'version': '1.0', 'parallel_read_safe': True} diff --git a/cpython_2/environment/repo/Doc/tools/extensions/suspicious.py b/cpython_2/environment/repo/Doc/tools/extensions/suspicious.py new file mode 100644 index 0000000000000000000000000000000000000000..9e814fb94d2b56f596a40055855249b6430bdb5f --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/extensions/suspicious.py @@ -0,0 +1,278 @@ +""" +Try to detect suspicious constructs, resembling markup +that has leaked into the final output. + +Suspicious lines are reported in a comma-separated-file, +``suspicious.csv``, located in the output directory. + +The file is utf-8 encoded, and each line contains four fields: + + * document name (normalized) + * line number in the source document + * problematic text + * complete line showing the problematic text in context + +It is common to find many false positives. To avoid reporting them +again and again, they may be added to the ``ignored.csv`` file +(located in the configuration directory). The file has the same +format as ``suspicious.csv`` with a few differences: + + - each line defines a rule; if the rule matches, the issue + is ignored. + - line number may be empty (that is, nothing between the + commas: ",,"). In this case, line numbers are ignored (the + rule matches anywhere in the file). + - the last field does not have to be a complete line; some + surrounding text (never more than a line) is enough for + context. + +Rules are processed sequentially. A rule matches when: + + * document names are the same + * problematic texts are the same + * line numbers are close to each other (5 lines up or down) + * the rule text is completely contained into the source line + +The simplest way to create the ignored.csv file is by copying +undesired entries from suspicious.csv (possibly trimming the last +field.) + +Copyright 2009 Gabriel A. Genellina + +""" + +import os +import re +import csv +import sys + +from docutils import nodes +from sphinx.builders import Builder +import sphinx.util + +detect_all = re.compile(r''' + ::(?=[^=])| # two :: (but NOT ::=) + :[a-zA-Z][a-zA-Z0-9]+| # :foo + `| # ` (seldom used by itself) + (?= (3, 0) + + +class Rule: + def __init__(self, docname, lineno, issue, line): + """A rule for ignoring issues""" + self.docname = docname # document to which this rule applies + self.lineno = lineno # line number in the original source; + # this rule matches only near that. + # None -> don't care + self.issue = issue # the markup fragment that triggered this rule + self.line = line # text of the container element (single line only) + self.used = False + + def __repr__(self): + return '{0.docname},,{0.issue},{0.line}'.format(self) + + + +class dialect(csv.excel): + """Our dialect: uses only linefeed as newline.""" + lineterminator = '\n' + + +class CheckSuspiciousMarkupBuilder(Builder): + """ + Checks for possibly invalid markup that may leak into the output. + """ + name = 'suspicious' + logger = sphinx.util.logging.getLogger("CheckSuspiciousMarkupBuilder") + + def init(self): + # create output file + self.log_file_name = os.path.join(self.outdir, 'suspicious.csv') + open(self.log_file_name, 'w').close() + # load database of previously ignored issues + self.load_rules(os.path.join(os.path.dirname(__file__), '..', + 'susp-ignored.csv')) + + def get_outdated_docs(self): + return self.env.found_docs + + def get_target_uri(self, docname, typ=None): + return '' + + def prepare_writing(self, docnames): + pass + + def write_doc(self, docname, doctree): + # set when any issue is encountered in this document + self.any_issue = False + self.docname = docname + visitor = SuspiciousVisitor(doctree, self) + doctree.walk(visitor) + + def finish(self): + unused_rules = [rule for rule in self.rules if not rule.used] + if unused_rules: + self.logger.warning( + 'Found %s/%s unused rules: %s' % ( + len(unused_rules), len(self.rules), + ''.join(repr(rule) for rule in unused_rules), + ) + ) + return + + def check_issue(self, line, lineno, issue): + if not self.is_ignored(line, lineno, issue): + self.report_issue(line, lineno, issue) + + def is_ignored(self, line, lineno, issue): + """Determine whether this issue should be ignored.""" + docname = self.docname + for rule in self.rules: + if rule.docname != docname: continue + if rule.issue != issue: continue + # Both lines must match *exactly*. This is rather strict, + # and probably should be improved. + # Doing fuzzy matches with levenshtein distance could work, + # but that means bringing other libraries... + # Ok, relax that requirement: just check if the rule fragment + # is contained in the document line + if rule.line not in line: continue + # Check both line numbers. If they're "near" + # this rule matches. (lineno=None means "don't care") + if (rule.lineno is not None) and \ + abs(rule.lineno - lineno) > 5: continue + # if it came this far, the rule matched + rule.used = True + return True + return False + + def report_issue(self, text, lineno, issue): + self.any_issue = True + self.write_log_entry(lineno, issue, text) + if py3: + self.logger.warning('[%s:%d] "%s" found in "%-.120s"' % + (self.docname, lineno, issue, text)) + else: + self.logger.warning( + '[%s:%d] "%s" found in "%-.120s"' % ( + self.docname.encode(sys.getdefaultencoding(),'replace'), + lineno, + issue.encode(sys.getdefaultencoding(),'replace'), + text.strip().encode(sys.getdefaultencoding(),'replace'))) + self.app.statuscode = 1 + + def write_log_entry(self, lineno, issue, text): + if py3: + f = open(self.log_file_name, 'a') + writer = csv.writer(f, dialect) + writer.writerow([self.docname, lineno, issue, text.strip()]) + f.close() + else: + f = open(self.log_file_name, 'ab') + writer = csv.writer(f, dialect) + writer.writerow([self.docname.encode('utf-8'), + lineno, + issue.encode('utf-8'), + text.strip().encode('utf-8')]) + f.close() + + def load_rules(self, filename): + """Load database of previously ignored issues. + + A csv file, with exactly the same format as suspicious.csv + Fields: document name (normalized), line number, issue, surrounding text + """ + self.logger.info("loading ignore rules... ", nonl=1) + self.rules = rules = [] + try: + if py3: + f = open(filename, 'r') + else: + f = open(filename, 'rb') + except IOError: + return + for i, row in enumerate(csv.reader(f)): + if len(row) != 4: + raise ValueError( + "wrong format in %s, line %d: %s" % (filename, i+1, row)) + docname, lineno, issue, text = row + if lineno: + lineno = int(lineno) + else: + lineno = None + if not py3: + docname = docname.decode('utf-8') + issue = issue.decode('utf-8') + text = text.decode('utf-8') + rule = Rule(docname, lineno, issue, text) + rules.append(rule) + f.close() + self.logger.info('done, %d rules loaded' % len(self.rules)) + + +def get_lineno(node): + """Obtain line number information for a node.""" + lineno = None + while lineno is None and node: + node = node.parent + lineno = node.line + return lineno + + +def extract_line(text, index): + """text may be a multiline string; extract + only the line containing the given character index. + + >>> extract_line("abc\ndefgh\ni", 6) + >>> 'defgh' + >>> for i in (0, 2, 3, 4, 10): + ... print extract_line("abc\ndefgh\ni", i) + abc + abc + abc + defgh + defgh + i + """ + p = text.rfind('\n', 0, index) + 1 + q = text.find('\n', index) + if q < 0: + q = len(text) + return text[p:q] + + +class SuspiciousVisitor(nodes.GenericNodeVisitor): + + lastlineno = 0 + + def __init__(self, document, builder): + nodes.GenericNodeVisitor.__init__(self, document) + self.builder = builder + + def default_visit(self, node): + if isinstance(node, (nodes.Text, nodes.image)): # direct text containers + text = node.astext() + # lineno seems to go backwards sometimes (?) + self.lastlineno = lineno = max(get_lineno(node) or 0, self.lastlineno) + seen = set() # don't report the same issue more than only once per line + for match in detect_all(text): + issue = match.group() + line = extract_line(text, match.start()) + if (issue, line) not in seen: + self.builder.check_issue(line, lineno, issue) + seen.add((issue, line)) + + unknown_visit = default_visit + + def visit_document(self, node): + self.lastlineno = 0 + + def visit_comment(self, node): + # ignore comments -- too much false positives. + # (although doing this could miss some errors; + # there were two sections "commented-out" by mistake + # in the Python docs that would not be caught) + raise nodes.SkipNode diff --git a/cpython_2/environment/repo/Doc/tools/rstlint.py b/cpython_2/environment/repo/Doc/tools/rstlint.py new file mode 100644 index 0000000000000000000000000000000000000000..a3024d6734d25b296b035b3a74aecaa67de3f74f --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/rstlint.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Check for stylistic and formal issues in .rst and .py +# files included in the documentation. +# +# 01/2009, Georg Brandl + +# TODO: - wrong versions in versionadded/changed +# - wrong markup after versionchanged directive + +import os +import re +import sys +import getopt +from os.path import join, splitext, abspath, exists +from collections import defaultdict + +directives = [ + # standard docutils ones + 'admonition', 'attention', 'caution', 'class', 'compound', 'container', + 'contents', 'csv-table', 'danger', 'date', 'default-role', 'epigraph', + 'error', 'figure', 'footer', 'header', 'highlights', 'hint', 'image', + 'important', 'include', 'line-block', 'list-table', 'meta', 'note', + 'parsed-literal', 'pull-quote', 'raw', 'replace', + 'restructuredtext-test-directive', 'role', 'rubric', 'sectnum', 'sidebar', + 'table', 'target-notes', 'tip', 'title', 'topic', 'unicode', 'warning', + # Sphinx and Python docs custom ones + 'acks', 'attribute', 'autoattribute', 'autoclass', 'autodata', + 'autoexception', 'autofunction', 'automethod', 'automodule', + 'availability', 'centered', 'cfunction', 'class', 'classmethod', 'cmacro', + 'cmdoption', 'cmember', 'code-block', 'confval', 'cssclass', 'ctype', + 'currentmodule', 'cvar', 'data', 'decorator', 'decoratormethod', + 'deprecated-removed', 'deprecated(?!-removed)', 'describe', 'directive', + 'doctest', 'envvar', 'event', 'exception', 'function', 'glossary', + 'highlight', 'highlightlang', 'impl-detail', 'index', 'literalinclude', + 'method', 'miscnews', 'module', 'moduleauthor', 'opcode', 'pdbcommand', + 'productionlist', 'program', 'role', 'sectionauthor', 'seealso', + 'sourcecode', 'staticmethod', 'tabularcolumns', 'testcode', 'testoutput', + 'testsetup', 'toctree', 'todo', 'todolist', 'versionadded', + 'versionchanged' +] + +all_directives = '(' + '|'.join(directives) + ')' +seems_directive_re = re.compile(r'(? 81: + # don't complain about tables, links and function signatures + if line.lstrip()[0] not in '+|' and \ + 'http://' not in line and \ + not line.lstrip().startswith(('.. function', + '.. method', + '.. cfunction')): + yield lno+1, "line too long" + + +@checker('.html', severity=2, falsepositives=True) +def check_leaked_markup(fn, lines): + """Check HTML files for leaked reST markup; this only works if + the HTML files have been built. + """ + for lno, line in enumerate(lines): + if leaked_markup_re.search(line): + yield lno+1, 'possibly leaked markup: %r' % line + + +def main(argv): + usage = '''\ +Usage: %s [-v] [-f] [-s sev] [-i path]* [path] + +Options: -v verbose (print all checked file names) + -f enable checkers that yield many false positives + -s sev only show problems with severity >= sev + -i path ignore subdir or file path +''' % argv[0] + try: + gopts, args = getopt.getopt(argv[1:], 'vfs:i:') + except getopt.GetoptError: + print(usage) + return 2 + + verbose = False + severity = 1 + ignore = [] + falsepos = False + for opt, val in gopts: + if opt == '-v': + verbose = True + elif opt == '-f': + falsepos = True + elif opt == '-s': + severity = int(val) + elif opt == '-i': + ignore.append(abspath(val)) + + if len(args) == 0: + path = '.' + elif len(args) == 1: + path = args[0] + else: + print(usage) + return 2 + + if not exists(path): + print('Error: path %s does not exist' % path) + return 2 + + count = defaultdict(int) + + for root, dirs, files in os.walk(path): + # ignore subdirs in ignore list + if abspath(root) in ignore: + del dirs[:] + continue + + for fn in files: + fn = join(root, fn) + if fn[:2] == './': + fn = fn[2:] + + # ignore files in ignore list + if abspath(fn) in ignore: + continue + + ext = splitext(fn)[1] + checkerlist = checkers.get(ext, None) + if not checkerlist: + continue + + if verbose: + print('Checking %s...' % fn) + + try: + with open(fn, 'r', encoding='utf-8') as f: + lines = list(f) + except (IOError, OSError) as err: + print('%s: cannot open: %s' % (fn, err)) + count[4] += 1 + continue + + for checker in checkerlist: + if checker.falsepositives and not falsepos: + continue + csev = checker.severity + if csev >= severity: + for lno, msg in checker(fn, lines): + print('[%d] %s:%d: %s' % (csev, fn, lno, msg)) + count[csev] += 1 + if verbose: + print() + if not count: + if severity > 1: + print('No problems with severity >= %d found.' % severity) + else: + print('No problems found.') + else: + for severity in sorted(count): + number = count[severity] + print('%d problem%s with severity %d found.' % + (number, number > 1 and 's' or '', severity)) + return int(bool(count)) + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/cpython_2/environment/repo/Doc/tools/static/changelog_search.js b/cpython_2/environment/repo/Doc/tools/static/changelog_search.js new file mode 100644 index 0000000000000000000000000000000000000000..c881a9bd4c84a768288dc7e1283388ae7d3f972c --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/static/changelog_search.js @@ -0,0 +1,53 @@ +$(document).ready(function() { + // add the search form and bind the events + $('h1').after([ + '

Filter entries by content:', + '', + '

' + ].join('\n')); + + function dofilter() { + try { + var query = new RegExp($('#searchbox').val(), 'i'); + } + catch (e) { + return; // not a valid regex (yet) + } + // find headers for the versions (What's new in Python X.Y.Z?) + $('#changelog h2').each(function(index1, h2) { + var h2_parent = $(h2).parent(); + var sections_found = 0; + // find headers for the sections (Core, Library, etc.) + h2_parent.find('h3').each(function(index2, h3) { + var h3_parent = $(h3).parent(); + var entries_found = 0; + // find all the entries + h3_parent.find('li').each(function(index3, li) { + var li = $(li); + // check if the query matches the entry + if (query.test(li.text())) { + li.show(); + entries_found++; + } + else { + li.hide(); + } + }); + // if there are entries, show the section, otherwise hide it + if (entries_found > 0) { + h3_parent.show(); + sections_found++; + } + else { + h3_parent.hide(); + } + }); + if (sections_found > 0) + h2_parent.show(); + else + h2_parent.hide(); + }); + } + $('#searchbox').keyup(dofilter); + $('#searchbox-submit').click(dofilter); +}); diff --git a/cpython_2/environment/repo/Doc/tools/static/switchers.js b/cpython_2/environment/repo/Doc/tools/static/switchers.js new file mode 100644 index 0000000000000000000000000000000000000000..e1ef91a8dfc686767adac6dd05028355dcd2178c --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/static/switchers.js @@ -0,0 +1,156 @@ +(function() { + 'use strict'; + + // Parses versions in URL segments like: + // "3", "dev", "release/2.7" or "3.6rc2" + var version_regexs = [ + '(?:\\d)', + '(?:\\d\\.\\d[\\w\\d\\.]*)', + '(?:dev)', + '(?:release/\\d.\\d[\\x\\d\\.]*)']; + + var all_versions = { + '3.9': 'dev (3.9)', + '3.8': '3.8', + '3.7': '3.7', + '3.6': '3.6', + '3.5': '3.5', + '2.7': '2.7', + }; + + var all_languages = { + 'en': 'English', + 'fr': 'French', + 'ja': 'Japanese', + 'ko': 'Korean', + 'pt-br': 'Brazilian Portuguese', + 'zh-cn': 'Simplified Chinese', + }; + + function build_version_select(current_version, current_release) { + var buf = [''); + return buf.join(''); + } + + function build_language_select(current_language) { + var buf = [''); + return buf.join(''); + } + + function navigate_to_first_existing(urls) { + // Navigate to the first existing URL in urls. + var url = urls.shift(); + if (urls.length == 0) { + window.location.href = url; + return; + } + $.ajax({ + url: url, + success: function() { + window.location.href = url; + }, + error: function() { + navigate_to_first_existing(urls); + } + }); + } + + function on_version_switch() { + var selected_version = $(this).children('option:selected').attr('value') + '/'; + var url = window.location.href; + var current_language = language_segment_from_url(url); + var current_version = version_segment_in_url(url); + var new_url = url.replace('.org/' + current_language + current_version, + '.org/' + current_language + selected_version); + if (new_url != url) { + navigate_to_first_existing([ + new_url, + url.replace('.org/' + current_language + current_version, + '.org/' + selected_version), + 'https://docs.python.org/' + current_language + selected_version, + 'https://docs.python.org/' + selected_version, + 'https://docs.python.org/' + ]); + } + } + + function on_language_switch() { + var selected_language = $(this).children('option:selected').attr('value') + '/'; + var url = window.location.href; + var current_language = language_segment_from_url(url); + var current_version = version_segment_in_url(url); + if (selected_language == 'en/') // Special 'default' case for english. + selected_language = ''; + var new_url = url.replace('.org/' + current_language + current_version, + '.org/' + selected_language + current_version); + if (new_url != url) { + navigate_to_first_existing([ + new_url, + 'https://docs.python.org/' + ]); + } + } + + // Returns the path segment of the language as a string, like 'fr/' + // or '' if not found. + function language_segment_from_url(url) { + var language_regexp = '\.org/([a-z]{2}(?:-[a-z]{2})?/)'; + var match = url.match(language_regexp); + if (match !== null) + return match[1]; + return ''; + } + + // Returns the path segment of the version as a string, like '3.6/' + // or '' if not found. + function version_segment_in_url(url) { + var language_segment = '(?:[a-z]{2}(?:-[a-z]{2})?/)'; + var version_segment = '(?:(?:' + version_regexs.join('|') + ')/)'; + var version_regexp = '\\.org/' + language_segment + '?(' + version_segment + ')'; + var match = url.match(version_regexp); + if (match !== null) + return match[1]; + return '' + } + + $(document).ready(function() { + var release = DOCUMENTATION_OPTIONS.VERSION; + var language_segment = language_segment_from_url(window.location.href); + var current_language = language_segment.replace(/\/+$/g, '') || 'en'; + var version = release.substr(0, 3); + var version_select = build_version_select(version, release); + + $('.version_switcher_placeholder').html(version_select); + $('.version_switcher_placeholder select').bind('change', on_version_switch); + + var language_select = build_language_select(current_language); + + $('.language_switcher_placeholder').html(language_select); + $('.language_switcher_placeholder select').bind('change', on_language_switch); + }); +})(); diff --git a/cpython_2/environment/repo/Doc/tools/susp-ignored.csv b/cpython_2/environment/repo/Doc/tools/susp-ignored.csv new file mode 100644 index 0000000000000000000000000000000000000000..7be8d0abd69a57e79a7c8e4cf3f64bb66c89a6b3 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/susp-ignored.csv @@ -0,0 +1,364 @@ +c-api/arg,,:ref,"PyArg_ParseTuple(args, ""O|O:ref"", &object, &callback)" +c-api/list,,:high,list[low:high] +c-api/sequence,,:i2,del o[i1:i2] +c-api/sequence,,:i2,o[i1:i2] +c-api/tuple,,:high,p[low:high] +c-api/unicode,,:end,str[start:end] +c-api/unicode,,:start,unicode[start:start+length] +distutils/examples,267,`,This is the description of the ``foobar`` package. +distutils/setupscript,,::, +extending/embedding,,:numargs,"if(!PyArg_ParseTuple(args, "":numargs""))" +extending/extending,,:myfunction,"PyArg_ParseTuple(args, ""D:myfunction"", &c);" +extending/extending,,:set,"if (PyArg_ParseTuple(args, ""O:set_callback"", &temp)) {" +extending/newtypes,,:call,"if (!PyArg_ParseTuple(args, ""sss:call"", &arg1, &arg2, &arg3)) {" +faq/programming,,:chr,">=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(" +faq/programming,,::,for x in sequence[::-1]: +faq/programming,,:reduce,"print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y," +faq/programming,,:reduce,"Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro," +faq/windows,,:d48eceb,"Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32" +howto/curses,,:black,"colors when it activates color mode. They are: 0:black, 1:red," +howto/curses,,:red,"colors when it activates color mode. They are: 0:black, 1:red," +howto/curses,,:green,"2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The" +howto/curses,,:yellow,"2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The" +howto/curses,,:blue,"2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The" +howto/curses,,:magenta,"2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The" +howto/curses,,:cyan,"2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The" +howto/curses,,:white,"2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The" +howto/instrumentation,,::,python$target:::function-entry +howto/instrumentation,,:function,python$target:::function-entry +howto/instrumentation,,::,python$target:::function-return +howto/instrumentation,,:function,python$target:::function-return +howto/instrumentation,,:call,156641360502280 function-entry:call_stack.py:start:23 +howto/instrumentation,,:start,156641360502280 function-entry:call_stack.py:start:23 +howto/instrumentation,,:function,156641360518804 function-entry: call_stack.py:function_1:1 +howto/instrumentation,,:function,156641360532797 function-entry: call_stack.py:function_3:9 +howto/instrumentation,,:function,156641360546807 function-return: call_stack.py:function_3:10 +howto/instrumentation,,:function,156641360563367 function-return: call_stack.py:function_1:2 +howto/instrumentation,,:function,156641360578365 function-entry: call_stack.py:function_2:5 +howto/instrumentation,,:function,156641360591757 function-entry: call_stack.py:function_1:1 +howto/instrumentation,,:function,156641360605556 function-entry: call_stack.py:function_3:9 +howto/instrumentation,,:function,156641360617482 function-return: call_stack.py:function_3:10 +howto/instrumentation,,:function,156641360629814 function-return: call_stack.py:function_1:2 +howto/instrumentation,,:function,156641360642285 function-return: call_stack.py:function_2:6 +howto/instrumentation,,:function,156641360656770 function-entry: call_stack.py:function_3:9 +howto/instrumentation,,:function,156641360669707 function-return: call_stack.py:function_3:10 +howto/instrumentation,,:function,156641360687853 function-entry: call_stack.py:function_4:13 +howto/instrumentation,,:function,156641360700719 function-return: call_stack.py:function_4:14 +howto/instrumentation,,:function,156641360719640 function-entry: call_stack.py:function_5:18 +howto/instrumentation,,:function,156641360732567 function-return: call_stack.py:function_5:21 +howto/instrumentation,,:call,156641360747370 function-return:call_stack.py:start:28 +howto/instrumentation,,:start,156641360747370 function-return:call_stack.py:start:28 +howto/ipaddress,,:DB8,>>> ipaddress.ip_address('2001:DB8::1') +howto/ipaddress,,::,>>> ipaddress.ip_address('2001:DB8::1') +howto/ipaddress,,:db8,IPv6Address('2001:db8::1') +howto/ipaddress,,::,IPv6Address('2001:db8::1') +howto/ipaddress,,::,IPv6Address('::1') +howto/ipaddress,,:db8,>>> ipaddress.ip_network('2001:db8::0/96') +howto/ipaddress,,::,>>> ipaddress.ip_network('2001:db8::0/96') +howto/ipaddress,,:db8,IPv6Network('2001:db8::/96') +howto/ipaddress,,::,IPv6Network('2001:db8::/96') +howto/ipaddress,,:db8,IPv6Network('2001:db8::/128') +howto/ipaddress,,::,IPv6Network('2001:db8::/128') +howto/ipaddress,,:db8,IPv6Interface('2001:db8::1/96') +howto/ipaddress,,::,IPv6Interface('2001:db8::1/96') +howto/ipaddress,,:db8,>>> addr6 = ipaddress.ip_address('2001:db8::1') +howto/ipaddress,,::,>>> addr6 = ipaddress.ip_address('2001:db8::1') +howto/ipaddress,,:db8,>>> host6 = ipaddress.ip_interface('2001:db8::1/96') +howto/ipaddress,,::,>>> host6 = ipaddress.ip_interface('2001:db8::1/96') +howto/ipaddress,,:db8,>>> net6 = ipaddress.ip_network('2001:db8::0/96') +howto/ipaddress,,::,>>> net6 = ipaddress.ip_network('2001:db8::0/96') +howto/ipaddress,,:ffff,IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::') +howto/ipaddress,,::,IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::') +howto/ipaddress,,::,IPv6Address('::ffff:ffff') +howto/ipaddress,,:ffff,IPv6Address('::ffff:ffff') +howto/ipaddress,,:db8,'2001:db8::/96' +howto/ipaddress,,::,'2001:db8::/96' +howto/ipaddress,,:db8,>>> ipaddress.ip_interface('2001:db8::1/96') +howto/ipaddress,,::,>>> ipaddress.ip_interface('2001:db8::1/96') +howto/ipaddress,,:db8,'2001:db8::1' +howto/ipaddress,,::,'2001:db8::1' +howto/ipaddress,,:db8,IPv6Address('2001:db8::ffff:ffff') +howto/ipaddress,,::,IPv6Address('2001:db8::ffff:ffff') +howto/ipaddress,,:ffff,IPv6Address('2001:db8::ffff:ffff') +howto/logging,,:And,"WARNING:And this, too" +howto/logging,,:And,"WARNING:root:And this, too" +howto/logging,,:And,"ERROR:root:And non-ASCII stuff, too, like " +howto/logging,,:Doing,INFO:root:Doing something +howto/logging,,:Finished,INFO:root:Finished +howto/logging,,:logger,severity:logger name:message +howto/logging,,:Look,WARNING:root:Look before you leap! +howto/logging,,:message,severity:logger name:message +howto/logging,,:root,DEBUG:root:This message should go to the log file +howto/logging,,:root,INFO:root:Doing something +howto/logging,,:root,INFO:root:Finished +howto/logging,,:root,INFO:root:So should this +howto/logging,,:root,"ERROR:root:And non-ASCII stuff, too, like " +howto/logging,,:root,INFO:root:Started +howto/logging,,:root,"WARNING:root:And this, too" +howto/logging,,:root,WARNING:root:Look before you leap! +howto/logging,,:root,WARNING:root:Watch out! +howto/logging,,:So,INFO:root:So should this +howto/logging,,:So,INFO:So should this +howto/logging,,:Started,INFO:root:Started +howto/logging,,:This,DEBUG:root:This message should go to the log file +howto/logging,,:This,DEBUG:This message should appear on the console +howto/logging,,:Watch,WARNING:root:Watch out! +howto/pyporting,,::,Programming Language :: Python :: 2 +howto/pyporting,,::,Programming Language :: Python :: 3 +howto/regex,,::, +howto/regex,,:foo,(?:foo) +howto/urllib2,,:password,"""joe:password@example.com""" +library/ast,,:upper,lower:upper +library/ast,,:step,lower:upper:step +library/audioop,,:ipos,"# factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)]," +library/bisect,32,:hi,all(val >= x for val in a[i:hi]) +library/bisect,42,:hi,all(val > x for val in a[i:hi]) +library/configparser,,:home,my_dir: ${Common:home_dir}/twosheds +library/configparser,,:option,${section:option} +library/configparser,,:path,python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python} +library/configparser,,:Python,python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python} +library/configparser,,:system,path: ${Common:system_dir}/Library/Frameworks/ +library/datetime,,:MM, +library/datetime,,:SS, +library/decimal,,:optional,"trailneg:optional trailing minus indicator" +library/difflib,,:ahi,a[alo:ahi] +library/difflib,,:bhi,b[blo:bhi] +library/difflib,,:i1, +library/difflib,,:i2, +library/difflib,,:j2, +library/doctest,,`,``factorial`` from the ``example`` module: +library/doctest,,`,The ``example`` module +library/doctest,,`,Using ``factorial`` +library/exceptions,,:err,err.object[err.start:err.end] +library/functions,,:step,a[start:stop:step] +library/functions,,:stop,"a[start:stop, i]" +library/functions,,:stop,a[start:stop:step] +library/hashlib,,:LEAF,"h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH," +library/http.client,,:port,host:port +library/http.cookies,,`,!#$%&'*+-.^_`|~: +library/imaplib,,:MM,"""DD-Mmm-YYYY HH:MM:SS" +library/imaplib,,:SS,"""DD-Mmm-YYYY HH:MM:SS" +library/inspect,,:int,">>> def foo(a, *, b:int, **kwargs):" +library/inspect,,:int,"'(a, *, b:int, **kwargs)'" +library/inspect,,:int,'b:int' +library/ipaddress,,:db8,>>> ipaddress.ip_address('2001:db8::') +library/ipaddress,,::,>>> ipaddress.ip_address('2001:db8::') +library/ipaddress,,:db8,IPv6Address('2001:db8::') +library/ipaddress,,::,IPv6Address('2001:db8::') +library/ipaddress,,:db8,>>> ipaddress.IPv6Address('2001:db8::1000') +library/ipaddress,,::,>>> ipaddress.IPv6Address('2001:db8::1000') +library/ipaddress,,:db8,IPv6Address('2001:db8::1000') +library/ipaddress,,::,IPv6Address('2001:db8::1000') +library/ipaddress,,::,IPv6Address('ff02::5678%1') +library/ipaddress,,::,fe80::1234 +library/ipaddress,,:db8,">>> ipaddress.ip_address(""2001:db8::1"").reverse_pointer" +library/ipaddress,,::,">>> ipaddress.ip_address(""2001:db8::1"").reverse_pointer" +library/ipaddress,,::,"""::abc:7:def""" +library/ipaddress,,:def,"""::abc:7:def""" +library/ipaddress,,::,::FFFF/96 +library/ipaddress,,::,2002::/16 +library/ipaddress,,::,2001::/32 +library/ipaddress,,::,>>> str(ipaddress.IPv6Address('::1')) +library/ipaddress,,::,'::1' +library/ipaddress,,:ff00,ffff:ff00:: +library/ipaddress,,:db00,2001:db00::0/24 +library/ipaddress,,::,2001:db00::0/24 +library/ipaddress,,:db00,2001:db00::0/ffff:ff00:: +library/ipaddress,,::,2001:db00::0/ffff:ff00:: +library/itertools,,:step,elements from seq[start:stop:step] +library/itertools,,:stop,elements from seq[start:stop:step] +library/logging.handlers,,:port,host:port +library/mmap,,:i2,obj[i1:i2] +library/multiprocessing,,`,# Add more tasks using `put()` +library/multiprocessing,,:queue,">>> QueueManager.register('get_queue', callable=lambda:queue)" +library/multiprocessing,,`,# register the Foo class; make `f()` and `g()` accessible via proxy +library/multiprocessing,,`,# register the Foo class; make `g()` and `_h()` accessible via proxy +library/multiprocessing,,`,# register the generator function baz; use `GeneratorProxy` to make proxies +library/nntplib,,:bytes,:bytes +library/nntplib,,:lines,:lines +library/optparse,,:len,"del parser.rargs[:len(value)]" +library/os.path,,:foo,c:foo +library/pathlib,,:bar,">>> PureWindowsPath('c:/Windows', 'd:bar')" +library/pathlib,,:bar,PureWindowsPath('d:bar') +library/pathlib,,:Program,>>> PureWindowsPath('c:Program Files/').root +library/pathlib,,:Program,>>> PureWindowsPath('c:Program Files/').anchor +library/pdb,,:lineno,filename:lineno +library/pickle,,:memory,"conn = sqlite3.connect("":memory:"")" +library/posix,,`,"CFLAGS=""`getconf LFS_CFLAGS`"" OPT=""-g -O2 $CFLAGS""" +library/pprint,,::,"'Programming Language :: Python :: 2.6'," +library/pprint,,::,"'Programming Language :: Python :: 2.7'," +library/pprint,,::,"'classifiers': ['Development Status :: 3 - Alpha'," +library/pprint,,::,"'Intended Audience :: Developers'," +library/pprint,,::,"'License :: OSI Approved :: MIT License'," +library/pprint,,::,"'Programming Language :: Python :: 2'," +library/pprint,,::,"'Programming Language :: Python :: 3'," +library/pprint,,::,"'Programming Language :: Python :: 3.2'," +library/pprint,,::,"'Programming Language :: Python :: 3.3'," +library/pprint,,::,"'Programming Language :: Python :: 3.4'," +library/pprint,,::,"'Topic :: Software Development :: Build Tools']," +library/profile,,:lineno,filename:lineno(function) +library/pyexpat,,:elem1, +library/pyexpat,,:py,"xmlns:py = ""http://www.python.org/ns/"">" +library/random,,:len,new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):]) +library/readline,,:bind,"python:bind -v" +library/readline,,:bind,"python:bind ^I rl_complete" +library/smtplib,,:port,method must support that as well as a regular host:port +library/socket,,::,'5aef:2b::8' +library/socket,,:can,"return (can_id, can_dlc, data[:can_dlc])" +library/socket,,:len,fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) +library/sqlite3,,:age,"cur.execute(""select * from people where name_last=:who and age=:age"", {""who"": who, ""age"": age})" +library/sqlite3,,:memory, +library/sqlite3,,:who,"cur.execute(""select * from people where name_last=:who and age=:age"", {""who"": who, ""age"": age})" +library/sqlite3,,:path,"db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)" +library/ssl,,:My,"Organizational Unit Name (eg, section) []:My Group" +library/ssl,,:My,"Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc." +library/ssl,,:myserver,"Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com" +library/ssl,,:MyState,State or Province Name (full name) [Some-State]:MyState +library/ssl,,:ops,Email Address []:ops@myserver.mygroup.myorganization.com +library/ssl,,:Some,"Locality Name (eg, city) []:Some City" +library/ssl,,:US,Country Name (2 letter code) [AU]:US +library/stdtypes,,:end,s[start:end] +library/stdtypes,,::,>>> hash(v[::-2]) == hash(b'abcefg'[::-2]) +library/stdtypes,,:len,s[len(s):len(s)] +library/stdtypes,,::,>>> y = m[::2] +library/stdtypes,,::,>>> z = y[::-2] +library/string,,`,"!""#$%&'()*+,-./:;<=>?@[\]^_`{|}~" +library/tarfile,,:bz2, +library/tarfile,,:compression,filemode[:compression] +library/tarfile,,:gz, +library/tarfile,,:xz,'a:xz' +library/tarfile,,:xz,'r:xz' +library/tarfile,,:xz,'w:xz' +library/time,,:mm, +library/time,,:ss, +library/tracemalloc,,:limit,"for index, stat in enumerate(top_stats[:limit], 1):" +library/turtle,,::,Example:: +library/unittest,,:foo,"self.assertEqual(cm.output, ['INFO:foo:first message'," +library/unittest,,:first,"self.assertEqual(cm.output, ['INFO:foo:first message'," +library/unittest,,:foo,'ERROR:foo.bar:second message']) +library/unittest,,:second,'ERROR:foo.bar:second message']) +library/urllib.request,,:close,Connection:close +library/urllib.request,,:port,:port +library/urllib.request,,:lang,"xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en"">\n\n\n" +library/urllib.request,,:password,"""joe:password@python.org""" +library/urllib.parse,,:scheme, +library/urllib.parse,,:scheme,URL:scheme://host/path +library/uuid,,:uuid,urn:uuid:12345678-1234-5678-1234-567812345678 +library/venv,,:param,":param nodist: If true, setuptools and pip are not installed into the" +library/venv,,:param,":param progress: If setuptools or pip are installed, the progress of the" +library/venv,,:param,":param nopip: If true, pip is not installed into the created" +library/venv,,:param,:param context: The information for the virtual environment +library/xmlrpc.client,,:nil,ex:nil +library/xmlrpc.client,,:pass,http://user:pass@host:port/path +library/xmlrpc.client,,:pass,user:pass +library/xmlrpc.client,,:port,http://user:pass@host:port/path +license,,`,"``Software''), to deal in the Software without restriction, including" +license,,`,"THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND," +license,,`,* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND +license,,`,THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +license,,`,* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY +license,,`,THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND +license,,:zooko,mailto:zooko@zooko.com +reference/expressions,,:index,x[index:index] +reference/lexical_analysis,,`,$ ? ` +reference/lexical_analysis,,:fileencoding,# vim:fileencoding= +tutorial/datastructures,,:value,It is also possible to delete a key:value +tutorial/datastructures,,:value,key:value pairs within the braces adds initial key:value pairs +tutorial/stdlib2,,:config,"logging.warning('Warning:config file %s not found', 'server.conf')" +tutorial/stdlib2,,:config,WARNING:root:Warning:config file server.conf not found +tutorial/stdlib2,,:Critical,CRITICAL:root:Critical error -- shutting down +tutorial/stdlib2,,:Error,ERROR:root:Error occurred +tutorial/stdlib2,,:root,CRITICAL:root:Critical error -- shutting down +tutorial/stdlib2,,:root,ERROR:root:Error occurred +tutorial/stdlib2,,:root,WARNING:root:Warning:config file server.conf not found +tutorial/stdlib2,,:start,extra = data[start:start+extra_size] +tutorial/stdlib2,,:start,"fields = struct.unpack('>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo') +whatsnew/2.7,,:Sunday,'2009:4:Sunday' +whatsnew/2.7,,:Cookie,"export PYTHONWARNINGS=all,error:::Cookie:0" +whatsnew/2.7,,::,"export PYTHONWARNINGS=all,error:::Cookie:0" +whatsnew/3.2,,:affe,"netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]'," +whatsnew/3.2,,:affe,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/') +whatsnew/3.2,,:beef,"netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]'," +whatsnew/3.2,,:beef,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/') +whatsnew/3.2,,:cafe,"netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]'," +whatsnew/3.2,,:cafe,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/') +whatsnew/3.2,,:deaf,"netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]'," +whatsnew/3.2,,:deaf,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/') +whatsnew/3.2,,:directory,${buildout:directory}/downloads/dist +whatsnew/3.2,,::,"$ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'" +whatsnew/3.2,,:feed,"netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]'," +whatsnew/3.2,,:feed,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/') +whatsnew/3.2,,:gz,">>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:" +whatsnew/3.2,,:location,zope9-location = ${zope9:location} +whatsnew/3.2,,:prefix,zope-conf = ${custom:prefix}/etc/zope.conf +library/re,,`,!#$%&'*+-.^_`|~: +library/re,,`,!\#\$%\&'\*\+\-\.\^_`\|\~: +library/tarfile,,:xz,'x:xz' +library/warnings,,:message,action:message:category:module:line +library/warnings,,:category,action:message:category:module:line +library/warnings,,:module,action:message:category:module:line +library/warnings,,:line,action:message:category:module:line +library/warnings,,::,error::ResourceWarning +library/warnings,,::,default::DeprecationWarning +library/warnings,,::,default:::mymodule +library/warnings,,:mymodule,default:::mymodule +library/warnings,,::,error:::mymodule +library/warnings,,:mymodule,error:::mymodule +library/warnings,,::,ignore::DeprecationWarning +library/warnings,,::,ignore::PendingDeprecationWarning +library/warnings,,::,ignore::ImportWarning +library/warnings,,::,ignore::ResourceWarning +library/xml.etree.elementtree,,:sometag,prefix:sometag +library/xml.etree.elementtree,,:fictional,"Lancelot +library/xml.etree.elementtree,,:character,Archie Leach +library/xml.etree.elementtree,,:character,Sir Robin +library/xml.etree.elementtree,,:character,Gunther +library/xml.etree.elementtree,,:character,Commander Clement +library/xml.etree.elementtree,,:actor,"for actor in root.findall('real_person:actor', ns):" +library/xml.etree.elementtree,,:name,"name = actor.find('real_person:name', ns)" +library/xml.etree.elementtree,,:character,"for char in actor.findall('role:character', ns):" +library/xml.etree.elementtree,,:xi, +library/xml.etree.elementtree,,:include, +library/xml.etree.elementtree,,:include, Copyright (c) . +library/zipapp,,:main,"$ python -m zipapp myapp -m ""myapp:main""" +library/zipapp,,:fn,"pkg.mod:fn" +library/zipapp,,:callable,"pkg.module:callable" +library/stdtypes,,::,>>> m[::2].tolist() +whatsnew/3.5,,:root,'WARNING:root:warning\n' +whatsnew/3.5,,:warning,'WARNING:root:warning\n' +whatsnew/3.5,,::,>>> addr6 = ipaddress.IPv6Address('::1') +whatsnew/3.5,,:root,ERROR:root:exception +whatsnew/3.5,,:exception,ERROR:root:exception +whatsnew/changelog,,`,'`' +whatsnew/changelog,,:end,str[start:end] +library/binascii,,`,'`' +library/uu,,`,'`' +whatsnew/3.7,,`,'`' +whatsnew/3.7,,::,error::BytesWarning +whatsnew/changelog,,::,error::BytesWarning +whatsnew/changelog,,::,default::BytesWarning +whatsnew/changelog,,::,default::DeprecationWarning +library/importlib.metadata,,:main,"EntryPoint(name='wheel', value='wheel.cli:main', group='console_scripts')" +library/importlib.metadata,,`,loading the metadata for packages for the indicated ``context``. +library/re,,`,"`" diff --git a/cpython_2/environment/repo/Doc/tools/templates/customsourcelink.html b/cpython_2/environment/repo/Doc/tools/templates/customsourcelink.html new file mode 100644 index 0000000000000000000000000000000000000000..fca44e9163cac744c03c4b9a80ffa5c6903f299c --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/templates/customsourcelink.html @@ -0,0 +1,13 @@ +{%- if show_source and has_source and sourcename %} + +{%- endif %} diff --git a/cpython_2/environment/repo/Doc/tools/templates/download.html b/cpython_2/environment/repo/Doc/tools/templates/download.html new file mode 100644 index 0000000000000000000000000000000000000000..987c63a7f3575ceba6984a541663667e3452f558 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/templates/download.html @@ -0,0 +1,64 @@ +{% extends "layout.html" %} +{% set title = 'Download' %} +{% if daily is defined %} + {% set dlbase = pathto('archives', 1) %} +{% else %} + {% set dlbase = 'https://docs.python.org/ftp/python/doc/' + release %} +{% endif %} + +{% block body %} +

Download Python {{ release }} Documentation

+ +{% if last_updated %}

Last updated on: {{ last_updated }}.

{% endif %} + +

To download an archive containing all the documents for this version of +Python in one of various formats, follow one of links in this table.

+ + + + + + + + + + + + + + + + + + + + + + + +
FormatPacked as .zipPacked as .tar.bz2
PDF (US-Letter paper size)Download (ca. 13 MiB)Download (ca. 13 MiB)
PDF (A4 paper size)Download (ca. 13 MiB)Download (ca. 13 MiB)
HTMLDownload (ca. 9 MiB)Download (ca. 6 MiB)
Plain TextDownload (ca. 3 MiB)Download (ca. 2 MiB)
EPUBDownload (ca. 5 MiB)
+ +

These archives contain all the content in the documentation.

+ +

HTML Help (.chm) files are made available in the "Windows" section +on the Python +download page.

+ + +

Unpacking

+ +

Unix users should download the .tar.bz2 archives; these are bzipped tar +archives and can be handled in the usual way using tar and the bzip2 +program. The InfoZIP unzip program can be +used to handle the ZIP archives if desired. The .tar.bz2 archives provide the +best compression and fastest download times.

+ +

Windows users can use the ZIP archives since those are customary on that +platform. These are created on Unix using the InfoZIP zip program.

+ + +

Problems

+ +

If you have comments or suggestions for the Python documentation, please send +email to docs@python.org.

+{% endblock %} diff --git a/cpython_2/environment/repo/Doc/tools/templates/dummy.html b/cpython_2/environment/repo/Doc/tools/templates/dummy.html new file mode 100644 index 0000000000000000000000000000000000000000..8d94137b01b5192096abfff8bb9568eaeae01e87 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/templates/dummy.html @@ -0,0 +1,7 @@ +This file is not an actual template, but used to add some +texts in extensions to sphinx.pot file. + +In extensions/pyspecific.py: + +{% trans %}CPython implementation detail:{% endtrans %} +{% trans %}Deprecated since version {deprecated}, will be removed in version {removed}{% endtrans %} diff --git a/cpython_2/environment/repo/Doc/tools/templates/indexcontent.html b/cpython_2/environment/repo/Doc/tools/templates/indexcontent.html new file mode 100644 index 0000000000000000000000000000000000000000..152162ab0dd28c7303d775e55e7844592ab0817c --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/templates/indexcontent.html @@ -0,0 +1,67 @@ +{% extends "layout.html" %} +{%- block htmltitle -%} +{{ shorttitle }} +{%- endblock -%} +{% block body %} +

{{ docstitle|e }}

+

+ {% trans %}Welcome! This is the documentation for Python {{ release }}.{% endtrans %} +

+

{% trans %}Parts of the documentation:{% endtrans %}

+ + +
+ + + + + + + + + + + + +
+ +

{% trans %}Indices and tables:{% endtrans %}

+ + +
+ + + + + + +
+ +

{% trans %}Meta information:{% endtrans %}

+ + +
+ + + + + + +
+{% endblock %} diff --git a/cpython_2/environment/repo/Doc/tools/templates/indexsidebar.html b/cpython_2/environment/repo/Doc/tools/templates/indexsidebar.html new file mode 100644 index 0000000000000000000000000000000000000000..4730a5fe5db7bcc28f92155b7c6f04e19448d9b7 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/templates/indexsidebar.html @@ -0,0 +1,22 @@ +

{% trans %}Download{% endtrans %}

+

{% trans %}Download these documents{% endtrans %}

+

{% trans %}Docs by version{% endtrans %}

+ + +

{% trans %}Other resources{% endtrans %}

+ diff --git a/cpython_2/environment/repo/Doc/tools/templates/layout.html b/cpython_2/environment/repo/Doc/tools/templates/layout.html new file mode 100644 index 0000000000000000000000000000000000000000..17592d74a4eb529250b1166260a05e5dc371cc06 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/templates/layout.html @@ -0,0 +1,44 @@ +{% extends "!layout.html" %} + +{% block header %} +{%- if outdated %} +
+ {% trans %}This document is for an old version of Python that is no longer supported. + You should upgrade, and read the {% endtrans %} + {% trans %} Python documentation for the current stable release{% endtrans %}. +
+{%- endif %} +{% endblock %} + +{% block rootrellink %} +{{ super() }} +
  • + {%- if switchers is defined %} + {{ language or 'en' }} + {{ release }} + {% trans %}Documentation {% endtrans %}{{ reldelim1 }} + {%- else %} + {{ shorttitle }}{{ reldelim1 }} + {%- endif %} +
  • +{% endblock %} + +{% block extrahead %} + + {% if builder != "htmlhelp" %} + {% if switchers is defined and not embedded %} + {% endif %} + {% if pagename == 'whatsnew/changelog' and not embedded %} + {% endif %} + {% endif %} + + {# custom CSS; used in asyncio docs! #} + +{{ super() }} +{% endblock %} diff --git a/cpython_2/environment/repo/Doc/tools/templates/opensearch.xml b/cpython_2/environment/repo/Doc/tools/templates/opensearch.xml new file mode 100644 index 0000000000000000000000000000000000000000..7a5cdddd2771235a670769aea6cda87f8b063cee --- /dev/null +++ b/cpython_2/environment/repo/Doc/tools/templates/opensearch.xml @@ -0,0 +1,4 @@ +{% extends "!opensearch.xml" %} +{% block extra -%} +https://www.python.org/images/favicon16x16.ico +{%- endblock %} diff --git a/cpython_2/environment/repo/Doc/tutorial/appendix.rst b/cpython_2/environment/repo/Doc/tutorial/appendix.rst new file mode 100644 index 0000000000000000000000000000000000000000..241a812037469e2e241b8fc95788b9cc0626754a --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/appendix.rst @@ -0,0 +1,124 @@ +.. _tut-appendix: + +******** +Appendix +******** + + +.. _tut-interac: + +Interactive Mode +================ + +.. _tut-error: + +Error Handling +-------------- + +When an error occurs, the interpreter prints an error message and a stack trace. +In interactive mode, it then returns to the primary prompt; when input came from +a file, it exits with a nonzero exit status after printing the stack trace. +(Exceptions handled by an :keyword:`except` clause in a :keyword:`try` statement +are not errors in this context.) Some errors are unconditionally fatal and +cause an exit with a nonzero exit; this applies to internal inconsistencies and +some cases of running out of memory. All error messages are written to the +standard error stream; normal output from executed commands is written to +standard output. + +Typing the interrupt character (usually :kbd:`Control-C` or :kbd:`Delete`) to the primary or +secondary prompt cancels the input and returns to the primary prompt. [#]_ +Typing an interrupt while a command is executing raises the +:exc:`KeyboardInterrupt` exception, which may be handled by a :keyword:`try` +statement. + + +.. _tut-scripts: + +Executable Python Scripts +------------------------- + +On BSD'ish Unix systems, Python scripts can be made directly executable, like +shell scripts, by putting the line :: + + #!/usr/bin/env python3.5 + +(assuming that the interpreter is on the user's :envvar:`PATH`) at the beginning +of the script and giving the file an executable mode. The ``#!`` must be the +first two characters of the file. On some platforms, this first line must end +with a Unix-style line ending (``'\n'``), not a Windows (``'\r\n'``) line +ending. Note that the hash, or pound, character, ``'#'``, is used to start a +comment in Python. + +The script can be given an executable mode, or permission, using the +:program:`chmod` command. + +.. code-block:: shell-session + + $ chmod +x myscript.py + +On Windows systems, there is no notion of an "executable mode". The Python +installer automatically associates ``.py`` files with ``python.exe`` so that +a double-click on a Python file will run it as a script. The extension can +also be ``.pyw``, in that case, the console window that normally appears is +suppressed. + + +.. _tut-startup: + +The Interactive Startup File +---------------------------- + +When you use Python interactively, it is frequently handy to have some standard +commands executed every time the interpreter is started. You can do this by +setting an environment variable named :envvar:`PYTHONSTARTUP` to the name of a +file containing your start-up commands. This is similar to the :file:`.profile` +feature of the Unix shells. + +This file is only read in interactive sessions, not when Python reads commands +from a script, and not when :file:`/dev/tty` is given as the explicit source of +commands (which otherwise behaves like an interactive session). It is executed +in the same namespace where interactive commands are executed, so that objects +that it defines or imports can be used without qualification in the interactive +session. You can also change the prompts ``sys.ps1`` and ``sys.ps2`` in this +file. + +If you want to read an additional start-up file from the current directory, you +can program this in the global start-up file using code like ``if +os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())``. +If you want to use the startup file in a script, you must do this explicitly +in the script:: + + import os + filename = os.environ.get('PYTHONSTARTUP') + if filename and os.path.isfile(filename): + with open(filename) as fobj: + startup_file = fobj.read() + exec(startup_file) + + +.. _tut-customize: + +The Customization Modules +------------------------- + +Python provides two hooks to let you customize it: :mod:`sitecustomize` and +:mod:`usercustomize`. To see how it works, you need first to find the location +of your user site-packages directory. Start Python and run this code:: + + >>> import site + >>> site.getusersitepackages() + '/home/user/.local/lib/python3.5/site-packages' + +Now you can create a file named :file:`usercustomize.py` in that directory and +put anything you want in it. It will affect every invocation of Python, unless +it is started with the :option:`-s` option to disable the automatic import. + +:mod:`sitecustomize` works in the same way, but is typically created by an +administrator of the computer in the global site-packages directory, and is +imported before :mod:`usercustomize`. See the documentation of the :mod:`site` +module for more details. + + +.. rubric:: Footnotes + +.. [#] A problem with the GNU Readline package may prevent this. diff --git a/cpython_2/environment/repo/Doc/tutorial/appetite.rst b/cpython_2/environment/repo/Doc/tutorial/appetite.rst new file mode 100644 index 0000000000000000000000000000000000000000..26e5168ab51a7ab5ed6ba17174746f69e468cbe0 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/appetite.rst @@ -0,0 +1,87 @@ +.. _tut-intro: + +********************** +Whetting Your Appetite +********************** + +If you do much work on computers, eventually you find that there's some task +you'd like to automate. For example, you may wish to perform a +search-and-replace over a large number of text files, or rename and rearrange a +bunch of photo files in a complicated way. Perhaps you'd like to write a small +custom database, or a specialized GUI application, or a simple game. + +If you're a professional software developer, you may have to work with several +C/C++/Java libraries but find the usual write/compile/test/re-compile cycle is +too slow. Perhaps you're writing a test suite for such a library and find +writing the testing code a tedious task. Or maybe you've written a program that +could use an extension language, and you don't want to design and implement a +whole new language for your application. + +Python is just the language for you. + +You could write a Unix shell script or Windows batch files for some of these +tasks, but shell scripts are best at moving around files and changing text data, +not well-suited for GUI applications or games. You could write a C/C++/Java +program, but it can take a lot of development time to get even a first-draft +program. Python is simpler to use, available on Windows, Mac OS X, and Unix +operating systems, and will help you get the job done more quickly. + +Python is simple to use, but it is a real programming language, offering much +more structure and support for large programs than shell scripts or batch files +can offer. On the other hand, Python also offers much more error checking than +C, and, being a *very-high-level language*, it has high-level data types built +in, such as flexible arrays and dictionaries. Because of its more general data +types Python is applicable to a much larger problem domain than Awk or even +Perl, yet many things are at least as easy in Python as in those languages. + +Python allows you to split your program into modules that can be reused in other +Python programs. It comes with a large collection of standard modules that you +can use as the basis of your programs --- or as examples to start learning to +program in Python. Some of these modules provide things like file I/O, system +calls, sockets, and even interfaces to graphical user interface toolkits like +Tk. + +Python is an interpreted language, which can save you considerable time during +program development because no compilation and linking is necessary. The +interpreter can be used interactively, which makes it easy to experiment with +features of the language, to write throw-away programs, or to test functions +during bottom-up program development. It is also a handy desk calculator. + +Python enables programs to be written compactly and readably. Programs written +in Python are typically much shorter than equivalent C, C++, or Java programs, +for several reasons: + +* the high-level data types allow you to express complex operations in a single + statement; + +* statement grouping is done by indentation instead of beginning and ending + brackets; + +* no variable or argument declarations are necessary. + +Python is *extensible*: if you know how to program in C it is easy to add a new +built-in function or module to the interpreter, either to perform critical +operations at maximum speed, or to link Python programs to libraries that may +only be available in binary form (such as a vendor-specific graphics library). +Once you are really hooked, you can link the Python interpreter into an +application written in C and use it as an extension or command language for that +application. + +By the way, the language is named after the BBC show "Monty Python's Flying +Circus" and has nothing to do with reptiles. Making references to Monty +Python skits in documentation is not only allowed, it is encouraged! + +Now that you are all excited about Python, you'll want to examine it in some +more detail. Since the best way to learn a language is to use it, the tutorial +invites you to play with the Python interpreter as you read. + +In the next chapter, the mechanics of using the interpreter are explained. This +is rather mundane information, but essential for trying out the examples shown +later. + +The rest of the tutorial introduces various features of the Python language and +system through examples, beginning with simple expressions, statements and data +types, through functions and modules, and finally touching upon advanced +concepts like exceptions and user-defined classes. + + diff --git a/cpython_2/environment/repo/Doc/tutorial/classes.rst b/cpython_2/environment/repo/Doc/tutorial/classes.rst new file mode 100644 index 0000000000000000000000000000000000000000..06bdd0d93515edd9751da61321448eaa209ff87b --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/classes.rst @@ -0,0 +1,927 @@ +.. _tut-classes: + +******* +Classes +******* + +Classes provide a means of bundling data and functionality together. Creating +a new class creates a new *type* of object, allowing new *instances* of that +type to be made. Each class instance can have attributes attached to it for +maintaining its state. Class instances can also have methods (defined by its +class) for modifying its state. + +Compared with other programming languages, Python's class mechanism adds classes +with a minimum of new syntax and semantics. It is a mixture of the class +mechanisms found in C++ and Modula-3. Python classes provide all the standard +features of Object Oriented Programming: the class inheritance mechanism allows +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 arbitrary amounts and kinds of data. As is true for +modules, classes partake of the dynamic nature of Python: they are created at +runtime, and can be modified further after creation. + +In C++ terminology, normally class members (including the data members) are +*public* (except see below :ref:`tut-private`), and all member functions are +*virtual*. As in Modula-3, there are no shorthands for referencing the object's +members from its methods: the method function is declared with an explicit first +argument representing the object, which is provided implicitly by the call. As +in Smalltalk, classes themselves are objects. This provides semantics for +importing and renaming. Unlike C++ and Modula-3, built-in types can be used as +base classes for extension by the user. Also, like in C++, most built-in +operators with special syntax (arithmetic operators, subscripting etc.) can be +redefined for class instances. + +(Lacking universally accepted terminology to talk about classes, I will make +occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, since +its object-oriented semantics are closer to those of Python than C++, but I +expect that few readers have heard of it.) + + +.. _tut-object: + +A Word About Names and Objects +============================== + +Objects have individuality, and multiple names (in multiple scopes) can be bound +to the same object. This is known as aliasing in other languages. This is +usually not appreciated on a first glance at Python, and can be safely ignored +when dealing with immutable basic types (numbers, strings, tuples). However, +aliasing has a possibly surprising effect on the semantics of Python code +involving mutable objects such as lists, dictionaries, and most other types. +This is usually used to the benefit of the program, since aliases behave like +pointers in some respects. For example, passing an object is cheap since only a +pointer is passed by the implementation; and if a function modifies an object +passed as an argument, the caller will see the change --- this eliminates the +need for two different argument passing mechanisms as in Pascal. + + +.. _tut-scopes: + +Python Scopes and Namespaces +============================ + +Before introducing classes, I first have to tell you something about Python's +scope rules. Class definitions play some neat tricks with namespaces, and you +need to know how scopes and namespaces work to fully understand what's going on. +Incidentally, knowledge about this subject is useful for any advanced Python +programmer. + +Let's begin with some definitions. + +A *namespace* is a mapping from names to objects. Most namespaces are currently +implemented as Python dictionaries, but that's normally not noticeable in any +way (except for performance), and it may change in the future. Examples of +namespaces are: the set of built-in names (containing functions such as :func:`abs`, and +built-in exception names); the global names in a module; and the local names in +a function invocation. In a sense the set of attributes of an object also form +a namespace. The important thing to know about namespaces is that there is +absolutely no relation between names in different namespaces; for instance, two +different modules may both define a function ``maximize`` without confusion --- +users of the modules must prefix it with the module name. + +By the way, I use the word *attribute* for any name following a dot --- for +example, in the expression ``z.real``, ``real`` is an attribute of the object +``z``. Strictly speaking, references to names in modules are attribute +references: in the expression ``modname.funcname``, ``modname`` is a module +object and ``funcname`` is an attribute of it. In this case there happens to be +a straightforward mapping between the module's attributes and the global names +defined in the module: they share the same namespace! [#]_ + +Attributes may be read-only or writable. In the latter case, assignment to +attributes is possible. Module attributes are writable: you can write +``modname.the_answer = 42``. Writable attributes may also be deleted with the +:keyword:`del` statement. For example, ``del modname.the_answer`` will remove +the attribute :attr:`the_answer` from the object named by ``modname``. + +Namespaces are created at different moments and have different lifetimes. The +namespace containing the built-in names is created when the Python interpreter +starts up, and is never deleted. The global namespace for a module is created +when the module definition is read in; normally, module namespaces also last +until the interpreter quits. The statements executed by the top-level +invocation of the interpreter, either read from a script file or interactively, +are considered part of a module called :mod:`__main__`, so they have their own +global namespace. (The built-in names actually also live in a module; this is +called :mod:`builtins`.) + +The local namespace for a function is created when the function is called, and +deleted when the function returns or raises an exception that is not handled +within the function. (Actually, forgetting would be a better way to describe +what actually happens.) Of course, recursive invocations each have their own +local namespace. + +A *scope* is a textual region of a Python program where a namespace is directly +accessible. "Directly accessible" here means that an unqualified reference to a +name attempts to find the name in the namespace. + +Although scopes are determined statically, they are used dynamically. At any +time during execution, there are at least three nested scopes whose namespaces +are directly accessible: + +* the innermost scope, which is searched first, contains the local names +* the scopes of any enclosing functions, which are searched starting with the + nearest enclosing scope, contains non-local, but also non-global names +* the next-to-last scope contains the current module's global names +* the outermost scope (searched last) is the namespace containing built-in names + +If a name is declared global, then all references and assignments go directly to +the middle scope containing the module's global names. To rebind variables +found outside of the innermost scope, the :keyword:`nonlocal` statement can be +used; if not declared nonlocal, those variables are read-only (an attempt to +write to such a variable will simply create a *new* local variable in the +innermost scope, leaving the identically named outer variable unchanged). + +Usually, the local scope references the local names of the (textually) current +function. Outside functions, the local scope references the same namespace as +the global scope: the module's namespace. Class definitions place yet another +namespace in the local scope. + +It is important to realize that scopes are determined textually: the global +scope of a function defined in a module is that module's namespace, no matter +from where or by what alias the function is called. On the other hand, the +actual search for names is done dynamically, at run time --- however, the +language definition is evolving towards static name resolution, at "compile" +time, so don't rely on dynamic name resolution! (In fact, local variables are +already determined statically.) + +A special quirk of Python is that -- if no :keyword:`global` or :keyword:`nonlocal` +statement is in effect -- assignments to names always go into the innermost scope. +Assignments do not copy data --- they just bind names to objects. The same is true +for deletions: the statement ``del x`` removes the binding of ``x`` from the +namespace referenced by the local scope. In fact, all operations that introduce +new names use the local scope: in particular, :keyword:`import` statements and +function definitions bind the module or function name in the local scope. + +The :keyword:`global` statement can be used to indicate that particular +variables live in the global scope and should be rebound there; the +:keyword:`nonlocal` statement indicates that particular variables live in +an enclosing scope and should be rebound there. + +.. _tut-scopeexample: + +Scopes and Namespaces Example +----------------------------- + +This is an example demonstrating how to reference the different scopes and +namespaces, and how :keyword:`global` and :keyword:`nonlocal` affect variable +binding:: + + def scope_test(): + def do_local(): + spam = "local spam" + + def do_nonlocal(): + nonlocal spam + spam = "nonlocal spam" + + def do_global(): + global spam + spam = "global spam" + + spam = "test spam" + do_local() + print("After local assignment:", spam) + do_nonlocal() + print("After nonlocal assignment:", spam) + do_global() + print("After global assignment:", spam) + + scope_test() + print("In global scope:", spam) + +The output of the example code is: + +.. code-block:: none + + After local assignment: test spam + After nonlocal assignment: nonlocal spam + After global assignment: nonlocal spam + In global scope: global spam + +Note how the *local* assignment (which is default) didn't change *scope_test*\'s +binding of *spam*. The :keyword:`nonlocal` assignment changed *scope_test*\'s +binding of *spam*, and the :keyword:`global` assignment changed the module-level +binding. + +You can also see that there was no previous binding for *spam* before the +:keyword:`global` assignment. + + +.. _tut-firstclasses: + +A First Look at Classes +======================= + +Classes introduce a little bit of new syntax, three new object types, and some +new semantics. + + +.. _tut-classdefinition: + +Class Definition Syntax +----------------------- + +The simplest form of class definition looks like this:: + + class ClassName: + + . + . + . + + +Class definitions, like function definitions (:keyword:`def` statements) must be +executed before they have any effect. (You could conceivably place a class +definition in a branch of an :keyword:`if` statement, or inside a function.) + +In practice, the statements inside a class definition will usually be function +definitions, but other statements are allowed, and sometimes useful --- we'll +come back to this later. The function definitions inside a class normally have +a peculiar form of argument list, dictated by the calling conventions for +methods --- again, this is explained later. + +When a class definition is entered, a new namespace is created, and used as the +local scope --- thus, all assignments to local variables go into this new +namespace. In particular, function definitions bind the name of the new +function here. + +When a class definition is left normally (via the end), a *class object* is +created. This is basically a wrapper around the contents of the namespace +created by the class definition; we'll learn more about class objects in the +next section. The original local scope (the one in effect just before the class +definition was entered) is reinstated, and the class object is bound here to the +class name given in the class definition header (:class:`ClassName` in the +example). + + +.. _tut-classobjects: + +Class Objects +------------- + +Class objects support two kinds of operations: attribute references and +instantiation. + +*Attribute references* use the standard syntax used for all attribute references +in Python: ``obj.name``. Valid attribute names are all the names that were in +the class's namespace when the class object was created. So, if the class +definition looked like this:: + + class MyClass: + """A simple example class""" + i = 12345 + + def f(self): + return 'hello world' + +then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, returning +an integer and a function object, respectively. Class attributes can also be +assigned to, so you can change the value of ``MyClass.i`` by assignment. +:attr:`__doc__` is also a valid attribute, returning the docstring belonging to +the class: ``"A simple example class"``. + +Class *instantiation* uses function notation. Just pretend that the class +object is a parameterless function that returns a new instance of the class. +For example (assuming the above class):: + + x = MyClass() + +creates a new *instance* of the class and assigns this object to the local +variable ``x``. + +The instantiation operation ("calling" a class object) creates an empty object. +Many classes like to create objects with instances customized to a specific +initial state. Therefore a class may define a special method named +:meth:`__init__`, like this:: + + def __init__(self): + self.data = [] + +When a class defines an :meth:`__init__` method, class instantiation +automatically invokes :meth:`__init__` for the newly-created class instance. So +in this example, a new, initialized instance can be obtained by:: + + x = MyClass() + +Of course, the :meth:`__init__` method may have arguments for greater +flexibility. In that case, arguments given to the class instantiation operator +are passed on to :meth:`__init__`. For example, :: + + >>> class Complex: + ... 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) + + +.. _tut-instanceobjects: + +Instance Objects +---------------- + +Now what can we do with instance objects? The only operations understood by +instance objects are attribute references. There are two kinds of valid +attribute names: data attributes and methods. + +*data attributes* correspond to "instance variables" in Smalltalk, and to "data +members" in C++. Data attributes need not be declared; like local variables, +they spring into existence when they are first assigned to. For example, if +``x`` is the instance of :class:`MyClass` created above, the following piece of +code will print the value ``16``, without leaving a trace:: + + x.counter = 1 + while x.counter < 10: + x.counter = x.counter * 2 + print(x.counter) + del x.counter + +The other kind of instance attribute reference is a *method*. A method is a +function that "belongs to" an object. (In Python, the term method is not unique +to class instances: other object types can have methods as well. For example, +list objects have methods called append, insert, remove, sort, and so on. +However, in the following discussion, we'll use the term method exclusively to +mean methods of class instance objects, unless explicitly stated otherwise.) + +.. index:: object: method + +Valid method names of an instance object depend on its class. By definition, +all attributes of a class that are function objects define corresponding +methods of its instances. So in our example, ``x.f`` is a valid method +reference, since ``MyClass.f`` is a function, but ``x.i`` is not, since +``MyClass.i`` is not. But ``x.f`` is not the same thing as ``MyClass.f`` --- it +is a *method object*, not a function object. + + +.. _tut-methodobjects: + +Method Objects +-------------- + +Usually, a method is called right after it is bound:: + + x.f() + +In the :class:`MyClass` example, this will return the string ``'hello world'``. +However, it is not necessary to call a method right away: ``x.f`` is a method +object, and can be stored away and called at a later time. For example:: + + xf = x.f + while True: + print(xf()) + +will continue to print ``hello world`` until the end of time. + +What exactly happens when a method is called? You may have noticed that +``x.f()`` was called without an argument above, even though the function +definition for :meth:`f` specified an argument. What happened to the argument? +Surely Python raises an exception when a function that requires an argument is +called without any --- even if the argument isn't actually used... + +Actually, you may have guessed the answer: the special thing about methods is +that the instance object is passed as the first argument of the function. In our +example, the call ``x.f()`` is exactly equivalent to ``MyClass.f(x)``. In +general, calling a method with a list of *n* arguments is equivalent to calling +the corresponding function with an argument list that is created by inserting +the method's instance object before the first argument. + +If you still don't understand how methods work, a look at the implementation can +perhaps clarify matters. When a non-data attribute of an instance is +referenced, the instance's class is searched. If the name denotes a valid class +attribute that is a function object, a method object is created by packing +(pointers to) the instance object and the function object just found together in +an abstract object: this is the method object. When the method object is called +with an argument list, a new argument list is constructed from the instance +object and the argument list, and the function object is called with this new +argument list. + + +.. _tut-class-and-instance-variables: + +Class and Instance Variables +---------------------------- + +Generally speaking, instance variables are for data unique to each instance +and class variables are for attributes and methods shared by all instances +of the class:: + + class Dog: + + kind = 'canine' # class variable shared by all instances + + def __init__(self, name): + self.name = name # instance variable unique to each instance + + >>> d = Dog('Fido') + >>> e = Dog('Buddy') + >>> d.kind # shared by all dogs + 'canine' + >>> e.kind # shared by all dogs + 'canine' + >>> d.name # unique to d + 'Fido' + >>> e.name # unique to e + 'Buddy' + +As discussed in :ref:`tut-object`, shared data can have possibly surprising +effects with involving :term:`mutable` objects such as lists and dictionaries. +For example, the *tricks* list in the following code should not be used as a +class variable because just a single list would be shared by all *Dog* +instances:: + + class Dog: + + tricks = [] # mistaken use of a class variable + + def __init__(self, name): + self.name = name + + def add_trick(self, trick): + self.tricks.append(trick) + + >>> d = Dog('Fido') + >>> e = Dog('Buddy') + >>> d.add_trick('roll over') + >>> e.add_trick('play dead') + >>> d.tricks # unexpectedly shared by all dogs + ['roll over', 'play dead'] + +Correct design of the class should use an instance variable instead:: + + class Dog: + + def __init__(self, name): + self.name = name + self.tricks = [] # creates a new empty list for each dog + + def add_trick(self, trick): + self.tricks.append(trick) + + >>> d = Dog('Fido') + >>> e = Dog('Buddy') + >>> d.add_trick('roll over') + >>> e.add_trick('play dead') + >>> d.tricks + ['roll over'] + >>> e.tricks + ['play dead'] + + +.. _tut-remarks: + +Random Remarks +============== + +.. These should perhaps be placed more carefully... + +If the same attribute name occurs in both an instance and in a class, +then attribute lookup prioritizes the instance:: + + >>> class Warehouse: + purpose = 'storage' + region = 'west' + + >>> w1 = Warehouse() + >>> print(w1.purpose, w1.region) + storage west + >>> w2 = Warehouse() + >>> w2.region = 'east' + >>> print(w2.purpose, w2.region) + storage east + +Data attributes may be referenced by methods as well as by ordinary users +("clients") of an object. In other words, classes are not usable to implement +pure abstract data types. In fact, nothing in Python makes it possible to +enforce data hiding --- it is all based upon convention. (On the other hand, +the Python implementation, written in C, can completely hide implementation +details and control access to an object if necessary; this can be used by +extensions to Python written in C.) + +Clients should use data attributes with care --- clients may mess up invariants +maintained by the methods by stamping on their data attributes. Note that +clients may add data attributes of their own to an instance object without +affecting the validity of the methods, as long as name conflicts are avoided --- +again, a naming convention can save a lot of headaches here. + +There is no shorthand for referencing data attributes (or other methods!) from +within methods. I find that this actually increases the readability of methods: +there is no chance of confusing local variables and instance variables when +glancing through a method. + +Often, the first argument of a method is called ``self``. This is nothing more +than a convention: the name ``self`` has absolutely no special meaning to +Python. Note, however, that by not following the convention your code may be +less readable to other Python programmers, and it is also conceivable that a +*class browser* program might be written that relies upon such a convention. + +Any function object that is a class attribute defines a method for instances of +that class. It is not necessary that the function definition is textually +enclosed in the class definition: assigning a function object to a local +variable in the class is also ok. For example:: + + # Function defined outside the class + def f1(self, x, y): + return min(x, x+y) + + class C: + f = f1 + + def g(self): + return 'hello world' + + h = g + +Now ``f``, ``g`` and ``h`` are all attributes of class :class:`C` that refer to +function objects, and consequently they are all methods of instances of +:class:`C` --- ``h`` being exactly equivalent to ``g``. Note that this practice +usually only serves to confuse the reader of a program. + +Methods may call other methods by using method attributes of the ``self`` +argument:: + + class Bag: + def __init__(self): + self.data = [] + + def add(self, x): + self.data.append(x) + + def addtwice(self, x): + self.add(x) + self.add(x) + +Methods may reference global names in the same way as ordinary functions. The +global scope associated with a method is the module containing its +definition. (A class is never used as a global scope.) While one +rarely encounters a good reason for using global data in a method, there are +many legitimate uses of the global scope: for one thing, functions and modules +imported into the global scope can be used by methods, as well as functions and +classes defined in it. Usually, the class containing the method is itself +defined in this global scope, and in the next section we'll find some good +reasons why a method would want to reference its own class. + +Each value is an object, and therefore has a *class* (also called its *type*). +It is stored as ``object.__class__``. + + +.. _tut-inheritance: + +Inheritance +=========== + +Of course, a language feature would not be worthy of the name "class" without +supporting inheritance. The syntax for a derived class definition looks like +this:: + + class DerivedClassName(BaseClassName): + + . + . + . + + +The name :class:`BaseClassName` must be defined in a scope containing the +derived class definition. In place of a base class name, other arbitrary +expressions are also allowed. This can be useful, for example, when the base +class is defined in another module:: + + class DerivedClassName(modname.BaseClassName): + +Execution of a derived class definition proceeds the same as for a base class. +When the class object is constructed, the base class is remembered. This is +used for resolving attribute references: if a requested attribute is not found +in the class, the search proceeds to look in the base class. This rule is +applied recursively if the base class itself is derived from some other class. + +There's nothing special about instantiation of derived classes: +``DerivedClassName()`` creates a new instance of the class. Method references +are resolved as follows: the corresponding class attribute is searched, +descending down the chain of base classes if necessary, and the method reference +is valid if this yields a function object. + +Derived classes may override methods of their base classes. Because methods +have no special privileges when calling other methods of the same object, a +method of a base class that calls another method defined in the same base class +may end up calling a method of a derived class that overrides it. (For C++ +programmers: all methods in Python are effectively ``virtual``.) + +An overriding method in a derived class may in fact want to extend rather than +simply replace the base class method of the same name. There is a simple way to +call the base class method directly: just call ``BaseClassName.methodname(self, +arguments)``. This is occasionally useful to clients as well. (Note that this +only works if the base class is accessible as ``BaseClassName`` in the global +scope.) + +Python has two built-in functions that work with inheritance: + +* Use :func:`isinstance` to check an instance's type: ``isinstance(obj, int)`` + will be ``True`` only if ``obj.__class__`` is :class:`int` or some class + derived from :class:`int`. + +* Use :func:`issubclass` to check class inheritance: ``issubclass(bool, int)`` + 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: + +Multiple Inheritance +-------------------- + +Python supports a form of multiple inheritance as well. A class definition with +multiple base classes looks like this:: + + class DerivedClassName(Base1, Base2, Base3): + + . + . + . + + +For most purposes, in the simplest cases, you can think of the search for +attributes inherited from a parent class as depth-first, left-to-right, not +searching twice in the same class where there is an overlap in the hierarchy. +Thus, if an attribute is not found in :class:`DerivedClassName`, it is searched +for in :class:`Base1`, then (recursively) in the base classes of :class:`Base1`, +and if it was not found there, it was searched for in :class:`Base2`, and so on. + +In fact, it is slightly more complex than that; the method resolution order +changes dynamically to support cooperative calls to :func:`super`. This +approach is known in some other multiple-inheritance languages as +call-next-method and is more powerful than the super call found in +single-inheritance languages. + +Dynamic ordering is necessary because all cases of multiple inheritance exhibit +one or more diamond relationships (where at least one of the parent classes +can be accessed through multiple paths from the bottommost class). For example, +all classes inherit from :class:`object`, so any case of multiple inheritance +provides more than one path to reach :class:`object`. To keep the base classes +from being accessed more than once, the dynamic algorithm linearizes the search +order in a way that preserves the left-to-right ordering specified in each +class, that calls each parent only once, and that is monotonic (meaning that a +class can be subclassed without affecting the precedence order of its parents). +Taken together, these properties make it possible to design reliable and +extensible classes with multiple inheritance. For more detail, see +https://www.python.org/download/releases/2.3/mro/. + + +.. _tut-private: + +Private Variables +================= + +"Private" instance variables that cannot be accessed except from inside an +object don't exist in Python. However, there is a convention that is followed +by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should +be treated as a non-public part of the API (whether it is a function, a method +or a data member). It should be considered an implementation detail and subject +to change without notice. + +.. index:: + pair: name; mangling + +Since there is a valid use-case for class-private members (namely to avoid name +clashes of names with names defined by subclasses), there is limited support for +such a mechanism, called :dfn:`name mangling`. Any identifier of the form +``__spam`` (at least two leading underscores, at most one trailing underscore) +is textually replaced with ``_classname__spam``, where ``classname`` is the +current class name with leading underscore(s) stripped. This mangling is done +without regard to the syntactic position of the identifier, as long as it +occurs within the definition of a class. + +Name mangling is helpful for letting subclasses override methods without +breaking intraclass method calls. For example:: + + class Mapping: + def __init__(self, iterable): + self.items_list = [] + self.__update(iterable) + + def update(self, iterable): + for item in iterable: + self.items_list.append(item) + + __update = update # private copy of original update() method + + class MappingSubclass(Mapping): + + def update(self, keys, values): + # provides new signature for update() + # but does not break __init__() + for item in zip(keys, values): + self.items_list.append(item) + +The above example would work even if ``MappingSubclass`` were to introduce a +``__update`` identifier since it is replaced with ``_Mapping__update`` in the +``Mapping`` class and ``_MappingSubclass__update`` in the ``MappingSubclass`` +class respectively. + +Note that the mangling rules are designed mostly to avoid accidents; it still is +possible to access or modify a variable that is considered private. This can +even be useful in special circumstances, such as in the debugger. + +Notice that code passed to ``exec()`` or ``eval()`` does not consider the +classname of the invoking class to be the current class; this is similar to the +effect of the ``global`` statement, the effect of which is likewise restricted +to code that is byte-compiled together. The same restriction applies to +``getattr()``, ``setattr()`` and ``delattr()``, as well as when referencing +``__dict__`` directly. + + +.. _tut-odds: + +Odds and Ends +============= + +Sometimes it is useful to have a data type similar to the Pascal "record" or C +"struct", bundling together a few named data items. An empty class definition +will do nicely:: + + class Employee: + pass + + john = Employee() # Create an empty employee record + + # Fill the fields of the record + john.name = 'John Doe' + john.dept = 'computer lab' + john.salary = 1000 + +A piece of Python code that expects a particular abstract data type can often be +passed a class that emulates the methods of that data type instead. For +instance, if you have a function that formats some data from a file object, you +can define a class with methods :meth:`read` and :meth:`!readline` that get the +data from a string buffer instead, and pass it as an argument. + +.. (Unfortunately, this technique has its limitations: a class can't define + operations that are accessed by special syntax such as sequence subscripting + or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will + not cause the interpreter to read further input from it.) + +Instance method objects have attributes, too: ``m.__self__`` is the instance +object with the method :meth:`m`, and ``m.__func__`` is the function object +corresponding to the method. + + +.. _tut-iterators: + +Iterators +========= + +By now you have probably noticed that most container objects can be looped over +using a :keyword:`for` statement:: + + for element in [1, 2, 3]: + print(element) + for element in (1, 2, 3): + print(element) + for key in {'one':1, 'two':2}: + print(key) + for char in "123": + print(char) + for line in open("myfile.txt"): + print(line, end='') + +This style of access is clear, concise, and convenient. The use of iterators +pervades and unifies Python. Behind the scenes, the :keyword:`for` statement +calls :func:`iter` on the container object. The function returns an iterator +object that defines the method :meth:`~iterator.__next__` which accesses +elements in the container one at a time. When there are no more elements, +:meth:`~iterator.__next__` raises a :exc:`StopIteration` exception which tells the +:keyword:`!for` loop to terminate. You can call the :meth:`~iterator.__next__` method +using the :func:`next` built-in function; this example shows how it all works:: + + >>> s = 'abc' + >>> it = iter(s) + >>> it + + >>> next(it) + 'a' + >>> next(it) + 'b' + >>> next(it) + 'c' + >>> next(it) + Traceback (most recent call last): + File "", line 1, in + next(it) + StopIteration + +Having seen the mechanics behind the iterator protocol, it is easy to add +iterator behavior to your classes. Define an :meth:`__iter__` method which +returns an object with a :meth:`~iterator.__next__` method. If the class +defines :meth:`__next__`, then :meth:`__iter__` can just return ``self``:: + + class Reverse: + """Iterator for looping over a sequence backwards.""" + def __init__(self, data): + self.data = data + self.index = len(data) + + def __iter__(self): + return self + + def __next__(self): + if self.index == 0: + raise StopIteration + self.index = self.index - 1 + return self.data[self.index] + +:: + + >>> rev = Reverse('spam') + >>> iter(rev) + <__main__.Reverse object at 0x00A1DB50> + >>> for char in rev: + ... print(char) + ... + m + a + p + s + + +.. _tut-generators: + +Generators +========== + +:term:`Generator`\s are a simple and powerful tool for creating iterators. They +are written like regular functions but use the :keyword:`yield` statement +whenever they want to return data. Each time :func:`next` is called on it, the +generator resumes where it left off (it remembers all the data values and which +statement was last executed). An example shows that generators can be trivially +easy to create:: + + def reverse(data): + for index in range(len(data)-1, -1, -1): + yield data[index] + +:: + + >>> for char in reverse('golf'): + ... print(char) + ... + f + l + o + g + +Anything that can be done with generators can also be done with class-based +iterators as described in the previous section. What makes generators so +compact is that the :meth:`__iter__` and :meth:`~generator.__next__` methods +are created automatically. + +Another key feature is that the local variables and execution state are +automatically saved between calls. This made the function easier to write and +much more clear than an approach using instance variables like ``self.index`` +and ``self.data``. + +In addition to automatic method creation and saving program state, when +generators terminate, they automatically raise :exc:`StopIteration`. In +combination, these features make it easy to create iterators with no more effort +than writing a regular function. + + +.. _tut-genexps: + +Generator Expressions +===================== + +Some simple generators can be coded succinctly as expressions using a syntax +similar to list comprehensions but with parentheses instead of square brackets. +These expressions are designed for situations where the generator is used right +away by an enclosing function. Generator expressions are more compact but less +versatile than full generator definitions and tend to be more memory friendly +than equivalent list comprehensions. + +Examples:: + + >>> sum(i*i for i in range(10)) # sum of squares + 285 + + >>> xvec = [10, 20, 30] + >>> yvec = [7, 5, 3] + >>> sum(x*y for x,y in zip(xvec, yvec)) # dot product + 260 + + >>> unique_words = set(word for line in page for word in line.split()) + + >>> valedictorian = max((student.gpa, student.name) for student in graduates) + + >>> data = 'golf' + >>> list(data[i] for i in range(len(data)-1, -1, -1)) + ['f', 'l', 'o', 'g'] + + + +.. rubric:: Footnotes + +.. [#] Except for one thing. Module objects have a secret read-only attribute called + :attr:`~object.__dict__` which returns the dictionary used to implement the module's + namespace; the name :attr:`~object.__dict__` is an attribute but not a global name. + Obviously, using this violates the abstraction of namespace implementation, and + should be restricted to things like post-mortem debuggers. diff --git a/cpython_2/environment/repo/Doc/tutorial/controlflow.rst b/cpython_2/environment/repo/Doc/tutorial/controlflow.rst new file mode 100644 index 0000000000000000000000000000000000000000..f05f5edd5ccc409cd210c0e0fa3c4c2c34b62a34 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/controlflow.rst @@ -0,0 +1,940 @@ +.. _tut-morecontrol: + +*********************** +More Control Flow Tools +*********************** + +Besides the :keyword:`while` statement just introduced, Python uses the usual +flow control statements known from other languages, with some twists. + + +.. _tut-if: + +:keyword:`!if` Statements +========================= + +Perhaps the most well-known statement type is the :keyword:`if` statement. For +example:: + + >>> x = int(input("Please enter an integer: ")) + Please enter an integer: 42 + >>> if x < 0: + ... x = 0 + ... print('Negative changed to zero') + ... elif x == 0: + ... print('Zero') + ... elif x == 1: + ... print('Single') + ... else: + ... print('More') + ... + More + +There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is +optional. The keyword ':keyword:`!elif`' is short for 'else if', and is useful +to avoid excessive indentation. An :keyword:`!if` ... :keyword:`!elif` ... +:keyword:`!elif` ... sequence is a substitute for the ``switch`` or +``case`` statements found in other languages. + + +.. _tut-for: + +:keyword:`!for` Statements +========================== + +.. index:: + statement: for + +The :keyword:`for` statement in Python differs a bit from what you may be used +to in C or Pascal. Rather than always iterating over an arithmetic progression +of numbers (like in Pascal), or giving the user the ability to define both the +iteration step and halting condition (as C), Python's :keyword:`!for` statement +iterates over the items of any sequence (a list or a string), in the order that +they appear in the sequence. For example (no pun intended): + +.. One suggestion was to give a real C example here, but that may only serve to + confuse non-C programmers. + +:: + + >>> # Measure some strings: + ... words = ['cat', 'window', 'defenestrate'] + >>> for w in words: + ... print(w, len(w)) + ... + cat 3 + window 6 + defenestrate 12 + +Code that modifies a collection while iterating over that same collection can +be tricky to get right. Instead, it is usually more straight-forward to loop +over a copy of the collection or to create a new collection:: + + # Strategy: Iterate over a copy + for user, status in users.copy().items(): + if status == 'inactive': + del users[user] + + # Strategy: Create a new collection + active_users = {} + for user, status in users.items(): + if status == 'active': + active_users[user] = status + + +.. _tut-range: + +The :func:`range` Function +========================== + +If you do need to iterate over a sequence of numbers, the built-in function +:func:`range` comes in handy. It generates arithmetic progressions:: + + >>> for i in range(5): + ... print(i) + ... + 0 + 1 + 2 + 3 + 4 + +The given end point is never part of the generated sequence; ``range(10)`` generates +10 values, the legal indices for items of a sequence of length 10. It +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) + 5, 6, 7, 8, 9 + + range(0, 10, 3) + 0, 3, 6, 9 + + range(-10, -100, -30) + -10, -40, -70 + +To iterate over the indices of a sequence, you can combine :func:`range` and +:func:`len` as follows:: + + >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] + >>> for i in range(len(a)): + ... print(i, a[i]) + ... + 0 Mary + 1 had + 2 a + 3 little + 4 lamb + +In most such cases, however, it is convenient to use the :func:`enumerate` +function, see :ref:`tut-loopidioms`. + +A strange thing happens if you just print a range:: + + >>> print(range(10)) + 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. + +We say such an object is :term:`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 a construct, while an example of a function +that takes an iterable is :func:`sum`:: + + >>> sum(range(4)) # 0 + 1 + 2 + 3 + 6 + +Later we will see more functions that return iterables and take iterables as +arguments. Lastly, maybe you are curious about how to get a list from a range. +Here is the solution:: + + >>> list(range(4)) + [0, 1, 2, 3] + +In chapter :ref:`tut-structures`, we will discuss in more detail about +:func:`list`. + +.. _tut-break: + +:keyword:`!break` and :keyword:`!continue` Statements, and :keyword:`!else` Clauses on Loops +============================================================================================ + +The :keyword:`break` statement, like in C, breaks out of the innermost enclosing +:keyword:`for` or :keyword:`while` loop. + +Loop statements may have an :keyword:`!else` clause; it is executed when the loop +terminates through exhaustion of the iterable (with :keyword:`for`) or when the +condition becomes false (with :keyword:`while`), but not when the loop is +terminated by a :keyword:`break` statement. This is exemplified by the +following loop, which searches for prime numbers:: + + >>> for n in range(2, 10): + ... for x in range(2, n): + ... if n % x == 0: + ... print(n, 'equals', x, '*', n//x) + ... break + ... 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 + 5 is a prime number + 6 equals 2 * 3 + 7 is a prime number + 8 equals 2 * 4 + 9 equals 3 * 3 + +(Yes, this is the correct code. Look closely: the ``else`` clause belongs to +the :keyword:`for` loop, **not** the :keyword:`if` statement.) + +When used with a loop, the ``else`` clause has more in common with the +``else`` clause of a :keyword:`try` statement than it does with that of +:keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs +when no exception occurs, and a loop's ``else`` clause runs when no ``break`` +occurs. For more on the :keyword:`!try` statement and exceptions, see +:ref:`tut-handling`. + +The :keyword:`continue` statement, also borrowed from C, continues with the next +iteration of the loop:: + + >>> for num in range(2, 10): + ... if num % 2 == 0: + ... print("Found an even number", num) + ... continue + ... print("Found a number", num) + Found an even number 2 + Found a number 3 + Found an even number 4 + Found a number 5 + Found an even number 6 + Found a number 7 + Found an even number 8 + Found a number 9 + +.. _tut-pass: + +:keyword:`!pass` Statements +=========================== + +The :keyword:`pass` statement does nothing. It can be used when a statement is +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:: + + >>> class MyEmptyClass: + ... pass + ... + +Another place :keyword:`pass` can be used is as a place-holder for a function or +conditional body when you are working on new code, allowing you to keep thinking +at a more abstract level. The :keyword:`!pass` is silently ignored:: + + >>> def initlog(*args): + ... pass # Remember to implement this! + ... + +.. _tut-functions: + +Defining Functions +================== + +We can create a function that writes the Fibonacci series to an arbitrary +boundary:: + + >>> def fib(n): # write Fibonacci series up to n + ... """Print a Fibonacci series up to n.""" + ... a, b = 0, 1 + ... while a < n: + ... print(a, end=' ') + ... a, b = b, a+b + ... print() + ... + >>> # Now call the function we just defined: + ... fib(2000) + 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 + +.. index:: + single: documentation strings + single: docstrings + single: strings, documentation + +The keyword :keyword:`def` introduces a function *definition*. It must be +followed by the function name and the parenthesized list of formal parameters. +The statements that form the body of the function start at the next line, and +must be indented. + +The first statement of the function body can optionally be a string literal; +this string literal is the function's documentation string, or :dfn:`docstring`. +(More about docstrings can be found in the section :ref:`tut-docstrings`.) +There are tools which use docstrings to automatically produce online or printed +documentation, or to let the user interactively browse through code; it's good +practice to include docstrings in code that you write, so make a habit of it. + +The *execution* of a function introduces a new symbol table used for the local +variables of the function. More precisely, all variable assignments in a +function store the value in the local symbol table; whereas variable references +first look in the local symbol table, then in the local symbol tables of +enclosing functions, then in the global symbol table, and finally in the table +of built-in names. Thus, global variables and variables of enclosing functions +cannot be directly assigned a value within a function (unless, for global +variables, named in a :keyword:`global` statement, or, for variables of enclosing +functions, named in a :keyword:`nonlocal` statement), although they may be +referenced. + +The actual parameters (arguments) to a function call are introduced in the local +symbol table of the called function when it is called; thus, arguments are +passed using *call by value* (where the *value* is always an object *reference*, +not the value of the object). [#]_ When a function calls another function, a new +local symbol table is created for that call. + +A function definition introduces the function name in the current symbol table. +The value of the function name has a type that is recognized by the interpreter +as a user-defined function. This value can be assigned to another name which +can then also be used as a function. This serves as a general renaming +mechanism:: + + >>> fib + + >>> f = fib + >>> f(100) + 0 1 1 2 3 5 8 13 21 34 55 89 + +Coming from other languages, you might object that ``fib`` is not a function but +a procedure since it doesn't return a value. In fact, even functions without a +:keyword:`return` statement do return a value, albeit a rather boring one. This +value is called ``None`` (it's a built-in name). Writing the value ``None`` is +normally suppressed by the interpreter if it would be the only value written. +You can see it if you really want to using :func:`print`:: + + >>> fib(0) + >>> print(fib(0)) + None + +It is simple to write a function that returns a list of the numbers of the +Fibonacci series, instead of printing it:: + + >>> def fib2(n): # return Fibonacci series up to n + ... """Return a list containing the Fibonacci series up to n.""" + ... result = [] + ... a, b = 0, 1 + ... while a < n: + ... result.append(a) # see below + ... a, b = b, a+b + ... return result + ... + >>> f100 = fib2(100) # call it + >>> f100 # write the result + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] + +This example, as usual, demonstrates some new Python features: + +* The :keyword:`return` statement returns with a value from a function. + :keyword:`!return` without an expression argument returns ``None``. Falling off + the end of a function also returns ``None``. + +* The statement ``result.append(a)`` calls a *method* of the list object + ``result``. A method is a function that 'belongs' to an object and is named + ``obj.methodname``, where ``obj`` is some object (this may be an expression), + and ``methodname`` is the name of a method that is defined by the object's type. + Different types define different methods. Methods of different types may have + the same name without causing ambiguity. (It is possible to define your own + object types and methods, using *classes*, see :ref:`tut-classes`) + The method :meth:`append` shown in the example is defined for list objects; it + adds a new element at the end of the list. In this example it is equivalent to + ``result = result + [a]``, but more efficient. + + +.. _tut-defining: + +More on Defining Functions +========================== + +It is also possible to define functions with a variable number of arguments. +There are three forms, which can be combined. + + +.. _tut-defaultargs: + +Default Argument Values +----------------------- + +The most useful form is to specify a default value for one or more arguments. +This creates a function that can be called with fewer arguments than it is +defined to allow. For example:: + + def ask_ok(prompt, retries=4, reminder='Please try again!'): + while True: + ok = input(prompt) + if ok in ('y', 'ye', 'yes'): + return True + if ok in ('n', 'no', 'nop', 'nope'): + return False + retries = retries - 1 + if retries < 0: + raise ValueError('invalid user response') + print(reminder) + +This function can be called in several ways: + +* giving only the mandatory argument: + ``ask_ok('Do you really want to quit?')`` +* giving one of the optional arguments: + ``ask_ok('OK to overwrite the file?', 2)`` +* or even giving all arguments: + ``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')`` + +This example also introduces the :keyword:`in` keyword. This tests whether or +not a sequence contains a certain value. + +The default values are evaluated at the point of function definition in the +*defining* scope, so that :: + + i = 5 + + def f(arg=i): + print(arg) + + i = 6 + f() + +will print ``5``. + +**Important warning:** The default value is evaluated only once. This makes a +difference when the default is a mutable object such as a list, dictionary, or +instances of most classes. For example, the following function accumulates the +arguments passed to it on subsequent calls:: + + def f(a, L=[]): + L.append(a) + return L + + print(f(1)) + print(f(2)) + print(f(3)) + +This will print :: + + [1] + [1, 2] + [1, 2, 3] + +If you don't want the default to be shared between subsequent calls, you can +write the function like this instead:: + + def f(a, L=None): + if L is None: + L = [] + L.append(a) + return L + + +.. _tut-keywordargs: + +Keyword Arguments +----------------- + +Functions can also be called using :term:`keyword arguments ` +of the form ``kwarg=value``. For instance, the following function:: + + def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): + print("-- This parrot wouldn't", action, end=' ') + print("if you put", voltage, "volts through it.") + print("-- Lovely plumage, the", type) + print("-- It's", state, "!") + +accepts one required argument (``voltage``) and three optional arguments +(``state``, ``action``, and ``type``). This function can be called in any +of the following ways:: + + parrot(1000) # 1 positional argument + parrot(voltage=1000) # 1 keyword argument + parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments + parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments + parrot('a million', 'bereft of life', 'jump') # 3 positional arguments + parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword + +but all the following calls would be invalid:: + + parrot() # required argument missing + parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument + parrot(110, voltage=220) # duplicate value for the same argument + parrot(actor='John Cleese') # unknown keyword argument + +In a function call, keyword arguments must follow positional arguments. +All the keyword arguments passed must match one of the arguments +accepted by the function (e.g. ``actor`` is not a valid argument for the +``parrot`` function), and their order is not important. This also includes +non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too). +No argument may receive a value more than once. +Here's an example that fails due to this restriction:: + + >>> def function(a): + ... pass + ... + >>> function(0, a=0) + Traceback (most recent call last): + File "", line 1, in + TypeError: function() got multiple values for keyword argument 'a' + +When a final formal parameter of the form ``**name`` is present, it receives a +dictionary (see :ref:`typesmapping`) containing all keyword arguments except for +those corresponding to a formal parameter. This may be combined with a formal +parameter of the form ``*name`` (described in the next subsection) which +receives a :ref:`tuple ` containing the positional +arguments beyond the formal parameter list. (``*name`` must occur +before ``**name``.) For example, if we define a function like this:: + + def cheeseshop(kind, *arguments, **keywords): + print("-- Do you have any", kind, "?") + print("-- I'm sorry, we're all out of", kind) + for arg in arguments: + print(arg) + print("-" * 40) + for kw in keywords: + print(kw, ":", keywords[kw]) + +It could be called like this:: + + cheeseshop("Limburger", "It's very runny, sir.", + "It's really very, VERY runny, sir.", + shopkeeper="Michael Palin", + client="John Cleese", + sketch="Cheese Shop Sketch") + +and of course it would print: + +.. code-block:: none + + -- Do you have any Limburger ? + -- I'm sorry, we're all out of Limburger + It's very runny, sir. + It's really very, VERY runny, sir. + ---------------------------------------- + shopkeeper : Michael Palin + client : John Cleese + sketch : Cheese Shop Sketch + +Note that the order in which the keyword arguments are printed is guaranteed +to match the order in which they were provided in the function call. + +Special parameters +------------------ + +By default, arguments may be passed to a Python function either by position +or explicitly by keyword. For readability and performance, it makes sense to +restrict the way arguments can be passed so that a developer need only look +at the function definition to determine if items are passed by position, by +position or keyword, or by keyword. + +A function definition may look like: + +.. code-block:: none + + def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): + ----------- ---------- ---------- + | | | + | Positional or keyword | + | - Keyword only + -- Positional only + +where ``/`` and ``*`` are optional. If used, these symbols indicate the kind of +parameter by how the arguments may be passed to the function: +positional-only, positional-or-keyword, and keyword-only. Keyword parameters +are also referred to as named parameters. + +------------------------------- +Positional-or-Keyword Arguments +------------------------------- + +If ``/`` and ``*`` are not present in the function definition, arguments may +be passed to a function by position or by keyword. + +-------------------------- +Positional-Only Parameters +-------------------------- + +Looking at this in a bit more detail, it is possible to mark certain parameters +as *positional-only*. If *positional-only*, the parameters' order matters, and +the parameters cannot be passed by keyword. Positional-only parameters are +placed before a ``/`` (forward-slash). The ``/`` is used to logically +separate the positional-only parameters from the rest of the parameters. +If there is no ``/`` in the function definition, there are no positional-only +parameters. + +Parameters following the ``/`` may be *positional-or-keyword* or *keyword-only*. + +---------------------- +Keyword-Only Arguments +---------------------- + +To mark parameters as *keyword-only*, indicating the parameters must be passed +by keyword argument, place an ``*`` in the arguments list just before the first +*keyword-only* parameter. + +----------------- +Function Examples +----------------- + +Consider the following example function definitions paying close attention to the +markers ``/`` and ``*``:: + + >>> def standard_arg(arg): + ... print(arg) + ... + >>> def pos_only_arg(arg, /): + ... print(arg) + ... + >>> def kwd_only_arg(*, arg): + ... print(arg) + ... + >>> def combined_example(pos_only, /, standard, *, kwd_only): + ... print(pos_only, standard, kwd_only) + + +The first function definition, ``standard_arg``, the most familiar form, +places no restrictions on the calling convention and arguments may be +passed by position or keyword:: + + >>> standard_arg(2) + 2 + + >>> standard_arg(arg=2) + 2 + +The second function ``pos_only_arg`` is restricted to only use positional +parameters as there is a ``/`` in the function definition:: + + >>> pos_only_arg(1) + 1 + + >>> pos_only_arg(arg=1) + Traceback (most recent call last): + File "", line 1, in + TypeError: pos_only_arg() got an unexpected keyword argument 'arg' + +The third function ``kwd_only_args`` only allows keyword arguments as indicated +by a ``*`` in the function definition:: + + >>> kwd_only_arg(3) + Traceback (most recent call last): + File "", line 1, in + TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given + + >>> kwd_only_arg(arg=3) + 3 + +And the last uses all three calling conventions in the same function +definition:: + + >>> combined_example(1, 2, 3) + Traceback (most recent call last): + File "", line 1, in + TypeError: combined_example() takes 2 positional arguments but 3 were given + + >>> combined_example(1, 2, kwd_only=3) + 1 2 3 + + >>> combined_example(1, standard=2, kwd_only=3) + 1 2 3 + + >>> combined_example(pos_only=1, standard=2, kwd_only=3) + Traceback (most recent call last): + File "", line 1, in + TypeError: combined_example() got an unexpected keyword argument 'pos_only' + + +Finally, consider this function definition which has a potential collision between the positional argument ``name`` and ``**kwds`` which has ``name`` as a key:: + + def foo(name, **kwds): + return 'name' in kwds + +There is no possible call that will make it return ``True`` as the keyword ``'name'`` +will always to bind to the first parameter. For example:: + + >>> foo(1, **{'name': 2}) + Traceback (most recent call last): + File "", line 1, in + TypeError: foo() got multiple values for argument 'name' + >>> + +But using ``/`` (positional only arguments), it is possible since it allows ``name`` as a positional argument and ``'name'`` as a key in the keyword arguments:: + + def foo(name, /, **kwds): + return 'name' in kwds + >>> foo(1, **{'name': 2}) + True + +In other words, the names of positional-only parameters can be used in +``**kwds`` without ambiguity. + +----- +Recap +----- + +The use case will determine which parameters to use in the function definition:: + + def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): + +As guidance: + +* Use positional-only if you want the name of the parameters to not be + available to the user. This is useful when parameter names have no real + meaning, if you want to enforce the order of the arguments when the function + is called or if you need to take some positional parameters and arbitrary + keywords. +* Use keyword-only when names have meaning and the function definition is + more understandable by being explicit with names or you want to prevent + users relying on the position of the argument being passed. +* For an API, use positional-only to prevent breaking API changes + if the parameter's name is modified in the future. + +.. _tut-arbitraryargs: + +Arbitrary Argument Lists +------------------------ + +.. index:: + single: * (asterisk); in function calls + +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 +up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments, +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 +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 +keywords rather than positional arguments. :: + + >>> def concat(*args, sep="/"): + ... return sep.join(args) + ... + >>> concat("earth", "mars", "venus") + 'earth/mars/venus' + >>> concat("earth", "mars", "venus", sep=".") + 'earth.mars.venus' + +.. _tut-unpacking-arguments: + +Unpacking Argument Lists +------------------------ + +The reverse situation occurs when the arguments are already in a list or tuple +but need to be unpacked for a function call requiring separate positional +arguments. For instance, the built-in :func:`range` function expects separate +*start* and *stop* arguments. If they are not available separately, write the +function call with the ``*``\ -operator to unpack the arguments out of a list +or tuple:: + + >>> list(range(3, 6)) # normal call with separate arguments + [3, 4, 5] + >>> args = [3, 6] + >>> list(range(*args)) # call with arguments unpacked from a list + [3, 4, 5] + +.. index:: + single: **; in function calls + +In the same fashion, dictionaries can deliver keyword arguments with the +``**``\ -operator:: + + >>> def parrot(voltage, state='a stiff', action='voom'): + ... print("-- This parrot wouldn't", action, end=' ') + ... print("if you put", voltage, "volts through it.", end=' ') + ... print("E's", state, "!") + ... + >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} + >>> parrot(**d) + -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised ! + + +.. _tut-lambda: + +Lambda Expressions +------------------ + +Small anonymous functions can be created with the :keyword:`lambda` keyword. +This function returns the sum of its two arguments: ``lambda a, b: a+b``. +Lambda functions can be used wherever function objects are required. They are +syntactically restricted to a single expression. Semantically, they are just +syntactic sugar for a normal function definition. Like nested function +definitions, lambda functions can reference variables from the containing +scope:: + + >>> def make_incrementor(n): + ... return lambda x: x + n + ... + >>> f = make_incrementor(42) + >>> f(0) + 42 + >>> f(1) + 43 + +The above example uses a lambda expression to return a function. Another use +is to pass a small function as an argument:: + + >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] + >>> pairs.sort(key=lambda pair: pair[1]) + >>> pairs + [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] + + +.. _tut-docstrings: + +Documentation Strings +--------------------- + +.. index:: + single: docstrings + single: documentation strings + single: strings, documentation + +Here are some conventions about the content and formatting of documentation +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, +since these are available by other means (except if the name happens to be a +verb describing a function's operation). This line should begin with a capital +letter and end with a period. + +If there are more lines in the documentation string, the second line should be +blank, visually separating the summary from the rest of the description. The +following lines should be one or more paragraphs describing the object's calling +conventions, its side effects, etc. + +The Python parser does not strip indentation from multi-line string literals in +Python, so tools that process documentation have to strip indentation if +desired. This is done using the following convention. The first non-blank line +*after* the first line of the string determines the amount of indentation for +the entire documentation string. (We can't use the first line since it is +generally adjacent to the string's opening quotes so its indentation is not +apparent in the string literal.) Whitespace "equivalent" to this indentation is +then stripped from the start of all lines of the string. Lines that are +indented less should not occur, but if they occur all their leading whitespace +should be stripped. Equivalence of whitespace should be tested after expansion +of tabs (to 8 spaces, normally). + +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. + + No, really, it doesn't do anything. + + +.. _tut-annotations: + +Function Annotations +-------------------- + +.. sectionauthor:: Zachary Ware +.. index:: + pair: function; annotations + single: ->; function annotations + single: : (colon); function annotations + +:ref:`Function annotations ` are completely optional metadata +information about the types used by user-defined functions (see :pep:`3107` and +:pep:`484` for more information). + +:term:`Annotations ` are stored in the :attr:`__annotations__` +attribute of the function as a dictionary and have no effect on any other part of the +function. Parameter annotations are defined by a colon after the parameter name, followed +by an expression evaluating to the value of the annotation. Return annotations are +defined by a literal ``->``, followed by an expression, between the parameter +list and the colon denoting the end of the :keyword:`def` statement. The +following example has a positional argument, a keyword argument, and the return +value annotated:: + + >>> def f(ham: str, eggs: str = 'eggs') -> str: + ... print("Annotations:", f.__annotations__) + ... print("Arguments:", ham, eggs) + ... return ham + ' and ' + eggs + ... + >>> f('spam') + Annotations: {'ham': , 'return': , 'eggs': } + Arguments: spam eggs + 'spam and eggs' + +.. _tut-codingstyle: + +Intermezzo: Coding Style +======================== + +.. sectionauthor:: Georg Brandl +.. index:: pair: coding; style + +Now that you are about to write longer, more complex pieces of Python, it is a +good time to talk about *coding style*. Most languages can be written (or more +concise, *formatted*) in different styles; some are more readable than others. +Making it easy for others to read your code is always a good idea, and adopting +a nice coding style helps tremendously for that. + +For Python, :pep:`8` has emerged as the style guide that most projects adhere to; +it promotes a very readable and eye-pleasing coding style. Every Python +developer should read it at some point; here are the most important points +extracted for you: + +* Use 4-space indentation, and no tabs. + + 4 spaces are a good compromise between small indentation (allows greater + nesting depth) and large indentation (easier to read). Tabs introduce + confusion, and are best left out. + +* Wrap lines so that they don't exceed 79 characters. + + This helps users with small displays and makes it possible to have several + code files side-by-side on larger displays. + +* Use blank lines to separate functions and classes, and larger blocks of + code inside functions. + +* When possible, put comments on a line of their own. + +* Use docstrings. + +* Use spaces around operators and after commas, but not directly inside + bracketing constructs: ``a = f(1, 2) + g(3, 4)``. + +* Name your classes and functions consistently; the convention is to use + ``UpperCamelCase`` for classes and ``lowercase_with_underscores`` for functions + and methods. Always use ``self`` as the name for the first method argument + (see :ref:`tut-firstclasses` for more on classes and methods). + +* Don't use fancy encodings if your code is meant to be used in international + environments. Python's default, UTF-8, or even plain ASCII work best in any + case. + +* Likewise, don't use non-ASCII characters in identifiers if there is only the + slightest chance people speaking a different language will read or maintain + the code. + + +.. rubric:: Footnotes + +.. [#] Actually, *call by object reference* would be a better description, + since if a mutable object is passed, the caller will see any changes the + callee makes to it (items inserted into a list). diff --git a/cpython_2/environment/repo/Doc/tutorial/datastructures.rst b/cpython_2/environment/repo/Doc/tutorial/datastructures.rst new file mode 100644 index 0000000000000000000000000000000000000000..0edb73ad736919dfe3e941e721b97d52ae9d0078 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/datastructures.rst @@ -0,0 +1,719 @@ +.. _tut-structures: + +*************** +Data Structures +*************** + +This chapter describes some things you've learned about already in more detail, +and adds some new things as well. + +.. _tut-morelists: + +More on Lists +============= + +The list data type has some more methods. Here are all of the methods of list +objects: + + +.. method:: list.append(x) + :noindex: + + Add an item to the end of the list. Equivalent to ``a[len(a):] = [x]``. + + +.. method:: list.extend(iterable) + :noindex: + + Extend the list by appending all the items from the iterable. Equivalent to + ``a[len(a):] = iterable``. + + +.. method:: list.insert(i, x) + :noindex: + + Insert an item at a given position. The first argument is the index of the + element before which to insert, so ``a.insert(0, x)`` inserts at the front of + the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``. + + +.. method:: list.remove(x) + :noindex: + + Remove the first item from the list whose value is equal to *x*. It raises a + :exc:`ValueError` if there is no such item. + + +.. method:: list.pop([i]) + :noindex: + + Remove the item at the given position in the list, and return it. If no index + is specified, ``a.pop()`` removes and returns the last item in the list. (The + square brackets around the *i* in the method signature denote that the parameter + is optional, not that you should type square brackets at that position. You + will see this notation frequently in the Python Library Reference.) + + +.. method:: list.clear() + :noindex: + + Remove all items from the list. Equivalent to ``del a[:]``. + + +.. method:: list.index(x[, start[, end]]) + :noindex: + + Return zero-based index in the list of the first item whose value is equal to *x*. + Raises a :exc:`ValueError` if there is no such item. + + The optional arguments *start* and *end* are interpreted as in the slice + notation and are used to limit the search to a particular subsequence of + the list. The returned index is computed relative to the beginning of the full + sequence rather than the *start* argument. + + +.. method:: list.count(x) + :noindex: + + Return the number of times *x* appears in the list. + + +.. method:: list.sort(key=None, reverse=False) + :noindex: + + Sort the items of the list in place (the arguments can be used for sort + customization, see :func:`sorted` for their explanation). + + +.. method:: list.reverse() + :noindex: + + Reverse the elements of the list in place. + + +.. method:: list.copy() + :noindex: + + Return a shallow copy of the list. Equivalent to ``a[:]``. + + +An example that uses most of the list methods:: + + >>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] + >>> fruits.count('apple') + 2 + >>> fruits.count('tangerine') + 0 + >>> fruits.index('banana') + 3 + >>> fruits.index('banana', 4) # Find next banana starting a position 4 + 6 + >>> fruits.reverse() + >>> fruits + ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange'] + >>> fruits.append('grape') + >>> fruits + ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape'] + >>> fruits.sort() + >>> fruits + ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear'] + >>> fruits.pop() + 'pear' + +You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that +only modify the list have no return value printed -- they return the default +``None``. [1]_ This is a design principle for all mutable data structures in +Python. + +Another thing you might notice is that not all data can be sorted or +compared. For instance, ``[None, 'hello', 10]`` doesn't sort because +integers can't be compared to strings and *None* can't be compared to +other types. Also, there are some types that don't have a defined +ordering relation. For example, ``3+4j < 5+7j`` isn't a valid +comparison. + + +.. _tut-lists-as-stacks: + +Using Lists as Stacks +--------------------- + +.. sectionauthor:: Ka-Ping Yee + + +The list methods make it very easy to use a list as a stack, where the last +element added is the first element retrieved ("last-in, first-out"). To add an +item to the top of the stack, use :meth:`append`. To retrieve an item from the +top of the stack, use :meth:`pop` without an explicit index. For example:: + + >>> stack = [3, 4, 5] + >>> stack.append(6) + >>> stack.append(7) + >>> stack + [3, 4, 5, 6, 7] + >>> stack.pop() + 7 + >>> stack + [3, 4, 5, 6] + >>> stack.pop() + 6 + >>> stack.pop() + 5 + >>> stack + [3, 4] + + +.. _tut-lists-as-queues: + +Using Lists as Queues +--------------------- + +.. sectionauthor:: Ka-Ping Yee + +It is also possible to use a list as a queue, where the first element added is +the first element retrieved ("first-in, first-out"); however, lists are not +efficient for this purpose. While appends and pops from the end of list are +fast, doing inserts or pops from the beginning of a list is slow (because all +of the other elements have to be shifted by one). + +To implement a queue, use :class:`collections.deque` which was designed to +have fast appends and pops from both ends. For example:: + + >>> from collections import deque + >>> queue = deque(["Eric", "John", "Michael"]) + >>> queue.append("Terry") # Terry arrives + >>> queue.append("Graham") # Graham arrives + >>> queue.popleft() # The first to arrive now leaves + 'Eric' + >>> queue.popleft() # The second to arrive now leaves + 'John' + >>> queue # Remaining queue in order of arrival + deque(['Michael', 'Terry', 'Graham']) + + +.. _tut-listcomps: + +List Comprehensions +------------------- + +List comprehensions provide a concise way to create lists. +Common applications are to make new lists where each element is the result of +some operations applied to each member of another sequence or iterable, or to +create a subsequence of those elements that satisfy a certain condition. + +For example, assume we want to create a list of squares, like:: + + >>> squares = [] + >>> for x in range(10): + ... squares.append(x**2) + ... + >>> squares + [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + +Note that this creates (or overwrites) a variable named ``x`` that still exists +after the loop completes. We can calculate the list of squares without any +side effects using:: + + squares = list(map(lambda x: x**2, range(10))) + +or, equivalently:: + + squares = [x**2 for x in range(10)] + +which is more concise and readable. + +A list comprehension consists of brackets containing an expression followed +by a :keyword:`!for` clause, then zero or more :keyword:`!for` or :keyword:`!if` +clauses. The result will be a new list resulting from evaluating the expression +in the context of the :keyword:`!for` and :keyword:`!if` clauses which follow it. +For example, this listcomp combines the elements of two lists if they are not +equal:: + + >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] + [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] + +and it's equivalent to:: + + >>> combs = [] + >>> for x in [1,2,3]: + ... for y in [3,1,4]: + ... if x != y: + ... combs.append((x, y)) + ... + >>> combs + [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] + +Note how the order of the :keyword:`for` and :keyword:`if` statements is the +same in both these snippets. + +If the expression is a tuple (e.g. the ``(x, y)`` in the previous example), +it must be parenthesized. :: + + >>> vec = [-4, -2, 0, 2, 4] + >>> # create a new list with the values doubled + >>> [x*2 for x in vec] + [-8, -4, 0, 4, 8] + >>> # filter the list to exclude negative numbers + >>> [x for x in vec if x >= 0] + [0, 2, 4] + >>> # apply a function to all the elements + >>> [abs(x) for x in vec] + [4, 2, 0, 2, 4] + >>> # call a method on each element + >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] + >>> [weapon.strip() for weapon in freshfruit] + ['banana', 'loganberry', 'passion fruit'] + >>> # create a list of 2-tuples like (number, square) + >>> [(x, x**2) for x in range(6)] + [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] + >>> # the tuple must be parenthesized, otherwise an error is raised + >>> [x, x**2 for x in range(6)] + File "", line 1, in + [x, x**2 for x in range(6)] + ^ + SyntaxError: invalid syntax + >>> # flatten a list using a listcomp with two 'for' + >>> vec = [[1,2,3], [4,5,6], [7,8,9]] + >>> [num for elem in vec for num in elem] + [1, 2, 3, 4, 5, 6, 7, 8, 9] + +List comprehensions can contain complex expressions and nested functions:: + + >>> from math import pi + >>> [str(round(pi, i)) for i in range(1, 6)] + ['3.1', '3.14', '3.142', '3.1416', '3.14159'] + +Nested List Comprehensions +-------------------------- + +The initial expression in a list comprehension can be any arbitrary expression, +including another list comprehension. + +Consider the following example of a 3x4 matrix implemented as a list of +3 lists of length 4:: + + >>> matrix = [ + ... [1, 2, 3, 4], + ... [5, 6, 7, 8], + ... [9, 10, 11, 12], + ... ] + +The following list comprehension will transpose rows and columns:: + + >>> [[row[i] for row in matrix] for i in range(4)] + [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] + +As we saw in the previous section, the nested listcomp is evaluated in +the context of the :keyword:`for` that follows it, so this example is +equivalent to:: + + >>> transposed = [] + >>> for i in range(4): + ... transposed.append([row[i] for row in matrix]) + ... + >>> transposed + [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] + +which, in turn, is the same as:: + + >>> transposed = [] + >>> for i in range(4): + ... # the following 3 lines implement the nested listcomp + ... transposed_row = [] + ... for row in matrix: + ... transposed_row.append(row[i]) + ... transposed.append(transposed_row) + ... + >>> transposed + [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] + +In the real world, you should prefer built-in functions to complex flow statements. +The :func:`zip` function would do a great job for this use case:: + + >>> list(zip(*matrix)) + [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] + +See :ref:`tut-unpacking-arguments` for details on the asterisk in this line. + +.. _tut-del: + +The :keyword:`!del` statement +============================= + +There is a way to remove an item from a list given its index instead of its +value: the :keyword:`del` statement. This differs from the :meth:`pop` method +which returns a value. The :keyword:`!del` statement can also be used to remove +slices from a list or clear the entire list (which we did earlier by assignment +of an empty list to the slice). For example:: + + >>> a = [-1, 1, 66.25, 333, 333, 1234.5] + >>> del a[0] + >>> a + [1, 66.25, 333, 333, 1234.5] + >>> del a[2:4] + >>> a + [1, 66.25, 1234.5] + >>> del a[:] + >>> a + [] + +:keyword:`del` can also be used to delete entire variables:: + + >>> del a + +Referencing the name ``a`` hereafter is an error (at least until another value +is assigned to it). We'll find other uses for :keyword:`del` later. + + +.. _tut-tuples: + +Tuples and Sequences +==================== + +We saw that lists and strings have many common properties, such as indexing and +slicing operations. They are two examples of *sequence* data types (see +:ref:`typesseq`). Since Python is an evolving language, other sequence data +types may be added. There is also another standard sequence data type: the +*tuple*. + +A tuple consists of a number of values separated by commas, for instance:: + + >>> t = 12345, 54321, 'hello!' + >>> t[0] + 12345 + >>> t + (12345, 54321, 'hello!') + >>> # Tuples may be nested: + ... u = t, (1, 2, 3, 4, 5) + >>> u + ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) + >>> # Tuples are immutable: + ... t[0] = 88888 + Traceback (most recent call last): + File "", line 1, in + TypeError: 'tuple' object does not support item assignment + >>> # but they can contain mutable objects: + ... v = ([1, 2, 3], [3, 2, 1]) + >>> v + ([1, 2, 3], [3, 2, 1]) + + +As you see, on output tuples are always enclosed in parentheses, so that nested +tuples are interpreted correctly; they may be input with or without surrounding +parentheses, although often parentheses are necessary anyway (if the tuple is +part of a larger expression). It is not possible to assign to the individual +items of a tuple, however it is possible to create tuples which contain mutable +objects, such as lists. + +Though tuples may seem similar to lists, they are often used in different +situations and for different purposes. +Tuples are :term:`immutable`, and usually contain a heterogeneous sequence of +elements that are accessed via unpacking (see later in this section) or indexing +(or even by attribute in the case of :func:`namedtuples `). +Lists are :term:`mutable`, and their elements are usually homogeneous and are +accessed by iterating over the list. + +A special problem is the construction of tuples containing 0 or 1 items: the +syntax has some extra quirks to accommodate these. Empty tuples are constructed +by an empty pair of parentheses; a tuple with one item is constructed by +following a value with a comma (it is not sufficient to enclose a single value +in parentheses). Ugly, but effective. For example:: + + >>> empty = () + >>> singleton = 'hello', # <-- note trailing comma + >>> len(empty) + 0 + >>> len(singleton) + 1 + >>> singleton + ('hello',) + +The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*: +the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple. +The reverse operation is also possible:: + + >>> x, y, z = t + +This is called, appropriately enough, *sequence unpacking* and works for any +sequence on the right-hand side. Sequence unpacking requires that there are as +many variables on the left side of the equals sign as there are elements in the +sequence. Note that multiple assignment is really just a combination of tuple +packing and sequence unpacking. + + +.. _tut-sets: + +Sets +==== + +Python also includes a data type for *sets*. A set is an unordered collection +with no duplicate elements. Basic uses include membership testing and +eliminating duplicate entries. Set objects also support mathematical operations +like union, intersection, difference, and symmetric difference. + +Curly braces or the :func:`set` function can be used to create sets. Note: to +create an empty set you have to use ``set()``, not ``{}``; the latter creates an +empty dictionary, a data structure that we discuss in the next section. + +Here is a brief demonstration:: + + >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} + >>> print(basket) # show that duplicates have been removed + {'orange', 'banana', 'pear', 'apple'} + >>> 'orange' in basket # fast membership testing + True + >>> 'crabgrass' in basket + False + + >>> # Demonstrate set operations on unique letters from two words + ... + >>> a = set('abracadabra') + >>> b = set('alacazam') + >>> a # unique letters in a + {'a', 'r', 'b', 'c', 'd'} + >>> a - b # letters in a but not in b + {'r', 'd', 'b'} + >>> a | b # letters in a or b or both + {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} + >>> a & b # letters in both a and b + {'a', 'c'} + >>> a ^ b # letters in a or b but not both + {'r', 'd', 'b', 'm', 'z', 'l'} + +Similarly to :ref:`list comprehensions `, set comprehensions +are also supported:: + + >>> a = {x for x in 'abracadabra' if x not in 'abc'} + >>> a + {'r', 'd'} + + +.. _tut-dictionaries: + +Dictionaries +============ + +Another useful data type built into Python is the *dictionary* (see +:ref:`typesmapping`). Dictionaries are sometimes found in other languages as +"associative memories" or "associative arrays". Unlike sequences, which are +indexed by a range of numbers, dictionaries are indexed by *keys*, which can be +any immutable type; strings and numbers can always be keys. Tuples can be used +as keys if they contain only strings, numbers, or tuples; if a tuple contains +any mutable object either directly or indirectly, it cannot be used as a key. +You can't use lists as keys, since lists can be modified in place using index +assignments, slice assignments, or methods like :meth:`append` and +:meth:`extend`. + +It is best to think of a dictionary as a set of *key: value* pairs, +with the requirement that the keys are unique (within one dictionary). A pair of +braces creates an empty dictionary: ``{}``. Placing a comma-separated list of +key:value pairs within the braces adds initial key:value pairs to the +dictionary; this is also the way dictionaries are written on output. + +The main operations on a dictionary are storing a value with some key and +extracting the value given the key. It is also possible to delete a key:value +pair with ``del``. If you store using a key that is already in use, the old +value associated with that key is forgotten. It is an error to extract a value +using a non-existent key. + +Performing ``list(d)`` on a dictionary returns a list of all the keys +used in the dictionary, in insertion order (if you want it sorted, just use +``sorted(d)`` instead). To check whether a single key is in the +dictionary, use the :keyword:`in` keyword. + +Here is a small example using a dictionary:: + + >>> tel = {'jack': 4098, 'sape': 4139} + >>> tel['guido'] = 4127 + >>> tel + {'jack': 4098, 'sape': 4139, 'guido': 4127} + >>> tel['jack'] + 4098 + >>> del tel['sape'] + >>> tel['irv'] = 4127 + >>> tel + {'jack': 4098, 'guido': 4127, 'irv': 4127} + >>> list(tel) + ['jack', 'guido', 'irv'] + >>> sorted(tel) + ['guido', 'irv', 'jack'] + >>> 'guido' in tel + True + >>> 'jack' not in tel + False + +The :func:`dict` constructor builds dictionaries directly from sequences of +key-value pairs:: + + >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) + {'sape': 4139, 'guido': 4127, 'jack': 4098} + +In addition, dict comprehensions can be used to create dictionaries from +arbitrary key and value expressions:: + + >>> {x: x**2 for x in (2, 4, 6)} + {2: 4, 4: 16, 6: 36} + +When the keys are simple strings, it is sometimes easier to specify pairs using +keyword arguments:: + + >>> dict(sape=4139, guido=4127, jack=4098) + {'sape': 4139, 'guido': 4127, 'jack': 4098} + + +.. _tut-loopidioms: + +Looping Techniques +================== + +When looping through dictionaries, the key and corresponding value can be +retrieved at the same time using the :meth:`items` method. :: + + >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} + >>> for k, v in knights.items(): + ... print(k, v) + ... + gallahad the pure + robin the brave + +When looping through a sequence, the position index and corresponding value can +be retrieved at the same time using the :func:`enumerate` function. :: + + >>> for i, v in enumerate(['tic', 'tac', 'toe']): + ... print(i, v) + ... + 0 tic + 1 tac + 2 toe + +To loop over two or more sequences at the same time, the entries can be paired +with the :func:`zip` function. :: + + >>> questions = ['name', 'quest', 'favorite color'] + >>> answers = ['lancelot', 'the holy grail', 'blue'] + >>> for q, a in zip(questions, answers): + ... print('What is your {0}? It is {1}.'.format(q, a)) + ... + What is your name? It is lancelot. + What is your quest? It is the holy grail. + What is your favorite color? It is blue. + +To loop over a sequence in reverse, first specify the sequence in a forward +direction and then call the :func:`reversed` function. :: + + >>> for i in reversed(range(1, 10, 2)): + ... print(i) + ... + 9 + 7 + 5 + 3 + 1 + +To loop over a sequence in sorted order, use the :func:`sorted` function which +returns a new sorted list while leaving the source unaltered. :: + + >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] + >>> for f in sorted(set(basket)): + ... print(f) + ... + apple + banana + orange + pear + +It is sometimes tempting to change a list while you are looping over it; +however, it is often simpler and safer to create a new list instead. :: + + >>> import math + >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8] + >>> filtered_data = [] + >>> for value in raw_data: + ... if not math.isnan(value): + ... filtered_data.append(value) + ... + >>> filtered_data + [56.2, 51.7, 55.3, 52.5, 47.8] + + +.. _tut-conditions: + +More on Conditions +================== + +The conditions used in ``while`` and ``if`` statements can contain any +operators, not just comparisons. + +The comparison operators ``in`` and ``not in`` check whether a value occurs +(does not occur) in a sequence. The operators ``is`` and ``is not`` compare +whether two objects are really the same object; this only matters for mutable +objects like lists. All comparison operators have the same priority, which is +lower than that of all numerical operators. + +Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is +less than ``b`` and moreover ``b`` equals ``c``. + +Comparisons may be combined using the Boolean operators ``and`` and ``or``, and +the outcome of a comparison (or of any other Boolean expression) may be negated +with ``not``. These have lower priorities than comparison operators; between +them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and +not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses +can be used to express the desired composition. + +The Boolean operators ``and`` and ``or`` are so-called *short-circuit* +operators: their arguments are evaluated from left to right, and evaluation +stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are +true but ``B`` is false, ``A and B and C`` does not evaluate the expression +``C``. When used as a general value and not as a Boolean, the return value of a +short-circuit operator is the last evaluated argument. + +It is possible to assign the result of a comparison or other Boolean expression +to a variable. For example, :: + + >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' + >>> non_null = string1 or string2 or string3 + >>> non_null + 'Trondheim' + +Note that in Python, unlike C, assignment inside expressions must be done +explicitly with the +:ref:`walrus operator ` ``:=``. +This avoids a common class of problems encountered in C programs: typing ``=`` +in an expression when ``==`` was intended. + + +.. _tut-comparing: + +Comparing Sequences and Other Types +=================================== +Sequence objects typically may be compared to other objects with the same sequence +type. The comparison uses *lexicographical* ordering: first the first two +items are compared, and if they differ this determines the outcome of the +comparison; if they are equal, the next two items are compared, and so on, until +either sequence is exhausted. If two items to be compared are themselves +sequences of the same type, the lexicographical comparison is carried out +recursively. If all items of two sequences compare equal, the sequences are +considered equal. If one sequence is an initial sub-sequence of the other, the +shorter sequence is the smaller (lesser) one. Lexicographical ordering for +strings uses the Unicode code point number to order individual characters. +Some examples of comparisons between sequences of the same type:: + + (1, 2, 3) < (1, 2, 4) + [1, 2, 3] < [1, 2, 4] + 'ABC' < 'C' < 'Pascal' < 'Python' + (1, 2, 3, 4) < (1, 2, 4) + (1, 2) < (1, 2, -1) + (1, 2, 3) == (1.0, 2.0, 3.0) + (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) + +Note that comparing objects of different types with ``<`` or ``>`` is legal +provided that the objects have appropriate comparison methods. For example, +mixed numeric types are compared according to their numeric value, so 0 equals +0.0, etc. Otherwise, rather than providing an arbitrary ordering, the +interpreter will raise a :exc:`TypeError` exception. + + +.. rubric:: Footnotes + +.. [1] Other languages may return the mutated object, which allows method + chaining, such as ``d->insert("a")->remove("b")->sort();``. diff --git a/cpython_2/environment/repo/Doc/tutorial/errors.rst b/cpython_2/environment/repo/Doc/tutorial/errors.rst new file mode 100644 index 0000000000000000000000000000000000000000..0ce96466e8c286913db59b8be607568a4bb3f18f --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/errors.rst @@ -0,0 +1,492 @@ +.. _tut-errors: + +********************* +Errors and Exceptions +********************* + +Until now error messages haven't been more than mentioned, but if you have tried +out the examples you have probably seen some. There are (at least) two +distinguishable kinds of errors: *syntax errors* and *exceptions*. + + +.. _tut-syntaxerrors: + +Syntax Errors +============= + +Syntax errors, also known as parsing errors, are perhaps the most common kind of +complaint you get while you are still learning Python:: + + >>> while True print('Hello world') + File "", line 1 + while True print('Hello world') + ^ + SyntaxError: invalid syntax + +The parser repeats the offending line and displays a little 'arrow' pointing at +the earliest point in the line where the error was detected. The error is +caused by (or at least detected at) the token *preceding* the arrow: in the +example, the error is detected at the function :func:`print`, since a colon +(``':'``) is missing before it. File name and line number are printed so you +know where to look in case the input came from a script. + + +.. _tut-exceptions: + +Exceptions +========== + +Even if a statement or expression is syntactically correct, it may cause an +error when an attempt is made to execute it. Errors detected during execution +are called *exceptions* and are not unconditionally fatal: you will soon learn +how to handle them in Python programs. Most exceptions are not handled by +programs, however, and result in error messages as shown here:: + + >>> 10 * (1/0) + Traceback (most recent call last): + File "", line 1, in + ZeroDivisionError: division by zero + >>> 4 + spam*3 + Traceback (most recent call last): + File "", line 1, in + NameError: name 'spam' is not defined + >>> '2' + 2 + Traceback (most recent call last): + File "", line 1, in + TypeError: Can't convert 'int' object to str implicitly + +The last line of the error message indicates what happened. Exceptions come in +different types, and the type is printed as part of the message: the types in +the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:`TypeError`. +The string printed as the exception type is the name of the built-in exception +that occurred. This is true for all built-in exceptions, but need not be true +for user-defined exceptions (although it is a useful convention). Standard +exception names are built-in identifiers (not reserved keywords). + +The rest of the line provides detail based on the type of exception and what +caused it. + +The preceding part of the error message shows the context where the exception +occurred, in the form of a stack traceback. In general it contains a stack +traceback listing source lines; however, it will not display lines read from +standard input. + +:ref:`bltin-exceptions` lists the built-in exceptions and their meanings. + + +.. _tut-handling: + +Handling Exceptions +=================== + +It is possible to write programs that handle selected exceptions. Look at the +following example, which asks the user for input until a valid integer has been +entered, but allows the user to interrupt the program (using :kbd:`Control-C` or +whatever the operating system supports); note that a user-generated interruption +is signalled by raising the :exc:`KeyboardInterrupt` exception. :: + + >>> while True: + ... try: + ... x = int(input("Please enter a number: ")) + ... break + ... except ValueError: + ... print("Oops! That was no valid number. Try again...") + ... + +The :keyword:`try` statement works as follows. + +* First, the *try clause* (the statement(s) between the :keyword:`try` and + :keyword:`except` keywords) is executed. + +* If no exception occurs, the *except clause* is skipped and execution of the + :keyword:`try` statement is finished. + +* If an exception occurs during execution of the try clause, the rest of the + clause is skipped. Then if its type matches the exception named after the + :keyword:`except` keyword, the except clause is executed, and then execution + continues after the :keyword:`try` statement. + +* If an exception occurs which does not match the exception named in the except + clause, it is passed on to outer :keyword:`try` statements; if no handler is + found, it is an *unhandled exception* and execution stops with a message as + shown above. + +A :keyword:`try` statement may have more than one except clause, to specify +handlers for different exceptions. At most one handler will be executed. +Handlers only handle exceptions that occur in the corresponding try clause, not +in other handlers of the same :keyword:`!try` statement. An except clause may +name multiple exceptions as a parenthesized tuple, for example:: + + ... except (RuntimeError, TypeError, NameError): + ... pass + +A class in an :keyword:`except` clause is compatible with an exception if it is +the same class or a base class thereof (but not the other way around --- an +except clause listing a derived class is not compatible with a base class). For +example, the following code will print B, C, D in that order:: + + class B(Exception): + pass + + class C(B): + pass + + class D(C): + pass + + for cls in [B, C, D]: + try: + raise cls() + except D: + print("D") + except C: + print("C") + except B: + print("B") + +Note that if the except clauses were reversed (with ``except B`` first), it +would have printed B, B, B --- the first matching except clause is triggered. + +The last except clause may omit the exception name(s), to serve as a wildcard. +Use this with extreme caution, since it is easy to mask a real programming error +in this way! It can also be used to print an error message and then re-raise +the exception (allowing a caller to handle the exception as well):: + + import sys + + try: + f = open('myfile.txt') + s = f.readline() + i = int(s.strip()) + except OSError as err: + print("OS error: {0}".format(err)) + except ValueError: + print("Could not convert data to an integer.") + except: + print("Unexpected error:", sys.exc_info()[0]) + raise + +The :keyword:`try` ... :keyword:`except` statement has an optional *else +clause*, which, when present, must follow all except clauses. It is useful for +code that must be executed if the try clause does not raise an exception. For +example:: + + for arg in sys.argv[1:]: + try: + f = open(arg, 'r') + except OSError: + print('cannot open', arg) + else: + print(arg, 'has', len(f.readlines()), 'lines') + f.close() + +The use of the :keyword:`!else` clause is better than adding additional code to +the :keyword:`try` clause because it avoids accidentally catching an exception +that wasn't raised by the code being protected by the :keyword:`!try` ... +:keyword:`!except` statement. + +When an exception occurs, it may have an associated value, also known as the +exception's *argument*. The presence and type of the argument depend on the +exception type. + +The except clause may specify a variable after the exception name. The +variable is bound to an exception instance with the arguments stored in +``instance.args``. For convenience, the exception instance defines +:meth:`__str__` so the arguments can be printed directly without having to +reference ``.args``. One may also instantiate an exception first before +raising it and add any attributes to it as desired. :: + + >>> try: + ... raise Exception('spam', 'eggs') + ... except Exception as inst: + ... print(type(inst)) # the exception instance + ... print(inst.args) # arguments stored in .args + ... print(inst) # __str__ allows args to be printed directly, + ... # but may be overridden in exception subclasses + ... x, y = inst.args # unpack args + ... print('x =', x) + ... print('y =', y) + ... + + ('spam', 'eggs') + ('spam', 'eggs') + x = spam + y = eggs + +If an exception has arguments, they are printed as the last part ('detail') of +the message for unhandled exceptions. + +Exception handlers don't just handle exceptions if they occur immediately in the +try clause, but also if they occur inside functions that are called (even +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: division by zero + + +.. _tut-raising: + +Raising Exceptions +================== + +The :keyword:`raise` statement allows the programmer to force a specified +exception to occur. For example:: + + >>> raise NameError('HiThere') + Traceback (most recent call last): + File "", line 1, in + NameError: HiThere + +The sole argument to :keyword:`raise` indicates the exception to be raised. +This must be either an exception instance or an exception class (a class that +derives from :class:`Exception`). If an exception class is passed, it will +be implicitly instantiated by calling its constructor with no arguments:: + + raise ValueError # shorthand for 'raise ValueError()' + +If you need to determine whether an exception was raised but don't intend to +handle it, a simpler form of the :keyword:`raise` statement allows you to +re-raise the exception:: + + >>> try: + ... raise NameError('HiThere') + ... except NameError: + ... print('An exception flew by!') + ... raise + ... + An exception flew by! + Traceback (most recent call last): + File "", line 2, in + NameError: HiThere + + +.. _tut-exception-chaining: + +Exception Chaining +================== + +The :keyword:`raise` statement allows an optional :keyword:`from` which enables +chaining exceptions by setting the ``__cause__`` attribute of the raised +exception. For example:: + + raise RuntimeError from OSError + +This can be useful when you are transforming exceptions. For example:: + + >>> def func(): + ... raise IOError + ... + >>> try: + ... func() + ... except IOError as exc: + ... raise RuntimeError('Failed to open database') from exc + ... + Traceback (most recent call last): + File "", line 2, in + File "", line 2, in func + OSError + + The above exception was the direct cause of the following exception: + + Traceback (most recent call last): + File "", line 4, in + RuntimeError + +The expression following the :keyword:`from` must be either an exception or +``None``. Exception chaining happens automatically when an exception is raised +inside an exception handler or :keyword:`finally` section. Exception chaining +can be disabled by using ``from None`` idiom: + + >>> try: + ... open('database.sqlite') + ... except IOError: + ... raise RuntimeError from None + ... + Traceback (most recent call last): + File "", line 4, in + RuntimeError + + +.. _tut-userexceptions: + +User-defined Exceptions +======================= + +Programs may name their own exceptions by creating a new exception class (see +:ref:`tut-classes` for more about Python classes). Exceptions should typically +be derived from the :exc:`Exception` class, either directly or indirectly. + +Exception classes can be defined which do anything any other class can do, but +are usually kept simple, often only offering a number of attributes that allow +information about the error to be extracted by handlers for the exception. When +creating a module that can raise several distinct errors, a common practice is +to create a base class for exceptions defined by that module, and subclass that +to create specific exception classes for different error conditions:: + + class Error(Exception): + """Base class for exceptions in this module.""" + pass + + class InputError(Error): + """Exception raised for errors in the input. + + Attributes: + expression -- input expression in which the error occurred + message -- explanation of the error + """ + + def __init__(self, expression, message): + self.expression = expression + self.message = message + + class TransitionError(Error): + """Raised when an operation attempts a state transition that's not + allowed. + + Attributes: + previous -- state at beginning of transition + next -- attempted new state + message -- explanation of why the specific transition is not allowed + """ + + def __init__(self, previous, next, message): + self.previous = previous + self.next = next + self.message = message + +Most exceptions are defined with names that end in "Error", similar to the +naming of the standard exceptions. + +Many standard modules define their own exceptions to report errors that may +occur in functions they define. More information on classes is presented in +chapter :ref:`tut-classes`. + + +.. _tut-cleanup: + +Defining Clean-up Actions +========================= + +The :keyword:`try` statement has another optional clause which is intended to +define clean-up actions that must be executed under all circumstances. For +example:: + + >>> try: + ... raise KeyboardInterrupt + ... finally: + ... print('Goodbye, world!') + ... + Goodbye, world! + Traceback (most recent call last): + File "", line 2, in + KeyboardInterrupt + +If a :keyword:`finally` clause is present, the :keyword:`!finally` +clause will execute as the last task before the :keyword:`try` +statement completes. The :keyword:`!finally` clause runs whether or +not the :keyword:`!try` statement produces an exception. The following +points discuss more complex cases when an exception occurs: + +* If an exception occurs during execution of the :keyword:`!try` + clause, the exception may be handled by an :keyword:`except` + clause. If the exception is not handled by an :keyword:`!except` + clause, the exception is re-raised after the :keyword:`!finally` + clause has been executed. + +* An exception could occur during execution of an :keyword:`!except` + or :keyword:`!else` clause. Again, the exception is re-raised after + the :keyword:`!finally` clause has been executed. + +* If the :keyword:`!try` statement reaches a :keyword:`break`, + :keyword:`continue` or :keyword:`return` statement, the + :keyword:`!finally` clause will execute just prior to the + :keyword:`!break`, :keyword:`!continue` or :keyword:`!return` + statement's execution. + +* If a :keyword:`!finally` clause includes a :keyword:`!return` + statement, the returned value will be the one from the + :keyword:`!finally` clause's :keyword:`!return` statement, not the + value from the :keyword:`!try` clause's :keyword:`!return` + statement. + +For example:: + + >>> def bool_return(): + ... try: + ... return True + ... finally: + ... return False + ... + >>> bool_return() + False + +A more complicated example:: + + >>> def divide(x, y): + ... try: + ... result = x / y + ... except ZeroDivisionError: + ... print("division by zero!") + ... else: + ... print("result is", result) + ... finally: + ... print("executing finally clause") + ... + >>> divide(2, 1) + result is 2.0 + executing finally clause + >>> divide(2, 0) + division by zero! + executing finally clause + >>> divide("2", "1") + executing finally clause + Traceback (most recent call last): + File "", line 1, in + File "", line 3, in divide + TypeError: unsupported operand type(s) for /: 'str' and 'str' + +As you can see, the :keyword:`finally` clause is executed in any event. The +:exc:`TypeError` raised by dividing two strings is not handled by the +:keyword:`except` clause and therefore re-raised after the :keyword:`!finally` +clause has been executed. + +In real world applications, the :keyword:`finally` clause is useful for +releasing external resources (such as files or network connections), regardless +of whether the use of the resource was successful. + + +.. _tut-cleanup-with: + +Predefined Clean-up Actions +=========================== + +Some objects define standard clean-up actions to be undertaken when the object +is no longer needed, regardless of whether or not the operation using the object +succeeded or failed. Look at the following example, which tries to open a file +and print its contents to the screen. :: + + for line in open("myfile.txt"): + print(line, end="") + +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 +used in a way that ensures they are always cleaned up promptly and correctly. :: + + with open("myfile.txt") as f: + for line in f: + print(line, end="") + +After the statement is executed, the file *f* is always closed, even if a +problem was encountered while processing the lines. Objects which, like files, +provide predefined clean-up actions will indicate this in their documentation. + + diff --git a/cpython_2/environment/repo/Doc/tutorial/floatingpoint.rst b/cpython_2/environment/repo/Doc/tutorial/floatingpoint.rst new file mode 100644 index 0000000000000000000000000000000000000000..0c0eb526fa9ed6054231c2e7464b73beb5297146 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/floatingpoint.rst @@ -0,0 +1,300 @@ +.. testsetup:: + + import math + +.. _tut-fp-issues: + +************************************************** +Floating Point Arithmetic: Issues and Limitations +************************************************** + +.. sectionauthor:: Tim Peters + + +Floating-point numbers are represented in computer hardware as base 2 (binary) +fractions. For example, the decimal fraction :: + + 0.125 + +has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction :: + + 0.001 + +has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only +real difference being that the first is written in base 10 fractional notation, +and the second in base 2. + +Unfortunately, most decimal fractions cannot be represented exactly as binary +fractions. A consequence is that, in general, the decimal floating-point +numbers you enter are only approximated by the binary floating-point numbers +actually stored in the machine. + +The problem is easier to understand at first in base 10. Consider the fraction +1/3. You can approximate that as a base 10 fraction:: + + 0.3 + +or, better, :: + + 0.33 + +or, better, :: + + 0.333 + +and so on. No matter how many digits you're willing to write down, the result +will never be exactly 1/3, but will be an increasingly better approximation of +1/3. + +In the same way, no matter how many base 2 digits you're willing to use, the +decimal value 0.1 cannot be represented exactly as a base 2 fraction. In base +2, 1/10 is the infinitely repeating fraction :: + + 0.0001100110011001100110011001100110011001100110011... + +Stop at any finite number of bits, and you get an approximation. On most +machines today, floats are approximated using a binary fraction with +the numerator using the first 53 bits starting with the most significant bit and +with the denominator as a power of two. In the case of 1/10, the binary fraction +is ``3602879701896397 / 2 ** 55`` which is close to but not exactly +equal to the true value of 1/10. + +Many users are not aware of the approximation because of the way values are +displayed. Python only prints a decimal approximation to the true decimal +value of the binary approximation stored by the machine. On most machines, if +Python were to print the true decimal value of the binary approximation stored +for 0.1, it would have to display :: + + >>> 0.1 + 0.1000000000000000055511151231257827021181583404541015625 + +That is more digits than most people find useful, so Python keeps the number +of digits manageable by displaying a rounded value instead :: + + >>> 1 / 10 + 0.1 + +Just remember, even though the printed result looks like the exact value +of 1/10, the actual stored value is the nearest representable binary fraction. + +Interestingly, there are many different decimal numbers that share the same +nearest approximate binary fraction. For example, the numbers ``0.1`` and +``0.10000000000000001`` and +``0.1000000000000000055511151231257827021181583404541015625`` are all +approximated by ``3602879701896397 / 2 ** 55``. Since all of these decimal +values share the same approximation, any one of them could be displayed +while still preserving the invariant ``eval(repr(x)) == x``. + +Historically, the Python prompt and built-in :func:`repr` function would choose +the one with 17 significant digits, ``0.10000000000000001``. Starting with +Python 3.1, Python (on most systems) is now able to choose the shortest of +these and simply display ``0.1``. + +Note that this is in the very nature of binary floating-point: this is not a bug +in Python, and it is not a bug in your code either. You'll see the same kind of +thing in all languages that support your hardware's floating-point arithmetic +(although some languages may not *display* the difference by default, or in all +output modes). + +For more pleasant output, you may wish to use string formatting to produce a limited number of significant digits:: + + >>> format(math.pi, '.12g') # give 12 significant digits + '3.14159265359' + + >>> format(math.pi, '.2f') # give 2 digits after the point + '3.14' + + >>> repr(math.pi) + '3.141592653589793' + + +It's important to realize that this is, in a real sense, an illusion: you're +simply rounding the *display* of the true machine value. + +One illusion may beget another. For example, since 0.1 is not exactly 1/10, +summing three values of 0.1 may not yield exactly 0.3, either:: + + >>> .1 + .1 + .1 == .3 + False + +Also, since the 0.1 cannot get any closer to the exact value of 1/10 and +0.3 cannot get any closer to the exact value of 3/10, then pre-rounding with +:func:`round` function cannot help:: + + >>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1) + False + +Though the numbers cannot be made closer to their intended exact values, +the :func:`round` function can be useful for post-rounding so that results +with inexact values become comparable to one another:: + + >>> round(.1 + .1 + .1, 10) == round(.3, 10) + True + +Binary floating-point arithmetic holds many surprises like this. The problem +with "0.1" is explained in precise detail below, in the "Representation Error" +section. See `The Perils of Floating Point `_ +for a more complete account of other common surprises. + +As that says near the end, "there are no easy answers." Still, don't be unduly +wary of floating-point! The errors in Python float operations are inherited +from the floating-point hardware, and on most machines are on the order of no +more than 1 part in 2\*\*53 per operation. That's more than adequate for most +tasks, but you do need to keep in mind that it's not decimal arithmetic and +that every float operation can suffer a new rounding error. + +While pathological cases do exist, for most casual use of floating-point +arithmetic you'll see the result you expect in the end if you simply round the +display of your final results to the number of decimal digits you expect. +:func:`str` usually suffices, and for finer control see the :meth:`str.format` +method's format specifiers in :ref:`formatstrings`. + +For use cases which require exact decimal representation, try using the +:mod:`decimal` module which implements decimal arithmetic suitable for +accounting applications and high-precision applications. + +Another form of exact arithmetic is supported by the :mod:`fractions` module +which implements arithmetic based on rational numbers (so the numbers like +1/3 can be represented exactly). + +If you are a heavy user of floating point operations you should take a look +at the Numerical Python package and many other packages for mathematical and +statistical operations supplied by the SciPy project. See . + +Python provides tools that may help on those rare occasions when you really +*do* want to know the exact value of a float. The +:meth:`float.as_integer_ratio` method expresses the value of a float as a +fraction:: + + >>> x = 3.14159 + >>> x.as_integer_ratio() + (3537115888337719, 1125899906842624) + +Since the ratio is exact, it can be used to losslessly recreate the +original value:: + + >>> x == 3537115888337719 / 1125899906842624 + True + +The :meth:`float.hex` method expresses a float in hexadecimal (base +16), again giving the exact value stored by your computer:: + + >>> x.hex() + '0x1.921f9f01b866ep+1' + +This precise hexadecimal representation can be used to reconstruct +the float value exactly:: + + >>> x == float.fromhex('0x1.921f9f01b866ep+1') + True + +Since the representation is exact, it is useful for reliably porting values +across different versions of Python (platform independence) and exchanging +data with other languages that support the same format (such as Java and C99). + +Another helpful tool is the :func:`math.fsum` function which helps mitigate +loss-of-precision during summation. It tracks "lost digits" as values are +added onto a running total. That can make a difference in overall accuracy +so that the errors do not accumulate to the point where they affect the +final total: + + >>> sum([0.1] * 10) == 1.0 + False + >>> math.fsum([0.1] * 10) == 1.0 + True + +.. _tut-fp-error: + +Representation Error +==================== + +This section explains the "0.1" example in detail, and shows how you can perform +an exact analysis of cases like this yourself. Basic familiarity with binary +floating-point representation is assumed. + +:dfn:`Representation error` refers to the fact that some (most, actually) +decimal fractions cannot be represented exactly as binary (base 2) fractions. +This is the chief reason why Python (or Perl, C, C++, Java, Fortran, and many +others) often won't display the exact decimal number you expect. + +Why is that? 1/10 is not exactly representable as a binary fraction. Almost all +machines today (November 2000) use IEEE-754 floating point arithmetic, and +almost all platforms map Python floats to IEEE-754 "double precision". 754 +doubles contain 53 bits of precision, so on input the computer strives to +convert 0.1 to the closest fraction it can of the form *J*/2**\ *N* where *J* is +an integer containing exactly 53 bits. Rewriting :: + + 1 / 10 ~= J / (2**N) + +as :: + + J ~= 2**N / 10 + +and recalling that *J* has exactly 53 bits (is ``>= 2**52`` but ``< 2**53``), +the best value for *N* is 56:: + + >>> 2**52 <= 2**56 // 10 < 2**53 + True + +That is, 56 is the only value for *N* that leaves *J* with exactly 53 bits. The +best possible value for *J* is then that quotient rounded:: + + >>> q, r = divmod(2**56, 10) + >>> r + 6 + +Since the remainder is more than half of 10, the best approximation is obtained +by rounding up:: + + >>> q+1 + 7205759403792794 + +Therefore the best possible approximation to 1/10 in 754 double precision is:: + + 7205759403792794 / 2 ** 56 + +Dividing both the numerator and denominator by two reduces the fraction to:: + + 3602879701896397 / 2 ** 55 + +Note that since we rounded up, this is actually a little bit larger than 1/10; +if we had not rounded up, the quotient would have been a little bit smaller than +1/10. But in no case can it be *exactly* 1/10! + +So the computer never "sees" 1/10: what it sees is the exact fraction given +above, the best 754 double approximation it can get:: + + >>> 0.1 * 2 ** 55 + 3602879701896397.0 + +If we multiply that fraction by 10\*\*55, we can see the value out to +55 decimal digits:: + + >>> 3602879701896397 * 10 ** 55 // 2 ** 55 + 1000000000000000055511151231257827021181583404541015625 + +meaning that the exact number stored in the computer is equal to +the decimal value 0.1000000000000000055511151231257827021181583404541015625. +Instead of displaying the full decimal value, many languages (including +older versions of Python), round the result to 17 significant digits:: + + >>> format(0.1, '.17f') + '0.10000000000000001' + +The :mod:`fractions` and :mod:`decimal` modules make these calculations +easy:: + + >>> from decimal import Decimal + >>> from fractions import Fraction + + >>> Fraction.from_float(0.1) + Fraction(3602879701896397, 36028797018963968) + + >>> (0.1).as_integer_ratio() + (3602879701896397, 36028797018963968) + + >>> Decimal.from_float(0.1) + Decimal('0.1000000000000000055511151231257827021181583404541015625') + + >>> format(Decimal.from_float(0.1), '.17') + '0.10000000000000001' diff --git a/cpython_2/environment/repo/Doc/tutorial/index.rst b/cpython_2/environment/repo/Doc/tutorial/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..8ee011e2827e79253fdcfc45c97d1f342a3b7cad --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/index.rst @@ -0,0 +1,60 @@ +.. _tutorial-index: + +###################### + The Python Tutorial +###################### + +Python is an easy to learn, powerful programming language. It has efficient +high-level data structures and a simple but effective approach to +object-oriented programming. Python's elegant syntax and dynamic typing, +together with its interpreted nature, make it an ideal language for scripting +and rapid application development in many areas on most platforms. + +The Python interpreter and the extensive standard library are freely available +in source or binary form for all major platforms from the Python Web site, +https://www.python.org/, and may be freely distributed. The same site also +contains distributions of and pointers to many free third party Python modules, +programs and tools, and additional documentation. + +The Python interpreter is easily extended with new functions and data types +implemented in C or C++ (or other languages callable from C). Python is also +suitable as an extension language for customizable applications. + +This tutorial introduces the reader informally to the basic concepts and +features of the Python language and system. It helps to have a Python +interpreter handy for hands-on experience, but all examples are self-contained, +so the tutorial can be read off-line as well. + +For a description of standard objects and modules, see :ref:`library-index`. +:ref:`reference-index` gives a more formal definition of the language. To write +extensions in C or C++, read :ref:`extending-index` and +:ref:`c-api-index`. There are also several books covering Python in depth. + +This tutorial does not attempt to be comprehensive and cover every single +feature, or even every commonly used feature. Instead, it introduces many of +Python's most noteworthy features, and will give you a good idea of the +language's flavor and style. After reading it, you will be able to read and +write Python modules and programs, and you will be ready to learn more about the +various Python library modules described in :ref:`library-index`. + +The :ref:`glossary` is also worth going through. + +.. toctree:: + :numbered: + + appetite.rst + interpreter.rst + introduction.rst + controlflow.rst + datastructures.rst + modules.rst + inputoutput.rst + errors.rst + classes.rst + stdlib.rst + stdlib2.rst + venv.rst + whatnow.rst + interactive.rst + floatingpoint.rst + appendix.rst diff --git a/cpython_2/environment/repo/Doc/tutorial/inputoutput.rst b/cpython_2/environment/repo/Doc/tutorial/inputoutput.rst new file mode 100644 index 0000000000000000000000000000000000000000..a404f4be19f1b91076290991ac9a8ce5108597bf --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/inputoutput.rst @@ -0,0 +1,505 @@ +.. _tut-io: + +**************** +Input and Output +**************** + +There are several ways to present the output of a program; data can be printed +in a human-readable form, or written to a file for future use. This chapter will +discuss some of the possibilities. + + +.. _tut-formatting: + +Fancier Output Formatting +========================= + +So far we've encountered two ways of writing values: *expression statements* and +the :func:`print` function. (A third way is using the :meth:`write` method +of file objects; the standard output file can be referenced as ``sys.stdout``. +See the Library Reference for more information on this.) + +Often you'll want more control over the formatting of your output than simply +printing space-separated values. There are several ways to format output. + +* To use :ref:`formatted string literals `, begin a string + with ``f`` or ``F`` before the opening quotation mark or triple quotation mark. + Inside this string, you can write a Python expression between ``{`` and ``}`` + characters that can refer to variables or literal values. + + :: + + >>> year = 2016 + >>> event = 'Referendum' + >>> f'Results of the {year} {event}' + 'Results of the 2016 Referendum' + +* The :meth:`str.format` method of strings requires more manual + effort. You'll still use ``{`` and ``}`` to mark where a variable + will be substituted and can provide detailed formatting directives, + but you'll also need to provide the information to be formatted. + + :: + + >>> yes_votes = 42_572_654 + >>> no_votes = 43_132_495 + >>> percentage = yes_votes / (yes_votes + no_votes) + >>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage) + ' 42572654 YES votes 49.67%' + +* Finally, you can do all the string handling yourself by using string slicing and + concatenation operations to create any layout you can imagine. The + string type has some methods that perform useful operations for padding + strings to a given column width. + +When you don't need fancy output but just want a quick display of some +variables for debugging purposes, you can convert any value to a string with +the :func:`repr` or :func:`str` functions. + +The :func:`str` function is meant to return representations of values which are +fairly human-readable, while :func:`repr` is meant to generate representations +which can be read by the interpreter (or will force a :exc:`SyntaxError` if +there is no equivalent syntax). For objects which don't have a particular +representation for human consumption, :func:`str` will return the same value as +:func:`repr`. Many values, such as numbers or structures like lists and +dictionaries, have the same representation using either function. Strings, in +particular, have two distinct representations. + +Some examples:: + + >>> s = 'Hello, world.' + >>> str(s) + 'Hello, world.' + >>> repr(s) + "'Hello, world.'" + >>> str(1/7) + '0.14285714285714285' + >>> x = 10 * 3.25 + >>> y = 200 * 200 + >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' + >>> print(s) + The value of x is 32.5, and y is 40000... + >>> # The repr() of a string adds string quotes and backslashes: + ... hello = 'hello, world\n' + >>> hellos = repr(hello) + >>> print(hellos) + 'hello, world\n' + >>> # The argument to repr() may be any Python object: + ... repr((x, y, ('spam', 'eggs'))) + "(32.5, 40000, ('spam', 'eggs'))" + +The :mod:`string` module contains a :class:`~string.Template` class that offers +yet another way to substitute values into strings, using placeholders like +``$x`` and replacing them with values from a dictionary, but offers much less +control of the formatting. + + +.. _tut-f-strings: + +Formatted String Literals +------------------------- + +:ref:`Formatted string literals ` (also called f-strings for +short) let you include the value of Python expressions inside a string by +prefixing the string with ``f`` or ``F`` and writing expressions as +``{expression}``. + +An optional format specifier can follow the expression. This allows greater +control over how the value is formatted. The following example rounds pi to +three places after the decimal:: + + >>> import math + >>> print(f'The value of pi is approximately {math.pi:.3f}.') + The value of pi is approximately 3.142. + +Passing an integer after the ``':'`` will cause that field to be a minimum +number of characters wide. This is useful for making columns line up. :: + + >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} + >>> for name, phone in table.items(): + ... print(f'{name:10} ==> {phone:10d}') + ... + Sjoerd ==> 4127 + Jack ==> 4098 + Dcab ==> 7678 + +Other modifiers can be used to convert the value before it is formatted. +``'!a'`` applies :func:`ascii`, ``'!s'`` applies :func:`str`, and ``'!r'`` +applies :func:`repr`:: + + >>> animals = 'eels' + >>> print(f'My hovercraft is full of {animals}.') + My hovercraft is full of eels. + >>> print(f'My hovercraft is full of {animals!r}.') + My hovercraft is full of 'eels'. + +For a reference on these format specifications, see +the reference guide for the :ref:`formatspec`. + +.. _tut-string-format: + +The String format() Method +-------------------------- + +Basic usage of the :meth:`str.format` method looks like this:: + + >>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) + We are the knights who say "Ni!" + +The brackets and characters within them (called format fields) are replaced with +the objects passed into the :meth:`str.format` method. A number in the +brackets can be used to refer to the position of the object passed into the +:meth:`str.format` method. :: + + >>> print('{0} and {1}'.format('spam', 'eggs')) + spam and eggs + >>> print('{1} and {0}'.format('spam', 'eggs')) + eggs and spam + +If keyword arguments are used in the :meth:`str.format` method, their values +are referred to by using the name of the argument. :: + + >>> print('This {food} is {adjective}.'.format( + ... food='spam', adjective='absolutely horrible')) + This spam is absolutely horrible. + +Positional and keyword arguments can be arbitrarily combined:: + + >>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', + other='Georg')) + The story of Bill, Manfred, and Georg. + +If you have a really long format string that you don't want to split up, it +would be nice if you could reference the variables to be formatted by name +instead of by position. This can be done by simply passing the dict and using +square brackets ``'[]'`` to access the keys :: + + >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} + >>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ' + ... 'Dcab: {0[Dcab]:d}'.format(table)) + Jack: 4098; Sjoerd: 4127; Dcab: 8637678 + +This could also be done by passing the table as keyword arguments with the '**' +notation. :: + + >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} + >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) + Jack: 4098; Sjoerd: 4127; Dcab: 8637678 + +This is particularly useful in combination with the built-in function +:func:`vars`, which returns a dictionary containing all local variables. + +As an example, the following lines produce a tidily-aligned +set of columns giving integers and their 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 + 4 16 64 + 5 25 125 + 6 36 216 + 7 49 343 + 8 64 512 + 9 81 729 + 10 100 1000 + +For a complete overview of string formatting with :meth:`str.format`, see +:ref:`formatstrings`. + + +Manual String Formatting +------------------------ + +Here's the same table of squares and cubes, formatted manually:: + + >>> for x in range(1, 11): + ... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ') + ... # Note use of 'end' on previous line + ... print(repr(x*x*x).rjust(4)) + ... + 1 1 1 + 2 4 8 + 3 9 27 + 4 16 64 + 5 25 125 + 6 36 216 + 7 49 343 + 8 64 512 + 9 81 729 + 10 100 1000 + +(Note that the one space between each column was added by the +way :func:`print` works: it always adds spaces between its arguments.) + +The :meth:`str.rjust` method of string objects right-justifies a string in a +field of a given width by padding it with spaces on the left. There are +similar methods :meth:`str.ljust` and :meth:`str.center`. These methods do +not write anything, they just return a new string. If the input string is too +long, they don't truncate it, but return it unchanged; this will mess up your +column lay-out but that's usually better than the alternative, which would be +lying about a value. (If you really want truncation you can always add a +slice operation, as in ``x.ljust(n)[:n]``.) + +There is another method, :meth:`str.zfill`, which pads a numeric string on the +left with zeros. It understands about plus and minus signs:: + + >>> '12'.zfill(5) + '00012' + >>> '-3.14'.zfill(7) + '-003.14' + >>> '3.14159265359'.zfill(5) + '3.14159265359' + + +Old string formatting +--------------------- + +The ``%`` operator can also be used for string formatting. It interprets the +left argument much like a :c:func:`sprintf`\ -style format string to be applied +to the right argument, and returns the string resulting from this formatting +operation. For example:: + + >>> import math + >>> print('The value of pi is approximately %5.3f.' % math.pi) + The value of pi is approximately 3.142. + +More information can be found in the :ref:`old-string-formatting` section. + + +.. _tut-files: + +Reading and Writing Files +========================= + +.. index:: + builtin: open + object: file + +:func:`open` returns a :term:`file object`, and is most commonly used with +two arguments: ``open(filename, mode)``. + +:: + + >>> f = open('workfile', 'w') + +.. XXX str(f) is + + >>> print(f) + + +The first argument is a string containing the filename. The second argument is +another string containing a few characters describing the way in which the file +will be used. *mode* can be ``'r'`` when the file will only be read, ``'w'`` +for only writing (an existing file with the same name will be erased), and +``'a'`` opens the file for appending; any data written to the file is +automatically added to the end. ``'r+'`` opens the file for both reading and +writing. The *mode* argument is optional; ``'r'`` will be assumed if it's +omitted. + +Normally, files are opened in :dfn:`text mode`, that means, you read and write +strings from and to the file, which are encoded in a specific encoding. If +encoding is not specified, the default is platform dependent (see +:func:`open`). ``'b'`` appended to the mode opens the file in +:dfn:`binary mode`: now the data is read and written in the form of bytes +objects. This mode should be used for all files that don't contain text. + +In text mode, the default when reading is to convert platform-specific line +endings (``\n`` on Unix, ``\r\n`` on Windows) to just ``\n``. When writing in +text mode, the default is to convert occurrences of ``\n`` back to +platform-specific line endings. This behind-the-scenes modification +to file data is fine for text files, but will corrupt binary data like that in +:file:`JPEG` or :file:`EXE` files. Be very careful to use binary mode when +reading and writing such files. + +It is good practice to use the :keyword:`with` keyword when dealing +with file objects. The advantage is that the file is properly closed +after its suite finishes, even if an exception is raised at some +point. Using :keyword:`!with` is also much shorter than writing +equivalent :keyword:`try`\ -\ :keyword:`finally` blocks:: + + >>> with open('workfile') as f: + ... read_data = f.read() + + >>> # We can check that the file has been automatically closed. + >>> f.closed + True + +If you're not using the :keyword:`with` keyword, then you should call +``f.close()`` to close the file and immediately free up any system +resources used by it. If you don't explicitly close a file, Python's +garbage collector will eventually destroy the object and close the +open file for you, but the file may stay open for a while. Another +risk is that different Python implementations will do this clean-up at +different times. + +After a file object is closed, either by a :keyword:`with` statement +or by calling ``f.close()``, attempts to use the file object will +automatically fail. :: + + >>> f.close() + >>> f.read() + Traceback (most recent call last): + File "", line 1, in + ValueError: I/O operation on closed file. + + +.. _tut-filemethods: + +Methods of File Objects +----------------------- + +The rest of the examples in this section will assume that a file object called +``f`` has already been created. + +To read a file's contents, call ``f.read(size)``, which reads some quantity of +data and returns it as a string (in text mode) or bytes object (in binary mode). +*size* is an optional numeric argument. When *size* is omitted or negative, the +entire contents of the file will be read and returned; it's your problem if the +file is twice as large as your machine's memory. Otherwise, at most *size* +characters (in text mode) or *size* bytes (in binary mode) are read and returned. +If the end of the file has been reached, ``f.read()`` will return an empty +string (``''``). :: + + >>> f.read() + 'This is the entire file.\n' + >>> f.read() + '' + +``f.readline()`` reads a single line from the file; a newline character (``\n``) +is left at the end of the string, and is only omitted on the last line of the +file if the file doesn't end in a newline. This makes the return value +unambiguous; if ``f.readline()`` returns an empty string, the end of the file +has been reached, while a blank line is represented by ``'\n'``, a string +containing only a single newline. :: + + >>> f.readline() + 'This is the first line of the file.\n' + >>> f.readline() + 'Second line of the file\n' + >>> f.readline() + '' + +For reading lines from a file, you can loop over the file object. This is memory +efficient, fast, and leads to simple code:: + + >>> for line in f: + ... print(line, end='') + ... + This is the first line of the file. + Second line of the file + +If you want to read all the lines of a file in a list you can also use +``list(f)`` or ``f.readlines()``. + +``f.write(string)`` writes the contents of *string* to the file, returning +the number of characters written. :: + + >>> f.write('This is a test\n') + 15 + +Other types of objects need to be converted -- either to a string (in text mode) +or a bytes object (in binary mode) -- before writing them:: + + >>> value = ('the answer', 42) + >>> s = str(value) # convert the tuple to string + >>> f.write(s) + 18 + +``f.tell()`` returns an integer giving the file object's current position in the file +represented as number of bytes from the beginning of the file when in binary mode and +an opaque number when in text mode. + +To change the file object's position, use ``f.seek(offset, whence)``. The position is computed +from adding *offset* to a reference point; the reference point is selected by +the *whence* argument. A *whence* value of 0 measures from the beginning +of the file, 1 uses the current file position, and 2 uses the end of the file as +the reference point. *whence* can be omitted and defaults to 0, using the +beginning of the file as the reference point. :: + + >>> f = open('workfile', 'rb+') + >>> f.write(b'0123456789abcdef') + 16 + >>> f.seek(5) # Go to the 6th byte in the file + 5 + >>> f.read(1) + b'5' + >>> f.seek(-3, 2) # Go to the 3rd byte before the end + 13 + >>> f.read(1) + b'd' + +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)``) and the only valid *offset* values are +those returned from the ``f.tell()``, or zero. Any other *offset* value produces +undefined behaviour. + +File objects have some additional methods, such as :meth:`~file.isatty` and +:meth:`~file.truncate` which are less frequently used; consult the Library +Reference for a complete guide to file objects. + + +.. _tut-json: + +Saving structured data with :mod:`json` +--------------------------------------- + +.. index:: module: json + +Strings can easily be written to and read from a file. Numbers take a bit more +effort, since the :meth:`read` method only returns strings, which will have to +be passed to a function like :func:`int`, which takes a string like ``'123'`` +and returns its numeric value 123. When you want to save more complex data +types like nested lists and dictionaries, parsing and serializing by hand +becomes complicated. + +Rather than having users constantly writing and debugging code to save +complicated data types to files, Python allows you to use the popular data +interchange format called `JSON (JavaScript Object Notation) +`_. The standard module called :mod:`json` can take Python +data hierarchies, and convert them to string representations; this process is +called :dfn:`serializing`. Reconstructing the data from the string representation +is called :dfn:`deserializing`. Between serializing and deserializing, the +string representing the object may have been stored in a file or data, or +sent over a network connection to some distant machine. + +.. note:: + The JSON format is commonly used by modern applications to allow for data + exchange. Many programmers are already familiar with it, which makes + it a good choice for interoperability. + +If you have an object ``x``, you can view its JSON string representation with a +simple line of code:: + + >>> import json + >>> json.dumps([1, 'simple', 'list']) + '[1, "simple", "list"]' + +Another variant of the :func:`~json.dumps` function, called :func:`~json.dump`, +simply serializes the object to a :term:`text file`. So if ``f`` is a +:term:`text file` object opened for writing, we can do this:: + + json.dump(x, f) + +To decode the object again, if ``f`` is a :term:`text file` object which has +been opened for reading:: + + x = json.load(f) + +This simple serialization technique can handle lists and dictionaries, but +serializing arbitrary class instances in JSON requires a bit of extra effort. +The reference for the :mod:`json` module contains an explanation of this. + +.. seealso:: + + :mod:`pickle` - the pickle module + + Contrary to :ref:`JSON `, *pickle* is a protocol which allows + the serialization of arbitrarily complex Python objects. As such, it is + specific to Python and cannot be used to communicate with applications + written in other languages. It is also insecure by default: + deserializing pickle data coming from an untrusted source can execute + arbitrary code, if the data was crafted by a skilled attacker. diff --git a/cpython_2/environment/repo/Doc/tutorial/interactive.rst b/cpython_2/environment/repo/Doc/tutorial/interactive.rst new file mode 100644 index 0000000000000000000000000000000000000000..c0eb1feec4eb4d1871db4b71cb7e91e6cdcda5b4 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/interactive.rst @@ -0,0 +1,54 @@ +.. _tut-interacting: + +************************************************** +Interactive Input Editing and History Substitution +************************************************** + +Some versions of the Python interpreter support editing of the current input +line and history substitution, similar to facilities found in the Korn shell and +the GNU Bash shell. This is implemented using the `GNU Readline`_ library, +which supports various styles of editing. This library has its own +documentation which we won't duplicate here. + + +.. _tut-keybindings: + +Tab Completion and History Editing +================================== + +Completion of variable and module names is +:ref:`automatically enabled ` at interpreter startup so +that the :kbd:`Tab` key invokes the completion function; it looks at +Python statement names, the current local variables, and the available +module names. For dotted expressions such as ``string.a``, it will evaluate +the expression up to the final ``'.'`` and then suggest completions from +the attributes of the resulting object. Note that this may execute +application-defined code if an object with a :meth:`__getattr__` method +is part of the expression. The default configuration also saves your +history into a file named :file:`.python_history` in your user directory. +The history will be available again during the next interactive interpreter +session. + + +.. _tut-commentary: + +Alternatives to the Interactive Interpreter +=========================================== + +This facility is an enormous step forward compared to earlier versions of the +interpreter; however, some wishes are left: It would be nice if the proper +indentation were suggested on continuation lines (the parser knows if an indent +token is required next). The completion mechanism might use the interpreter's +symbol table. A command to check (or even suggest) matching parentheses, +quotes, etc., would also be useful. + +One alternative enhanced interactive interpreter that has been around for quite +some time is IPython_, which features tab completion, object exploration and +advanced history management. It can also be thoroughly customized and embedded +into other applications. Another similar enhanced interactive environment is +bpython_. + + +.. _GNU Readline: https://tiswww.case.edu/php/chet/readline/rltop.html +.. _IPython: https://ipython.org/ +.. _bpython: https://www.bpython-interpreter.org/ diff --git a/cpython_2/environment/repo/Doc/tutorial/interpreter.rst b/cpython_2/environment/repo/Doc/tutorial/interpreter.rst new file mode 100644 index 0000000000000000000000000000000000000000..b78d2960ac5432a2b6e6c353309c591d1c879eff --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/interpreter.rst @@ -0,0 +1,163 @@ +.. _tut-using: + +**************************** +Using the Python Interpreter +**************************** + + +.. _tut-invoking: + +Invoking the Interpreter +======================== + +The Python interpreter is usually installed as :file:`/usr/local/bin/python3.9` +on those machines where it is available; putting :file:`/usr/local/bin` in your +Unix shell's search path makes it possible to start it by typing the command: + +.. code-block:: text + + python3.9 + +to the shell. [#]_ Since the choice of the directory where the interpreter lives +is an installation option, other places are possible; check with your local +Python guru or system administrator. (E.g., :file:`/usr/local/python` is a +popular alternative location.) + +On Windows machines where you have installed Python from the :ref:`Microsoft Store +`, the :file:`python3.9` command will be available. If you have +the :ref:`py.exe launcher ` installed, you can use the :file:`py` +command. See :ref:`setting-envvars` for other ways to launch Python. + +Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on +Windows) at the primary prompt causes the interpreter to exit with a zero exit +status. If that doesn't work, you can exit the interpreter by typing the +following command: ``quit()``. + +The interpreter's line-editing features include interactive editing, history +substitution and code completion on systems that support the `GNU Readline +`_ library. +Perhaps the quickest check to see whether command line editing is supported is +typing :kbd:`Control-P` to the first Python prompt you get. If it beeps, you +have command line editing; see Appendix :ref:`tut-interacting` for an +introduction to the keys. If nothing appears to happen, or if ``^P`` is +echoed, command line editing isn't available; you'll only be able to use +backspace to remove characters from the current line. + +The interpreter operates somewhat like the Unix shell: when called with standard +input connected to a tty device, it reads and executes commands interactively; +when called with a file name argument or with a file as standard input, it reads +and executes a *script* from that file. + +A second way of starting the interpreter is ``python -c command [arg] ...``, +which executes the statement(s) in *command*, analogous to the shell's +:option:`-c` option. Since Python statements often contain spaces or other +characters that are special to the shell, it is usually advised to quote +*command* in its entirety with single quotes. + +Some Python modules are also useful as scripts. These can be invoked using +``python -m module [arg] ...``, which executes the source file for *module* as +if you had spelled out its full name on the command line. + +When a script file is used, it is sometimes useful to be able to run the script +and enter interactive mode afterwards. This can be done by passing :option:`-i` +before the script. + +All command line options are described in :ref:`using-on-general`. + + +.. _tut-argpassing: + +Argument Passing +---------------- + +When known to the interpreter, the script name and additional arguments +thereafter are turned into a list of strings and assigned to the ``argv`` +variable in the ``sys`` module. You can access this list by executing ``import +sys``. The length of the list is at least one; when no script and no arguments +are given, ``sys.argv[0]`` is an empty string. When the script name is given as +``'-'`` (meaning standard input), ``sys.argv[0]`` is set to ``'-'``. When +:option:`-c` *command* is used, ``sys.argv[0]`` is set to ``'-c'``. When +:option:`-m` *module* is used, ``sys.argv[0]`` is set to the full name of the +located module. Options found after :option:`-c` *command* or :option:`-m` +*module* are not consumed by the Python interpreter's option processing but +left in ``sys.argv`` for the command or module to handle. + + +.. _tut-interactive: + +Interactive Mode +---------------- + +When commands are read from a tty, the interpreter is said to be in *interactive +mode*. In this mode it prompts for the next command with the *primary prompt*, +usually three greater-than signs (``>>>``); for continuation lines it prompts +with the *secondary prompt*, by default three dots (``...``). The interpreter +prints a welcome message stating its version number and a copyright notice +before printing the first prompt: + +.. code-block:: shell-session + + $ python3.9 + Python 3.9 (default, June 4 2019, 09:25:04) + [GCC 4.8.2] on linux + Type "help", "copyright", "credits" or "license" for more information. + >>> + +.. XXX update for new releases + +Continuation lines are needed when entering a multi-line construct. As an +example, take a look at this :keyword:`if` statement:: + + >>> the_world_is_flat = True + >>> if the_world_is_flat: + ... print("Be careful not to fall off!") + ... + Be careful not to fall off! + + +For more on interactive mode, see :ref:`tut-interac`. + + +.. _tut-interp: + +The Interpreter and Its Environment +=================================== + + +.. _tut-source-encoding: + +Source Code Encoding +-------------------- + +By default, Python source files are treated as encoded in UTF-8. In that +encoding, characters of most languages in the world can be used simultaneously +in string literals, identifiers and comments --- although the standard library +only uses ASCII characters for identifiers, a convention that any portable code +should follow. To display all these characters properly, your editor must +recognize that the file is UTF-8, and it must use a font that supports all the +characters in the file. + +To declare an encoding other than the default one, a special comment line +should be added as the *first* line of the file. The syntax is as follows:: + + # -*- coding: encoding -*- + +where *encoding* is one of the valid :mod:`codecs` supported by Python. + +For example, to declare that Windows-1252 encoding is to be used, the first +line of your source code file should be:: + + # -*- coding: cp1252 -*- + +One exception to the *first line* rule is when the source code starts with a +:ref:`UNIX "shebang" line `. In this case, the encoding +declaration should be added as the second line of the file. For example:: + + #!/usr/bin/env python3 + # -*- coding: cp1252 -*- + +.. rubric:: Footnotes + +.. [#] On Unix, the Python 3.x interpreter is by default not installed with the + executable named ``python``, so that it does not conflict with a + simultaneously installed Python 2.x executable. diff --git a/cpython_2/environment/repo/Doc/tutorial/introduction.rst b/cpython_2/environment/repo/Doc/tutorial/introduction.rst new file mode 100644 index 0000000000000000000000000000000000000000..2a1666128a20155cb38e3fbdc3c255b7d38a31a6 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/introduction.rst @@ -0,0 +1,546 @@ +.. _tut-informal: + +********************************** +An Informal Introduction to Python +********************************** + +In the following examples, input and output are distinguished by the presence or +absence of prompts (:term:`>>>` and :term:`...`): to repeat the example, you must type +everything after the prompt, when the prompt appears; lines that do not begin +with a prompt are output from the interpreter. Note that a secondary prompt on a +line by itself in an example means you must type a blank line; this is used to +end a multi-line command. + +.. index:: single: # (hash); comment + +Many of the examples in this manual, even those entered at the interactive +prompt, include comments. Comments in Python start with the hash character, +``#``, and extend to the end of the physical line. A comment may appear at the +start of a line or following whitespace or code, but not within a string +literal. A hash character within a string literal is just a hash character. +Since comments are to clarify code and are not interpreted by Python, they may +be omitted when typing in examples. + +Some examples:: + + # this is the first comment + spam = 1 # and this is the second comment + # ... and now a third! + text = "# This is not a comment because it's inside quotes." + + +.. _tut-calculator: + +Using Python as a Calculator +============================ + +Let's try some simple Python commands. Start the interpreter and wait for the +primary prompt, ``>>>``. (It shouldn't take long.) + + +.. _tut-numbers: + +Numbers +------- + +The interpreter acts as a simple calculator: you can type an expression at it +and it will write the value. Expression syntax is straightforward: the +operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages +(for example, Pascal or C); parentheses (``()``) can be used for grouping. +For example:: + + >>> 2 + 2 + 4 + >>> 50 - 5*6 + 20 + >>> (50 - 5*6) / 4 + 5.0 + >>> 8 / 5 # division always returns a floating point number + 1.6 + +The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`, +the ones with a fractional part (e.g. ``5.0``, ``1.6``) have type +:class:`float`. We will see more about numeric types later in the tutorial. + +Division (``/``) always returns a float. To do :term:`floor division` and +get an integer result (discarding any fractional result) you can use the ``//`` +operator; to calculate the remainder you can use ``%``:: + + >>> 17 / 3 # classic division returns a float + 5.666666666666667 + >>> + >>> 17 // 3 # floor division discards the fractional part + 5 + >>> 17 % 3 # the % operator returns the remainder of the division + 2 + >>> 5 * 3 + 2 # result * divisor + remainder + 17 + +With Python, it is possible to use the ``**`` operator to calculate powers [#]_:: + + >>> 5 ** 2 # 5 squared + 25 + >>> 2 ** 7 # 2 to the power of 7 + 128 + +The equal sign (``=``) is used to assign a value to a variable. Afterwards, no +result is displayed before the next interactive prompt:: + + >>> width = 20 + >>> height = 5 * 9 + >>> width * height + 900 + +If a variable is not "defined" (assigned a value), trying to use it will +give you an error:: + + >>> n # try to access an undefined variable + Traceback (most recent call last): + File "", line 1, in + NameError: name 'n' is not defined + +There is full support for floating point; operators with mixed type operands +convert the integer operand to floating point:: + + >>> 4 * 3.75 - 1 + 14.0 + +In interactive mode, the last printed expression is assigned to the variable +``_``. This means that when you are using Python as a desk calculator, it is +somewhat easier to continue calculations, for example:: + + >>> tax = 12.5 / 100 + >>> price = 100.50 + >>> price * tax + 12.5625 + >>> price + _ + 113.0625 + >>> round(_, 2) + 113.06 + +This variable should be treated as read-only by the user. Don't explicitly +assign a value to it --- you would create an independent local variable with the +same name masking the built-in variable with its magic behavior. + +In addition to :class:`int` and :class:`float`, Python supports other types of +numbers, such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`. +Python also has built-in support for :ref:`complex numbers `, +and uses the ``j`` or ``J`` suffix to indicate the imaginary part +(e.g. ``3+5j``). + + +.. _tut-strings: + +Strings +------- + +Besides numbers, Python can also manipulate strings, which can be expressed +in several ways. They can be enclosed in single quotes (``'...'``) or +double quotes (``"..."``) with the same result [#]_. ``\`` can be used +to escape quotes:: + + >>> 'spam eggs' # single quotes + 'spam eggs' + >>> 'doesn\'t' # use \' to escape the single quote... + "doesn't" + >>> "doesn't" # ...or use double quotes instead + "doesn't" + >>> '"Yes," they said.' + '"Yes," they said.' + >>> "\"Yes,\" they said." + '"Yes," they said.' + >>> '"Isn\'t," they said.' + '"Isn\'t," they said.' + +In the interactive interpreter, the output string is enclosed in quotes and +special characters are escaped with backslashes. While this might sometimes +look different from the input (the enclosing quotes could change), the two +strings are equivalent. The string is enclosed in double quotes if +the string contains a single quote and no double quotes, otherwise it is +enclosed in single quotes. The :func:`print` function produces a more +readable output, by omitting the enclosing quotes and by printing escaped +and special characters:: + + >>> '"Isn\'t," they said.' + '"Isn\'t," they said.' + >>> print('"Isn\'t," they said.') + "Isn't," they said. + >>> s = 'First line.\nSecond line.' # \n means newline + >>> s # without print(), \n is included in the output + 'First line.\nSecond line.' + >>> print(s) # with print(), \n produces a new line + First line. + Second line. + +If you don't want characters prefaced by ``\`` to be interpreted as +special characters, you can use *raw strings* by adding an ``r`` before +the first quote:: + + >>> print('C:\some\name') # here \n means newline! + C:\some + ame + >>> print(r'C:\some\name') # note the r before the quote + C:\some\name + +String literals can span multiple lines. One way is using triple-quotes: +``"""..."""`` or ``'''...'''``. End of lines are automatically +included in the string, but it's possible to prevent this by adding a ``\`` at +the end of the line. The following example:: + + print("""\ + Usage: thingy [OPTIONS] + -h Display this usage message + -H hostname Hostname to connect to + """) + +produces the following output (note that the initial newline is not included): + +.. code-block:: text + + Usage: thingy [OPTIONS] + -h Display this usage message + -H hostname Hostname to connect to + +Strings can be concatenated (glued together) with the ``+`` operator, and +repeated with ``*``:: + + >>> # 3 times 'un', followed by 'ium' + >>> 3 * 'un' + 'ium' + 'unununium' + +Two or more *string literals* (i.e. the ones enclosed between quotes) next +to each other are automatically concatenated. :: + + >>> 'Py' 'thon' + 'Python' + +This feature is particularly useful when you want to break long strings:: + + >>> text = ('Put several strings within parentheses ' + ... 'to have them joined together.') + >>> text + 'Put several strings within parentheses to have them joined together.' + +This only works with two literals though, not with variables or expressions:: + + >>> prefix = 'Py' + >>> prefix 'thon' # can't concatenate a variable and a string literal + File "", line 1 + prefix 'thon' + ^ + SyntaxError: invalid syntax + >>> ('un' * 3) 'ium' + File "", line 1 + ('un' * 3) 'ium' + ^ + SyntaxError: invalid syntax + +If you want to concatenate variables or a variable and a literal, use ``+``:: + + >>> prefix + 'thon' + 'Python' + +Strings can be *indexed* (subscripted), with the first character having index 0. +There is no separate character type; a character is simply a string of size +one:: + + >>> word = 'Python' + >>> word[0] # character in position 0 + 'P' + >>> word[5] # character in position 5 + 'n' + +Indices may also be negative numbers, to start counting from the right:: + + >>> word[-1] # last character + 'n' + >>> word[-2] # second-last character + 'o' + >>> word[-6] + 'P' + +Note that since -0 is the same as 0, negative indices start from -1. + +In addition to indexing, *slicing* is also supported. While indexing is used +to obtain individual characters, *slicing* allows you to obtain substring:: + + >>> word[0:2] # characters from position 0 (included) to 2 (excluded) + 'Py' + >>> word[2:5] # characters from position 2 (included) to 5 (excluded) + 'tho' + +Note how the start is always included, and the end always excluded. This +makes sure that ``s[:i] + s[i:]`` is always equal to ``s``:: + + >>> word[:2] + word[2:] + 'Python' + >>> word[:4] + word[4:] + 'Python' + +Slice indices have useful defaults; an omitted first index defaults to zero, an +omitted second index defaults to the size of the string being sliced. :: + + >>> word[:2] # character from the beginning to position 2 (excluded) + 'Py' + >>> word[4:] # characters from position 4 (included) to the end + 'on' + >>> word[-2:] # characters from the second-last (included) to the end + 'on' + +One way to remember how slices work is to think of the indices as pointing +*between* characters, with the left edge of the first character numbered 0. +Then the right edge of the last character of a string of *n* characters has +index *n*, for example:: + + +---+---+---+---+---+---+ + | P | y | t | h | o | n | + +---+---+---+---+---+---+ + 0 1 2 3 4 5 6 + -6 -5 -4 -3 -2 -1 + +The first row of numbers gives the position of the indices 0...6 in the string; +the second row gives the corresponding negative indices. The slice from *i* to +*j* consists of all characters between the edges labeled *i* and *j*, +respectively. + +For non-negative indices, the length of a slice is the difference of the +indices, if both are within bounds. For example, the length of ``word[1:3]`` is +2. + +Attempting to use an index that is too large will result in an error:: + + >>> word[42] # the word only has 6 characters + Traceback (most recent call last): + File "", line 1, in + IndexError: string index out of range + +However, out of range slice indexes are handled gracefully when used for +slicing:: + + >>> word[4:42] + 'on' + >>> word[42:] + '' + +Python strings cannot be changed --- they are :term:`immutable`. +Therefore, assigning to an indexed position in the string results in an error:: + + >>> word[0] = 'J' + Traceback (most recent call last): + File "", line 1, in + TypeError: 'str' object does not support item assignment + >>> word[2:] = 'py' + Traceback (most recent call last): + File "", line 1, in + TypeError: 'str' object does not support item assignment + +If you need a different string, you should create a new one:: + + >>> 'J' + word[1:] + 'Jython' + >>> word[:2] + 'py' + 'Pypy' + +The built-in function :func:`len` returns the length of a string:: + + >>> s = 'supercalifragilisticexpialidocious' + >>> len(s) + 34 + + +.. seealso:: + + :ref:`textseq` + Strings are examples of *sequence types*, and support the common + operations supported by such types. + + :ref:`string-methods` + Strings support a large number of methods for + basic transformations and searching. + + :ref:`f-strings` + String literals that have embedded expressions. + + :ref:`formatstrings` + Information about string formatting with :meth:`str.format`. + + :ref:`old-string-formatting` + The old formatting operations invoked when strings are + the left operand of the ``%`` operator are described in more detail here. + + +.. _tut-lists: + +Lists +----- + +Python knows a number of *compound* data types, used to group together other +values. The most versatile is the *list*, which can be written as a list of +comma-separated values (items) between square brackets. Lists might contain +items of different types, but usually the items all have the same type. :: + + >>> squares = [1, 4, 9, 16, 25] + >>> squares + [1, 4, 9, 16, 25] + +Like strings (and all other built-in :term:`sequence` types), lists can be +indexed and sliced:: + + >>> squares[0] # indexing returns the item + 1 + >>> squares[-1] + 25 + >>> squares[-3:] # slicing returns a new list + [9, 16, 25] + +All slice operations return a new list containing the requested elements. This +means that the following slice returns a +:ref:`shallow copy ` of the list:: + + >>> squares[:] + [1, 4, 9, 16, 25] + +Lists also support operations like concatenation:: + + >>> squares + [36, 49, 64, 81, 100] + [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] + +Unlike strings, which are :term:`immutable`, lists are a :term:`mutable` +type, i.e. it is possible to change their content:: + + >>> cubes = [1, 8, 27, 65, 125] # something's wrong here + >>> 4 ** 3 # the cube of 4 is 64, not 65! + 64 + >>> cubes[3] = 64 # replace the wrong value + >>> cubes + [1, 8, 27, 64, 125] + +You can also add new items at the end of the list, by using +the :meth:`~list.append` *method* (we will see more about methods later):: + + >>> cubes.append(216) # add the cube of 6 + >>> cubes.append(7 ** 3) # and the cube of 7 + >>> cubes + [1, 8, 27, 64, 125, 216, 343] + +Assignment to slices is also possible, and this can even change the size of the +list or clear it entirely:: + + >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] + >>> letters + ['a', 'b', 'c', 'd', 'e', 'f', 'g'] + >>> # replace some values + >>> letters[2:5] = ['C', 'D', 'E'] + >>> letters + ['a', 'b', 'C', 'D', 'E', 'f', 'g'] + >>> # now remove them + >>> letters[2:5] = [] + >>> letters + ['a', 'b', 'f', 'g'] + >>> # clear the list by replacing all the elements with an empty list + >>> letters[:] = [] + >>> letters + [] + +The built-in function :func:`len` also applies to lists:: + + >>> letters = ['a', 'b', 'c', 'd'] + >>> len(letters) + 4 + +It is possible to nest lists (create lists containing other lists), for +example:: + + >>> a = ['a', 'b', 'c'] + >>> n = [1, 2, 3] + >>> x = [a, n] + >>> x + [['a', 'b', 'c'], [1, 2, 3]] + >>> x[0] + ['a', 'b', 'c'] + >>> x[0][1] + 'b' + +.. _tut-firststeps: + +First Steps Towards Programming +=============================== + +Of course, we can use Python for more complicated tasks than adding two and two +together. For instance, we can write an initial sub-sequence of the +`Fibonacci series `_ +as follows:: + + >>> # Fibonacci series: + ... # the sum of two elements defines the next + ... a, b = 0, 1 + >>> while a < 10: + ... print(a) + ... a, b = b, a+b + ... + 0 + 1 + 1 + 2 + 3 + 5 + 8 + +This example introduces several new features. + +* The first line contains a *multiple assignment*: the variables ``a`` and ``b`` + simultaneously get the new values 0 and 1. On the last line this is used again, + demonstrating that the expressions on the right-hand side are all evaluated + first before any of the assignments take place. The right-hand side expressions + are evaluated from the left to the right. + +* The :keyword:`while` loop executes as long as the condition (here: ``a < 10``) + remains true. In Python, like in C, any non-zero integer value is true; zero is + false. The condition may also be a string or list value, in fact any sequence; + anything with a non-zero length is true, empty sequences are false. The test + used in the example is a simple comparison. The standard comparison operators + are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==`` + (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to) + and ``!=`` (not equal to). + +* The *body* of the loop is *indented*: indentation is Python's way of grouping + statements. At the interactive prompt, you have to type a tab or space(s) for + each indented line. In practice you will prepare more complicated input + for Python with a text editor; all decent text editors have an auto-indent + facility. When a compound statement is entered interactively, it must be + followed by a blank line to indicate completion (since the parser cannot + guess when you have typed the last line). Note that each line within a basic + block must be indented by the same amount. + +* The :func:`print` function writes the value of the argument(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 arguments, + 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:: + + >>> i = 256*256 + >>> print('The value of i is', i) + The value of i is 65536 + + The keyword argument *end* can be used to avoid the newline after the output, + or end the output with a different string:: + + >>> a, b = 0, 1 + >>> while a < 1000: + ... print(a, end=',') + ... a, b = b, a+b + ... + 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987, + + +.. rubric:: Footnotes + +.. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be + interpreted as ``-(3**2)`` and thus result in ``-9``. To avoid this + and get ``9``, you can use ``(-3)**2``. + +.. [#] Unlike other languages, special characters such as ``\n`` have the + same meaning with both single (``'...'``) and double (``"..."``) quotes. + The only difference between the two is that within single quotes you don't + need to escape ``"`` (but you have to escape ``\'``) and vice versa. diff --git a/cpython_2/environment/repo/Doc/tutorial/modules.rst b/cpython_2/environment/repo/Doc/tutorial/modules.rst new file mode 100644 index 0000000000000000000000000000000000000000..af595e5ca04d7e17185e47d4a5fbc24a2405dba1 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/modules.rst @@ -0,0 +1,576 @@ +.. _tut-modules: + +******* +Modules +******* + +If you quit from the Python interpreter and enter it again, the definitions you +have made (functions and variables) are lost. Therefore, if you want to write a +somewhat longer program, you are better off using a text editor to prepare the +input for the interpreter and running it with that file as input instead. This +is known as creating a *script*. As your program gets longer, you may want to +split it into several files for easier maintenance. You may also want to use a +handy function that you've written in several programs without copying its +definition into each program. + +To support this, Python has a way to put definitions in a file and use them in a +script or in an interactive instance of the interpreter. Such a file is called a +*module*; definitions from a module can be *imported* into other modules or into +the *main* module (the collection of variables that you have access to in a +script executed at the top level and in calculator mode). + +A module is a file containing Python definitions and statements. The file name +is the module name with the suffix :file:`.py` appended. Within a module, the +module's name (as a string) is available as the value of the global variable +``__name__``. For instance, use your favorite text editor to create a file +called :file:`fibo.py` in the current directory with the following contents:: + + # Fibonacci numbers module + + def fib(n): # write Fibonacci series up to n + a, b = 0, 1 + while a < n: + print(a, end=' ') + a, b = b, a+b + print() + + def fib2(n): # return Fibonacci series up to n + result = [] + a, b = 0, 1 + while a < n: + result.append(a) + a, b = b, a+b + return result + +Now enter the Python interpreter and import this module with the following +command:: + + >>> import fibo + +This does not enter the names of the functions defined in ``fibo`` directly in +the current symbol table; it only enters the module name ``fibo`` there. Using +the module name you can access the functions:: + + >>> fibo.fib(1000) + 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 + >>> fibo.fib2(100) + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] + >>> fibo.__name__ + 'fibo' + +If you intend to use a function often you can assign it to a local name:: + + >>> fib = fibo.fib + >>> fib(500) + 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 + + +.. _tut-moremodules: + +More on Modules +=============== + +A module can contain executable statements as well as function definitions. +These statements are intended to initialize the module. They are executed only +the *first* time the module name is encountered in an import statement. [#]_ +(They are also run if the file is executed as a script.) + +Each module has its own private symbol table, which is used as the global symbol +table by all functions defined in the module. Thus, the author of a module can +use global variables in the module without worrying about accidental clashes +with a user's global variables. On the other hand, if you know what you are +doing you can touch a module's global variables with the same notation used to +refer to its functions, ``modname.itemname``. + +Modules can import other modules. It is customary but not required to place all +:keyword:`import` statements at the beginning of a module (or script, for that +matter). The imported module names are placed in the importing module's global +symbol table. + +There is a variant of the :keyword:`import` statement that imports names from a +module directly into the importing module's symbol table. For example:: + + >>> from fibo import fib, fib2 + >>> fib(500) + 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 + +This does not introduce the module name from which the imports are taken in the +local symbol table (so in the example, ``fibo`` is not defined). + +There is even a variant to import all names that a module defines:: + + >>> from fibo import * + >>> fib(500) + 0 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 +you have already defined. + +Note that in general the practice of importing ``*`` from a module or package is +frowned upon, since it often causes poorly readable code. However, it is okay to +use it to save typing in interactive sessions. + +If the module name is followed by :keyword:`!as`, then the name +following :keyword:`!as` is bound directly to the imported module. + +:: + + >>> import fibo as fib + >>> fib.fib(500) + 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 + +This is effectively importing the module in the same way that ``import fibo`` +will do, with the only difference of it being available as ``fib``. + +It can also be used when utilising :keyword:`from` with similar effects:: + + >>> from fibo import fib as fibonacci + >>> fibonacci(500) + 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 + + +.. note:: + + For efficiency reasons, each module is only imported once per interpreter + session. Therefore, if you change your modules, you must restart the + interpreter -- or, if it's just one module you want to test interactively, + use :func:`importlib.reload`, e.g. ``import importlib; + importlib.reload(modulename)``. + + +.. _tut-modulesasscripts: + +Executing modules as scripts +---------------------------- + +When you run a Python module with :: + + python fibo.py + +the code in the module will be executed, just as if you imported it, but with +the ``__name__`` set to ``"__main__"``. That means that by adding this code at +the end of your module:: + + if __name__ == "__main__": + import sys + fib(int(sys.argv[1])) + +you can make the file usable as a script as well as an importable module, +because the code that parses the command line only runs if the module is +executed as the "main" file: + +.. code-block:: shell-session + + $ python fibo.py 50 + 0 1 1 2 3 5 8 13 21 34 + +If the module is imported, the code is not run:: + + >>> import fibo + >>> + +This is often used either to provide a convenient user interface to a module, or +for testing purposes (running the module as a script executes a test suite). + + +.. _tut-searchpath: + +The Module Search Path +---------------------- + +.. index:: triple: module; search; path + +When a module named :mod:`spam` is imported, the interpreter first searches for +a built-in module with that name. If not found, it then searches for a file +named :file:`spam.py` in a list of directories given by the variable +:data:`sys.path`. :data:`sys.path` is initialized from these locations: + +* The directory containing the input script (or the current directory when no + file is specified). +* :envvar:`PYTHONPATH` (a list of directory names, with the same syntax as the + shell variable :envvar:`PATH`). +* The installation-dependent default. + +.. note:: + On file systems which support symlinks, the directory containing the input + script is calculated after the symlink is followed. In other words the + directory containing the symlink is **not** added to the module search path. + +After initialization, Python programs can modify :data:`sys.path`. The +directory containing the script being run is placed at the beginning of the +search path, ahead of the standard library path. This means that scripts in that +directory will be loaded instead of modules of the same name in the library +directory. This is an error unless the replacement is intended. See section +:ref:`tut-standardmodules` for more information. + +.. % + Do we need stuff on zip files etc. ? DUBOIS + +"Compiled" Python files +----------------------- + +To speed up loading modules, Python caches the compiled version of each module +in the ``__pycache__`` directory under the name :file:`module.{version}.pyc`, +where the version encodes the format of the compiled file; it generally contains +the Python version number. For example, in CPython release 3.3 the compiled +version of spam.py would be cached as ``__pycache__/spam.cpython-33.pyc``. This +naming convention allows compiled modules from different releases and different +versions of Python to coexist. + +Python checks the modification date of the source against the compiled version +to see if it's out of date and needs to be recompiled. This is a completely +automatic process. Also, the compiled modules are platform-independent, so the +same library can be shared among systems with different architectures. + +Python does not check the cache in two circumstances. First, it always +recompiles and does not store the result for the module that's loaded directly +from the command line. Second, it does not check the cache if there is no +source module. To support a non-source (compiled only) distribution, the +compiled module must be in the source directory, and there must not be a source +module. + +Some tips for experts: + +* You can use the :option:`-O` or :option:`-OO` switches on the Python command + to reduce the size of a compiled module. The ``-O`` switch removes assert + statements, the ``-OO`` switch removes both assert statements and __doc__ + strings. Since some programs may rely on having these available, you should + only use this option if you know what you're doing. "Optimized" modules have + an ``opt-`` tag and are usually smaller. Future releases may + change the effects of optimization. + +* A program doesn't run any faster when it is read from a ``.pyc`` + file than when it is read from a ``.py`` file; the only thing that's faster + about ``.pyc`` files is the speed with which they are loaded. + +* The module :mod:`compileall` can create .pyc files for all modules in a + directory. + +* There is more detail on this process, including a flow chart of the + decisions, in :pep:`3147`. + + +.. _tut-standardmodules: + +Standard Modules +================ + +.. index:: module: sys + +Python comes with a library of standard modules, described in a separate +document, the Python Library Reference ("Library Reference" hereafter). Some +modules are built into the interpreter; these provide access to operations that +are not part of the core of the language but are nevertheless built in, either +for efficiency or to provide access to operating system primitives such as +system calls. The set of such modules is a configuration option which also +depends on the underlying platform. For example, the :mod:`winreg` module is only +provided on Windows systems. One particular module deserves some attention: +:mod:`sys`, which is built into every Python interpreter. The variables +``sys.ps1`` and ``sys.ps2`` define the strings used as primary and secondary +prompts:: + + >>> import sys + >>> sys.ps1 + '>>> ' + >>> sys.ps2 + '... ' + >>> sys.ps1 = 'C> ' + C> print('Yuck!') + Yuck! + C> + + +These two variables are only defined if the interpreter is in interactive mode. + +The variable ``sys.path`` is a list of strings that determines the interpreter's +search path for modules. It is initialized to a default path taken from the +environment variable :envvar:`PYTHONPATH`, or from a built-in default if +:envvar:`PYTHONPATH` is not set. You can modify it using standard list +operations:: + + >>> import sys + >>> sys.path.append('/ufs/guido/lib/python') + + +.. _tut-dir: + +The :func:`dir` Function +======================== + +The built-in function :func:`dir` is used to find out which names a module +defines. It returns a sorted list of strings:: + + >>> import fibo, sys + >>> dir(fibo) + ['__name__', 'fib', 'fib2'] + >>> dir(sys) # doctest: +NORMALIZE_WHITESPACE + ['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', + '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', + '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__', + '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework', + '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook', + 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix', + 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', + 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', + 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', + 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', + 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags', + 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', + 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', + 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', + 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value', + 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', + 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix', + 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags', + 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', + 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info', + 'warnoptions'] + +Without arguments, :func:`dir` lists the names you have defined currently:: + + >>> a = [1, 2, 3, 4, 5] + >>> import fibo + >>> fib = fibo.fib + >>> dir() + ['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys'] + +Note that it lists all types of names: variables, modules, functions, etc. + +.. index:: module: builtins + +:func:`dir` does not list the names of built-in functions and variables. If you +want a list of those, they are defined in the standard module +:mod:`builtins`:: + + >>> import builtins + >>> dir(builtins) # doctest: +NORMALIZE_WHITESPACE + ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', + 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', + 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', + 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', + 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', + 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', + 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', + 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', + 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', + 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', + 'NotImplementedError', 'OSError', 'OverflowError', + 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', + 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', + 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', + 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', + 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', + 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', + 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', + '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', + 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', + 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', + 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', + 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', + 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', + 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', + 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', + 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', + 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', + 'zip'] + +.. _tut-packages: + +Packages +======== + +Packages are a way of structuring Python's module namespace by using "dotted +module names". For example, the module name :mod:`A.B` designates a submodule +named ``B`` in a package named ``A``. Just like the use of modules saves the +authors of different modules from having to worry about each other's global +variable names, the use of dotted module names saves the authors of multi-module +packages like NumPy or Pillow from having to worry about +each other's module names. + +Suppose you want to design a collection of modules (a "package") for the uniform +handling of sound files and sound data. There are many different sound file +formats (usually recognized by their extension, for example: :file:`.wav`, +:file:`.aiff`, :file:`.au`), so you may need to create and maintain a growing +collection of modules for the conversion between the various file formats. +There are also many different operations you might want to perform on sound data +(such as mixing, adding echo, applying an equalizer function, creating an +artificial stereo effect), so in addition you will be writing a never-ending +stream of modules to perform these operations. Here's a possible structure for +your package (expressed in terms of a hierarchical filesystem): + +.. code-block:: text + + sound/ Top-level package + __init__.py Initialize the sound package + formats/ Subpackage for file format conversions + __init__.py + wavread.py + wavwrite.py + aiffread.py + aiffwrite.py + auread.py + auwrite.py + ... + effects/ Subpackage for sound effects + __init__.py + echo.py + surround.py + reverse.py + ... + filters/ Subpackage for filters + __init__.py + equalizer.py + vocoder.py + karaoke.py + ... + +When importing the package, Python searches through the directories on +``sys.path`` looking for the package subdirectory. + +The :file:`__init__.py` files are required to make Python treat directories +containing the file as packages. This prevents directories with a common name, +such as ``string``, unintentionally hiding valid modules that occur later +on the module search path. In the simplest case, :file:`__init__.py` can just be +an empty file, but it can also execute initialization code for the package or +set the ``__all__`` variable, described later. + +Users of the package can import individual modules from the package, for +example:: + + import sound.effects.echo + +This loads the submodule :mod:`sound.effects.echo`. It must be referenced with +its full name. :: + + sound.effects.echo.echofilter(input, output, delay=0.7, atten=4) + +An alternative way of importing the submodule is:: + + from sound.effects import echo + +This also loads the submodule :mod:`echo`, and makes it available without its +package prefix, so it can be used as follows:: + + echo.echofilter(input, output, delay=0.7, atten=4) + +Yet another variation is to import the desired function or variable directly:: + + from sound.effects.echo import echofilter + +Again, this loads the submodule :mod:`echo`, but this makes its function +:func:`echofilter` directly available:: + + echofilter(input, output, delay=0.7, atten=4) + +Note that when using ``from package import item``, the item can be either a +submodule (or subpackage) of the package, or some other name defined in the +package, like a function, class or variable. The ``import`` statement first +tests whether the item is defined in the package; if not, it assumes it is a +module and attempts to load it. If it fails to find it, an :exc:`ImportError` +exception is raised. + +Contrarily, when using syntax like ``import item.subitem.subsubitem``, each item +except for the last must be a package; the last item can be a module or a +package but can't be a class or function or variable defined in the previous +item. + + +.. _tut-pkg-import-star: + +Importing \* From a Package +--------------------------- + +.. index:: single: __all__ + +Now what happens when the user writes ``from sound.effects import *``? Ideally, +one would hope that this somehow goes out to the filesystem, finds which +submodules are present in the package, and imports them all. This could take a +long time and importing sub-modules might have unwanted side-effects that should +only happen when the sub-module is explicitly imported. + +The only solution is for the package author to provide an explicit index of the +package. The :keyword:`import` statement uses the following convention: if a package's +:file:`__init__.py` code defines a list named ``__all__``, it is taken to be the +list of module names that should be imported when ``from package import *`` is +encountered. It is up to the package author to keep this list up-to-date when a +new version of the package is released. Package authors may also decide not to +support it, if they don't see a use for importing \* from their package. For +example, the file :file:`sound/effects/__init__.py` could contain the following +code:: + + __all__ = ["echo", "surround", "reverse"] + +This would mean that ``from sound.effects import *`` would import the three +named submodules of the :mod:`sound` package. + +If ``__all__`` is not defined, the statement ``from sound.effects import *`` +does *not* import all submodules from the package :mod:`sound.effects` into the +current namespace; it only ensures that the package :mod:`sound.effects` has +been imported (possibly running any initialization code in :file:`__init__.py`) +and then imports whatever names are defined in the package. This includes any +names defined (and submodules explicitly loaded) by :file:`__init__.py`. It +also includes any submodules of the package that were explicitly loaded by +previous :keyword:`import` statements. Consider this code:: + + import sound.effects.echo + import sound.effects.surround + from sound.effects import * + +In this example, the :mod:`echo` and :mod:`surround` modules are imported in the +current namespace because they are defined in the :mod:`sound.effects` package +when the ``from...import`` statement is executed. (This also works when +``__all__`` is defined.) + +Although certain modules are designed to export only names that follow certain +patterns when you use ``import *``, it is still considered bad practice in +production code. + +Remember, there is nothing wrong with using ``from package import +specific_submodule``! In fact, this is the recommended notation unless the +importing module needs to use submodules with the same name from different +packages. + + +Intra-package References +------------------------ + +When packages are structured into subpackages (as with the :mod:`sound` package +in the example), you can use absolute imports to refer to submodules of siblings +packages. For example, if the module :mod:`sound.filters.vocoder` needs to use +the :mod:`echo` module in the :mod:`sound.effects` package, it can use ``from +sound.effects import echo``. + +You can also write relative imports, with the ``from module import name`` form +of import statement. These imports use leading dots to indicate the current and +parent packages involved in the relative import. From the :mod:`surround` +module for example, you might use:: + + from . import echo + from .. import formats + from ..filters import equalizer + +Note that relative imports are based on the name of the current module. Since +the name of the main module is always ``"__main__"``, modules intended for use +as the main module of a Python application must always use absolute imports. + + +Packages in Multiple Directories +-------------------------------- + +Packages support one more special attribute, :attr:`__path__`. This is +initialized to be a list containing the name of the directory holding the +package's :file:`__init__.py` before the code in that file is executed. This +variable can be modified; doing so affects future searches for modules and +subpackages contained in the package. + +While this feature is not often needed, it can be used to extend the set of +modules found in a package. + + +.. rubric:: Footnotes + +.. [#] In fact function definitions are also 'statements' that are 'executed'; the + execution of a module-level function definition enters the function name in + the module's global symbol table. diff --git a/cpython_2/environment/repo/Doc/tutorial/stdlib.rst b/cpython_2/environment/repo/Doc/tutorial/stdlib.rst new file mode 100644 index 0000000000000000000000000000000000000000..a52653b94a32535a92265178453415ed22b3523a --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/stdlib.rst @@ -0,0 +1,353 @@ +.. _tut-brieftour: + +********************************** +Brief Tour of the Standard Library +********************************** + + +.. _tut-os-interface: + +Operating System Interface +========================== + +The :mod:`os` module provides dozens of functions for interacting with the +operating system:: + + >>> import os + >>> os.getcwd() # Return the current working directory + 'C:\\Python39' + >>> os.chdir('/server/accesslogs') # Change current working directory + >>> os.system('mkdir today') # Run the command mkdir in the system shell + 0 + +Be sure to use the ``import os`` style instead of ``from os import *``. This +will keep :func:`os.open` from shadowing the built-in :func:`open` function which +operates much differently. + +.. index:: builtin: help + +The built-in :func:`dir` and :func:`help` functions are useful as interactive +aids for working with large modules like :mod:`os`:: + + >>> import os + >>> dir(os) + + >>> help(os) + + +For daily file and directory management tasks, the :mod:`shutil` module provides +a higher level interface that is easier to use:: + + >>> import shutil + >>> shutil.copyfile('data.db', 'archive.db') + 'archive.db' + >>> shutil.move('/build/executables', 'installdir') + 'installdir' + + +.. _tut-file-wildcards: + +File Wildcards +============== + +The :mod:`glob` module provides a function for making file lists from directory +wildcard searches:: + + >>> import glob + >>> glob.glob('*.py') + ['primes.py', 'random.py', 'quote.py'] + + +.. _tut-command-line-arguments: + +Command Line Arguments +====================== + +Common utility scripts often need to process command line arguments. These +arguments are stored in the :mod:`sys` module's *argv* attribute as a list. For +instance the following output results from running ``python demo.py one two +three`` at the command line:: + + >>> import sys + >>> print(sys.argv) + ['demo.py', 'one', 'two', 'three'] + +The :mod:`argparse` module provides a more sophisticated mechanism to process +command line arguments. The following script extracts one or more filenames +and an optional number of lines to be displayed:: + + import argparse + + parser = argparse.ArgumentParser(prog = 'top', + description = 'Show top lines from each file') + parser.add_argument('filenames', nargs='+') + parser.add_argument('-l', '--lines', type=int, default=10) + args = parser.parse_args() + print(args) + +When run at the command line with ``python top.py --lines=5 alpha.txt +beta.txt``, the script sets ``args.lines`` to ``5`` and ``args.filenames`` +to ``['alpha.txt', 'beta.txt']``. + + +.. _tut-stderr: + +Error Output Redirection and Program Termination +================================================ + +The :mod:`sys` module also has attributes for *stdin*, *stdout*, and *stderr*. +The latter is useful for emitting warnings and error messages to make them +visible even when *stdout* has been redirected:: + + >>> sys.stderr.write('Warning, log file not found starting a new one\n') + Warning, log file not found starting a new one + +The most direct way to terminate a script is to use ``sys.exit()``. + + +.. _tut-string-pattern-matching: + +String Pattern Matching +======================= + +The :mod:`re` module provides regular expression tools for advanced string +processing. For complex matching and manipulation, regular expressions offer +succinct, optimized solutions:: + + >>> import re + >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') + ['foot', 'fell', 'fastest'] + >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') + 'cat in the hat' + +When only simple capabilities are needed, string methods are preferred because +they are easier to read and debug:: + + >>> 'tea for too'.replace('too', 'two') + 'tea for two' + + +.. _tut-mathematics: + +Mathematics +=========== + +The :mod:`math` module gives access to the underlying C library functions for +floating point math:: + + >>> import math + >>> math.cos(math.pi / 4) + 0.70710678118654757 + >>> math.log(1024, 2) + 10.0 + +The :mod:`random` module provides tools for making random selections:: + + >>> import random + >>> random.choice(['apple', 'pear', 'banana']) + 'apple' + >>> random.sample(range(100), 10) # sampling without replacement + [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] + >>> random.random() # random float + 0.17970987693706186 + >>> random.randrange(6) # random integer chosen from range(6) + 4 + +The :mod:`statistics` module calculates basic statistical properties +(the mean, median, variance, etc.) of numeric data:: + + >>> import statistics + >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] + >>> statistics.mean(data) + 1.6071428571428572 + >>> statistics.median(data) + 1.25 + >>> statistics.variance(data) + 1.3720238095238095 + +The SciPy project has many other modules for numerical +computations. + +.. _tut-internet-access: + +Internet Access +=============== + +There are a number of modules for accessing the internet and processing internet +protocols. Two of the simplest are :mod:`urllib.request` for retrieving data +from URLs and :mod:`smtplib` for sending mail:: + + >>> from urllib.request import urlopen + >>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response: + ... for line in response: + ... line = line.decode('utf-8') # Decoding the binary data to text. + ... if 'EST' in line or 'EDT' in line: # look for Eastern Time + ... print(line) + +
    Nov. 25, 09:43:32 PM EST + + >>> import smtplib + >>> server = smtplib.SMTP('localhost') + >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org', + ... """To: jcaesar@example.org + ... From: soothsayer@example.org + ... + ... Beware the Ides of March. + ... """) + >>> server.quit() + +(Note that the second example needs a mailserver running on localhost.) + + +.. _tut-dates-and-times: + +Dates and Times +=============== + +The :mod:`datetime` module supplies classes for manipulating dates and times in +both simple and complex ways. While date and time arithmetic is supported, the +focus of the implementation is on efficient member extraction for output +formatting and manipulation. The module also supports objects that are timezone +aware. :: + + >>> # dates are easily constructed and formatted + >>> from datetime import date + >>> now = date.today() + >>> now + datetime.date(2003, 12, 2) + >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") + '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.' + + >>> # dates support calendar arithmetic + >>> birthday = date(1964, 7, 31) + >>> age = now - birthday + >>> age.days + 14368 + + +.. _tut-data-compression: + +Data Compression +================ + +Common data archiving and compression formats are directly supported by modules +including: :mod:`zlib`, :mod:`gzip`, :mod:`bz2`, :mod:`lzma`, :mod:`zipfile` and +:mod:`tarfile`. :: + + >>> import zlib + >>> s = b'witch which has which witches wrist watch' + >>> len(s) + 41 + >>> t = zlib.compress(s) + >>> len(t) + 37 + >>> zlib.decompress(t) + b'witch which has which witches wrist watch' + >>> zlib.crc32(s) + 226805979 + + +.. _tut-performance-measurement: + +Performance Measurement +======================= + +Some Python users develop a deep interest in knowing the relative performance of +different approaches to the same problem. Python provides a measurement tool +that answers those questions immediately. + +For example, it may be tempting to use the tuple packing and unpacking feature +instead of the traditional approach to swapping arguments. The :mod:`timeit` +module quickly demonstrates a modest performance advantage:: + + >>> from timeit import Timer + >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() + 0.57535828626024577 + >>> Timer('a,b = b,a', 'a=1; b=2').timeit() + 0.54962537085770791 + +In contrast to :mod:`timeit`'s fine level of granularity, the :mod:`profile` and +:mod:`pstats` modules provide tools for identifying time critical sections in +larger blocks of code. + + +.. _tut-quality-control: + +Quality Control +=============== + +One approach for developing high quality software is to write tests for each +function as it is developed and to run those tests frequently during the +development process. + +The :mod:`doctest` module provides a tool for scanning a module and validating +tests embedded in a program's docstrings. Test construction is as simple as +cutting-and-pasting a typical call along with its results into the docstring. +This improves the documentation by providing the user with an example and it +allows the doctest module to make sure the code remains true to the +documentation:: + + def average(values): + """Computes the arithmetic mean of a list of numbers. + + >>> print(average([20, 30, 70])) + 40.0 + """ + return sum(values) / len(values) + + import doctest + doctest.testmod() # automatically validate the embedded tests + +The :mod:`unittest` module is not as effortless as the :mod:`doctest` module, +but it allows a more comprehensive set of tests to be maintained in a separate +file:: + + import unittest + + class TestStatisticalFunctions(unittest.TestCase): + + def test_average(self): + self.assertEqual(average([20, 30, 70]), 40.0) + self.assertEqual(round(average([1, 5, 7]), 1), 4.3) + with self.assertRaises(ZeroDivisionError): + average([]) + with self.assertRaises(TypeError): + average(20, 30, 70) + + unittest.main() # Calling from the command line invokes all tests + + +.. _tut-batteries-included: + +Batteries Included +================== + +Python has a "batteries included" philosophy. This is best seen through the +sophisticated and robust capabilities of its larger packages. For example: + +* The :mod:`xmlrpc.client` and :mod:`xmlrpc.server` modules make implementing + remote procedure calls into an almost trivial task. Despite the modules + names, no direct knowledge or handling of XML is needed. + +* The :mod:`email` package is a library for managing email messages, including + MIME and other :rfc:`2822`-based message documents. Unlike :mod:`smtplib` and + :mod:`poplib` which actually send and receive messages, the email package has + a complete toolset for building or decoding complex message structures + (including attachments) and for implementing internet encoding and header + protocols. + +* The :mod:`json` package provides robust support for parsing this + popular data interchange format. The :mod:`csv` module supports + direct reading and writing of files in Comma-Separated Value format, + commonly supported by databases and spreadsheets. XML processing is + supported by the :mod:`xml.etree.ElementTree`, :mod:`xml.dom` and + :mod:`xml.sax` packages. Together, these modules and packages + greatly simplify data interchange between Python applications and + other tools. + +* The :mod:`sqlite3` module is a wrapper for the SQLite database + library, providing a persistent database that can be updated and + accessed using slightly nonstandard SQL syntax. + +* Internationalization is supported by a number of modules including + :mod:`gettext`, :mod:`locale`, and the :mod:`codecs` package. diff --git a/cpython_2/environment/repo/Doc/tutorial/stdlib2.rst b/cpython_2/environment/repo/Doc/tutorial/stdlib2.rst new file mode 100644 index 0000000000000000000000000000000000000000..299482856ff324716618538007e74c2833a92554 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/stdlib2.rst @@ -0,0 +1,405 @@ +.. _tut-brieftourtwo: + +********************************************** +Brief Tour of the Standard Library --- Part II +********************************************** + +This second tour covers more advanced modules that support professional +programming needs. These modules rarely occur in small scripts. + + +.. _tut-output-formatting: + +Output Formatting +================= + +The :mod:`reprlib` module provides a version of :func:`repr` customized for +abbreviated displays of large or deeply nested containers:: + + >>> import reprlib + >>> reprlib.repr(set('supercalifragilisticexpialidocious')) + "{'a', 'c', 'd', 'e', 'f', 'g', ...}" + +The :mod:`pprint` module offers more sophisticated control over printing both +built-in and user defined objects in a way that is readable by the interpreter. +When the result is longer than one line, the "pretty printer" adds line breaks +and indentation to more clearly reveal data structure:: + + >>> import pprint + >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', + ... 'yellow'], 'blue']]] + ... + >>> pprint.pprint(t, width=30) + [[[['black', 'cyan'], + 'white', + ['green', 'red']], + [['magenta', 'yellow'], + 'blue']]] + +The :mod:`textwrap` module formats paragraphs of text to fit a given screen +width:: + + >>> import textwrap + >>> doc = """The wrap() method is just like fill() except that it returns + ... a list of strings instead of one big string with newlines to separate + ... the wrapped lines.""" + ... + >>> print(textwrap.fill(doc, width=40)) + The wrap() method is just like fill() + except that it returns a list of strings + instead of one big string with newlines + to separate the wrapped lines. + +The :mod:`locale` module accesses a database of culture specific data formats. +The grouping attribute of locale's format function provides a direct way of +formatting numbers with group separators:: + + >>> import locale + >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') + 'English_United States.1252' + >>> conv = locale.localeconv() # get a mapping of conventions + >>> x = 1234567.8 + >>> locale.format("%d", x, grouping=True) + '1,234,567' + >>> locale.format_string("%s%.*f", (conv['currency_symbol'], + ... conv['frac_digits'], x), grouping=True) + '$1,234,567.80' + + +.. _tut-templating: + +Templating +========== + +The :mod:`string` module includes a versatile :class:`~string.Template` class +with a simplified syntax suitable for editing by end-users. This allows users +to customize their applications without having to alter the application. + +The format uses placeholder names formed by ``$`` with valid Python identifiers +(alphanumeric characters and underscores). Surrounding the placeholder with +braces allows it to be followed by more alphanumeric letters with no intervening +spaces. Writing ``$$`` creates a single escaped ``$``:: + + >>> from string import Template + >>> t = Template('${village}folk send $$10 to $cause.') + >>> t.substitute(village='Nottingham', cause='the ditch fund') + 'Nottinghamfolk send $10 to the ditch fund.' + +The :meth:`~string.Template.substitute` method raises a :exc:`KeyError` when a +placeholder is not supplied in a dictionary or a keyword argument. For +mail-merge style applications, user supplied data may be incomplete and the +:meth:`~string.Template.safe_substitute` method may be more appropriate --- +it will leave placeholders unchanged if data is missing:: + + >>> t = Template('Return the $item to $owner.') + >>> d = dict(item='unladen swallow') + >>> t.substitute(d) + Traceback (most recent call last): + ... + KeyError: 'owner' + >>> t.safe_substitute(d) + 'Return the unladen swallow to $owner.' + +Template subclasses can specify a custom delimiter. For example, a batch +renaming utility for a photo browser may elect to use percent signs for +placeholders such as the current date, image sequence number, or file format:: + + >>> import time, os.path + >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg'] + >>> class BatchRename(Template): + ... delimiter = '%' + >>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ') + Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f + + >>> t = BatchRename(fmt) + >>> date = time.strftime('%d%b%y') + >>> for i, filename in enumerate(photofiles): + ... base, ext = os.path.splitext(filename) + ... newname = t.substitute(d=date, n=i, f=ext) + ... print('{0} --> {1}'.format(filename, newname)) + + img_1074.jpg --> Ashley_0.jpg + img_1076.jpg --> Ashley_1.jpg + img_1077.jpg --> Ashley_2.jpg + +Another application for templating is separating program logic from the details +of multiple output formats. This makes it possible to substitute custom +templates for XML files, plain text reports, and HTML web reports. + + +.. _tut-binary-formats: + +Working with Binary Data Record Layouts +======================================= + +The :mod:`struct` module provides :func:`~struct.pack` and +:func:`~struct.unpack` functions for working with variable length binary +record formats. The following example shows +how to loop through header information in a ZIP file without using the +:mod:`zipfile` module. Pack codes ``"H"`` and ``"I"`` represent two and four +byte unsigned numbers respectively. The ``"<"`` indicates that they are +standard size and in little-endian byte order:: + + import struct + + with open('myfile.zip', 'rb') as f: + data = f.read() + + start = 0 + for i in range(3): # show the first 3 file headers + start += 14 + fields = struct.unpack('>> import weakref, gc + >>> class A: + ... def __init__(self, value): + ... self.value = value + ... def __repr__(self): + ... return str(self.value) + ... + >>> a = A(10) # create a reference + >>> d = weakref.WeakValueDictionary() + >>> d['primary'] = a # does not create a reference + >>> d['primary'] # fetch the object if it is still alive + 10 + >>> del a # remove the one reference + >>> gc.collect() # run garbage collection right away + 0 + >>> d['primary'] # entry was automatically removed + Traceback (most recent call last): + File "", line 1, in + d['primary'] # entry was automatically removed + File "C:/python39/lib/weakref.py", line 46, in __getitem__ + o = self.data[key]() + KeyError: 'primary' + + +.. _tut-list-tools: + +Tools for Working with Lists +============================ + +Many data structure needs can be met with the built-in list type. However, +sometimes there is a need for alternative implementations with different +performance trade-offs. + +The :mod:`array` module provides an :class:`~array.array()` object that is like +a list that stores only homogeneous data and stores it more compactly. The +following example shows an array of numbers stored as two byte unsigned binary +numbers (typecode ``"H"``) rather than the usual 16 bytes per entry for regular +lists of Python int objects:: + + >>> from array import array + >>> a = array('H', [4000, 10, 700, 22222]) + >>> sum(a) + 26932 + >>> a[1:3] + array('H', [10, 700]) + +The :mod:`collections` module provides a :class:`~collections.deque()` object +that is like a list with faster appends and pops from the left side but slower +lookups in the middle. These objects are well suited for implementing queues +and breadth first tree searches:: + + >>> from collections import deque + >>> d = deque(["task1", "task2", "task3"]) + >>> d.append("task4") + >>> print("Handling", d.popleft()) + Handling task1 + +:: + + unsearched = deque([starting_node]) + def breadth_first_search(unsearched): + node = unsearched.popleft() + for m in gen_moves(node): + if is_goal(m): + return m + unsearched.append(m) + +In addition to alternative list implementations, the library also offers other +tools such as the :mod:`bisect` module with functions for manipulating sorted +lists:: + + >>> import bisect + >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')] + >>> bisect.insort(scores, (300, 'ruby')) + >>> scores + [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')] + +The :mod:`heapq` module provides functions for implementing heaps based on +regular lists. The lowest valued entry is always kept at position zero. This +is useful for applications which repeatedly access the smallest element but do +not want to run a full list sort:: + + >>> from heapq import heapify, heappop, heappush + >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] + >>> heapify(data) # rearrange the list into heap order + >>> heappush(data, -5) # add a new entry + >>> [heappop(data) for i in range(3)] # fetch the three smallest entries + [-5, 0, 1] + + +.. _tut-decimal-fp: + +Decimal Floating Point Arithmetic +================================= + +The :mod:`decimal` module offers a :class:`~decimal.Decimal` datatype for +decimal floating point arithmetic. Compared to the built-in :class:`float` +implementation of binary floating point, the class is especially helpful for + +* financial applications and other uses which require exact decimal + representation, +* control over precision, +* control over rounding to meet legal or regulatory requirements, +* tracking of significant decimal places, or +* applications where the user expects the results to match calculations done by + hand. + +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 * + >>> round(Decimal('0.70') * Decimal('1.05'), 2) + Decimal('0.74') + >>> round(.70 * 1.05, 2) + 0.73 + +The :class:`~decimal.Decimal` result keeps a trailing zero, automatically +inferring four place significance from multiplicands with two place +significance. Decimal reproduces mathematics as done by hand and avoids +issues that can arise when binary floating point cannot exactly represent +decimal quantities. + +Exact representation enables the :class:`~decimal.Decimal` class to perform +modulo calculations and equality tests that are unsuitable for binary floating +point:: + + >>> Decimal('1.00') % Decimal('.10') + Decimal('0.00') + >>> 1.00 % 0.10 + 0.09999999999999995 + + >>> sum([Decimal('0.1')]*10) == Decimal('1.0') + True + >>> sum([0.1]*10) == 1.0 + False + +The :mod:`decimal` module provides arithmetic with as much precision as needed:: + + >>> getcontext().prec = 36 + >>> Decimal(1) / Decimal(7) + Decimal('0.142857142857142857142857142857142857') + + diff --git a/cpython_2/environment/repo/Doc/tutorial/venv.rst b/cpython_2/environment/repo/Doc/tutorial/venv.rst new file mode 100644 index 0000000000000000000000000000000000000000..f422146aae8a30ec2565a00b6420cc1f12697696 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/venv.rst @@ -0,0 +1,216 @@ + +.. _tut-venv: + +********************************* +Virtual Environments and Packages +********************************* + +Introduction +============ + +Python applications will often use packages and modules that don't +come as part of the standard library. Applications will sometimes +need a specific version of a library, because the application may +require that a particular bug has been fixed or the application may be +written using an obsolete version of the library's interface. + +This means it may not be possible for one Python installation to meet +the requirements of every application. If application A needs version +1.0 of a particular module but application B needs version 2.0, then +the requirements are in conflict and installing either version 1.0 or 2.0 +will leave one application unable to run. + +The solution for this problem is to create a :term:`virtual environment`, a +self-contained directory tree that contains a Python installation for a +particular version of Python, plus a number of additional packages. + +Different applications can then use different virtual environments. +To resolve the earlier example of conflicting requirements, +application A can have its own virtual environment with version 1.0 +installed while application B has another virtual environment with version 2.0. +If application B requires a library be upgraded to version 3.0, this will +not affect application A's environment. + + +Creating Virtual Environments +============================= + +The module used to create and manage virtual environments is called +:mod:`venv`. :mod:`venv` will usually install the most recent version of +Python that you have available. If you have multiple versions of Python on your +system, you can select a specific Python version by running ``python3`` or +whichever version you want. + +To create a virtual environment, decide upon a directory where you want to +place it, and run the :mod:`venv` module as a script with the directory path:: + + python3 -m venv tutorial-env + +This will create the ``tutorial-env`` directory if it doesn't exist, +and also create directories inside it containing a copy of the Python +interpreter, the standard library, and various supporting files. + +A common directory location for a virtual environment is ``.venv``. +This name keeps the directory typically hidden in your shell and thus +out of the way while giving it a name that explains why the directory +exists. It also prevents clashing with ``.env`` environment variable +definition files that some tooling supports. + +Once you've created a virtual environment, you may activate it. + +On Windows, run:: + + tutorial-env\Scripts\activate.bat + +On Unix or MacOS, run:: + + source tutorial-env/bin/activate + +(This script is written for the bash shell. If you use the +:program:`csh` or :program:`fish` shells, there are alternate +``activate.csh`` and ``activate.fish`` scripts you should use +instead.) + +Activating the virtual environment will change your shell's prompt to show what +virtual environment you're using, and modify the environment so that running +``python`` will get you that particular version and installation of Python. +For example: + +.. code-block:: bash + + $ source ~/envs/tutorial-env/bin/activate + (tutorial-env) $ python + Python 3.5.1 (default, May 6 2016, 10:59:36) + ... + >>> import sys + >>> sys.path + ['', '/usr/local/lib/python35.zip', ..., + '~/envs/tutorial-env/lib/python3.5/site-packages'] + >>> + + +Managing Packages with pip +========================== + +You can install, upgrade, and remove packages using a program called +:program:`pip`. By default ``pip`` will install packages from the Python +Package Index, . You can browse the Python +Package Index by going to it in your web browser, or you can use ``pip``'s +limited search feature: + +.. code-block:: bash + + (tutorial-env) $ pip search astronomy + skyfield - Elegant astronomy for Python + gary - Galactic astronomy and gravitational dynamics. + novas - The United States Naval Observatory NOVAS astronomy library + astroobs - Provides astronomy ephemeris to plan telescope observations + PyAstronomy - A collection of astronomy related tools for Python. + ... + +``pip`` has a number of subcommands: "search", "install", "uninstall", +"freeze", etc. (Consult the :ref:`installing-index` guide for +complete documentation for ``pip``.) + +You can install the latest version of a package by specifying a package's name: + +.. code-block:: bash + + (tutorial-env) $ python -m pip install novas + Collecting novas + Downloading novas-3.1.1.3.tar.gz (136kB) + Installing collected packages: novas + Running setup.py install for novas + Successfully installed novas-3.1.1.3 + +You can also install a specific version of a package by giving the +package name followed by ``==`` and the version number: + +.. code-block:: bash + + (tutorial-env) $ python -m pip install requests==2.6.0 + Collecting requests==2.6.0 + Using cached requests-2.6.0-py2.py3-none-any.whl + Installing collected packages: requests + Successfully installed requests-2.6.0 + +If you re-run this command, ``pip`` will notice that the requested +version is already installed and do nothing. You can supply a +different version number to get that version, or you can run ``pip +install --upgrade`` to upgrade the package to the latest version: + +.. code-block:: bash + + (tutorial-env) $ python -m pip install --upgrade requests + Collecting requests + Installing collected packages: requests + Found existing installation: requests 2.6.0 + Uninstalling requests-2.6.0: + Successfully uninstalled requests-2.6.0 + Successfully installed requests-2.7.0 + +``pip uninstall`` followed by one or more package names will remove the +packages from the virtual environment. + +``pip show`` will display information about a particular package: + +.. code-block:: bash + + (tutorial-env) $ pip show requests + --- + Metadata-Version: 2.0 + Name: requests + Version: 2.7.0 + Summary: Python HTTP for Humans. + Home-page: http://python-requests.org + Author: Kenneth Reitz + Author-email: me@kennethreitz.com + License: Apache 2.0 + Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages + Requires: + +``pip list`` will display all of the packages installed in the virtual +environment: + +.. code-block:: bash + + (tutorial-env) $ pip list + novas (3.1.1.3) + numpy (1.9.2) + pip (7.0.3) + requests (2.7.0) + setuptools (16.0) + +``pip freeze`` will produce a similar list of the installed packages, +but the output uses the format that ``pip install`` expects. +A common convention is to put this list in a ``requirements.txt`` file: + +.. code-block:: bash + + (tutorial-env) $ pip freeze > requirements.txt + (tutorial-env) $ cat requirements.txt + novas==3.1.1.3 + numpy==1.9.2 + requests==2.7.0 + +The ``requirements.txt`` can then be committed to version control and +shipped as part of an application. Users can then install all the +necessary packages with ``install -r``: + +.. code-block:: bash + + (tutorial-env) $ python -m pip install -r requirements.txt + Collecting novas==3.1.1.3 (from -r requirements.txt (line 1)) + ... + Collecting numpy==1.9.2 (from -r requirements.txt (line 2)) + ... + Collecting requests==2.7.0 (from -r requirements.txt (line 3)) + ... + Installing collected packages: novas, numpy, requests + Running setup.py install for novas + Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0 + +``pip`` has many more options. Consult the :ref:`installing-index` +guide for complete documentation for ``pip``. When you've written +a package and want to make it available on the Python Package Index, +consult the :ref:`distributing-index` guide. diff --git a/cpython_2/environment/repo/Doc/tutorial/whatnow.rst b/cpython_2/environment/repo/Doc/tutorial/whatnow.rst new file mode 100644 index 0000000000000000000000000000000000000000..3208201312b8710a791f1207c5fc36322a612888 --- /dev/null +++ b/cpython_2/environment/repo/Doc/tutorial/whatnow.rst @@ -0,0 +1,76 @@ +.. _tut-whatnow: + +********* +What Now? +********* + +Reading this tutorial has probably reinforced your interest in using Python --- +you should be eager to apply Python to solving your real-world problems. Where +should you go to learn more? + +This tutorial is part of Python's documentation set. Some other documents in +the set are: + +* :ref:`library-index`: + + You should browse through this manual, which gives complete (though terse) + reference material about types, functions, and the modules in the standard + library. The standard Python distribution includes a *lot* of additional code. + There are modules to read Unix mailboxes, retrieve documents via HTTP, generate + random numbers, parse command-line options, write CGI programs, compress data, + and many other tasks. Skimming through the Library Reference will give you an + idea of what's available. + +* :ref:`installing-index` explains how to install additional modules written + by other Python users. + +* :ref:`reference-index`: A detailed explanation of Python's syntax and + semantics. It's heavy reading, but is useful as a complete guide to the + language itself. + +More Python resources: + +* https://www.python.org: The major Python Web site. It contains code, + documentation, and pointers to Python-related pages around the Web. This Web + site is mirrored in various places around the world, such as Europe, Japan, and + Australia; a mirror may be faster than the main site, depending on your + geographical location. + +* https://docs.python.org: Fast access to Python's documentation. + +* https://pypi.org: The Python Package Index, previously also nicknamed + the Cheese Shop [#]_, is an index of user-created Python modules that are available + for download. Once you begin releasing code, you can register it here so that + others can find it. + +* https://code.activestate.com/recipes/langs/python/: The Python Cookbook is a + sizable collection of code examples, larger modules, and useful scripts. + Particularly notable contributions are collected in a book also titled Python + Cookbook (O'Reilly & Associates, ISBN 0-596-00797-3.) + +* http://www.pyvideo.org collects links to Python-related videos from + conferences and user-group meetings. + +* https://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, + random number distributions, statistical analysis and the like. + +For Python-related questions and problem reports, you can post to the newsgroup +:newsgroup:`comp.lang.python`, or send them to the mailing list at +python-list@python.org. The newsgroup and mailing list are gatewayed, so +messages posted to one will automatically be forwarded to the other. There are +hundreds of postings a day, asking (and +answering) questions, suggesting new features, and announcing new modules. +Mailing list archives are available at https://mail.python.org/pipermail/. + +Before posting, be sure to check the list of +:ref:`Frequently Asked Questions ` (also called the FAQ). The +FAQ answers many of the questions that come up again and again, and may +already contain the solution for your problem. + +.. rubric:: Footnotes + +.. [#] "Cheese Shop" is a Monty Python's sketch: a customer enters a cheese shop, + but whatever cheese he asks for, the clerk says it's missing. + diff --git a/cpython_2/environment/repo/Doc/using/cmdline.rst b/cpython_2/environment/repo/Doc/using/cmdline.rst new file mode 100644 index 0000000000000000000000000000000000000000..b0911956a9eb8688118f3176ad086d6a3330e65d --- /dev/null +++ b/cpython_2/environment/repo/Doc/using/cmdline.rst @@ -0,0 +1,966 @@ +.. highlight:: sh + +.. ATTENTION: You probably should update Misc/python.man, too, if you modify + this file. + +.. _using-on-general: + +Command line and environment +============================ + +The CPython interpreter scans the command line and the environment for various +settings. + +.. impl-detail:: + + Other implementations' command line schemes may differ. See + :ref:`implementations` for further resources. + + +.. _using-on-cmdline: + +Command line +------------ + +When invoking Python, you may specify any of these options:: + + python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args] + +The most common use case is, of course, a simple invocation of a script:: + + python myscript.py + + +.. _using-on-interface-options: + +Interface options +~~~~~~~~~~~~~~~~~ + +The interpreter interface resembles that of the UNIX shell, but provides some +additional methods of invocation: + +* When called with standard input connected to a tty device, it prompts for + commands and executes them until an EOF (an end-of-file character, you can + produce that with :kbd:`Ctrl-D` on UNIX or :kbd:`Ctrl-Z, Enter` on Windows) is read. +* When called with a file name argument or with a file as standard input, it + reads and executes a script from that file. +* When called with a directory name argument, it reads and executes an + appropriately named script from that directory. +* When called with ``-c command``, it executes the Python statement(s) given as + *command*. Here *command* may contain multiple statements separated by + newlines. Leading whitespace is significant in Python statements! +* When called with ``-m module-name``, the given module is located on the + Python module path and executed as a script. + +In non-interactive mode, the entire input is parsed before it is executed. + +An interface option terminates the list of options consumed by the interpreter, +all consecutive arguments will end up in :data:`sys.argv` -- note that the first +element, subscript zero (``sys.argv[0]``), is a string reflecting the program's +source. + +.. cmdoption:: -c + + Execute the Python code in *command*. *command* can be one or 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 + level modules). + + .. audit-event:: cpython.run_command command cmdoption-c + +.. cmdoption:: -m + + 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 absolute Python module name, but + the implementation may not always enforce this (e.g. it may allow you to + use a name that includes a hyphen). + + Package names (including namespace packages) are also permitted. When a + package name is supplied instead + of a normal module, the interpreter will execute ``.__main__`` as + the main module. This behaviour is deliberately similar to the handling + of directories and zipfiles that are passed to the interpreter as the + script argument. + + .. note:: + + This option cannot be used with built-in modules and extension modules + 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 (while the module file is being located, the + first element will be set to ``"-m"``). As with the :option:`-c` option, + the current directory will be added to the start of :data:`sys.path`. + + :option:`-I` option can be used to run the script in isolated mode where + :data:`sys.path` contains neither the current directory nor the user's + site-packages directory. All :envvar:`PYTHON*` environment variables are + ignored, too. + + Many standard library modules contain code that is invoked on their execution + as a script. An example is the :mod:`timeit` module:: + + python -m timeit -s 'setup here' 'benchmarked code here' + python -m timeit -h # for details + + .. audit-event:: cpython.run_module module-name cmdoption-m + + .. seealso:: + :func:`runpy.run_module` + Equivalent functionality directly available to Python code + + :pep:`338` -- Executing modules as scripts + + .. versionchanged:: 3.1 + Supply the package name to run a ``__main__`` submodule. + + .. versionchanged:: 3.4 + namespace packages are also supported + +.. _cmdarg-dash: + +.. describe:: - + + Read commands from standard input (:data:`sys.stdin`). If standard input is + a terminal, :option:`-i` is implied. + + If this option is given, the first element of :data:`sys.argv` will be + ``"-"`` and the current directory will be added to the start of + :data:`sys.path`. + + .. audit-event:: cpython.run_stdin "" "" + +.. _cmdarg-script: + +.. describe::