invalid.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """
  2. Templates for invalid operations.
  3. """
  4. from __future__ import annotations
  5. import operator
  6. import numpy as np
  7. def invalid_comparison(left, right, op) -> np.ndarray:
  8. """
  9. If a comparison has mismatched types and is not necessarily meaningful,
  10. follow python3 conventions by:
  11. - returning all-False for equality
  12. - returning all-True for inequality
  13. - raising TypeError otherwise
  14. Parameters
  15. ----------
  16. left : array-like
  17. right : scalar, array-like
  18. op : operator.{eq, ne, lt, le, gt}
  19. Raises
  20. ------
  21. TypeError : on inequality comparisons
  22. """
  23. if op is operator.eq:
  24. res_values = np.zeros(left.shape, dtype=bool)
  25. elif op is operator.ne:
  26. res_values = np.ones(left.shape, dtype=bool)
  27. else:
  28. typ = type(right).__name__
  29. raise TypeError(f"Invalid comparison between dtype={left.dtype} and {typ}")
  30. return res_values
  31. def make_invalid_op(name: str):
  32. """
  33. Return a binary method that always raises a TypeError.
  34. Parameters
  35. ----------
  36. name : str
  37. Returns
  38. -------
  39. invalid_op : function
  40. """
  41. def invalid_op(self, other=None):
  42. typ = type(self).__name__
  43. raise TypeError(f"cannot perform {name} with this index type: {typ}")
  44. invalid_op.__name__ = name
  45. return invalid_op