Michael Merickel
2018-10-26 035f6cf8238211d097c991677fde6b5bc046a57b
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import inspect
import platform
import sys
import types
 
WIN = platform.system() == 'Windows'
 
try:  # pragma: no cover
    import __pypy__
 
    PYPY = True
except BaseException:  # pragma: no cover
    __pypy__ = None
    PYPY = False
 
try:
    import cPickle as pickle
except ImportError:  # pragma: no cover
    import pickle
 
try:
    from functools import lru_cache
except ImportError:
    from repoze.lru import lru_cache
 
# PY3 is left as bw-compat but PY2 should be used for most checks.
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
 
if PY2:
    string_types = (basestring,)
    integer_types = (int, long)
    class_types = (type, types.ClassType)
    text_type = unicode
    binary_type = str
    long = long
else:
    string_types = (str,)
    integer_types = (int,)
    class_types = (type,)
    text_type = str
    binary_type = bytes
    long = int
 
 
def text_(s, encoding='latin-1', errors='strict'):
    """ If ``s`` is an instance of ``binary_type``, return
    ``s.decode(encoding, errors)``, otherwise return ``s``"""
    if isinstance(s, binary_type):
        return s.decode(encoding, errors)
    return s
 
 
def bytes_(s, encoding='latin-1', errors='strict'):
    """ If ``s`` is an instance of ``text_type``, return
    ``s.encode(encoding, errors)``, otherwise return ``s``"""
    if isinstance(s, text_type):
        return s.encode(encoding, errors)
    return s
 
 
if PY2:
 
    def ascii_native_(s):
        if isinstance(s, text_type):
            s = s.encode('ascii')
        return str(s)
 
 
else:
 
    def ascii_native_(s):
        if isinstance(s, text_type):
            s = s.encode('ascii')
        return str(s, 'ascii', 'strict')
 
 
ascii_native_.__doc__ = """
Python 3: If ``s`` is an instance of ``text_type``, return
``s.encode('ascii')``, otherwise return ``str(s, 'ascii', 'strict')``
 
Python 2: If ``s`` is an instance of ``text_type``, return
``s.encode('ascii')``, otherwise return ``str(s)``
"""
 
 
if PY2:
 
    def native_(s, encoding='latin-1', errors='strict'):
        """ If ``s`` is an instance of ``text_type``, return
        ``s.encode(encoding, errors)``, otherwise return ``str(s)``"""
        if isinstance(s, text_type):
            return s.encode(encoding, errors)
        return str(s)
 
 
else:
 
    def native_(s, encoding='latin-1', errors='strict'):
        """ If ``s`` is an instance of ``text_type``, return
        ``s``, otherwise return ``str(s, encoding, errors)``"""
        if isinstance(s, text_type):
            return s
        return str(s, encoding, errors)
 
 
native_.__doc__ = """
Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise
return ``str(s, encoding, errors)``
 
Python 2: If ``s`` is an instance of ``text_type``, return
``s.encode(encoding, errors)``, otherwise return ``str(s)``
"""
 
if PY2:
    import urlparse
    from urllib import quote as url_quote
    from urllib import quote_plus as url_quote_plus
    from urllib import unquote as url_unquote
    from urllib import urlencode as url_encode
    from urllib2 import urlopen as url_open
 
    def url_unquote_text(
        v, encoding='utf-8', errors='replace'
    ):  # pragma: no cover
        v = url_unquote(v)
        return v.decode(encoding, errors)
 
    def url_unquote_native(
        v, encoding='utf-8', errors='replace'
    ):  # pragma: no cover
        return native_(url_unquote_text(v, encoding, errors))
 
 
else:
    from urllib import parse
 
    urlparse = parse
    from urllib.parse import quote as url_quote
    from urllib.parse import quote_plus as url_quote_plus
    from urllib.parse import unquote as url_unquote
    from urllib.parse import urlencode as url_encode
    from urllib.request import urlopen as url_open
 
    url_unquote_text = url_unquote
    url_unquote_native = url_unquote
 
 
