import packet.module without importing packet.__init__ ?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Sep 10 20:56:42 EDT 2011


Gelonida N wrote:


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

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:

modules/
+-- spam.py
+-- ham.py
+-- package/
    +-- __init__.py
    +-- cheese.py

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 cheese.py 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:

modules/
+-- spam.py
+-- ham.py
+-- cheese.py <------------+
+-- package/               |
    +-- __init__.py        |
    +-- cheese.py <--------+


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 __init__.py is imported first. I see three reasnable
situations:

(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 __init__.py.)

(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 cheese.py 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 cheese.py as a
dependency of package, and ensure that they are both installed.)



-- 
Steven




More information about the Python-list mailing list