pysys.utils.pycompat module

pycompat is a small PySys module containing a minimal set of utilities for writing single-source Python that runs in multiple python versions, for example both Python 2 and Python 3.

class pysys.utils.pycompat.Enum[source]

Bases: object

Generic enumeration.

Derive from this class to define new enumerations.

pysys.utils.pycompat.isstring(s)[source]

Returns True if the specified object is a python string. On Python 2 this could be a unicode character string or a byte str, on python 3 this must be a character str.

pysys.utils.pycompat.openfile(path, mode='r', encoding=None, errors=None, **kwargs)[source]

Opens the specified file, following the default “open()” semantics for this Python version unless an encoding is explicitly specified, in which case a file stream yielding (unicode) character strings is always returned.

Specifically:

On Python 3 this method returns a file stream yielding character strings unless a binary mode was specified in which case a stream yielding bytes is returned.

On Python 2 this method returns a file stream yielding unicode character strings only if an encoding was explicitly specified; otherwise it returns a file stream yielding “str” bytes objects.

Parameters:
  • path – The path to open; must be an absolute path. Even on Windows this path can be long (e.g. more than the usual 256 character Windows limit).
  • mode – The file mode, e.g. ‘r’ for reading, ‘wb’ for binary writing.
  • encoding – The encoding to use to translate between the bytes of the file and the characters used in the returned stream. If an encoding is specified then the returned stream is always a unicode character stream. This must be None if the mode specifies binary.
  • errors – Optional string that specifies how encoding/decoding errors are handled, such as ‘strict’, ‘ignore’, ‘replace’; see documentation of io module for more details. The value of this attribute is ignored if using the python 2 open() built-in with bytes mode that does not support it.
  • kwargs – Any additional args to be passed to open() or io.open().
Returns:

A file stream, either using unicode characters or binary bytes. This stream should be closed when no longer required.

pysys.utils.pycompat.quotestring(s)[source]

Adds double quotation marks around the specified character string (but does not escape quotes contained within it). If a byte string is provided and this is Python 3+ then the ‘repr’ representation is used instead.