You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.6 KiB

4 years ago
  1. import re
  2. import six
  3. def get_type_and_data(h_node):
  4. """ Helper function to return the py_type and data block for a HDF node """
  5. py_type = h_node.attrs["type"][0]
  6. if h_node.shape == ():
  7. data = h_node.value
  8. else:
  9. data = h_node[:]
  10. return py_type, data
  11. def sort_keys(key_list):
  12. """ Take a list of strings and sort it by integer value within string
  13. Args:
  14. key_list (list): List of keys
  15. Returns:
  16. key_list_sorted (list): List of keys, sorted by integer
  17. """
  18. # Py3 h5py returns an irritating KeysView object
  19. # Py3 also complains about bytes and strings, convert all keys to bytes
  20. if six.PY3:
  21. key_list2 = []
  22. for key in key_list:
  23. if isinstance(key, str):
  24. key = bytes(key, 'ascii')
  25. key_list2.append(key)
  26. key_list = key_list2
  27. to_int = lambda x: int(re.search(b'\d+', x).group(0))
  28. keys_by_int = sorted([(to_int(key), key) for key in key_list])
  29. return [ii[1] for ii in keys_by_int]
  30. def check_is_iterable(py_obj):
  31. """ Check whether a python object is iterable.
  32. Note: this treats unicode and string as NON ITERABLE
  33. Args:
  34. py_obj: python object to test
  35. Returns:
  36. iter_ok (bool): True if item is iterable, False is item is not
  37. """
  38. if six.PY2:
  39. string_types = (str, unicode)
  40. else:
  41. string_types = (str, bytes, bytearray)
  42. if type(py_obj) in string_types:
  43. return False
  44. try:
  45. iter(py_obj)
  46. return True
  47. except TypeError:
  48. return False
  49. def check_is_hashable(py_obj):
  50. """ Check if a python object is hashable
  51. Note: this function is currently not used, but is useful for future
  52. development.
  53. Args:
  54. py_obj: python object to test
  55. """
  56. try:
  57. py_obj.__hash__()
  58. return True
  59. except TypeError:
  60. return False
  61. def check_iterable_item_type(iter_obj):
  62. """ Check if all items within an iterable are the same type.
  63. Args:
  64. iter_obj: iterable object
  65. Returns:
  66. iter_type: type of item contained within the iterable. If
  67. the iterable has many types, a boolean False is returned instead.
  68. References:
  69. http://stackoverflow.com/questions/13252333/python-check-if-all-elements-of-a-list-are-the-same-type
  70. """
  71. iseq = iter(iter_obj)
  72. try:
  73. first_type = type(next(iseq))
  74. except StopIteration:
  75. return False
  76. except Exception as ex:
  77. return False
  78. if isinstance(iter_obj, dict):
  79. return first_type
  80. else:
  81. return first_type if all((type(x) is first_type) for x in iseq) else False