Search code examples
pythonimporterror

How do I import a python file into another python file where both files do not have classes and are under the same directory?


I have 3 files inside the same folder:

  1. qrcodeTest.py
  2. Data.py
  3. Tray.py

They're all under the folder called "Project". Only Tray.py has a class called "Tray" but the other 2 files do not contain classes. I am trying to run qrcodeTest.py but I need to import Data and Tray (this previously worked when I had all these files under the same folder and ran it in Pycharm).

Inside my qrcodeTest.py file, I used to have the following import statements import Data and import Tray but now these lead to an import error. How do I properly import the Data and Tray files inside qrcodeTest? My files Data and Tray do not contain functions.

[Edit 1] I have included a screenshot of the error shown in VSCode enter image description here


Solution

  • You can run your code, right?

    The import error was not true.

    I can reproduce your problem, but I am not sure the import error you met was prompted by Pylance like me.

    If it is, you can add this in the settings.json file:

      "python.analysis.extraPaths": [
        "${workspaceFolder}/[some paths]/Project",
      ],
    

    If it is not, please let me know.

    Update:

    File > Preferences > Settings Or shortcut Ctrl+, to open the settings.json file. And then click here to open the json file:

    enter image description here

    If you open the qrcodeTest.py file directly in the VSCode, you should add this in the settings.json file:

      "python.analysis.extraPaths": [
        "C:/Users/zacha/ZCFTest",
      ],
    

    If you open the ZCFTest folder in the VSCode, you need not configure anything.

    "python.analysis.extraPaths" means Addtional import search resolution path

    Pylance needs to know which import resolution paths to use. By default, it uses the root of your workspace. You will need to add these additional paths using the "python.analysis.extraPaths" setting like this: "python.analysis.extraPaths": ["base", "utils", "dataset", ""] Note that these paths are relative to your workspace root directory.

    From the developer explain.