1

I found an interesting behavior in Python which I would like to fully understand.

setup.py:

good='hello'
def isGood(testGood): return testGood == good
print(isGood('hello'))
print(isGood('bye'))
good='bye'
print(isGood('bye'))

Output is:

True
False
True

main.py:

from setup import *
print(good)
print(isGood('hello'))
good='hello'
print(good)
print(isGood('hello'))

Output is:

True
False
True
bye
False
hello
False

In short: Function isGood() is sensitive to the changes of global variable 'good' when the function is used inside setup.py. However, once imported (with from setup import *), the function is no more sensitive to changes of variable 'good'. There is no difference in the behavior if declaring 'global good' (it is also not expected to make such, in this case).

How is this explained? It is if the function content (non-input variables) are "compiled" after the import. I'm looking for a source that documents this behavior (to know if it can be trusted).

Aviram Tal
  • 31
  • 2

1 Answers1

1

When you use from module import * you will create duplicate instances of them locally.

In your example, good in main.py is just a copy of good in setup.py, and changing it in main.py does not affect the variable in setup.py.

If you want to be able to access it, You can use one of these methods below:

Method 1

Use a function to set the variable:

setup.py

def set_good(value):
    global good
    good = value

main.py

from setup import *

set_good('bye')

Method 2

Use a class to keep the variable

class variables:
    good = 'good'

def isGood(testGood): 
    return testGood == variables.good

main.py

from setup import *

variables.good = 'bye'

Method 3

Import module and access the variable

main.py

import setup

setup.isGood('hello')  # True
setup.good = 'bye'
setup.isGood('bye')    # True
Ashenguard
  • 174
  • 1
  • 10
  • "When you use from module import * you will create duplicate instances of them locally." This says it all, thanks. – Aviram Tal Aug 06 '23 at 12:06
  • 1
    I think it is even more accurate to say that using "from mymodule import *" will duplicate all immutable variables in mymodule, whereas mutable variables are preserved (pointing to the same memory address). – Aviram Tal Aug 06 '23 at 12:15
  • Well to be more exact even if you import a mutable variable like a list, still you won't be able to change it with `mylist = []`. You can just access its methods and fields like removing or adding to it. – Ashenguard Aug 06 '23 at 12:43
  • What you are describing is the normal use of mutable variables. – Aviram Tal Aug 06 '23 at 19:51