Python setting global variables in different ways in 2.7
<p>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 .</p>

<pre><code>#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()
</code></pre>

<p>It gives the following result </p>

<pre><code>in f1
in f1
in f1
</code></pre>

<p>While as per my understanding it shd result in</p>

<pre><code>in f1
in f2
in f3
</code></pre>

<p>Can someone help me in understanding what am i doing wrong ??</p>

<p>Check out this modified piece of code.</p>

<pre><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)
</code></pre>

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

python scope