Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create recalculating variables in Python

Tags:

python

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?

like image 431
Anton Tarasenko Avatar asked Aug 05 '13 17:08

Anton Tarasenko


People also ask

Can you reassign variables in Python?

Reassigning variablesValues can be reassigned to variables in Python. When variables are reassigned, their value changes to that of the newer value specified, and the previous value is lost. Let's look at an example. We can reassign variable values in Python as follows.


1 Answers

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
like image 77
Maxime Lorant Avatar answered Oct 04 '22 02:10

Maxime Lorant