Avatar ·

Relative imports in Python

📁 Advanced Python Topics, question, Help

For some time (since relative imports were cancelled) I can't normally solve the following question:

Suppose, the program structure

app/
    __init__.py
    foo/
        __init__.py
        handler.py

How to load something from the package foo from the module handler.py?

The whole point is that the name of the package foo is unknown, it is loaded using importlib.

For now I found such a crutch: I parse the variable __name__, which in handler.py equals 'foo.handler', i.e. like this

foo_name = __name__.rsplit('.',