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
  Eliminate entering QR - Whatsapp web automated by selenium akanowhere 1 3,018 Jan-21-2024, 01:12 PM
Last Post: owalahtole
  My code works on Jupyter Lab/Notebook, but NOT on Visual Code Editor jst 4 872 Nov-15-2023, 06:56 PM
Last Post: jst
  problem in entering address of a file in input akbarza 0 619 Oct-18-2023, 08:16 AM
Last Post: akbarza
  Error on import: SyntaxError: source code string cannot contain null bytes kirkwilliams2049 7 6,151 Aug-03-2023, 06:00 PM
Last Post: Gribouillis
  Import XML file directly into Excel spreadsheet demdej 0 798 Jan-24-2023, 02:48 PM
Last Post: demdej
  python multiple try except block in my code -- can we shorten code mg24 10 5,890 Nov-10-2022, 12:48 PM
Last Post: DeaD_EyE
  faster code for my code kucingkembar 19 3,107 Aug-09-2022, 09:48 AM
Last Post: DPaul
  help for use print in REPL jip31 10 4,125 Apr-30-2021, 03:52 PM
Last Post: bowlofred
  Putting code into a function breaks its functionality, though the code is identical! PCesarano 1 1,949 Apr-05-2021, 05:40 PM
Last Post: deanhystad
  HackerRank Problem: Code works on VS Code but not on the HackerRank site Pnerd 3 2,594 Feb-28-2021, 07:12 PM
Last Post: Pnerd

Forum Jump:

User Panel Messages

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