eb749681028e4e9956352b55c400d51387dcf2aa
[pyi2ncommon] / src / type_helpers.py
1 # The software in this package is distributed under the GNU General
2 # Public License version 2 (with a special exception described below).
3 #
4 # A copy of GNU General Public License (GPL) is included in this distribution,
5 # in the file COPYING.GPL.
6 #
7 # As a special exception, if other files instantiate templates or use macros
8 # or inline functions from this file, or you compile this file and link it
9 # with other works to produce a work based on this file, this file
10 # does not by itself cause the resulting work to be covered
11 # by the GNU General Public License.
12 #
13 # However the source code for this file must still be made available
14 # in accordance with section (3) of the GNU General Public License.
15 #
16 # This exception does not invalidate any other reasons why a work based
17 # on this file might be covered by the GNU General Public License.
18 #
19 # Copyright (c) 2016-2018 Intra2net AG <info@intra2net.com>
20
21 """
22 Helpers for type checking and conversion, like isstr(x), is_file_obj(x)
23 """
24
25 import sys
26 from io import IOBase
27
28
29 def isstr(var):
30     """ determines if the given var is a (regular/unicode/raw) string or not
31
32     in python2, u'a' is not a subclass of str, so to get a True as result, you
33       have to test for basestring as superclass.
34
35     In python3 that is no longer the case
36
37     @returns True if the input is a regular string, a unicode or a raw string,
38        False for everything else (including byte literals like b'abc')
39
40     For more complex py2/py3 compatibility issues, consider using six
41       (https://pythonhosted.org/six)
42     """
43
44     return isinstance(var, str)
45
46
47 def is_str_or_byte(var):
48     """ returns true for str, unicode and byte objects """
49     return isinstance(var, (str, bytes))
50
51
52 def is_unicode(var):
53     """ returns true for unicode strings
54
55     py2: return True for type unicode but not type str
56     py3: return True for type str but not type bytes
57     """
58     return isinstance(var, str)
59
60
61 def is_file_obj(var):
62     """ determines whether given input is the result of 'open(file_name)'
63
64     just checks whether given var is subclass of io.IOBase, which is also True
65     for 'file-like objects' like StringIO
66     """
67     return isinstance(var, IOBase)