[Tutor] Newbie trying to understand modules and code reuse
karl.fast at pobox.com
Thu Feb 5 15:25:17 EST 2004
> I tried create a file and putting it in my /python/lib directory and
> importing it. Surprisingly I was able to import it but I was unable
> to access the variables or methods in the file.
Namespaces are an important concept in Python and I suspect that is
what's tripping you up. If it gets imported then you should be fine.
When you import something all of the variables and functions (or
classes) are available in that namespace.
Suppose you've for a module called "mymodule.py" and it looks kinda
myvar = "something"
print "something else"
Now suppose you've got that module somewhere in your python library
path (that is, when you importy mymodule, python can find it).
So now you write a script called "myscript.py" and you import that
module. It looks like this:
When you run this the output should be:
The trick is that python imports everything into the mymodule
namespace and that's how you access it.
You can import them directly into the main namespace by doing
something like this:
from mymodule import *
Note the difference. Now the variable and the function are not
qualified as being part of the mymodule namespace.
Namespaces are really important in python. They are in most
programming languages actually. The syntax is different and some
behaviours are slightly different, but the basic concept is pretty
More information about the Tutor