infinity.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. class Inf:
  2. """ Singleton class: the single instance "INFINITY" stands for infinity.
  3. By Jean-Sebastien and Hans Vangheluwe"""
  4. __instantiated = False
  5. def __init__(self):
  6. if self.__instantiated:
  7. raise NotImplementedError, "singleton class already instantiated"
  8. self.__instantiatiated = True
  9. def __deepcopy__(self, memo):
  10. """ When deepcopy (in the copy module) makes a deep copy,
  11. an instance of Inf should NOT be cloned as Inf would
  12. then no longer be a Singleton.
  13. Rather, deepcopy should return a reference to the
  14. unique (singleton) instance.
  15. With this approach
  16. inf = INFINITY
  17. inf_copy = deepcopy(inf)
  18. inf == inf_copy
  19. """
  20. return self
  21. def __add__(self, other):
  22. """ INFINITY + x = INFINITY """
  23. return self
  24. def __sub__(self, other):
  25. """ INFINITY - x = INFINITY (if x != INF), or NaN (if x == INFINITY) """
  26. if other == self:
  27. raise ValueError, "INFINITY - INFINITY gives NaN (not defined)"
  28. return self
  29. def __radd__(self, other):
  30. """ x + INFINITY = INFINITY """
  31. return self
  32. def __rsub__(self, other):
  33. """ x - INFINITY = -INFINITY (if x != INFINITY), or NaN (if x == INFINITY) """
  34. if other == self:
  35. raise ValueError, "INFINITY - INFINITY gives NaN (not defined)"
  36. raise ValueError, "x - INFINITY gives MINUS_INFINITY (not defined)"
  37. def __abs__(self):
  38. """ abs(INFINITY) = INFINITY -- absolute value """
  39. return self
  40. # def __cmp__(self, other):
  41. # if other is self:
  42. # return 0
  43. # else:
  44. # return 1
  45. def __eq__(self, other):
  46. if other is self:
  47. return True
  48. else:
  49. return False
  50. def __ne__(self, other):
  51. if other is self:
  52. return False
  53. else:
  54. return True
  55. def __lt__(self, other):
  56. return False
  57. def __le__(self, other):
  58. if other is self:
  59. return True
  60. else:
  61. return False
  62. def __gt__(self, other):
  63. if other is self:
  64. return False
  65. else:
  66. return True
  67. def __ge__(self, other):
  68. return True
  69. def __repr__(self):
  70. return "+INFINITY"
  71. # Instantiate singleton:
  72. INFINITY = Inf()