ImportError : Attempted relative import with no known parent package

Isaac Anatolio picture Isaac Anatolio · Mar 9, 2020 · Viewed 40.3k times · Source

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

Answer

FishingCode picture FishingCode · Mar 9, 2020

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.