'How can I use a global variable in another file in Python?

I want to make i into 3 in file s2.py, but it keeps becoming 1.

File s1.py

i=1

class a():
    def f():
        global i
        i = 3

File s2.py

from s1 import *

a.f()
print(i)


Solution 1:[1]

Every module has its own global scope, and Python is lexically scoped, meaning a.f refers to the global scope of s1 no matter where it is called from. i is initialized to the value of s1.i, but is otherwise independent of it. Changes to s1.i do not affect s2.i.

Solution 2:[2]

You have to re-import your variable after calling your method if you want to see any changes made.

#s1.py
i=1

class a():
    def f():
        global i
        i = 3

#s2.py
from s1 import *    
a.f()

from s1 import i
print(i)

Solution 3:[3]

#s1.py
i=1

class a():
    def f():
        global i
        i += 3



#s2.py
import s1

s1.a.f()
print(s1.i)

Solution 4:[4]

I believe you are referencing the local variable i and aren't referencing the instance of i in the class. Try this.

print(a.i)

Solution 5:[5]

Reimport the variable after calling the method:

File s1.py

i = 1

class a():
    def f():
        global i
        i += 3

File s2.py

import s1

s1.a.f()
print(s1.i)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chepner
Solution 2 Andrew M.
Solution 3 vexem
Solution 4 Donald Duck
Solution 5 Peter Mortensen