Problem

ImportError: attempted relative import with no known parent package

If you are developing a python package and try to import a module from the current package using relative path, you may get the following error.

from .docdb_json_importer  import DocDbJsonImporter

OR

from . import utils

ImportError: attempted relative import with no known parent package

For example in my case I was developing a package called docdb-import-export and I was trying to import a module from the current package using relative path like this:

src/docdb_import_export/__main__.py

import sys
import os
# Import local packages
from . import utils
from .docdb_json_importer  import DocDbJsonImporter

And I was getting error like this:

Traceback (most recent call last):
  File "/Users/mutant/Sites/htdocs/work/docdb-import-export/src/docdb_import_export/__main__.py", line 26, in <module>
    from . import utils
ImportError: attempted relative import with no known parent package
(docdb-import-export)

Solution

According to the Module documentation, for main modules, you have to use absolute imports.

When we do the relative import it is going to look for sys.path and it is not going to find the current package in the sys.path and that is why it is going to throw the error.

So the solution is that we have to add the current package path to the sys.path and then we can do the relative import. Then use the current package name.

from <CURRENT_PACKAGE_NAME> import <FILENAME/MODULENAME>

src/docdb_import_export/__main__.py

import sys
import os

# Add current package path to sys.path
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

# Now import local packages with current package name
from docdb_import_export import utils
from docdb_import_export.docdb_json_importer  import DocDbJsonImporter

Example

src/docdb_import_export/docdb_json_importer.py

import json
import os
from abc import ABC, abstractmethod
# Now import local packages with current package name
from docdb_import_export.docdb_client import DocDbClient