1

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?

2
  • 2
    import * is generally bad practice, be careful. Commented Feb 7, 2020 at 17:25
  • This is a great question because it shows how confusing imports can become if you are not careful. Commented Feb 8, 2020 at 0:42

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes @dhke, just like you say from one import * is importing everything from one.py and making it essentially a local variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.