Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dynamic import and __all__

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,

like image 547
t00f Avatar asked Jan 21 '26 04:01

t00f


1 Answers

You just need to assign attributes on the module: globals().update(members).

like image 126
Davis Herring Avatar answered Jan 22 '26 16:01

Davis Herring



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!