Sugetha Chandhrasekar
Sugetha Chandhrasekar

Reputation: 103

__all__ variable not picked up in __init__.py

I have a __init__.py that looks like this

__init__.py:

__all__ = ['cooling', 'counters']

my directory structure looks like:

example_dir/  
    __init__.py  
    cooling.py  
    power.py  
    counters.py  

When I try to import example_dir, python doesn't import cooling and counters. It imports nothing. Using Pdb, I see that it reads the __init__.py but it's refusing to read the __all__ variable.

I use imp.load_module to load the modules

My entire program:

def import_module(name, path=None):
    parts = name.split('.')
    module_name = ""
    for index, part in enumerate(parts):
        module_name = part if index == 0 else '%s.%s' % (module_name, part)
        if path is not None:
            path = [path]
        fh, path, descr = imp.find_module(part, path)
        mod = imp.load_module(module_name, fh, path, descr)
    return mod


def load_module(name):
    try:
        mod = None
        mod = sys.modules[name]
    except KeyError:
        mod = import_module(name)
    finally:
        if not mod:
            raise ImportError('unable to import module %s' % name)
        return mod

load_module('example_dir')

Upvotes: 1

Views: 186

Answers (1)

mgilson
mgilson

Reputation: 310097

I think you might be misunderstanding what __all__ does ...

In __init__.py, you want to actually import the modules you want. e.g.

# __init__.py
import example_dir.cooling as cooling
import example_dir.counters as counters

__all__ on the other hand says what names in the current module should be imported when the user writes from ... import *.

In short, __all__ has nothing to do with what modules get imported, only what names are available after a module is imported (and then, only if the user is importing everything from a module).

Upvotes: 2

Related Questions