Variable inside module

Alex Martelli aleax at aleax.it
Mon Apr 14 17:39:52 EDT 2003


Marcelo A. Camelo wrote:

> 
> Hi!
> 
> Can someone please explain-me what is
> happening here:
> 
> Given the followin bar.py file (placed
> inside a foo/ directory):
> 
> var = 'foo'
> 
> def SetVar():
> global var
> var = 'bar'
> 
> def PrintVar():
> global var
> print 'var:', var
>       
> In the same foo/ directory, I've placed
> the following __init__.py:
> 
> from bar import *

"from X import" binds names in the current module (or
current local namespace) to the values those names
hold _at this time_ in module X.  And this is all it
ever does and all it will ever do.


> Then, in the interactive python interpreter:
> 
> >>> import foo
> >>> print foo.var
> foo
> >>> foo.PrintVar()
> var: foo
> >>> foo.SetVar()
> >>> foo.PrintVar()
> var: bar
> >>> print foo.var
> foo
> >>>
>       
> What I don't understand is that foo.var seems
> to be two different variables: one accessed
> inside the bar.py file and one accessed from
> within the python interpreter. What is going on
> here?

Essentially the same thing as having, in foo/__init__.py
(which is the module body for "module foo" -- that's how
packages work):

import bar
var = bar.var
SetVar = bar.SetVar
PrintVar = bar.PrintVar
del bar

any future rebinding of bar.var will have no effect
on what foo.var is bound to now.

Yes, there ARE two different names (and variables are
just that -- names): foo.var and bar.var.


I've often recommended forgetting the existence of
statement from -- the confusion it can cause is not
justified by the modest advantages it can provide
when compared to using import (plus potentially one
or more assignments).


Alex





More information about the Python-list mailing list