File: _compat.py

package info (click to toggle)
python-thriftpy 0.3.9%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 560 kB
  • sloc: python: 3,287; ansic: 30; makefile: 7
file content (63 lines) | stat: -rw-r--r-- 1,800 bytes parent folder | download | duplicates (2)
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# -*- coding: utf-8 -*-

"""
    thriftpy._compat
    ~~~~~~~~~~~~~

    py2/py3 compatibility support.
"""

from __future__ import absolute_import

import platform
import sys

PY3 = sys.version_info[0] == 3
PYPY = "__pypy__" in sys.modules

UNIX = platform.system() in ("Linux", "Darwin")
CYTHON = UNIX and not PYPY  # Cython always disabled in pypy and windows

# only python2.7.9 and python 3.4 or above have true ssl context
MODERN_SSL = (2, 7, 9) <= sys.version_info < (3, 0, 0) or \
    sys.version_info >= (3, 4)

if PY3:
    text_type = str
    string_types = (str,)
    from urllib.request import urlopen
    from urllib.parse import urlparse

    def u(s):
        return s
else:
    text_type = unicode  # noqa
    string_types = (str, unicode)  # noqa
    from urllib2 import urlopen
    from urlparse import urlparse

    def u(s):
        if not isinstance(s, text_type):
            s = s.decode("utf-8")
        return s


def with_metaclass(meta, *bases):
    """Create a base class with a metaclass for py2 & py3

    This code snippet is copied from six."""
    # This requires a bit of explanation: the basic idea is to make a
    # dummy metaclass for one level of class instantiation that replaces
    # itself with the actual metaclass.  Because of internal type checks
    # we also need to make sure that we downgrade the custom metaclass
    # for one level to something closer to type (that's why __call__ and
    # __init__ comes back from type etc.).
    class metaclass(meta):
        __call__ = type.__call__
        __init__ = type.__init__

        def __new__(cls, name, this_bases, d):
            if this_bases is None:
                return type.__new__(cls, name, (), d)
            return meta(name, bases, d)
    return metaclass('temporary_class', None, {})