Re: Dictionaries in Python

Jim Roskind (jar@infoseek.com)
Tue, 23 Aug 1994 16:28:00 -0700

> From: powers@dvts.com (Michael Powers)
>
> My question is in simplified form:
>
> FILE a.py LOOKS LIKE
>
> yes = "yes"
> no = "no"
> from b import *
> main()
>
>
> FILE b.py LOOKS LIKE
>
> def main():
> print yes
> print no
>
> The problem is that yes and no are not found inside of the main function.
> How do I share global variables between separate files??

The confusion is that you are thinking of the "from b import ..." as
though it were a C language #include. In truth, all it does is
introduce "main" into the namespace (actually, module dictionary) of
the file a.py. Alas, when you call "main()" the call goes to a
function in b.py, and executes *there* (in module b.py). When "main"
is executing, over in file b.py, I'm sure you can see the $@%& hits
the fan.

I don't really think you *want* to fix this (I'm just guessing you're
trying to play games akin to C language header file inclusion in
different contexts), but the solution to "fix" your error is to help
the "main" program *properly* identify the variables `yes' and `no'.
First of all, since they are not in the module b.py, you'll have to
reference them more explicitly, by writing:

FILE b.py (when first fixed) LOOKS LIKE

def main():
print a.yes
print a.no

...but then you'll notice that `a' is not known in module b.py. To
get it added to a dictionary, you have to add an import statement.
I'll do it in a very private, very non-C-like way, to help to
illuminate the distinction (between import and #include):

FILE b.py (when really fixed) LOOKS LIKE

def main():
import a # add `a' to local namespace, and load a.py into
# Python if not already done
print a.yes
print a.no

When you see the import directive used in this way it is *much*
clearer that a C-like include is *not* being done, and *only* a name
is being added to the local namespace (in this case, the name is added
to the dictionary that roughly corresponds to where C-language auto
variables are kept (i.e., on the stack).

Hope that helped (though I doubt the solution is what you were really
after).

Jim

-- 
Jim Roskind
voice: 408.982.4469
fax: 408.986.1889
jar@infoseek.com