compat.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 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. """A tiny version of `six` to help with backwards compability.
  15. Also includes compatibility helpers for numpy.
  16. """
  17. import sys
  18. PY2 = sys.version_info[0] == 2
  19. PY26 = sys.version_info[0:2] == (2, 6)
  20. PY27 = sys.version_info[0:2] == (2, 7)
  21. PY275 = sys.version_info[0:3] >= (2, 7, 5)
  22. PY3 = sys.version_info[0] == 3
  23. PY34 = sys.version_info[0:2] >= (3, 4)
  24. if PY3:
  25. import importlib.machinery
  26. string_types = (str,)
  27. binary_types = (bytes, bytearray)
  28. range_func = range
  29. memoryview_type = memoryview
  30. struct_bool_decl = "?"
  31. else:
  32. import imp
  33. string_types = (unicode,)
  34. if PY26 or PY27:
  35. binary_types = (str, bytearray)
  36. else:
  37. binary_types = (str,)
  38. range_func = xrange
  39. if PY26 or (PY27 and not PY275):
  40. memoryview_type = buffer
  41. struct_bool_decl = "<b"
  42. else:
  43. memoryview_type = memoryview
  44. struct_bool_decl = "?"
  45. # Helper functions to facilitate making numpy optional instead of required
  46. def import_numpy():
  47. """Returns the numpy module if it exists on the system,
  48. otherwise returns None.
  49. """
  50. if PY3:
  51. numpy_exists = importlib.machinery.PathFinder.find_spec("numpy") is not None
  52. else:
  53. try:
  54. imp.find_module("numpy")
  55. numpy_exists = True
  56. except ImportError:
  57. numpy_exists = False
  58. if numpy_exists:
  59. # We do this outside of try/except block in case numpy exists
  60. # but is not installed correctly. We do not want to catch an
  61. # incorrect installation which would manifest as an
  62. # ImportError.
  63. import numpy as np
  64. else:
  65. np = None
  66. return np
  67. class NumpyRequiredForThisFeature(RuntimeError):
  68. """Error raised when user tries to use a feature that
  69. requires numpy without having numpy installed.
  70. """
  71. pass
  72. # NOTE: Future Jython support may require code here (look at `six`).