I have a following file structure:
mymodule/
    __init__.py
    mylib.py
test.py
File mymodule/__init__.py:
# mymodule/__init__.py
def call_me():
    module = __import__('.mylib')
    module.my_func()
File mymodule/mylib.py:
# mymodule/mylib.py
def my_func():
    print("hi!")
File test.py:
# test.py
from mymodule import call_me
call_me()
If I run python3 test.py it fails with the error:
    module = __import__('.mylib')
ImportError: No module named '.mylib'
I want to perform a relative import inside of call_me that equals to the static import from . import mylib. How can I do it?
Use importlib.import_module and specify your package from __name__ in __init__.py:
importlib.import_module(name, package=None)Import a module.The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import.
Example:
import importlib
def call_me():
    module = importlib.import_module('.mylib', package=__name__)
    module.my_func()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With