Q: organizing classes in modules

Greg Ewing greg at cosc.canterbury.ac.nz
Wed Mar 22 04:42:04 CET 2000


Stephan Reiling wrote:

> I looked into what I can do in the __init__.py file of the module. The only
> thing I could figure out was to put something like the following there:
> 
> from Class1 import *
> from Class2 import *
> ...
> 
> Which according to what I have read is not a good idea

As long as you intend all the names defined in the Class1,
Class2 etc. submodules to appear in the package namespace,
it doesn't do any great harm here. The advice against using "import
*" applies when you're importing from some module that you
don't know the full contents of. One reason is to prevent you from
accidentally importing some name that clashes with another one
you've already got. In this case, you're in control of both
modules, so you can make sure that there are no clashes.

The other reason for not using "import *" is that it makes it
harder to trace where names are coming from. That could be a
concern here, but as long as there is a clear relationship
between the class name and the module it comes from (as there
obviously is in your case) it's not going to be a serious
problem.

Nevertheless, you can easily avoid using "import *" if you
want:

  from Class1 import Class1
  from Class2 import Class2

etc.

> and also seems to increase startup time.

That's because it forces all the submodules to be loaded when
the package is first imported, rather than waiting until one
of the submodules is referenced. If your submodules are all
closely related, so that using one of them requires all or most
of the others as well, the user is going to have to wait for
them to load anyway.

On the other hand, if your submodules are independent and
the user is likely to want to load only some of them, and
startup time is a problem, you may be forced to put up with
the more verbose importing syntax.

> (And what happens if Class1 and Class2 cross-reference each other,

That's no problem as long as you make the cross-references in the
right way, e.g. in Class1.py you say

  import Class2

and then refer to Class2.Class2 wherever needed. 

> or one of my classes has to be a singleton)

  class _Singleton:
    ...

  Singleton = _Singleton()

Names beginning with "_" are ignored by "import *", so only
Singleton will be imported into the main package.

Hope that helps,

-- 
Greg Ewing, Computer Science Dept,
+--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg at cosc.canterbury.ac.nz	   +--------------------------------------+



More information about the Python-list mailing list