validation.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """Helper functions to validate input data and produce error messages."""
  2. import imgaug as ia
  3. def convert_iterable_to_string_of_types(iterable_var):
  4. """Convert an iterable of values to a string of their types.
  5. Parameters
  6. ----------
  7. iterable_var : iterable
  8. An iterable of variables, e.g. a list of integers.
  9. Returns
  10. -------
  11. str
  12. String representation of the types in `iterable_var`. One per item
  13. in `iterable_var`. Separated by commas.
  14. """
  15. types = [str(type(var_i)) for var_i in iterable_var]
  16. return ", ".join(types)
  17. def is_iterable_of(iterable_var, classes):
  18. """Check whether `iterable_var` contains only instances of given classes.
  19. Parameters
  20. ----------
  21. iterable_var : iterable
  22. An iterable of items that will be matched against `classes`.
  23. classes : type or iterable of type
  24. One or more classes that each item in `var` must be an instanceof.
  25. If this is an iterable, a single match per item is enough.
  26. Returns
  27. -------
  28. bool
  29. Whether `var` only contains instances of `classes`.
  30. If `var` was empty, ``True`` will be returned.
  31. """
  32. if not ia.is_iterable(iterable_var):
  33. return False
  34. for var_i in iterable_var:
  35. if not isinstance(var_i, classes):
  36. return False
  37. return True
  38. def assert_is_iterable_of(iterable_var, classes):
  39. """Assert that `iterable_var` only contains instances of given classes.
  40. Parameters
  41. ----------
  42. iterable_var : iterable
  43. See :func:`~imgaug.validation.is_iterable_of`.
  44. classes : type or iterable of type
  45. See :func:`~imgaug.validation.is_iterable_of`.
  46. """
  47. valid = is_iterable_of(iterable_var, classes)
  48. if not valid:
  49. expected_types_str = (
  50. ", ".join([class_.__name__ for class_ in classes])
  51. if not isinstance(classes, type)
  52. else classes.__name__)
  53. if not ia.is_iterable(iterable_var):
  54. raise AssertionError(
  55. "Expected an iterable of the following types: %s. "
  56. "Got instead a single instance of: %s." % (
  57. expected_types_str,
  58. type(iterable_var).__name__)
  59. )
  60. raise AssertionError(
  61. "Expected an iterable of the following types: %s. "
  62. "Got an iterable of types: %s." % (
  63. expected_types_str,
  64. convert_iterable_to_string_of_types(iterable_var))
  65. )