Suppose I have the code:
a = 2 b = a + 2 a = 3
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
>>> a = 2 >>> b = lambda: a + 2 >>> b() 4 >>> a = 3 >>> b() 5