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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With