[Python] Global Variables between different modules

Discussão em 'Python' iniciado por Stack, Junho 28, 2025.

  1. Stack

    Stack Membro Participativo

    main.py:

    from module import *
    var=10

    def func2():
    print "func2:" ,var

    def main():
    global var
    var=20
    print "main - before", var
    func2()
    func1()
    print "main - after", var

    if __name__=='__main__':
    main()


    module.py

    from main import *

    def func1():
    global var
    print "func1:", var


    The program prints:


    main - before: 20

    func2: 20

    func1: 10

    main - after 20
    ​

    'var' is a global variable. I would expect that the moment I change var's value, it will be changed wherever the variable 'var' appears. The only difference between func1 and func2 is that func1 is in another module. Still, I don't understand why the value of 'var' is different between func1 and func2.

    Continue reading...

Compartilhe esta Página