Getting "ImportError: attempting relative import without known parent package" when starting from Python Interpreter

I am creating a modular application using Flask blueprints . As a result, my directory structure looks like this:

project
    __init__.py
    config.py
    mould.py
    modules
        __init__.py
        core
            __init__.py
            core.py
            db.py
            models.py

The catalog of modules here is not confused with the Python modules, they are intended to provide a modular structure to my project (main module, foo module, bar module, etc.). Now each folder in the modules directory (and the module inside it with the same name as core.core) is dynamically imported into my main jar application ( mould.py), doing the following:

for item in os.listdir("modules"):
    if not os.path.isfile("modules" + os.sep + item) and not item.startswith("__"):
        ppath = "modules" + "." + item
        fullpath = "modules" + "." + item + "." + item
        module = importlib.import_module(fullpath)
        app.register_blueprint(module.app)
        print("Registered: " + ppath)

As a result of this, I cannot do this in module scripts such as db.py:

import models

, , :

from . import models

, . , python, db:

>>> import db
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "db.py", line 7, in <module>
    from . import models
ImportError: attempted relative import with no known parent package

? , db , ?

+4

Source: https://habr.com/ru/post/1681384/


All Articles