About one class/function per module

Dave Angel davea at ieee.org
Mon Nov 2 03:52:19 CET 2009

Peng Yu wrote:
> <snip>
> Some people mentioned an good IDE can do 1 and 4. But I'm not aware of
> an IDE that can allow me to change file name freely. I tried Visual
> Studio long time ago, I have to delete a file, change the file name
> and add the file back in order to change the file.
I use Komodo IDE version 5, where right-click->Rename works fine on 
files within a project.
> Now let us consider how well python can support one function/class per
> file style. I encounter the following problems. Suppose that the
> parent directory of 'test' is in $PYTHONPATH and __init__.py is empty,
> test/
> |-- __init__.py
> |-- A.py
> `-- B.py
> where A.py has only class A and B.py has only class B.
> The end user of the test package has to either
>   import test.A
>   a=test.A.A()
> or
>   from test.A import A
>   a=A()
> <snip>
I'm neither agreeing nor disagreeing with the self-imposed restriction 
of one class per module.  But I'd like to jump in with an idea on 
dealing with the namespaces involved.

How about a two-line import, where the second line is a simple assignment?

import test.A
test.A = test.A.A

Now, you can use the class A just as you wanted --
     obj = test.A()

This has the disadvantage that the module itself is no longer 
addressable from here.  But since the only symbol you apparently want 
from the module is the one class, it should be fine.  And you could 
presumably have saved it in a module-specific global anyway.

Note that I did not test whether other modules that also import test.A 
are affected.  So some further study would be necessary.  Also, I tried 
it only in CPython 2.6.2


More information about the Python-list mailing list