Coverage for /usr/lib/python3/dist-packages/sympy/core/rules.py: 57%
14 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
1"""
2Replacement rules.
3"""
5class Transform:
6 """
7 Immutable mapping that can be used as a generic transformation rule.
9 Parameters
10 ==========
12 transform : callable
13 Computes the value corresponding to any key.
15 filter : callable, optional
16 If supplied, specifies which objects are in the mapping.
18 Examples
19 ========
21 >>> from sympy.core.rules import Transform
22 >>> from sympy.abc import x
24 This Transform will return, as a value, one more than the key:
26 >>> add1 = Transform(lambda x: x + 1)
27 >>> add1[1]
28 2
29 >>> add1[x]
30 x + 1
32 By default, all values are considered to be in the dictionary. If a filter
33 is supplied, only the objects for which it returns True are considered as
34 being in the dictionary:
36 >>> add1_odd = Transform(lambda x: x + 1, lambda x: x%2 == 1)
37 >>> 2 in add1_odd
38 False
39 >>> add1_odd.get(2, 0)
40 0
41 >>> 3 in add1_odd
42 True
43 >>> add1_odd[3]
44 4
45 >>> add1_odd.get(3, 0)
46 4
47 """
49 def __init__(self, transform, filter=lambda x: True):
50 self._transform = transform
51 self._filter = filter
53 def __contains__(self, item):
54 return self._filter(item)
56 def __getitem__(self, key):
57 if self._filter(key):
58 return self._transform(key)
59 else:
60 raise KeyError(key)
62 def get(self, item, default=None):
63 if item in self:
64 return self[item]
65 else:
66 return default