diff --git a/Doc/library/array.rst b/Doc/library/array.rst --- a/Doc/library/array.rst +++ b/Doc/library/array.rst @@ -49,7 +49,11 @@ The actual representation of values is d (strictly speaking, by the C implementation). The actual size can be accessed through the :attr:`itemsize` attribute. -The module defines the following type: +The module defines one constant and one type. + +.. data:: typecodes + + A string with all available type codes. .. class:: array(typecode[, initializer]) @@ -65,177 +69,178 @@ The module defines the following type: passed to the :meth:`extend` method. -.. data:: typecodes + Array objects support the ordinary sequence operations of indexing, slicing, + concatenation, and multiplication. When using slice assignment, the assigned + value must be an array object with the same type code; in all other cases, + :exc:`TypeError` is raised. Array objects also implement the buffer + interface, and may be used wherever buffer objects are supported. - A string with all available type codes. + The following data items and methods are also supported: -Array objects support the ordinary sequence operations of indexing, slicing, -concatenation, and multiplication. When using slice assignment, the assigned -value must be an array object with the same type code; in all other cases, -:exc:`TypeError` is raised. Array objects also implement the buffer interface, -and may be used wherever buffer objects are supported. + .. attribute:: array.typecode -The following data items and methods are also supported: + The typecode character used to create the array. -.. attribute:: array.typecode - The typecode character used to create the array. + .. attribute:: array.itemsize + The length in bytes of one array item in the internal representation. -.. attribute:: array.itemsize - The length in bytes of one array item in the internal representation. + .. method:: append(x) + Append a new item with value *x* to the end of the array. -.. method:: array.append(x) - Append a new item with value *x* to the end of the array. + .. method:: buffer_info() + Return a tuple ``(address, length)`` giving the current memory address and + the length in elements of the buffer used to hold array's contents. The + size of the memory buffer in bytes can be computed as + ``array.buffer_info()[1] * array.itemsize``. This is occasionally useful + when working with low-level (and inherently unsafe) I/O interfaces that + require memory addresses, such as certain :c:func:`ioctl` operations. The + returned numbers are valid as long as the array exists and no + length-changing operations are applied to it. -.. method:: array.buffer_info() + .. note:: - Return a tuple ``(address, length)`` giving the current memory address and the - length in elements of the buffer used to hold array's contents. The size of the - memory buffer in bytes can be computed as ``array.buffer_info()[1] * - array.itemsize``. This is occasionally useful when working with low-level (and - inherently unsafe) I/O interfaces that require memory addresses, such as certain - :c:func:`ioctl` operations. The returned numbers are valid as long as the array - exists and no length-changing operations are applied to it. + When using array objects from code written in C or C++ (the only way to + effectively make use of this information), it makes more sense to use + the buffer interface supported by array objects. This method is + maintained for backward compatibility and should be avoided in new + code. The buffer interface is documented in :ref:`bufferobjects`. - .. note:: - When using array objects from code written in C or C++ (the only way to - effectively make use of this information), it makes more sense to use the buffer - interface supported by array objects. This method is maintained for backward - compatibility and should be avoided in new code. The buffer interface is - documented in :ref:`bufferobjects`. + .. method:: byteswap() + "Byteswap" all items of the array. This is only supported for values + which are 1, 2, 4, or 8 bytes in size; for other types of values, + :exc:`RuntimeError` is raised. It is useful when reading data from a file + written on a machine with a different byte order. -.. method:: array.byteswap() - "Byteswap" all items of the array. This is only supported for values which are - 1, 2, 4, or 8 bytes in size; for other types of values, :exc:`RuntimeError` is - raised. It is useful when reading data from a file written on a machine with a - different byte order. + .. method:: count(x) + Return the number of occurrences of *x* in the array. -.. method:: array.count(x) - Return the number of occurrences of *x* in the array. + .. method:: extend(iterable) + Append items from *iterable* to the end of the array. If *iterable* is + another array, it must have *exactly* the same type code; if not, + :exc:`TypeError` will be raised. If *iterable* is not an array, it must + be iterable and its elements must be the right type to be appended to the + array. -.. method:: array.extend(iterable) - Append items from *iterable* to the end of the array. If *iterable* is another - array, it must have *exactly* the same type code; if not, :exc:`TypeError` will - be raised. If *iterable* is not an array, it must be iterable and its elements - must be the right type to be appended to the array. + .. method:: frombytes(s) + Appends items from the string, interpreting the string as an array of + machine values (as if it had been read from a file using the + :meth:`fromfile` method). -.. method:: array.frombytes(s) + .. versionadded:: 3.2 + :meth:`fromstring` is renamed to :meth:`frombytes` for clarity. - Appends items from the string, interpreting the string as an array of machine - values (as if it had been read from a file using the :meth:`fromfile` method). - .. versionadded:: 3.2 - :meth:`fromstring` is renamed to :meth:`frombytes` for clarity. + .. method:: fromfile(f, n) + Read *n* items (as machine values) from the :term:`file object` *f* and + append them to the end of the array. If less than *n* items are + available, :exc:`EOFError` is raised, but the items that were available + are still inserted into the array. *f* must be a real built-in file + object; something else with a :meth:`read` method won't do. -.. method:: array.fromfile(f, n) - Read *n* items (as machine values) from the :term:`file object` *f* and append - them to the end of the array. If less than *n* items are available, - :exc:`EOFError` is raised, but the items that were available are still - inserted into the array. *f* must be a real built-in file object; something - else with a :meth:`read` method won't do. + .. method:: fromlist(list) + Append items from the list. This is equivalent to ``for x in list: + a.append(x)`` except that if there is a type error, the array is + unchanged. -.. method:: array.fromlist(list) - Append items from the list. This is equivalent to ``for x in list: - a.append(x)`` except that if there is a type error, the array is unchanged. + .. method:: fromstring() + Deprecated alias for :meth:`frombytes`. -.. method:: array.fromstring() - Deprecated alias for :meth:`frombytes`. + .. method:: fromunicode(s) + Extends this array with data from the given unicode string. The array + must be a type ``'u'`` array; otherwise a :exc:`ValueError` is raised. + Use ``array.frombytes(unicodestring.encode(enc))`` to append Unicode data + to an array of some other type. -.. method:: array.fromunicode(s) - Extends this array with data from the given unicode string. The array must - be a type ``'u'`` array; otherwise a :exc:`ValueError` is raised. Use - ``array.frombytes(unicodestring.encode(enc))`` to append Unicode data to an - array of some other type. + .. method:: index(x) + Return the smallest *i* such that *i* is the index of the first occurrence + of *x* in the array. -.. method:: array.index(x) - Return the smallest *i* such that *i* is the index of the first occurrence of - *x* in the array. + .. method:: insert(i, x) + Insert a new item with value *x* in the array before position *i*. + Negative values are treated as being relative to the end of the array. -.. method:: array.insert(i, x) - Insert a new item with value *x* in the array before position *i*. Negative - values are treated as being relative to the end of the array. + .. method:: pop([i]) + Removes the item with the index *i* from the array and returns it. The + optional argument defaults to ``-1``, so that by default the last item is + removed and returned. -.. method:: array.pop([i]) - Removes the item with the index *i* from the array and returns it. The optional - argument defaults to ``-1``, so that by default the last item is removed and - returned. + .. method:: remove(x) + Remove the first occurrence of *x* from the array. -.. method:: array.remove(x) - Remove the first occurrence of *x* from the array. + .. method:: reverse() + Reverse the order of the items in the array. -.. method:: array.reverse() - Reverse the order of the items in the array. + .. method:: tobytes() + Convert the array to an array of machine values and return the bytes + representation (the same sequence of bytes that would be written to a file + by the :meth:`tofile` method.) -.. method:: array.tobytes() + .. versionadded:: 3.2 + :meth:`tostring` is renamed to :meth:`tobytes` for clarity. - Convert the array to an array of machine values and return the bytes - representation (the same sequence of bytes that would be written to a file by - the :meth:`tofile` method.) - .. versionadded:: 3.2 - :meth:`tostring` is renamed to :meth:`tobytes` for clarity. + .. method:: tofile(f) + Write all items (as machine values) to the :term:`file object` *f*. -.. method:: array.tofile(f) - Write all items (as machine values) to the :term:`file object` *f*. + .. method:: tolist() + Convert the array to an ordinary list with the same items. -.. method:: array.tolist() - Convert the array to an ordinary list with the same items. + .. method:: tostring() + Deprecated alias for :meth:`tobytes`. -.. method:: array.tostring() - Deprecated alias for :meth:`tobytes`. + .. method:: tounicode() - -.. method:: array.tounicode() - - Convert the array to a unicode string. The array must be a type ``'u'`` array; - otherwise a :exc:`ValueError` is raised. Use ``array.tobytes().decode(enc)`` to - obtain a unicode string from an array of some other type. + Convert the array to a unicode string. The array must be a type ``'u'`` + array; otherwise a :exc:`ValueError` is raised. Use + ``array.tobytes().decode(enc)`` to obtain a unicode string from an array + of some other type. When an array object is printed or converted to a string, it is represented as ``array(typecode, initializer)``. The *initializer* is omitted if the array is empty, otherwise it is a string if the *typecode* is ``'u'``, otherwise it is a list of numbers. The string is guaranteed to be able to be converted back to an -array with the same type and value using :func:`eval`, so long as the -:func:`array` function has been imported using ``from array import array``. +array with the same type and value using :func:`eval`, as long as the +:class:`array` type has been imported using ``from array import array``. Examples:: array('l') diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -670,55 +670,55 @@ In addition to the methods inherited fro three additional methods and one attribute. To prevent conflicts with field names, the method and attribute names start with an underscore. -.. classmethod:: somenamedtuple._make(iterable) +.. class:: somenamedtuple - Class method that makes a new instance from an existing sequence or iterable. + .. classmethod:: _make(iterable) -.. doctest:: + Class method that makes a new instance from an existing sequence or iterable. - >>> t = [11, 22] - >>> Point._make(t) - Point(x=11, y=22) + .. doctest:: -.. method:: somenamedtuple._asdict() + >>> t = [11, 22] + >>> Point._make(t) + Point(x=11, y=22) - Return a new :class:`OrderedDict` which maps field names to their corresponding - values:: + .. method:: _asdict() - >>> p._asdict() - OrderedDict([('x', 11), ('y', 22)]) + Return a new :class:`OrderedDict` which maps field names to their corresponding + values:: - .. versionchanged:: 3.1 - Returns an :class:`OrderedDict` instead of a regular :class:`dict`. + >>> p._asdict() + OrderedDict([('x', 11), ('y', 22)]) -.. method:: somenamedtuple._replace(kwargs) + .. versionchanged:: 3.1 + Returns an :class:`OrderedDict` instead of a regular :class:`dict`. - Return a new instance of the named tuple replacing specified fields with new - values: + .. method:: _replace(kwargs) -:: + Return a new instance of the named tuple replacing specified fields with new + values:: - >>> p = Point(x=11, y=22) - >>> p._replace(x=33) - Point(x=33, y=22) + >>> p = Point(x=11, y=22) + >>> p._replace(x=33) + Point(x=33, y=22) - >>> for partnum, record in inventory.items(): - ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now()) + >>> for partnum, record in inventory.items(): + ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now()) -.. attribute:: somenamedtuple._fields + .. attribute:: _fields - Tuple of strings listing the field names. Useful for introspection - and for creating new named tuple types from existing named tuples. + Tuple of strings listing the field names. Useful for introspection + and for creating new named tuple types from existing named tuples. -.. doctest:: + .. doctest:: - >>> p._fields # view the field names - ('x', 'y') + >>> p._fields # view the field names + ('x', 'y') - >>> Color = namedtuple('Color', 'red green blue') - >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) - >>> Pixel(11, 22, 128, 255, 0) - Pixel(x=11, y=22, red=128, green=255, blue=0) + >>> Color = namedtuple('Color', 'red green blue') + >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) + >>> Pixel(11, 22, 128, 255, 0) + Pixel(x=11, y=22, red=128, green=255, blue=0) To retrieve a field whose name is stored in a string, use the :func:`getattr` function: diff --git a/Doc/library/gettext.rst b/Doc/library/gettext.rst --- a/Doc/library/gettext.rst +++ b/Doc/library/gettext.rst @@ -347,46 +347,53 @@ while reading the file, instantiating a The following methods are overridden from the base class implementation: -.. method:: GNUTranslations.gettext(message) +.. class:: GNUTranslations - 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:`gettext` method. Otherwise, the *message* id is returned. + .. 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:`gettext` method. Otherwise, the + *message* id is returned. -.. method:: GNUTranslations.lgettext(message) - Equivalent to :meth:`gettext`, but the translation is returned as a - bytestring encoded in the selected output charset, or in the preferred system - encoding if no encoding was explicitly set with :meth:`set_output_charset`. + .. method:: lgettext(message) + Equivalent to :meth:`gettext`, but the translation is returned as a + bytestring encoded in the selected output charset, or in the preferred + system encoding if no encoding was explicitly set with + :meth:`set_output_charset`. -.. method:: GNUTranslations.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. + .. method:: ngettext(singular, plural, n) - If the message id is not found in the catalog, and a fallback is specified, the - request is forwarded to the fallback's :meth:`ngettext` method. Otherwise, when - *n* is 1 *singular* is returned, and *plural* is returned in all other cases. + 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. - Here is an example:: + If the message id is not found in the catalog, and a fallback is + specified, the request is forwarded to the fallback's :meth:`ngettext` + method. Otherwise, when *n* is 1 *singular* is returned, and *plural* is + returned in all other cases. - 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} + 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:: GNUTranslations.lngettext(singular, plural, n) - Equivalent to :meth:`gettext`, but the translation is returned as a - bytestring encoded in the selected output charset, or in the preferred system - encoding if no encoding was explicitly set with :meth:`set_output_charset`. + .. method:: lngettext(singular, plural, n) + + Equivalent to :meth:`gettext`, but the translation is returned as a + bytestring encoded in the selected output charset, or in the preferred + system encoding if no encoding was explicitly set with + :meth:`set_output_charset`. Solaris message catalog support @@ -617,19 +624,12 @@ The following people contributed code, f 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 diff --git a/Doc/library/hmac.rst b/Doc/library/hmac.rst --- a/Doc/library/hmac.rst +++ b/Doc/library/hmac.rst @@ -24,32 +24,35 @@ This module implements the HMAC algorith An HMAC object has the following methods: -.. method:: hmac.update(msg) +.. class:: HMAC - Update the hmac object with the bytes object *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)``. + .. method:: update(msg) + Update the hmac object with the bytes object *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)``. -.. 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. + .. method:: 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. -.. 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. + .. method:: 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. -.. 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. + .. method:: 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. .. seealso:: diff --git a/Doc/library/pipes.rst b/Doc/library/pipes.rst --- a/Doc/library/pipes.rst +++ b/Doc/library/pipes.rst @@ -16,22 +16,18 @@ The :mod:`pipes` module defines a class 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: +The :mod:`pipes` module defines one class: :class:`Template`. - -.. class:: Template() - - An abstraction of a pipeline. - -Example:: +Example use:: >>> import pipes - >>> t=pipes.Template() + >>> t = pipes.Template() >>> t.append('tr a-z A-Z', '--') - >>> f=t.open('/tmp/1', 'w') - >>> f.write('hello world') - >>> f.close() - >>> open('/tmp/1').read() + >>> with t.open('/tmp/1', 'w') as f: + ... f.write('hello world') + ... + >>> with open('/tmp/1') as f: + ... print(f.read()) 'HELLO WORLD' @@ -40,55 +36,55 @@ Example:: Template Objects ---------------- -Template objects following methods: +.. class:: Template() + An abstraction of a pipeline. Template objects have the following methods: -.. method:: Template.reset() + .. method:: reset() - Restore a pipeline template to its initial state. + Restore a pipeline template to its initial state. -.. method:: Template.clone() + .. method:: clone() - Return a new, equivalent, pipeline template. + Return a new, equivalent, pipeline template. -.. method:: Template.debug(flag) + .. method:: 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. + 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) + .. method:: 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. + 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.) + 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.) + 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) + .. method:: prepend(cmd, kind) - Add a new action at the beginning. See :meth:`append` for explanations of the - arguments. + Add a new action at the beginning. See :meth:`append` for explanations of + the arguments. -.. method:: Template.open(file, mode) + .. method:: 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. + 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) + .. method:: copy(infile, outfile) - Copy *infile* to *outfile* through the pipe. - + Copy *infile* to *outfile* through the pipe. diff --git a/Doc/library/rlcompleter.rst b/Doc/library/rlcompleter.rst --- a/Doc/library/rlcompleter.rst +++ b/Doc/library/rlcompleter.rst @@ -49,20 +49,22 @@ this module can still be used for custom Completer Objects ----------------- -Completer objects have the following method: +.. class:: Completer -.. method:: Completer.complete(text, state) + Completer objects have the following method: - Return the *state*\ th completion for *text*. + .. method:: complete(text, state) - 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). + Return the *state*\ th completion for *text*. - 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. + 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/Doc/library/tarfile.rst b/Doc/library/tarfile.rst --- a/Doc/library/tarfile.rst +++ b/Doc/library/tarfile.rst @@ -117,7 +117,7 @@ Some facts and figures: .. function:: is_tarfile(name) - Return :const:`True` if *name* is a tar archive file, that the :mod:`tarfile` + Return ``True`` if *name* is a tar archive file, that the :mod:`tarfile` module can read. @@ -222,7 +222,10 @@ be finalized; only the internally used f .. versionadded:: 3.2 Added support for the context manager 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) +.. 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. @@ -249,12 +252,12 @@ be finalized; only the internally used f 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 + If *dereference* is ``False``, add symbolic and hard links to the archive. If it + is ``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 + If *ignore_zeros* is ``False``, treat an empty block as the end of the archive. + If it is ``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 @@ -278,153 +281,158 @@ be finalized; only the internally used f will be added as a pax global header if *format* is :const:`PAX_FORMAT`. -.. method:: TarFile.open(...) + .. method:: open(...) - Alternative constructor. The :func:`tarfile.open` function is actually a - shortcut to this classmethod. + Alternative constructor. The :func:`tarfile.open` function is actually a + shortcut to this classmethod. -.. method:: TarFile.getmember(name) + .. method:: getmember(name) - Return a :class:`TarInfo` object for member *name*. If *name* can not be found - in the archive, :exc:`KeyError` is raised. + Return a :class:`TarInfo` object for member *name*. If *name* can not be + found in the archive, :exc:`KeyError` is raised. - .. note:: + .. note:: - If a member occurs more than once in the archive, its last occurrence is assumed - to be the most up-to-date version. + 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() + .. method:: 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. + 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() + .. method:: getnames() - Return the members as a list of their names. It has the same order as the list - returned by :meth:`getmembers`. + 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) + .. method:: list(verbose=True) - 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. + Print a table of contents to ``sys.stdout``. If *verbose* is + ``False``, only the names of the members are printed. If it is + ``True``, output similar to that of :program:`ls -l` is produced. -.. method:: TarFile.next() + .. method:: 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. + Return the next member of the archive as a :class:`TarInfo` object, when + :class:`TarFile` is opened for reading. Return ``None`` if there is + no more available. -.. method:: TarFile.extractall(path=".", members=None) + .. method:: extractall(path=".", members=None) - 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. + 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. - .. warning:: + .. 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 ``".."``. + 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 ``".."``. -.. method:: TarFile.extract(member, path="", set_attrs=True) + .. method:: extract(member, path="", set_attrs=True) - 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*. File attributes (owner, mtime, mode) are set unless - *set_attrs* is 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*. File attributes (owner, mtime, + mode) are set unless *set_attrs* is False. - .. note:: + .. note:: - The :meth:`extract` method does not take care of several extraction issues. - In most cases you should consider using the :meth:`extractall` method. + The :meth:`extract` method does not take care of several extraction + issues. In most cases you should consider using the :meth:`extractall` + method. - .. warning:: + .. warning:: - See the warning for :meth:`extractall`. + See the warning for :meth:`extractall`. - .. versionchanged:: 3.2 - Added the *set_attrs* parameter. + .. versionchanged:: 3.2 + Added the *set_attrs* parameter. -.. method:: TarFile.extractfile(member) + .. method:: 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, a :term:`file-like - object` is returned. If *member* is a link, a file-like object is constructed from - the link's target. If *member* is none of the above, :const:`None` is returned. + 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, a + :term:`file-like object` is returned. If *member* is a link, a file-like + object is constructed from the link's target. If *member* is none of the + above, ``None`` is returned. - .. note:: + .. note:: - The file-like object is read-only. It provides the methods - :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`seek`, :meth:`tell`, - and :meth:`close`, and also supports iteration over its lines. + The file-like object is read-only. It provides the methods + :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`seek`, + :meth:`tell`, and :meth:`close`, and also supports iteration over its + lines. -.. method:: TarFile.add(name, arcname=None, recursive=True, exclude=None, *, filter=None) + .. method:: add(name, arcname=None, recursive=True, exclude=None, *, 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`. If *exclude* is given, it must be a function that takes one - filename argument and returns a boolean value. Depending on this value the - respective file is either excluded (:const:`True`) or added - (:const:`False`). If *filter* is specified it must be a keyword argument. 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. + 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 + ``False``. If *exclude* is given, it must be a function that takes one + filename argument and returns a boolean value. Depending on this value the + respective file is either excluded (``True``) or added (``False``). If + *filter* is specified it must be a keyword argument. It should be a + function that takes a :class:`TarInfo` object argument and returns the + changed :class:`TarInfo` object. If it instead returns ``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.2 + Added the *filter* parameter. - .. deprecated:: 3.2 - The *exclude* parameter is deprecated, please use the *filter* parameter - instead. + .. deprecated:: 3.2 + The *exclude* parameter is deprecated, please use the *filter* parameter + instead. -.. method:: TarFile.addfile(tarinfo, fileobj=None) + .. method:: addfile(tarinfo, fileobj=None) - Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given, - ``tarinfo.size`` bytes are read from it and added to the archive. You can - create :class:`TarInfo` objects using :meth:`gettarinfo`. + Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is + given, ``tarinfo.size`` bytes are read from it and added to the archive. + You can create :class:`TarInfo` objects using :meth:`gettarinfo`. - .. note:: + .. note:: - On Windows platforms, *fileobj* should always be opened with mode ``'rb'`` to - avoid irritation about the file size. + On Windows platforms, *fileobj* should always be opened with mode + ``'rb'`` to avoid irritation about the file size. -.. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None) + .. method:: gettarinfo(name=None, arcname=None, fileobj=None) - Create a :class:`TarInfo` object for either the file *name* or the :term:`file - object` *fileobj* (using :func:`os.fstat` on its file descriptor). You can modify - some of the :class:`TarInfo`'s attributes before you add it using :meth:`addfile`. - If given, *arcname* specifies an alternative name for the file in the archive. + Create a :class:`TarInfo` object for either the file *name* or the + :term:`file object` *fileobj* (using :func:`os.fstat` on its file + descriptor). You can modify some of the :class:`TarInfo`'s attributes + before you add it using :meth:`addfile`. If given, *arcname* specifies an + alternative name for the file in the archive. -.. method:: TarFile.close() + .. method:: close() - Close the :class:`TarFile`. In write mode, two finishing zero blocks are - appended to the archive. + Close the :class:`TarFile`. In write mode, two finishing zero blocks are + appended to the archive. -.. attribute:: TarFile.pax_headers + .. attribute:: pax_headers - A dictionary containing key-value pairs of pax global headers. + A dictionary containing key-value pairs of pax global headers. @@ -447,137 +455,137 @@ It does *not* contain the file's data it Create a :class:`TarInfo` object. -.. method:: TarInfo.frombuf(buf) + .. method:: frombuf(buf) - Create and return a :class:`TarInfo` object from string buffer *buf*. + Create and return a :class:`TarInfo` object from string buffer *buf*. + Raises :exc:`HeaderError` if the buffer is invalid.. - Raises :exc:`HeaderError` if the buffer is invalid.. + .. method:: fromtarfile(tarfile) -.. method:: TarInfo.fromtarfile(tarfile) + Read the next member from the :class:`TarFile` object *tarfile* and return + it as a :class:`TarInfo` object. - Read the next member from the :class:`TarFile` object *tarfile* and return it as - a :class:`TarInfo` object. + .. method:: tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape') -.. 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. - 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. - .. versionchanged:: 3.2 - Use ``'surrogateescape'`` as the default for the *errors* argument. + A ``TarInfo`` object has the following public data attributes: -A ``TarInfo`` object has the following public data attributes: + .. attribute:: name -.. attribute:: TarInfo.name + Name of the archive member. - Name of the archive member. + .. attribute:: size -.. attribute:: TarInfo.size + Size in bytes. - Size in bytes. + .. attribute:: mtime -.. attribute:: TarInfo.mtime + Time of last modification. - Time of last modification. + .. attribute:: mode -.. attribute:: TarInfo.mode + Permission bits. - Permission bits. + .. attribute:: type -.. 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. - 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:: linkname -.. attribute:: TarInfo.linkname + Name of the target file name, which is only present in :class:`TarInfo` + objects of type :const:`LNKTYPE` and :const:`SYMTYPE`. - Name of the target file name, which is only present in :class:`TarInfo` objects - of type :const:`LNKTYPE` and :const:`SYMTYPE`. + .. attribute:: uid -.. attribute:: TarInfo.uid + User ID of the user who originally stored this member. - User ID of the user who originally stored this member. + .. attribute:: gid -.. attribute:: TarInfo.gid + Group ID of the user who originally stored this member. - Group ID of the user who originally stored this member. + .. attribute:: uname -.. attribute:: TarInfo.uname + User name. - User name. + .. attribute:: gname -.. attribute:: TarInfo.gname + Group name. - Group name. + .. attribute:: pax_headers -.. attribute:: TarInfo.pax_headers + A dictionary containing key-value pairs of an associated pax extended + header. - A dictionary containing key-value pairs of an associated pax extended header. + A :class:`TarInfo` object also provides some convenient query methods: -A :class:`TarInfo` object also provides some convenient query methods: + .. method:: isfile() -.. method:: TarInfo.isfile() + Return ``True`` if the :class:`Tarinfo` object is a regular file. - Return :const:`True` if the :class:`Tarinfo` object is a regular file. + .. method:: isreg() -.. method:: TarInfo.isreg() + Same as :meth:`isfile`. - Same as :meth:`isfile`. + .. method:: isdir() -.. method:: TarInfo.isdir() + Return ``True`` if it is a directory. - Return :const:`True` if it is a directory. + .. method:: issym() -.. method:: TarInfo.issym() + Return ``True`` if it is a symbolic link. - Return :const:`True` if it is a symbolic link. + .. method:: islnk() -.. method:: TarInfo.islnk() + Return ``True`` if it is a hard link. - Return :const:`True` if it is a hard link. + .. method:: ischr() -.. method:: TarInfo.ischr() + Return ``True`` if it is a character device. - Return :const:`True` if it is a character device. + .. method:: isblk() -.. method:: TarInfo.isblk() + Return ``True`` if it is a block device. - Return :const:`True` if it is a block device. + .. method:: isfifo() -.. method:: TarInfo.isfifo() + Return ``True`` if it is a FIFO. - Return :const:`True` if it is a FIFO. + .. method:: isdev() -.. method:: TarInfo.isdev() - - Return :const:`True` if it is one of character device, block device or FIFO. + Return ``True`` if it is one of character device, block device or FIFO. .. _tar-examples: @@ -723,4 +731,3 @@ In case of :const:`PAX_FORMAT` archives, 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/Doc/library/timeit.rst b/Doc/library/timeit.rst --- a/Doc/library/timeit.rst +++ b/Doc/library/timeit.rst @@ -25,11 +25,11 @@ The module defines the following public 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 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. To measure the execution time of the first statement, use the :meth:`timeit` method. The :meth:`repeat` method is a convenience to call :meth:`timeit` @@ -41,62 +41,64 @@ The module defines the following public little larger in this case because of the extra function calls. -.. method:: Timer.print_exc(file=None) + .. method:: print_exc(file=None) - Helper to print a traceback from the timed code. + Helper to print a traceback from the timed code. - Typical use:: + Typical use:: - t = Timer(...) # outside the try/except - try: - t.timeit(...) # or t.repeat(...) - except: - t.print_exc() + t = Timer(...) # outside the try/except + try: + t.timeit(...) # or t.repeat(...) + except: + 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 ``sys.stderr``. + 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 ``sys.stderr``. -.. method:: Timer.repeat(repeat=3, number=1000000) + .. method:: repeat(repeat=3, number=1000000) - Call :meth:`timeit` a few times. + 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 - :func:`timeit`. + 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 :func:`timeit`. - .. note:: + .. 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. + 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. -.. method:: Timer.timeit(number=1000000) + .. method:: 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. + 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:: + .. 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. This 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:: + 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. This 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() + timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit() The module also defines two convenience functions: @@ -245,4 +247,3 @@ To give the :mod:`timeit` module access from timeit import Timer t = Timer("test()", "from __main__ import test") print(t.timeit()) - diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst --- a/Doc/library/weakref.rst +++ b/Doc/library/weakref.rst @@ -153,17 +153,16 @@ Extension types can easily be made to su performed by the program during iteration may cause items in the dictionary to vanish "by magic" (as a side effect of garbage collection). -:class:`WeakKeyDictionary` objects have the following additional methods. These -expose 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. + :class:`WeakKeyDictionary` objects have the following additional methods. + These expose 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:: keyrefs() -.. method:: WeakKeyDictionary.keyrefs() - - Return an iterable of the weak references to the keys. + Return an iterable of the weak references to the keys. .. class:: WeakValueDictionary([dict]) @@ -179,14 +178,14 @@ than needed. by the program during iteration may cause items in the dictionary to vanish "by magic" (as a side effect of garbage collection). -:class:`WeakValueDictionary` objects have the following additional methods. -These method have the same issues as the and :meth:`keyrefs` method of -:class:`WeakKeyDictionary` objects. + :class:`WeakValueDictionary` objects have the following additional methods. + These method have the same issues as the and :meth:`keyrefs` method of + :class:`WeakKeyDictionary` objects. -.. method:: WeakValueDictionary.valuerefs() + .. method:: valuerefs() - Return an iterable of the weak references to the values. + Return an iterable of the weak references to the values. .. class:: WeakSet([elements]) diff --git a/Doc/library/zipfile.rst b/Doc/library/zipfile.rst --- a/Doc/library/zipfile.rst +++ b/Doc/library/zipfile.rst @@ -61,16 +61,13 @@ The module defines the following items: Class for creating ZIP archives containing Python libraries. -.. class:: ZipInfo(filename='NoName', date_time=(1980,1,1,0,0,0)) +.. class:: ZipInfo + :noindex: 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`. + methods of :class:`ZipFile` objects. See :ref:`zipinfo-objects` for more + info. .. function:: is_zipfile(filename) @@ -147,182 +144,188 @@ ZipFile Objects Added the ability to use :class:`ZipFile` as a context manager. -.. method:: ZipFile.close() + .. method:: close() - Close the archive file. You must call :meth:`close` before exiting your program - or essential records will not be written. + Close the archive file. You must call :meth:`close` before exiting your + program or essential records will not be written. -.. method:: ZipFile.getinfo(name) + .. method:: 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`. + 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() + .. method:: 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. + 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() + .. method:: namelist() - Return a list of archive members by name. + Return a list of archive members by name. -.. method:: ZipFile.open(name, mode='r', pwd=None) + .. method:: open(name, mode='r', pwd=None) - Extract a member from the archive as a file-like object (ZipExtFile). *name* is - the name of the file in the archive, or a :class:`ZipInfo` object. The *mode* - parameter, if included, must be one of the following: ``'r'`` (the default), - ``'U'``, or ``'rU'``. Choosing ``'U'`` or ``'rU'`` will enable universal newline - support in the read-only object. *pwd* is the password used for encrypted files. - Calling :meth:`open` on a closed ZipFile will raise a :exc:`RuntimeError`. + Extract a member from the archive as a file-like object (ZipExtFile). + *name* is the name of the file in the archive, or a :class:`ZipInfo` + object. The *mode* parameter, if included, must be one of the following: + ``'r'`` (the default), ``'U'``, or ``'rU'``. Choosing ``'U'`` or + ``'rU'`` will enable universal newline support in the read-only object. + *pwd* is the password used for encrypted files. Calling :meth:`open` on + a closed ZipFile will raise a :exc:`RuntimeError`. - .. note:: + .. note:: - The file-like object is read-only and provides the following methods: - :meth:`!read`, :meth:`!readline`, :meth:`!readlines`, :meth:`!__iter__`, - :meth:`!__next__`. + The file-like object is read-only and provides the following methods: + :meth:`!read`, :meth:`!readline`, :meth:`!readlines`, + :meth:`!__iter__`, :meth:`!__next__`. - .. note:: + .. note:: - If the ZipFile was created by passing in a file-like object as the first - argument to the constructor, then the object returned by :meth:`.open` shares the - ZipFile's file pointer. Under these circumstances, the object returned by - :meth:`.open` should not be used after any additional operations are performed - on the ZipFile object. If the ZipFile was created by passing in a string (the - filename) as the first argument to the constructor, then :meth:`.open` will - create a new file object that will be held by the ZipExtFile, allowing it to - operate independently of the ZipFile. + If the ZipFile was created by passing in a file-like object as the + first argument to the constructor, then the object returned by + :meth:`.open` shares the ZipFile's file pointer. Under these + circumstances, the object returned by :meth:`.open` should not be used + after any additional operations are performed on the ZipFile object. + If the ZipFile was created by passing in a string (the filename) as the + first argument to the constructor, then :meth:`.open` will create a + new file object that will be held by the ZipExtFile, allowing it to + operate independently of the ZipFile. - .. note:: + .. 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. + 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. -.. method:: ZipFile.extract(member, path=None, pwd=None) + .. method:: 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. + 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. -.. method:: ZipFile.extractall(path=None, members=None, pwd=None) + .. method:: 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. + 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:: + .. 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 ``".."``. + 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 ``".."``. -.. method:: ZipFile.printdir() + .. method:: printdir() - Print a table of contents for the archive to ``sys.stdout``. + Print a table of contents for the archive to ``sys.stdout``. -.. method:: ZipFile.setpassword(pwd) + .. method:: setpassword(pwd) - Set *pwd* as default password to extract encrypted files. + Set *pwd* as default password to extract encrypted files. -.. method:: ZipFile.read(name, pwd=None) + .. method:: 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 closed ZipFile will raise a :exc:`RuntimeError`. + 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 closed ZipFile will raise + a :exc:`RuntimeError`. -.. method:: ZipFile.testzip() + .. method:: 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``. Calling - :meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`. + 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``. Calling + :meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`. -.. method:: ZipFile.write(filename, arcname=None, compress_type=None) + .. method:: write(filename, arcname=None, compress_type=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. The archive must be open with mode ``'w'`` or ``'a'`` -- calling - :meth:`write` on a ZipFile created with mode ``'r'`` will raise a - :exc:`RuntimeError`. Calling :meth:`write` on a closed ZipFile will raise a - :exc:`RuntimeError`. + 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. The archive must be open with mode + ``'w'`` or ``'a'`` -- calling :meth:`write` on a ZipFile created with mode + ``'r'`` will raise a :exc:`RuntimeError`. Calling :meth:`write` on a + closed ZipFile will raise a :exc:`RuntimeError`. - .. note:: + .. note:: - There is no official file name encoding for ZIP files. If you have unicode file - names, you must convert them to byte strings in your desired encoding before - passing them to :meth:`write`. WinZip interprets all file names as encoded in - CP437, also known as DOS Latin. + There is no official file name encoding for ZIP files. If you have + unicode file names, you must convert them to byte strings in your + desired encoding before passing them to :meth:`write`. WinZip + interprets all file names as encoded in CP437, also known as DOS Latin. - .. note:: + .. note:: - Archive names should be relative to the archive root, that is, they should not - start with a path separator. + Archive names should be relative to the archive root, that is, they + should not start with a path separator. - .. note:: + .. 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. + 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. -.. method:: ZipFile.writestr(zinfo_or_arcname, bytes[, compress_type]) + .. method:: writestr(zinfo_or_arcname, bytes[, compress_type]) - Write the string *bytes* to the archive; *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'`` or ``'a'`` -- calling :meth:`writestr` on a ZipFile - created with mode ``'r'`` will raise a :exc:`RuntimeError`. Calling - :meth:`writestr` on a closed ZipFile will raise a :exc:`RuntimeError`. + Write the string *bytes* to the archive; *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'`` or ``'a'`` -- calling + :meth:`writestr` on a ZipFile created with mode ``'r'`` will raise a + :exc:`RuntimeError`. Calling :meth:`writestr` on a closed ZipFile will + raise a :exc:`RuntimeError`. - 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). + 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). - .. note:: + .. 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`. + 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 *compression_type* argument. + .. versionchanged:: 3.2 The *compression_type* argument. -The following data attributes are also available: + The following data attributes are also available: -.. 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:: debug -.. attribute:: ZipFile.comment + 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``. - The comment text associated with the ZIP file. If assigning a comment to a - :class:`ZipFile` instance created with mode 'a' or 'w', this should be a - string no longer than 65535 bytes. Comments longer than this will be - truncated in the written archive when :meth:`ZipFile.close` is called. + .. attribute:: comment + + The comment text associated with the ZIP file. If assigning a comment to + a :class:`ZipFile` instance created with mode 'a' or 'w', this should be a + string no longer than 65535 bytes. Comments longer than this will be + truncated in the written archive when :meth:`ZipFile.close` is called. .. _pyzipfile-objects: @@ -341,7 +344,7 @@ The :class:`PyZipFile` constructor takes Instances have one method in addition to those of :class:`ZipFile` objects: - .. method:: PyZipFile.writepy(pathname, basename='') + .. method:: writepy(pathname, basename='') Search for files :file:`\*.py` and add the corresponding file to the archive. @@ -378,113 +381,113 @@ The :class:`PyZipFile` constructor takes 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. +.. class:: ZipInfo(filename='NoName', date_time=(1980, 1, 1, 0, 0, 0)) -Instances have the following attributes: + 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. 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 + Instances have the following attributes: -.. attribute:: ZipInfo.filename + .. attribute:: filename - Name of the file in the archive. + Name of the file in the archive. -.. attribute:: ZipInfo.date_time + .. attribute:: date_time - The time and date of the last modification to the archive member. This is a - tuple of six values: + The time and date of the last modification to the archive member. This is + a tuple of six values: - +-------+--------------------------+ - | Index | Value | - +=======+==========================+ - | ``0`` | Year | - +-------+--------------------------+ - | ``1`` | Month (one-based) | - +-------+--------------------------+ - | ``2`` | Day of month (one-based) | - +-------+--------------------------+ - | ``3`` | Hours (zero-based) | - +-------+--------------------------+ - | ``4`` | Minutes (zero-based) | - +-------+--------------------------+ - | ``5`` | Seconds (zero-based) | - +-------+--------------------------+ + ======= ========================= + Index Value + ======= ========================= + ``0`` Year + ``1`` Month (one-based) + ``2`` Day of month (one-based) + ``3`` Hours (zero-based) + ``4`` Minutes (zero-based) + ``5`` Seconds (zero-based) + ======= ========================= -.. attribute:: ZipInfo.compress_type + .. attribute:: compress_type - Type of compression for the archive member. + Type of compression for the archive member. -.. attribute:: ZipInfo.comment + .. attribute:: comment - Comment for the individual archive member. + Comment for the individual archive member. -.. attribute:: ZipInfo.extra + .. attribute:: extra - Expansion field data. The `PKZIP Application Note - `_ contains - some comments on the internal structure of the data contained in this string. + Expansion field data. The `PKZIP Application Note + `_ contains some + comments on the internal structure of the data contained in this string. -.. attribute:: ZipInfo.create_system + .. attribute:: create_system - System which created ZIP archive. + System which created ZIP archive. -.. attribute:: ZipInfo.create_version + .. attribute:: create_version - PKZIP version which created ZIP archive. + PKZIP version which created ZIP archive. -.. attribute:: ZipInfo.extract_version + .. attribute:: extract_version - PKZIP version needed to extract archive. + PKZIP version needed to extract archive. -.. attribute:: ZipInfo.reserved + .. attribute:: reserved - Must be zero. + Must be zero. -.. attribute:: ZipInfo.flag_bits + .. attribute:: flag_bits - ZIP flag bits. + ZIP flag bits. -.. attribute:: ZipInfo.volume + .. attribute:: volume - Volume number of file header. + Volume number of file header. -.. attribute:: ZipInfo.internal_attr + .. attribute:: internal_attr - Internal attributes. + Internal attributes. -.. attribute:: ZipInfo.external_attr + .. attribute:: external_attr - External file attributes. + External file attributes. -.. attribute:: ZipInfo.header_offset + .. attribute:: header_offset - Byte offset to the file header. + Byte offset to the file header. -.. attribute:: ZipInfo.CRC + .. attribute:: CRC - CRC-32 of the uncompressed file. + CRC-32 of the uncompressed file. -.. attribute:: ZipInfo.compress_size + .. attribute:: compress_size - Size of the compressed data. + Size of the compressed data. -.. attribute:: ZipInfo.file_size + .. attribute:: file_size - Size of the uncompressed file. - + Size of the uncompressed file.