Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: import submodule from importlib module

I have a directory like this:

parent.py ------+
    child1.py---+
    child2.py---+
    ... etc

I can import the parent module like this:

importlib.import_module("parent"))

So, what is the best way to get the child module now that I already have the parent module? I've tried parent.child1, importlib.import_module("child1", parent), parent.import_module('child1'), etc. to no avail.

Any advice?

Thanks

like image 601
Conrad Avatar asked Jan 20 '26 18:01

Conrad


1 Answers

You can try to organize files in this way:

parent (directory)-+
    __init__.py ---+
    child1.py   ---+
    child2.py   ---+

In init.py you can import from child* files and that will be available to import from outside the module in parent.

Example __init__.py. It can also be empty, but it must exist.

from child1 import foo
from child2 import bar

Use from outside:

from parent import foo
or
from parent.child1 import foo

This doesn't answer directly your question. But, after you reorganize files in above way try to use importlib again.

like image 94
Mateusz Raczyński Avatar answered Jan 22 '26 08:01

Mateusz Raczyński



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!