if PY2:  # pragma: no cover
 
    def exec_(code, globs=None, locs=None):
        """Execute code in a namespace."""
        if globs is None:
            frame = sys._getframe(1)
            globs = frame.f_globals
            if locs is None:
                locs = frame.f_locals
            del frame
        elif locs is None:
            locs = globs
        exec("""exec code in globs, locs""")
 
    exec_(
        """def reraise(tp, value, tb=None):
    raise tp, value, tb
"""
    )
 
else:  # pragma: no cover
    import builtins
 
    exec_ = getattr(builtins, "exec")
 
    def reraise(tp, value, tb=None):
        if value is None:
            value = tp
        if value.__traceback__ is not tb:
            raise value.with_traceback(tb)
        raise value
 
    del builtins
 
 
if PY2:  # pragma: no cover
 
    def iteritems_(d):
        return d.iteritems()
 
    def itervalues_(d):
        return d.itervalues()
 
    def iterkeys_(d):
        return d.iterkeys()
 
 
else:  # pragma: no cover
 
    def iteritems_(d):
        return d.items()
 
    def itervalues_(d):
        return d.values()
 
    def iterkeys_(d):
        return d.keys()
 
 
if PY2:
    map_ = map
else:
 
    def map_(*arg):
        return list(map(*arg))
 
 
if PY2:
 
    def is_nonstr_iter(v):
        return hasattr(v, '__iter__')
 
 
else:
 
    def is_nonstr_iter(v):
        if isinstance(v, str):
            return False
        return hasattr(v, '__iter__')
 
 
if PY2:
    im_func = 'im_func'
    im_self = 'im_self'
else:
    im_func = '__func__'
    im_self = '__self__'
 
try:
    import configparser
except ImportError:
    import ConfigParser as configparser
 
try:
    from http.cookies import SimpleCookie
except ImportError:
    from Cookie import SimpleCookie
 
if PY2:
    from cgi import escape
else:
    from html import escape
 
if PY2:
    input_ = raw_input
else:
    input_ = input
 
if PY2:
    from io import BytesIO as NativeIO
else:
    from io import StringIO as NativeIO
 
# "json" is not an API; it's here to support older pyramid_debugtoolbar
# versions which attempt to import it
import json
 
if PY2:
 
    def decode_path_info(path):
        return path.decode('utf-8')
 
 
else:
    # see PEP 3333 for why we encode WSGI PATH_INFO to latin-1 before
    # decoding it to utf-8
    def decode_path_info(path):
        return path.encode('latin-1').decode('utf-8')
 
 
if PY2:
    from urlparse import unquote as unquote_to_bytes
 
    def unquote_bytes_to_wsgi(bytestring):
        return unquote_to_bytes(bytestring)
 
 
else:
    # see PEP 3333 for why we decode the path to latin-1
    from urllib.parse import unquote_to_bytes
 
    def unquote_bytes_to_wsgi(bytestring):
        return unquote_to_bytes(bytestring).decode('latin-1')
 
 
def is_bound_method(ob):
    return inspect.ismethod(ob) and getattr(ob, im_self, None) is not None
 
 
# support annotations and keyword-only arguments in PY3
if PY2:
    from inspect import getargspec
else:
    from inspect import getfullargspec as getargspec
 
if PY2:
    from itertools import izip_longest as zip_longest
else:
    from itertools import zip_longest
 
 
def is_unbound_method(fn):
    """
    This consistently verifies that the callable is bound to a
    class.
    """
    is_bound = is_bound_method(fn)
 
    if not is_bound and inspect.isroutine(fn):
        spec = getargspec(fn)
        has_self = len(spec.args) > 0 and spec.args[0] == 'self'
 
        if PY2 and inspect.ismethod(fn):
            return True
        elif inspect.isfunction(fn) and has_self:
            return True
 
    return False