rules.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. Replacement rules.
  3. """
  4. class Transform:
  5. """
  6. Immutable mapping that can be used as a generic transformation rule.
  7. Parameters
  8. ==========
  9. transform : callable
  10. Computes the value corresponding to any key.
  11. filter : callable, optional
  12. If supplied, specifies which objects are in the mapping.
  13. Examples
  14. ========
  15. >>> from sympy.core.rules import Transform
  16. >>> from sympy.abc import x
  17. This Transform will return, as a value, one more than the key:
  18. >>> add1 = Transform(lambda x: x + 1)
  19. >>> add1[1]
  20. 2
  21. >>> add1[x]
  22. x + 1
  23. By default, all values are considered to be in the dictionary. If a filter
  24. is supplied, only the objects for which it returns True are considered as
  25. being in the dictionary:
  26. >>> add1_odd = Transform(lambda x: x + 1, lambda x: x%2 == 1)
  27. >>> 2 in add1_odd
  28. False
  29. >>> add1_odd.get(2, 0)
  30. 0
  31. >>> 3 in add1_odd
  32. True
  33. >>> add1_odd[3]
  34. 4
  35. >>> add1_odd.get(3, 0)
  36. 4
  37. """
  38. def __init__(self, transform, filter=lambda x: True):
  39. self._transform = transform
  40. self._filter = filter
  41. def __contains__(self, item):
  42. return self._filter(item)
  43. def __getitem__(self, key):
  44. if self._filter(key):
  45. return self._transform(key)
  46. else:
  47. raise KeyError(key)
  48. def get(self, item, default=None):
  49. if item in self:
  50. return self[item]
  51. else:
  52. return default