Why is from code import * different from entering that code directly into the REPL? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Why is from code import * different from entering that code directly into the REPL? (/thread-17232.html) |
Why is from code import * different from entering that code directly into the REPL? - sebi - Apr-03-2019 ...indeed, for code.py being a = 0 def func(): global a a = 1after 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. RE: Why is from code import * different from entering that code directly into the REPL? - Gribouillis - Apr-03-2019 When you import the module, the function is defined but it is not called. The module doesn't contain the line func() RE: Why is from code import * different from entering that code directly into the REPL? - sebi - Apr-03-2019 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... RE: Why is from code import * different from entering that code directly into the REPL? - Gribouillis - Apr-03-2019 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 usefrom code import * import code func() print(code.a)It is usually best to avoid functions that update global variables. RE: Why is from code import * different from entering that code directly into the REPL? - buran - Apr-03-2019 And also star import is considered bad practice altogether, so better avoid it RE: Why is from code import * different from entering that code directly into the REPL? - sebi - Apr-03-2019 Thank you all |