How to import only one module in a package when the package __init__.py has already imports the modules?
pengyu.ut at gmail.com
Sat Oct 31 21:31:37 CET 2009
On Sat, Oct 31, 2009 at 12:47 PM, Duncan Booth
<duncan.booth at invalid.invalid> wrote:
> 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
> import test.a
> or even
> import test.a
> 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.
The original problem comes from the maintenance of the package. When A
and B are large classes, it is better to put them in separate files
under the directory 'test' than put them in the file 'test.py'. The
interface 'test.A' is used by end users. However, there will be a
problem if 'import test' is used for developers, because both A and B
are imported, which cause dependence between A and B. For example,
during the modification of B (not finished), 'import A' would not
work. This is means that modifications of A and B are not independent,
which cause a lot of problem when maintaining the package.
Naming the filename different from the class is a solution, but it is
a little bit annoying.
I'm wondering how people handle this situation when they have to
separate a module into multiple modules.
More information about the Python-list