I have an import error with python on VS Code. Although I had this error, I could run this code with no error. Maybe, VS Code can not recognize the "import" statement. I'm glad if anyone solve this problem. Thank you.
Error on from statement : Unable to import 'ClassSample'
main.py
#main.py
#path
sys.path.append('sampleClass/myClass')
#my class
from ClassSample import ClassSample #error on from statement : Unable to import 'ClassSample'
ClassSample.py
#ClassSample.py
class ClassSample:
#select param
def selectParam(self, param):
param = "_" param
return param
CodePudding user response:
The VSCode Intellisense can not analysis this code when linting:
sys.path.append("sampleClass/myClass")
So, it will prompt you with the import error
.
This code can work because it's under the workspace folder directly. If you move sampleClass
folder to another place, such as the sample
folder, it will not work.
This is because you are using the relative path, it depends on the cwd
-- workspace folder path by default
.
CodePudding user response:
It seems you confused yourself when importing.
You have to tell to python which directory you want to import a module. Since main.py
is in another subdirectory, we need to move one folder up and locate the proper subdirectory hence the inclusion of sampleClass
when importing.
from sampleClass.myClass import ClassSample
The above code worked when importing the class ClassSample
. All you have to do now is to initialize it.
If you want a solution with minimal change, you could do:
from ..myClass.ClassSample import ClassSample
Where ..
is moving one directory up which means you are basically doing sampleClass.myClass
here.
Sample Code.
# from sampleClass.myClass import ClassSample
from ..myClass.ClassSample import ClassSample
my_class = ClassSample