Modules, namespaces, parents, and import
Dietrich Epp
dietrich at zdome.net
Wed Feb 4 02:00:40 EST 2004
On Feb 3, 2004, at 10:28 PM, Dan Williams wrote:
> Hi people
>
> I've just joined the Python list and although I'm sure my question
> must be
> asked fairly frequently, I have been unable to find an answer after
> two days
> of searching. For the record, my total Python experience is also two
> days :)
> (I come from a C++ background though, so I have good programming
> knowledge
> in general).
>
> My question is thus: how do I reference a parent module and its
> children?
--- foo/__init__.py ---
import module1
a = 5
module1.DoStuff
--- foo/module1.py ---
import sys
import foo
def DoStuff():
print foo.a
sys.exit(0)
------
The idea is that when you look at a single source file, all the imports
are right there. Each module has its own namespace, and doesn't
inherit from its parent. Otherwise it would get cluttered to heck!
You said that importing sys from module1 is inefficient and
impractical. Why? It takes more writing to use parent.sys.bar instead
of just sys.bar... I'd regard putting 'parent' in front of every
occurrence of 'sys' impractical. Plus, if you use parent.sys, it looks
like your using the module 'sys' from the package 'parent', which isn't
the case.
You might have been thinking about speed... but don't. First of all,
you're forgetting the first rule of optimization: Don't. Second rule
of optimization: Don't, yet. Third rule of optimization: The
bottleneck isn't where you think it is. For a lot of code, the
bottleneck is actually writing the code. So to make the whole process
faster, write the code faster. This means write less code, and
especially don't do anything just because you think it would be faster
for the computer. Often you're wrong, and you've just wasted a lot of
your time, and the computer is probably fast enough.
And finally, using 'parent.sys.exit' is slower because Python has to
get the value of 'parent', then get its attribute named 'sys', then get
sys's attribute named 'exit', than call it. If you import sys
directly, you don't have to retrieve it from 'parent' every time, and
no, this does not load additional code -- it just references the
already loaded module.
Please, please don't be seduced by optimization. Make your code work.
It is far easier to optimize correct code than correct optimized code.
Also, never optimize code not checked into a revision control system.
More information about the Python-list
mailing list