Python dynamic import and __all__
Question: I am facing a behaviour that I don't understand even through I feel it is a
very basic question...

Imagine you have a python package `mypackage` containing a module `mymodule`
with 2 files `__init__.py` and `my_object.py`. Last file contains a class
named `MyObject`.

I am trying to right an automatic import within the `__init__.py` that is an
equivalent to :

**__init__.py**

    
    
    __all__ = ['MyObject']
    from my_object import MyObject 
    

in order to be able to do:

    
    
    from mypackge.mymodule import MyObject
    

I came up with a solution that fill **all** with all classes' names. It uses
`__import__` (also tried the `importlib.import_module()` method) but when I
try to import `MyObject` from the `mymodule`, it keeps telling me:

    
    
    ImportError: cannot import name MyObject
    

Here is the script I started with :

    
    
    classes = []
    for module in os.listdir(os.path.dirname(__file__)):
        if module != '__init__.py' and module[-3:] == '.py':
    
            module_name = module[:-3]
            import_name = '%s.%s' % (__name__, module_name)
    
            # Import module here! Looking for an equivalent to 'from module import MyObject' 
            # importlib.import_module(import_name)  # Same behaviour
            __import__(import_name, globals(), locals(), ['*'])
    
            members = inspect.getmembers(sys.modules[import_name], lambda member: inspect.isclass(member) and member.__module__.startswith(__name__) )
    
            names = [member[0] for member in members]
            classes.extend(names)
    
    __all__ = classes
    

Can someone help me on that point ?

Many thanks,


Answer: I think you don't need heavy script to perform what you are looking for. It
should work with simple basic python.

It seems there is a mistake in your `__init__.py` file within your package.

You should have something like :

    
    
    from mymodule import MyObject
    

instead of

    
    
    from my_object import MyObject
    

Here is a working simple example : <https://github.com/julozi/package-test>

CHeers,

Julien

