PaxPrz
PaxPrz

Reputation: 1928

Using global variable from one python file to another

I have created 3 python files in a folder. Here are each of the files and their contents:

one.py

products="testvar"
def oneFn():
    global products
    products=[1,2,3,4,5]
    print("one Function")

two.py

import one

def twoFn():
    one.products.append(100)
    print(one.products)
    print("two Function")

test.py

from one import *
from two import *

if __name__=="__main__":
    oneFn()
    twoFn()
    print(products) # testvar
    print(one.products) # [1,2,3,4,5,100]

Why is products and one.products returning different values?

Upvotes: 1

Views: 74

Answers (1)

dhke
dhke

Reputation: 15398

from one import * pulls in all exported names from module one into the current namespace. It does so, by creating (or overwriting) variables in the local namespace that (initially) refer to the same objects as the variables from the imported module.

However, it is still possible to assign different values to the variables within the main module without affecting the references in the imported module and the other way round.

If you re-assign a variable within a module after importing it, that modification will not be visible in the importing module.

Hence, within oneFn(), you overwrite the products reference in the one module. This does not affect the products reference in the main module.

The global in oneFn() just makes products within the function to refer to the one from the outer namespace and is more or less irrelevant wrt. to the behaviour you experience. If you write

from one import products
import one
one.products = 'othervalue'

You still get products == 'testvar', locally.

Upvotes: 3

Related Questions