organizing classes in modules

Emile van Sebille emile at fenx.com
Wed Mar 22 13:07:29 EST 2000


Hi Stephan,

If you put the following in __init__.py under module1 you'll
be able to do what you want.

import os

for pyclass in os.listdir(__path__[0]):
    if pyclass[0] != "_" and pyclass[-3:] == '.py':
        __import__(pyclass[:-3],globals(),locals(),pyclass[:-3])


Note:  Add any qualifiers as needed, and I doubt this will help
your start-up time issue.

HTH


Emile van Sebille
emile at fenx.com
-------------------


----- Original Message -----
From: Stephan Reiling <sreiling at elara.tripos.com>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Tuesday, March 21, 2000 7:27 AM
Subject: Q: organizing classes in modules


> I have a question about how to organize classes in modules:
> I would like to organize my classes so that every class has its own
file, the
> file having the same name as the class, e.g.
> In file Class1.py
>     class Class1:
>         ...
>
> I would also like to put these into a module, for example module1.
When I now
> want to use Class1, I would like to just say:
>
> import module1
> c=module1.Class1()
>
> instead I have to say:
>
> import module1
> c=module1.Class1.Class1()
>
> I have quite a few of these classes, so this gets annoying after a
while.
> 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, and also seems
to
> increase startup time.
> (And what happens if Class1 and Class2 cross-reference each other, or
one of my
> classes has to be a singleton)
>
> So the question is:
> How can I do this? Obviously I am trying to organize my code in a way
like C++
> and java do it. Right now I have around 30 classes distributed over 6
modules
> and sub-modules and I expect the number of classes to grow.
>
> Thanks,
>     Stephan
>






More information about the Python-list mailing list