3

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

Conrad
  • 239
  • 2
  • 8
  • Possible duplicate [how to import a module in python with importlib import-module](https://stackoverflow.com/questions/10675054/how-to-import-a-module-in-python-with-importlib-import-module) – Drees Aug 01 '19 at 21:54

2 Answers2

2

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.

1

You can use the optional parameter package for this:

importlib.import_module("child1", package="parent")

Documentation reference: https://docs.python.org/3.7/library/importlib.html#importlib.import_module

mickours
  • 1,113
  • 12
  • 13