what is happening here?

DomF fidtz at clara#spam#.co.uk
Thu Apr 8 07:11:02 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!

This is an instance of "from x import *" being harmful. Try this with just
"import test" in the shell and it doesn't look confusing at all:

>>> import test
>>> glob
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'glob' is not defined
>>> test.glob
1
>>> test.getglob()
1
>>> glob=2
>>> glob
2
>>> test.getglob()
1
>>> test.setglob(3)
>>> test.getglob()
3
>>> glob
2

Dom





More information about the Python-list mailing list