Dynamic Scoping problem

Andrew Koenig ark at acm.org
Mon Aug 23 11:47:20 EDT 2004


"Daniel Lemos Itaborai" <itaborai83 at yahoo.com.br> wrote in message
news:b8320fb9.0408230713.5f3d2d7a at posting.google.com...

> I would like to first apologize my question, I just picked up Python
> for a spin 4 days ago(loving it so far). I am having some trouble with
> this...
>
> # myproblem.py
>
> x = 'wrong'
>
> def bluft(x) : x()
>
> def foo():
>         x = 'right'
>         def bar():
>                 global x
>                 print x
>         bluft(bar)
>
> # end myproblem.py
>
>
> Is there a way to enforce scope resolution?

When you write

     def foo():
        x = 'right'
        ...

you are defining a new variable, local to foo, named x.  When you say
"global x" inside bar, you are saying that you do not want that variable;
you want the global one instead.

If you want to assign 'right' to the global x, do it this way:

    def foo():
        global x
        x = 'right'
        def bar():
            print x
        bluft(bar)

That said, I should point out that global variables are usually a bad idea.





More information about the Python-list mailing list