[Distutils] imp.find_modules and namespaces

PJ Eby pje at telecommunity.com
Tue Feb 12 05:22:17 CET 2013


On Mon, Feb 11, 2013 at 4:56 PM, Alessandro Dentella <sandro at e-den.it> wrote:
> thanks for the answer but this way I need to really import jmb while
> imp.find_module doesn't really import it.

If you want to know whether the module 'jmb' exists, you can certainly
do that by using pkgutil.iter_modules().  What you *can't* do -- in
*any* version of Python as far as I know -- is tell for certain
whether 'jmb.foo' exists, without first importing jmb.  (Since until
jmb is imported, there's no way to know what __path__ value it will
end up with.)

This is true for namespace packages in all versions of Python; the
best that you can do is try to write code that does the same thing as
the import system...  but even then your code will be just guessing
(and failing to guess correctly) in the case where a package's
initialization involves altering its __path__ or if .pth files with
dynamic code are involved.

Similarly, for any module foo.bar.baz, foo.bar must be imported in
order to know what path to use for checking for the existence of
foo.bar.baz.


More information about the Distutils-SIG mailing list