global name space and importing

emile at fenx.com emile at fenx.com
Sat May 27 21:47:51 EDT 2000


Your 'y' variable exists at the module level in foo_bar.

See section 4.1 in the Python Refernce Manual the explains namespaces.

Also, from import * can be dangerous as it replaces references in the
current namespace.  

>>> bar(3)
>>> foo_bar.y
3
>>> 


HTH,


Emile van Sebille
emile at fenx.com

Curtis Jensen <cjensen at bioeng.ucsd.edu> wrote in message
news:<39306CB7.B5419219 at bioeng.ucsd.edu>...
> How come the global declaration works when I define it from withing the
> interpreter, but not from within a file that I import?  See following
> example.
> 
> file: foo_bar.py:
> def foo(i):
>   x = i
> 
> def bar(i):
>   global y
>   y = i
> 
> Python interpreter:
> >>> from foo_bar import *
> >>> bar(0)
> >>> print y
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> NameError: y
> >>> def other(i):
> ...   global z
> ...   z = i
> ...
> >>> other(5)
> >>> print z
> 5
> >>> ^D
> 
> 
> -- 
> Curtis Jensen
> cjensen at bioeng.ucsd.edu
> http://www-bioeng.ucsd.edu/~cjensen/
> FAX (425) 740-1451
> -- 
> http://www.python.org/mailman/listinfo/python-list
>




More information about the Python-list mailing list