简体   繁体   中英

“Attempted relative import with no known parent package” error in visual studio code with python

I am trying to assemble a python project using visual studio code, and I would like to import functions and classes between the files. My folders are structured as such:

chessboards
|-> __pycache__
|-> .vscode
|-> boards
   |-> __init__.py
   |-> queens.py
   |-> knights.py
|-> __init__.py
|-> board.py

I have a function in the "boards.py" file called my_func. In the init.py file in the outer directory, if I type:

from .board import my_func

I get the error in the title. I have also tried:

from chessboards.board import my_func

In which case it tells me there is no module named "chessboards", which I don't understand because there is an init.py file in there.

I have changed the setting for imports in vscode from auto to relative, but neither seems to work. If anyone could help me I would really appreciate it. Most of the answers on other questions say to change the PYTHONPATH or the .env file but none of those have worked so far.

You can add those at the top of your code before importing

import sys
from pathlib import Path
sys.path[0] = str(Path(sys.path[0]).parent)
from board import my_func

or you can add a .env file :

PYTHONPATH=.:${PYTHONPATH}

When we use the relative path to find the file, VSCode will find the imported file based on the folder location of the current file.

For the convenience of description, if we import the "my_func" of the file "board.py" into the file "queens.py", then VSCode cannot find "board.py because it is not in the folder "boards".

Therefore, we need to add this path to help it find it.

You could also use the following statement to import the file path into the system path to be found.

import os,sys 
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM