modules and namespaces
Jaime Wyant
programmer.py at gmail.com
Tue Apr 19 09:35:43 EDT 2005
Each module has its own "namespace", which is like a dictionary of
objects that the module can "see". I use the term dicitionary because
locals() and globals() both return dictionaries -- someone may correct
me on this (or confirm what I say)...
You have local and global variables.
Locals are variables in the scope of a function.
def myfun():
localvar = 1
`globals' are really 'module' global only.
# mymodule
global_var = 3
def myfun()
print global_var
# This is a *gotcha* -- you can't change global variables this way.
# here, a new local variable global_var is initialized.
global_var = 3
def changeglobal():
# you have to use `global' to instruct python to use the `global'
instance of the variable
# instead of creating a new one when you assign to it.
global global_var
global_var = 3
You can only see variables you've created or modules you've imported.
Becase you haven't imported string in m2 or m3, you can't see them.
hth,
jw
On 4/19/05, Mage <mage at mage.hu> wrote:
> Hello,
>
> I thought that this will work:
>
> #m1.py
> def f1():
> return string.join('a','a')
>
> #m2.py
> def f2():
> return string.join('b','b')
>
> #main.py
> import string
> import m1
> import m2
>
> print f1()
> print f2()
>
> ---------
>
> However it doesn't work until I import the string module into m1 and m2
> modules. I found in the manual that imported modules will be searched in
> the container module first. Is it more efficient to import the string
> module into main and m1 and m2 than importing only into m1 and m2?
>
> Mage
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list