Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError : Attempted relative import with no known parent package

Tags:

python

pylint

I am learning to program with python and I am having issues with importing from a module in a package. I am usingvisual studio code with Python 3.8.2 64 bit.

My Project Directory

.vscode ├── ecommerce │   ├── __init__.py │   ├── database.py │   ├── products.py │   └── payments │       ├── __init__.py │       ├── authorizenet.py │       └── paypal.py ├── __init__.py └── main.py 

in the ecommerce/products.py file I have:

#products.py from .database import Database p = Database(3,2) 

So that I can import the Database class from the ecommerce/database.py file. But I get error

ImportError : Attempted relative import with no known parent package 
like image 829
Isaac Anatolio Avatar asked Mar 09 '20 01:03

Isaac Anatolio


People also ask

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.

How do I fix 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.

What is __ init __ py for?

The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.


1 Answers

Since you are using Python 3.8 version, the imports work a little differently, but I think this should work:

Use either:

from database import Database #Database is the class 

or try:

import database.Database 

lastly, this one is very secure and best practice possibly:

from . import Database   # The '.' (dot) means from within the same directory as this __init__.py module grab the Database class. 
like image 50
FishingCode Avatar answered Oct 05 '22 17:10

FishingCode