casey
casey

Reputation: 6915

import not seeing modules in a package, inconsistent between two imports

I have a peculiar problem with importing modules in some code I am working on. The directory layout is:

main.py
cm1sinit/
   __init__.py
   MainInterface.py
   soundings/
      __init__.py
      WK82.py
   hodographs/
      __init__.py
      curved90.py

__init__.py in all cases is a 0-length empty file.

In MainInterface.py I have the following imports:

import soundings
import hodographs

and calling dir() or inspect.getmembers() on each of these produces:

dir(soundings)
['WK82', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

dir(hodographs)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

Why is the soundings import picking up its module WK82 while the hodographs import is not picking up curved90? I am trying to dynamically produce pyQt widgets that are populated just by adding files to the module directories. This works for the sounding module but not for hodographs.

I can remedy this by using:

import hodographs.curved90
dir(hodographs)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'curved90']

but this defeats the purpose of not having to explicitly name the imports in my dynamic content generation.

How can I fix this so that 'import hodographs' is properly importing all files in that directory?

Upvotes: 1

Views: 114

Answers (1)

Max Noel
Max Noel

Reputation: 8910

When you import a package, only the package (that is, what's defined in __init__.py) is initialized and imported -- the sub-packages and modules contained in the package aren't automatically imported.

For that to happen, you need to edit your __init__.py files so that they look like this:

# cms1init/soundings/__init__.py
from cms1init.soundings import WK82

That way, the WK82 module is imported and made available as an attribute of cms1init.soundings. Just repeat the maneuver for the cms1init.hodographs package.

Does that make sense?

Upvotes: 1

Related Questions