Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: attempted relative import with no known parent package :(

I'm attempting to import a script from my Items file but I keeps on getting an error

 from .Items.Quest1_items import *

gives

from .Items.Quest1_items import *
ImportError: attempted relative import with no known parent package

Process finished with exit code 1

Here my project tree, I'm running the script from the main.py file

Quest1/
|
|- main.py
|
|- Items/
| |- __init__.py
| |- Quest1_items.py

like image 693
ElLoko 233 Avatar asked Aug 08 '20 07:08

ElLoko 233


People also ask

How do you solve Importerror attempted relative import without known parent package?

How to fix the "Importerror attempted relative import with no known parent package" error in Python? The solution to this problem is easy. Before advancing to the body of the Python program, programmers first create a Python file with their setup name; then make that package global so they can easily access it.

How do you fix ModuleNotFoundError and Importerror?

Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .

What is a parent package in Python?

It is an environment variable that contains the list of packages that will be loaded by Python. The list of packages presents in PYTHONPATH is also present in sys. path, so will add the parent directory path to the sys.


2 Answers

Remove the dot from the beginning. Relative paths with respect to main.py are found automatically.

from Items.Quest1_items import *

like image 135
Xorekteer Avatar answered Sep 22 '22 11:09

Xorekteer


You can only perform relative import (ie., starting with a dot), inside a package that you import. For instance, imagine the situation:

project/
├ main.py
├ mylib/
├ __init__.py
│ ├ module1.py
│ └ module2.py

in main.py, you would have import mylib or from mylib import *, but inside module1.py, you could have from . import module2, because here the . stands for mylib (which is a python package, because you imported it within main.py).

So, the solution is simply remove the dot, it's not useful in your situation.

like image 24
BlackBeans Avatar answered Sep 19 '22 11:09

BlackBeans