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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.