김동동
김동동

Reputation: 1

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)

Upvotes: 0

Views: 67

Answers (5)

BigJosher
BigJosher

Reputation: 1

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)

Upvotes: 0

RLee
RLee

Reputation: 1

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)

Upvotes: 0

vexem
vexem

Reputation: 86

#s1.py
i=1

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



#s2.py
import s1

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

Upvotes: 0

chepner
chepner

Reputation: 532538

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.

Upvotes: 1

Andrew M.
Andrew M.

Reputation: 41

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)

Upvotes: 0

Related Questions