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