Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a dynamic relative import in Python 3?

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?

like image 807
Fomalhaut Avatar asked Dec 10 '22 08:12

Fomalhaut


1 Answers

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()
like image 97
Mike Müller Avatar answered Dec 28 '22 23:12

Mike Müller