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

Duncan Booth duncan.booth at invalid.invalid
Sat Oct 31 13:47:16 EDT 2009


Peng Yu <pengyu.ut at gmail.com> wrote:

> I'm wondering if there is a way to make the following two things hold.
> Thank you1
> 1. When I 'import test', I can refer to class A as 'test.A'.
> 2. When I 'import test.A', I can refer to class A as 'test.A.A' and
> class B shall not be imported.
> 
No. Either import adds the name 'test' to the current namespace. That name 
in each case references the same thing.

Your simplest solution would be to give the sub-modules lowercase 
filenames, then you can do:

   import test
   test.A()

or

   import test.a
   test.a.A()

or even

   import test.a
   test.b.B()

It would probably be best though just to be consistent as to how you 
reference the classes: define a public interface for your package and stick 
to it.



More information about the Python-list mailing list