Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempted relative import with no known parent package

from ..box_utils import decode, nms 

This line is giving error

ImportError: attempted relative import with no known parent package

What is this error and how to resolve this error?

like image 971
Puneet Shekhawat Avatar asked Mar 10 '19 06:03

Puneet Shekhawat


People also ask

What is relative import in Python?

A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is. There are two types of relative imports: implicit and explicit. Implicit relative imports have been deprecated in Python 3, so I won't be covering them here.

How do I fix Valueerror attempted relative import beyond top level package?

The beyond top level package error in relative import error occurs when you use a relative import without the file you are importing being part of a package. To fix this error, make sure that any directories that you import relatively are in their own packages.

Is __ init __ py necessary?

If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.


2 Answers

Apparently, box_utils.py isn't part of a package. You still can import functions defined in this file, but only if the python script that tries to import these functions lives in the same directory as box_utils.py, see this answer.

Nota bene: In my case, I stumbled upon this error with an import statement with one period, like this: from .foo import foo. This syntax, however, tells Python that foo.py is part of a package, which wasn't the case. The error disappeared when I removed the period.

like image 132
Tobias Feil Avatar answered Dec 17 '22 12:12

Tobias Feil


If a different dictionary contains script.py, it can be accessed from the root. For instance:

If your program is structured...:

/alpha   /beta     /delta   /gamma     /epsilon       script.py     /zeta 

...then a script in the epsilon directory can be called by:

from alpha.gamma.epsilon import script

like image 32
Wychh Avatar answered Dec 17 '22 13:12

Wychh