Python Forum
Why is from code import * different from entering that code directly into the REPL?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why is from code import * different from entering that code directly into the REPL?
#1
...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.
Reply
#2
When you import the module, the function is defined but it is not called. The module doesn't contain the line
func()
Reply
#3
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...
Reply
#4
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.
Reply
#5
And also star import is considered bad practice altogether, so better avoid it
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
Thank you all
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  20 Ways To Call QuickBooks Customer Service Directly by Phone, Chat, and Email: A Ste james34 0 6 Less than 1 minute ago
Last Post: james34
  I am getting an IndentError on my python code in VS Code and i dont know why jcardenas1980 11 4,403 Mar-22-2025, 09:49 AM
Last Post: Pedroski55
  Python: How to import data from txt, instead of running the data from the code? Melcu54 1 660 Dec-13-2024, 06:50 AM
Last Post: Gribouillis
  Merge Python code with Micro Python code? adzy 2 978 Jul-03-2024, 11:41 AM
Last Post: kkinder
  Eliminate entering QR - Whatsapp web automated by selenium akanowhere 1 4,046 Jan-21-2024, 01:12 PM
Last Post: owalahtole
  My code works on Jupyter Lab/Notebook, but NOT on Visual Code Editor jst 4 4,427 Nov-15-2023, 06:56 PM
Last Post: jst
  problem in entering address of a file in input akbarza 0 1,489 Oct-18-2023, 08:16 AM
Last Post: akbarza
  Error on import: SyntaxError: source code string cannot contain null bytes kirkwilliams2049 7 20,224 Aug-03-2023, 06:00 PM
Last Post: Gribouillis
  Import XML file directly into Excel spreadsheet demdej 0 1,602 Jan-24-2023, 02:48 PM
Last Post: demdej
  python multiple try except block in my code -- can we shorten code mg24 10 15,194 Nov-10-2022, 12:48 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020