Python setting global variables in different ways in 2.7
Question: I was trying to practice a concept related to setting global variables using
diff methods , but the following example is not working as per my
understanding .

    
    
    #Scope.py
    
        import os
        x = 'mod' 
    
        def f1() :
            global x
            x = 'in f1'
    
        def f2() :
            import scope
            scope.x = 'in f2'
    
        def print_x() :
            print x
    
        def f3() :
            import sys
            sc = sys.modules['scope']
            sc.x =  'in f3'
    
    
    
    
        if __name__  == "__main__" :
            f1()
            print_x()
            f2()
            print_x()
            f3()
            print_x()
    

It gives the following result

    
    
    in f1
    in f1
    in f1
    

While as per my understanding it shd result in

    
    
    in f1
    in f2
    in f3
    

Can someone help me in understanding what am i doing wrong ??


Answer: Check out this modified piece of code.

    
    
    x = 'mod'
    
    
    def f1():
        global x
        x = 'in f1'
    
    
    def f2():
        import scope
        scope.x = 'in f2'
        return scope
    
    
    def print_x():
        print(x)
    
    
    def f3():
        import sys
        sc = sys.modules['__main__']
        sc.x = 'in f3'
        return sc
    
    
    if __name__ == "__main__":
        f1()
        print_x()
        sc = f2()
        print_x()
        print(sc.x)
        sc = f3()
        print_x()
        print(sc.x)
    

The thing is that in the original `f2()` you actually import your `scope`
module under name `scope` and modify its variable. And in following
`print_x()` you refer to an unchanged `x` in `__main__`. In `f3()`, you
reference your module by wrong name: to modify it, you should use `__main__`
here. With `scope`, you're actually referencing the module that was imported
in `f2()` (Try removing `f2()` call)... Which is clearly not what you want.

