Why is a variable not updating after changing its dependent variable?

Issue

I don’t understand why the variable ‘y’ doesn’t update when I change the x? (The ‘y’ variable is dependent on ‘x’ right?)

x = 5
y = x*2

print(x)
print(y)

x = 3

# Expect it to print '3' and '6' instead it print '3' and '10'
print(x)
print(y)

Solution

(The ‘y’ variable is dependent on ‘x’ right?

No.

Few programming languages have dependent / computed variables[0] and Python is not one of them[1]. When y = x*2 is executed, the expression on the right-side of the = is fully evaluated and the result set as the value of y. y is thereafter independent from x[2].

Generally speaking, if you want y to be a function of x… you define it as a function of x:

x = 5
def y(): return x*2

print(x)
print(y())

x = 3

# Expect it to print '3' and '6' instead it print '3' and '10'
print(x)
print(y())

  1. I know of make‘s lazy variables and Perl’s tied scalars
  2. it does have computed attributes (aka properties) but that’s a very different thing
  3. There are situations which kind-of look like dependent variables e.g. if you set y to a mutable sub-structure of x changes to this sub-part of x will be visible through y. That’s not actually a dependency though, it’s just that the two variables point to the same (mutable) structure, so both "see" mutations applied to that shared structure.

Answered By – Masklinn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published