import packet.module without importing packet.__init__ ?

Steven D'Aprano steve+comp.lang.python at
Sun Sep 11 02:56:42 CEST 2011

Gelonida N wrote:

> Is it possible to import a module from a packet without importing its
> ?

Untested, but I think so. But you shouldn't. The solution (if it does work,
as I said I haven't tested it) is a hack.

Suppose you have a library like this:

+-- package/

The directory "modules" is in your Python path, so you can "import spam"
or "import package". The trick is to add "modules/package" to the Python
path so that "import cheese" will find directly.

You can do that by manipulating sys.path, or by setting the environment
variable PYTHONPATH.

Another hack would be to add a hard link to the top level:

+-- <------------+
+-- package/               |
    +--        |
    +-- <--------+

This is not a copy, it is a hard link: the same file appears in literally
two places. (But note that not all file systems support hard linking.) Soft
links or shortcuts might also work. Now you can "import cheese".

But generally, you should design your package so that it doesn't matter
whether or not is imported first. I see three reasnable

(1) package.cheese should rely on package, in which case it requires
package.__init__ to be imported first. (Sometimes I put code common to the
entire package in

(2) Just don't worry about the fact that package.__init__ gets imported
first. Do you have any idea how many modules get imported when Python
starts up? What's one more?

(3) If truly is independent of package, then it shouldn't be part
of package. Just make it a stand alone module outside the package
directory, and be done. (Your installer can still treat as a
dependency of package, and ensure that they are both installed.)


More information about the Python-list mailing list