[Python] Python global variable changes depending on how script is run

Discussão em 'Python' iniciado por Stack, Maio 14, 2025.

  1. Stack

    Stack Membro Participativo

    I have a short example python script that I'm calling glbltest.py:

    a = []

    def fun():
    global a
    a = [20,30,40]

    print("before ",a)
    fun()
    print("after ",a)


    If I run it from the command line, I get what I expect:

    $ python glbltest.py
    before []
    after [20, 30, 40]


    I open a python shell and run it by importing, and I get basically the same thing:

    >>> from glbltest import *
    before []
    after [20, 30, 4]


    So far so good. Now I comment out those last three lines and do everything "by hand":

    >>> from glbltest import *
    >>> a
    []
    >>> fun() # I run fun() myself
    >>> a # I look at a again. Surely I will get the same result as before!
    [] # No! I don't!


    What is the difference between fun() being run "automatically" by the importing of the script, and me running fun() "by hand"?

    Continue reading...

Compartilhe esta Página