yanwii
yanwii

Reputation: 170

How can I change a variable defined in another file?

I have two files: test1.py and test2.py

in test1.py:

a = 1
def printa():
    print a

in test2.py:

from test1 import a, printa
a = 2
printa()

I got

1

but if I change the test2.py to

import test1
test1.a = 2
printa()

I got 2 instead. How does it work?

Upvotes: 1

Views: 2902

Answers (2)

Matt_G
Matt_G

Reputation: 516

What you're encountering is variable scoping.

If you import all of test1, you have access to the variables in test 1 because they are within your current operating scope, so directly accessing it, and changing it, allows you to print 2.

In your second snippet, you are defining a local variable a=2, which has no bearing on test1.a and therefore when you print, it displays test1.a value of 1.

In other words, when you reference test1.a you are accessing one variable, but when you define a local a=2, this is a different variable altogether than printa() is referencing. Variables in python are created and destroyed within their scope. As such, you can create multiple variables in the same python script with the same name without undesired functionality, provided they are encapsulated within their scope.

try printing both versions to see the difference.

import test1

a=2
print a
print test1.a

Upvotes: 2

Ari K
Ari K

Reputation: 444

When you assign a=2, it's in the scope of test2.py, and the test1.printa() method still holds reference to the variable a from test1.

To test this try

import test1
from test1 import a, printa

a = 2
a #will return 2

test1.a #will still return 1

In other words, when you set a = 2, you didn't change the class variable test1.a, which is separate from the a defined in test2.py in memory.

Upvotes: 0

Related Questions