How to import only one module in a package when the package __init__.py has already imports the modules?
robert.kern at gmail.com
Sat Oct 31 22:14:43 CET 2009
On 2009-10-31 15:31 PM, Peng Yu wrote:
> 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.
To be frank, that development process is going to cause you a lot of problems
well beyond these import entanglements. Developers should have their own
workspace! They shouldn't push things into production until the system is
working. Checking something into source control shouldn't automatically deploy
things into production.
> 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.
Even if we organize things along the lines of "one class per module", we use
different capitalization conventions for modules and classes. In part, this
helps solve your problem, but it mostly saves the developer thought-cycles from
having to figure out which you are referring to when reading the code.
Personally, I like to keep my __init__.py files empty such that I can import
exactly what I need from the package. This allows me to import exactly the
module that I need. In large packages with extension modules that can be
expensive to load, this is useful. We usually augment this with an api.py that
exposes the convenient "public API" of the package, the A and B classes in your
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list