Relative Import Errors in Python
Using relative imports in python seems to be a straightforward task. However, you may find that mysterious exceptions with obscure messages are raised when using relative imports.
In python2, I sometimes get ValueError: attempted relative import beyond top-level package?. This is strange, Why ValueError is raised? I did not call any function at this line - I try to do a relative import. In python docs, we know that ValueError should be raised when an operation or function receives an argument that has the right type but an inappropriate value.
To solve the mystery, the message gives you some hint. It is related to the relative import I tried to do. However, what exactly is a top-level package, and why it is forbidden to import beyond this top-level package?
In python3, Sometimes I get ImportError: attempted relative import with no known parent package. It seems there were some efforts to resolve the mystery. Yes, in this case, a specific exception is raised and its name clarifies that this exception is related to the import statement. However, the message is still obscure. What is mean a package with no known parent package?
I finally understand those mysterious exceptions. I recommend reading the following articles which explain how relative imports work and how to fix those issues: