-
-
Notifications
You must be signed in to change notification settings - Fork 308
Expand file tree
/
Copy pathcompat.py
More file actions
65 lines (50 loc) · 1.39 KB
/
compat.py
File metadata and controls
65 lines (50 loc) · 1.39 KB
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
# -*- coding: utf-8 -*-
""" py3 compatibility class
"""
from __future__ import absolute_import, print_function, with_statement
try:
basestring
except NameError:
basestring = str
try:
unicode
except NameError:
unicode = str
if isinstance(b"", type("")): # py 2.x
text_types = (basestring,) # noqa
bytes_type = bytes
str_type = basestring # noqa
def utf8(data):
"""return utf8-encoded string"""
if isinstance(data, basestring):
return data.decode("utf8")
return unicode(data)
def to_string(data):
"""return string"""
if isinstance(data, unicode):
return data.encode("utf8")
return str(data)
def to_bytes(data):
"""return bytes"""
if isinstance(data, unicode):
return data.encode("utf8")
return str(data)
else: # py 3.x
text_types = (bytes, str)
bytes_type = bytes
str_type = str
def utf8(data):
"""return utf8-encoded string"""
if isinstance(data, bytes):
return data.decode("utf8")
return str(data)
def to_string(data):
"""convert to string"""
if isinstance(data, bytes):
return data.decode("utf8")
return str(data)
def to_bytes(data):
"""return bytes"""
if isinstance(data, str):
return data.encode("utf8")
return bytes(data)