blob: 0244c9787ee1d4342bab43ff6f7abd86c15c0e95 [file] [log] [blame]
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001# Copyright 2016 Google Inc. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15""" A tiny version of `six` to help with backwards compability. Also includes
16 compatibility helpers for numpy. """
17
18import sys
Austin Schuhe89fa2d2019-08-14 20:24:23 -070019
20PY2 = sys.version_info[0] == 2
21PY26 = sys.version_info[0:2] == (2, 6)
22PY27 = sys.version_info[0:2] == (2, 7)
23PY275 = sys.version_info[0:3] >= (2, 7, 5)
24PY3 = sys.version_info[0] == 3
25PY34 = sys.version_info[0:2] >= (3, 4)
26
27if PY3:
James Kuszmaul8e62b022022-03-22 09:33:25 -070028 import importlib.machinery
Austin Schuhe89fa2d2019-08-14 20:24:23 -070029 string_types = (str,)
30 binary_types = (bytes,bytearray)
31 range_func = range
32 memoryview_type = memoryview
33 struct_bool_decl = "?"
34else:
James Kuszmaul8e62b022022-03-22 09:33:25 -070035 import imp
Austin Schuhe89fa2d2019-08-14 20:24:23 -070036 string_types = (unicode,)
37 if PY26 or PY27:
38 binary_types = (str,bytearray)
39 else:
40 binary_types = (str,)
41 range_func = xrange
42 if PY26 or (PY27 and not PY275):
43 memoryview_type = buffer
44 struct_bool_decl = "<b"
45 else:
46 memoryview_type = memoryview
47 struct_bool_decl = "?"
48
49# Helper functions to facilitate making numpy optional instead of required
50
51def import_numpy():
52 """
53 Returns the numpy module if it exists on the system,
54 otherwise returns None.
55 """
James Kuszmaul8e62b022022-03-22 09:33:25 -070056 if PY3:
57 numpy_exists = (
58 importlib.machinery.PathFinder.find_spec('numpy') is not None)
59 else:
60 try:
61 imp.find_module('numpy')
62 numpy_exists = True
63 except ImportError:
64 numpy_exists = False
Austin Schuhe89fa2d2019-08-14 20:24:23 -070065
66 if numpy_exists:
67 # We do this outside of try/except block in case numpy exists
68 # but is not installed correctly. We do not want to catch an
69 # incorrect installation which would manifest as an
70 # ImportError.
71 import numpy as np
72 else:
73 np = None
74
75 return np
76
77
78class NumpyRequiredForThisFeature(RuntimeError):
79 """
80 Error raised when user tries to use a feature that
81 requires numpy without having numpy installed.
82 """
83 pass
84
85
86# NOTE: Future Jython support may require code here (look at `six`).