Home > database >  ImportError: attempted relative import with no known parent package - Only getting error while in vs
ImportError: attempted relative import with no known parent package - Only getting error while in vs

Time:10-23

This is what my file structure looks like

assignment
|
|__ qn1
|    |__ qn1.py
|    
|__ qn1
     |__ qn2.py

This is the simplified content of qn1.py

class A:
  def __init__(self):
    pass
  def method(self):
    pass

This is the simplified content of qn2.py

from qn1.qn1 import A

This works perfectly in pycharm but I can't seem to get it to work in vscode and I get this error message

ModuleNotFoundError: No module named 'qn1'

I also tried using these import lines

from ..qn1.qn1 import A
from ..qn1 import qn1; qn1.A

but I get this error for both

ImportError: attempted relative import with no known parent package

I also tried adding

__init__.py 

into the directory qn1 but it did not seem to help.

Not using vscode is not an option as the school requires me to submit it through an online vscode editor.

CodePudding user response:

this should work:

import sys
sys.path.append("path to qn1") 
import qn1

have a look at this website for some more guidance: https://linuxhint.com/sys-path-append-python/ In essence, sys.path.append adds the directory to where python looks for libraries (which is how qn1 will be treated).

  • Related