How to import only one module in a package when the package has already imports the modules?

Steven D'Aprano steve at
Sun Nov 1 04:03:07 CET 2009

On Sat, 31 Oct 2009 16:53:50 -0500, Peng Yu wrote:

> I know that multiple classes or functions are typically defined in one
> file (i.e. module in python). However, I feel this make the code not
> easy to read. Therefore, I insist on one class or function per file (i.e
> module in python).
> When one class per module is strictly enforced, there will be no need to
> have different capitalization conventions for modules and classes.
> Developers should be able to tell whether it is a class or a module from
> the context.

Classes and modules are first-class objects in Python, so you can't 
necessarily tell what they are from context. I frequently have code like 

def verify(test_func, objects_to_process, expected_results):
    for obj, result in zip(objects_to_process, expected_results):
        print "Testing %r..." % obj, 
        r = test_func(obj)
        if r == result:
            print "verified"
            print "expected %r but got %s" % (result, r)

objects_to_process could be a list of floats, strings, functions, 
modules, or anything else. Having a naming convention is still useful for 
distinguishing (say) factory functions from classes, or modules from 

> In my question, module A and B exist just for the sake of
> implementation. Even if I have module A and B, I don't want the user
> feel the existence of module A and B. I want them feel exact like class
> A and B are defined in module 'test' instead of feeling two modules A
> and B are in package 'test'. 

Inside test/

from A import A  # class A from file
from B import B  # class B from file

or better still:

from a import A  # class A from file
from b import B  # class B from file

> I know that module names should be in lower
> cases, in general. However, it is OK to have the module name capitalized
> in this case since the end users don't see them.

Of course they do.

> I looked at python library, there are quite a few files are
> not empty. In fact, they are quite long. I agree with you that
> '' should not be long. But I'm wondering why in python
> library are quite long.

Define "quite long".

In Python 2.6, I have:

[steve at sylar python2.6]$ for file in */; do echo "$file" `cat 
$file | wc -l` ; done
bsddb/ 450
compiler/ 29
ctypes/ 546
curses/ 59
distutils/ 26
email/ 123
encodings/ 157
hotshot/ 78
idlelib/ 1
json/ 318
lib2to3/ 1
logging/ 1490
multiprocessing/ 271
sqlite3/ 24
test/ 1
wsgiref/ 23
xml/ 47

With the exception of logging, I don't see any of those as quite long.


More information about the Python-list mailing list