Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference

Grant Edwards grant.b.edwards at gmail.com
Wed Mar 6 20:55:40 EST 2024


On 2024-03-07, dn via Python-list <python-list at python.org> wrote:

> The idea of importing a module into the REPL and then (repeatedly) 
> manually entering the code to set-up and execute is unusual (surely type 
> such into a script (once), and run that (repeatedly). As you say, most 
> of us would be working from an IDE and hitting 'Run'. Am wondering why 
> you weren't - but it's not important.

Unless the code is intended to be used as a module, 'import'ing it into
the REPL doesn't make sense.

A simple example:

---------------------------testit.py------------------------------
x = 'x'
y = 'y'
def foo():
    global y
    print("hi")
    x = 'X'
    y = 'Y'
    print(x)
    print(y)
------------------------------------------------------------------

The usual method to play with that interactively is

    $ python -i testit.py
    >>> x
    'x'
    >>> y
    'y'
    >>> foo()
    hi
    X
    Y
    >>> x
    'x'
    >>> y
    'Y'
    >>>

As we've seen, doing a 'from testit.py import *' doesn't let you test
what the OP was trying to test. Doing 'import testit.py' gets you
closer, but it's a hassle to test code that way. The right thing to do
is 'python -i <filename>' (or the equivalent button/option in an IDE).

  https://docs.python.org/3/tutorial/interpreter.html

If you intended to use testit.py as a module, and wanted to experiment
with its behavior as a module, then go ahead and import it. But, don't
do 'from testit.py import *' until

 1. you know how that differs from 'import testit.py'

and

 2. you want to use that difference




More information about the Python-list mailing list