Suppose I have the code:
JavaScript
x
4
1
a = 2
2
b = a + 2
3
a = 3
4
The question is: how to keep b
updated on each change in a
? E.g., after the above code I would like to get: print(b)
to be 5
, not 4
.
Of course, b
can be a function of a
via def
, but, say, in IPython it’s more comfortable to have simple variables. Are there way to do so? Maybe via SymPy
or other libraries?
Advertisement
Answer
You can do a lambda, which is basically a function… The only malus is that you have to do b()
to get the value instead of just b
JavaScript
1
8
1
>>> a = 2
2
>>> b = lambda: a + 2
3
>>> b()
4
4
5
>>> a = 3
6
>>> b()
7
5
8