How to properly import a shared variable?

Viewed 28

I am having the following 3 Python files:

a.py:

myvar = 1
   
def increment():
    global myvar
    myvar += 1

b.py:

import a
    
a.increment()
print(a.myvar)

c.py:

from a import increment, myvar
    
increment()
print(myvar)

Now when I run b.py and c.py independently, I get:

python3 ./b.py
2
python3 ./c.py
1

Can you explain the difference?

Thanks!

This is Python 3.7.3 on the latest Debian GNU/Linux (stable).

1 Answers

The overall reason is that integers are immutable.

Let me explain. In your c.py script, a variable myvar is imported from the module a, and then, the increment() method is called on a.myvar doing myvar += 1 in module a. Since we have the reference to myvar already, and integers are immutable, Python can't set that reference to the new value. The reassignment happened only in module a.

To get the updated value after increment(), you should also import your module a, and try to access the reference directly via a.myvar

NOTE that c.py will work correctly if myvar was any of list,dict,set, or other mutable objects.

Here's the updated c.py, which works correctly on integers.

import a
from a import increment, myvar

increment()
print(myvar)

print(a.myvar)

And here's an a.py example with mutable ojbects. Try it with the same c.py and see how it works.

# a.py
myvar = ["some"]

def increment():
    global myvar
    myvar.append("thing")

Related