[Tutor] Style question with classes and modules

Luke Paireepinart rabidpoobear at gmail.com
Thu Jul 19 21:15:17 CEST 2007


Tino Dai wrote:
> Hi there Everybody,
>
>        I have style question with importing of modules and classes. 
> Presently, I have several files importing several modules.
>
> #apacheModule
> import dbBase
> import dbCommon
> import miscBase
>
> My question is there any advantage to me wrapping them in a single 
> file (wrapper), and the importing a single file
> into that file (barring namespace collisons). Example shown below:
>
> In aggreateBase:
> import dbBase
> import dbCommon
> import miscBase
>
> In apacheModule:
> import aggreateBase
This statement binds the variable name aggreateBase (do you mean 
aggregate?) to the module aggreateBase.py
which has imports inside of it.
So every time you want to use one of the modules you import via 
aggreateBase, you'd have to type:
aggreateBase.dbBase.function_name()
you can get around this by typing
from aggreateBase import *
> # instead of
> #import dbBase
> #import dbCommon
> #import miscBase
>
> or perhaps even
> In aggreateBase:
> from dbBase import dbBase
> from dbCommon import dbCommon
> from miscBase import miscBase
This doesn't work.  try it out.
 >>> from sys import sys

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in -toplevel-
    from sys import sys
ImportError: cannot import name sys
>
> The two advantages that I can see are, I don't need to type as much, 
> and there would be a speed up in the execution of code.
> Is there a reason why I shouldn't?
You need to type more or the same amount, not less.
There wouldn't be a speed up in code execution. Why would there be?

The reason why you shouldn't is because it hides the external modules 
you're using in that particular module's implementation.
Secondly, you'd have to create a new aggreateBase for each new set of 
imports that you'd want to use, otherwise certain modules would be 
importing things they didn't actually need.
It's much easier and clearer to put the imports of the modules that 
you're using in the module that you're using them.

For what purpose would you do this?
-Luke


More information about the Tutor mailing list