view configmix/compat.py @ 284:4aaf74858d07

Some links to AWS docu into the aws moduleSome links to AWS docu into the aws moduleSome links to AWS docu into the aws moduleSome links to AWS docu into the aws moduleSome links to AWS docu into the aws moduleSome links to AWS docu into the aws moduleSome links to AWS docu into the aws moduleSome links to AWS docu into the aws module
author Franz Glasner <fzglas.hg@dom66.de>
date Mon, 07 Dec 2020 01:59:11 +0100
parents ff964825a75a
children eed16a1ec8f3
line wrap: on
line source

# -*- coding: utf-8 -*-
# :-
# :Copyright: (c) 2015-2020, Franz Glasner. All rights reserved.
# :License:   3-clause BSD. See LICENSE.txt for details.
# :-
"""Some minimal compatibility shim between Python2 and Python3

"""

from __future__ import division, absolute_import, print_function


__all__ = ["PY2",
           "text_to_native_os_str",
           "native_os_str_to_text",
           "u",
           "u2fs"]


import sys
import os
import locale


PY2 = sys.version_info[0] <= 2


if PY2:

    _OS_ENCODING = locale.getpreferredencoding()

    _FS_ENCODING = sys.getfilesystemencoding() or _OS_ENCODING


    def text_to_native_os_str(s, encoding=None):
        if isinstance(s, unicode):                       # noqa: F821
            return s.encode(encoding or _OS_ENCODING)
        else:
            return s


    def native_os_str_to_text(s, encoding=None):
        return s.decode(encoding or _OS_ENCODING)


    def u(s, encoding="utf-8"):
        if isinstance(s, unicode):                       # noqa: F821
            return s
        else:
            return s.decode(encoding)


    def u2fs(s, force=False):
        """Convert a text (Unicode) string to the filesystem encoding.

        .. note:: The filesystem encoding on Python 3 is a Unicode text
                  string. The function is a noop when called on Python 3.

        .. note:: If `s` is already a byte string be permissive and
                  return `s` unchanged.

        """
        if isinstance(s, str):
            return s
        if not force and os.name in ("nt", "ce"):
            # WinNT and CE have native Unicode support: nothing to convert
            return s
        return s.encode(_FS_ENCODING)

else:

    def text_to_native_os_str(s, encoding=None):
        return s


    def native_os_str_to_text(s, encoding=None):
        return s


    def u(s, encoding="utf-8"):
        if isinstance(s, str):
            return s
        else:
            return s.decode(encoding)


    def u2fs(s, force=False):
        """Convert a text (Unicode) string to the filesystem encoding.

        .. note:: The filesystem encoding on Python 3 is a Unicode text
                  string. The function is a noop when called on Python 3.

        .. note:: If `s` is already a byte string be permissive and
                  return `s` unchanged.

        """
        assert isinstance(s, str)
        return s