what is happening here?

John Roth newsgroups at jhrothjr.com
Tue Apr 6 18:49:23 EDT 2004


"dan miller (moderator, s.p.d)" <danbmil at cmu.edu> wrote in message
news:c4vaum$q39$1 at nntp.ece.cmu.edu...
> trying to figure out scoping of 'globals' in modules.  So I have test.py:
>
> glob = 1
>
> def setglob(v):
>    global glob
>    glob = v
>
> def getglob():
>    return glob
>
>
> and I do this:
>
>  >>> from test import *
>  >>> glob
> 1
>  >>> getglob()
> 1
>  >>> glob=2
>  >>> glob
> 2
>  >>> getglob()
> 1
>  >>> setglob(3)
>  >>> getglob()
> 3
>  >>> glob
> 2
>
>
> Seems to me like the first time I invoke glob, it creates a new global
> in my namespace, and initializes it to the value of the glob in test.py.
>     Seems counterintuitive!

Sure seems wierd. What it looks like to me is that
your import is binding three objects, but the actual
functions are still refering to whatever object is bound
in the "test" module, not in the interpreter's namespace.
In other words, they are using the global dictionary
they were compiled with, not their caller's global
dictionary.

Make sense?

John Roth
>





More information about the Python-list mailing list