Importing a global function vs. Defining a global function (Python)

45 Views Asked by At

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).

1

There are 1 best solutions below

4
On

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