Search code examples
pythonvisual-studio-codeproject-structure

Cannot Import internal modules in VSCode


I have created internal modules which follow the structure such as follows-

project
└── src
    └── rogers
          └──__init__.py
          └── cd
            ├── __init__.py
            ├── preprocessor
            └── dataOps
                   └── __init__.py
                   └── verint.py                 

The error I get -

Traceback (most recent call last):
  File "main_scripts/PreprocessingStep/verint_preprocessing.py", line 11, in <module>
    from rogers.cd.dataOPs import Verint
ImportError: No module named rogers.cd.dataOPs

The init.py in the dataops looks like this

from rogers.cd.dataOPs.boldchat import *
from rogers.cd.dataOPs.verint import *

This is what my setup.py looks like (not showing the entire file, only part of it)

classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
    ],
    install_requires = external_packages,
    package_dir={"": "src"},
    packages=  setuptools.find_namespace_packages(where="src"),
    package_data={'': ['*.yaml']},
    include_package_data=True,
    python_requires=">=3.7",

I recently migrated from PyCharm to VSCode. The code was running fine in PyCharm but doesn't work for VSCode.


Solution

  • setup.py does not work in VSCode, you can modify the PYTHONPATH in VSCode through (terminal.integrated.env.*) and/or within an .env file:

    The PYTHONPATH environment variable specifies additional locations where the Python interpreter should look for modules. In VS Code, PYTHONPATH can be set through the terminal settings (terminal.integrated.env.*) and/or within an .env file.

    When the terminal settings are used, PYTHONPATH affects any tools that are run within the terminal by a user, as well as any action the extension performs for a user that is routed through the terminal such as debugging. However, in this case when the extension is performing an action that isn't routed through the terminal, such as the use of a linter or formatter, then this setting will not have an effect on module look-up.

    When PYTHONPATH is set using an .env file, it will affect anything the extension does on your behalf and actions performed by the debugger, but it will not affect tools run in the terminal.

    If needed, you can set PYTHONPATH using both methods.

    An example of when to use PYTHONPATH would be if you have source code in a src folder and tests in a tests folder. When running tests, however, those tests can't normally access modules in src unless you hard-code relative paths.

    To solve this problem, you could add the path to src to PYTHONPATH by creating an .env file within your VS Code workspace.

    PYTHONPATH=src

    official docs