codekingpro/portable-devtools
115k
1# 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 at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# 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 and13# limitations under the License.14 15"""A tiny version of `six` to help with backwards compability.16 17Also includes compatibility helpers for numpy.18"""19 20import sys21 22PY2 = sys.version_info[0] == 223PY26 = sys.version_info[0:2] == (2, 6)24PY27 = sys.version_info[0:2] == (2, 7)25PY275 = sys.version_info[0:3] >= (2, 7, 5)26PY3 = sys.version_info[0] == 327PY34 = sys.version_info[0:2] >= (3, 4)28 29if PY3:30 import importlib.machinery31 32 string_types = (str,)33 binary_types = (bytes, bytearray)34 range_func = range35 memoryview_type = memoryview36 struct_bool_decl = "?"37else:38 import imp39 40 string_types = (unicode,)41 if PY26 or PY27:42 binary_types = (str, bytearray)43 else:44 binary_types = (str,)45 range_func = xrange46 if PY26 or (PY27 and not PY275):47 memoryview_type = buffer48 struct_bool_decl = "<b"49 else:50 memoryview_type = memoryview51 struct_bool_decl = "?"52 53# Helper functions to facilitate making numpy optional instead of required54 55 56def import_numpy():57 """Returns the numpy module if it exists on the system,58 59 otherwise returns None.60 """61 if PY3:62 numpy_exists = importlib.machinery.PathFinder.find_spec("numpy") is not None63 else:64 try:65 imp.find_module("numpy")66 numpy_exists = True67 except ImportError:68 numpy_exists = False69 70 if numpy_exists:71 # We do this outside of try/except block in case numpy exists72 # but is not installed correctly. We do not want to catch an73 # incorrect installation which would manifest as an74 # ImportError.75 import numpy as np76 else:77 np = None78 79 return np80 81 82class NumpyRequiredForThisFeature(RuntimeError):83 """Error raised when user tries to use a feature that84 85 requires numpy without having numpy installed.86 """87 88 pass89 90 91# NOTE: Future Jython support may require code here (look at `six`).92 