Python Forum

Full Version: Why is from code import * different from entering that code directly into the REPL?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
...indeed, for code.py being
a = 0
def func():
    global a
    a = 1
after entering that code directly into the REPL and typing
func()
print(a)
I get 1, while I get 0 after a
from code import *
Why? Dear community, I am a noob looking forward to understanding such different behaviors. Any help would be greatly appreciated.
When you import the module, the function is defined but it is not called. The module doesn't contain the line
func()
Indeed.
...but I do call the function from within the REPL (not the module) as I enter:
from code import *
func()
print(a)
I would expect to get 1 (rather than 0) as when entering the content from code.py directly into the REPL. I am still puzzled...
It is because each module has its own global namespace, so the global a in module code is not the global a in module __main__. You can use
from code import *
import code
func()
print(code.a)
It is usually best to avoid functions that update global variables.
And also star import is considered bad practice altogether, so better avoid it
Thank you all