Namespaces, classes, and using standard modules
Andrew Dalke
adalke at mindspring.com
Wed Aug 13 14:54:17 EDT 2003
Dan Rawson
> Hmm . . . I'm still a bit confused . . . The naming doc says that
>
> from MyClass import MyClass
>
> will only import the stuff that is part of the class scope (if I read it
correctly). But it
> appears to also read and use the 'import os' at the module level for the
MyClass.py file.
>
> The second question is why "import os" doesn't work at the interactive
prompt; once
> I say that, isn't that a 'global' ??
Every module has its own namespace. The interactive prompt has its own
namespace, called "__main__". This is not the global namespace. (There is
a 'global' namespace called "__builtin__", but you should almost never put
anything into it because doing so most often indicates 'bad', or at least
non-standard/non-Pythonic programming style.)
All code in a module looks for so-called globals only in the module's
namespace
and, failing that, in the __builtin__ namespace. So your
MyClass.MyClass.show
method looks for 'os' first in the MyClass module and then in the
__builtin__,
finding it in neither.
This is what's often called "static scoping," as compared to "dynamic
scoping,"
which is what you are looking for. That wouldn't lead to easy to use code
because then when you import a class or function you would need to also
import all the modules it uses. I sure don't want to remember all those.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list