[Solved] Python Relative Reference Error: ImportError: attempted relative import with no known parent package

└── Project
    ├── dir1
    │   ├── __init__.py
    │   └── module1.py     
    │   └── module1_2.py     
    ├── dir2
    │  
    │   └── module2.py
    ├── file_a.py   
    └── main.py

1. In main.py, you want to   use   from .   import   file_ Import error: attempted relative import with no known parent package

The error message means that an attempt was made to import using a relative path, but a known parent package could not be found. Generally speaking, this error occurs when you try to use relative path import in a running. Py file. The reason for the error is that the relative path import of Python actually needs to be implemented with the help of the parent package path of the current file, that is, by judging the path of a. Py file__ name__ And__ package__ Property to get information about the parent package. In a running. Py application file, there are:

if __name__ == '__main__':

This introduces the main entry into the file. At this time, the file __ name__’s  attribute is’ ‘__ main__’ And __ package__’s attribute is none. If the relative path is used in such a file, the interpreter cannot find any information about the parent package, so an error is reported.

Python seems to have a setting. The directory of the current executable file will not be treated as a package.

To solve the problem, you can add the following code to the file where the import code is located

print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__))) 

The running result shows: __name__ = __main__ and __package__ = None, the python interpreter does not have any information about the package to which the module belongs, so it throws an exception that the parent package cannot be found.

solution:

Import directly from the module

from file_a import xxx

2. When I want to use from .. import file_a in module1.py, an error message is reported: attempted relative import beyond top-level package

The reason is the same as the above situation, that is, the current project directory is not a package, that is, the cheating setting of Python, and the current directory of the project entry will not be regarded as a package.

solution:

The content of file_a.py to be imported in module1.py:

from file_a import xxx

To import the content of module1_2.py in module1.py, you can use relative import:

from. import module1_2 as module12


Read More: