-
-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy path_compat.py
More file actions
58 lines (41 loc) · 1.32 KB
/
_compat.py
File metadata and controls
58 lines (41 loc) · 1.32 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
# -*- coding: utf-8 -*-
import sys
PY2 = sys.version_info[0] == 2
PY3K = sys.version_info[0] >= 3
PY36 = sys.version_info >= (3, 6)
try: # Python 2
long
unicode
basestring
except NameError: # Python 3
long = int
unicode = str
basestring = str
try: # Python >= 3.3
FileNotFoundError = FileNotFoundError
except NameError: # Python < 3.3
FileNotFoundError = IOError # cf PEP-3151
def decode(string, encodings=None):
if not PY2 and not isinstance(string, bytes):
return string
if PY2 and isinstance(string, unicode):
return string
encodings = encodings or ['utf-8', 'latin1', 'ascii']
for encoding in encodings:
try:
return string.decode(encoding)
except (UnicodeEncodeError, UnicodeDecodeError):
pass
return string.decode(encodings[0], errors='ignore')
def encode(string, encodings=None):
if not PY2 and isinstance(string, bytes):
return string
if PY2 and isinstance(string, str):
return string
encodings = encodings or ['utf-8', 'latin1', 'ascii']
for encoding in encodings:
try:
return string.encode(encoding)
except (UnicodeEncodeError, UnicodeDecodeError):
pass
return string.encode(encodings[0], errors='ignore')