1"""
2Python 3 compatibility tools.
3
4"""
5
6__all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',
7           'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',
8           'asstr', 'open_latin1']
9
10import sys
11
12if sys.version_info[0] >= 3:
13    import io
14    bytes = bytes
15    unicode = str
16    asunicode = str
17    def asbytes(s):
18        if isinstance(s, bytes):
19            return s
20        return s.encode('latin1')
21    def asstr(s):
22        if isinstance(s, str):
23            return s
24        return s.decode('latin1')
25    def asstr2(s):  #added JP, not in numpy version
26        if isinstance(s, str):
27            return s
28        elif isinstance(s, bytes):
29            return s.decode('latin1')
30        else:
31            return str(s)
32    def isfileobj(f):
33        return isinstance(f, io.FileIO)
34    def open_latin1(filename, mode='r'):
35        return open(filename, mode=mode, encoding='iso-8859-1')
36    strchar = 'U'
37    from io import BytesIO, StringIO  #statsmodels
38else:
39    bytes = str
40    unicode = unicode
41    asbytes = str
42    asstr = str
43    asstr2 = str
44    strchar = 'S'
45    def isfileobj(f):
46        return isinstance(f, file)
47    def asunicode(s):
48        if isinstance(s, unicode):
49            return s
50        return s.decode('ascii')
51    def open_latin1(filename, mode='r'):
52        return open(filename, mode=mode)
53    from StringIO import StringIO
54    BytesIO = StringIO
55
56def getexception():
57    return sys.exc_info()[1]
58
59def asbytes_nested(x):
60    if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
61        return [asbytes_nested(y) for y in x]
62    else:
63        return asbytes(x)
64
65def asunicode_nested(x):
66    if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
67        return [asunicode_nested(y) for y in x]
68    else:
69        return asunicode(x)
70