pythonpackage

Why can't find imported editable python package?


  1. The dir1 directory structure:
dir1/
|-- helloworld/
    |-- __init__.py
    |-- hello.py
|-- setup.py
|-- venv/ #The dir1 virtual environment
  1. The dir2 directory structure:
dir2/
|-- app2.py
|-- venv/ #The dir2 virtual environment
# hello.py
def say_hello():
    return "Hello, World!"
# setup.py
from setuptools import setup, find_packages

setup(
    name='helloworld',
    version='0.1',
    packages=find_packages(),
)
  1. Activate dir2 venv
C:\Users\TC\temp\editable\dir2>venv\Scripts\activate
(venv) C:\Users\TC\temp\editable\dir2>
  1. Install helloworld package to the dir2 venv in editable mode.
(venv) C:\Users\TC\temp\editable\dir2>pip install -e C:\Users\TC\temp\editable\dir1
  1. Import helloworld package from app2.py
# app2.py
from helloworld.hello import say_hello

print(say_hello())
  1. Run app2.py
python app2.py

Now here is the problem. helloworld package is not found from app2.py. However, pip list does show that the helloworld package has been installed. Using VS Code, there is a yellow squiggly line underneath helloword.hello, which indicates that package not found.

This is a very simple setup to test the editable installation of a python package. I wonder the error is producible. Or this is a bug! OS is windows.

Please let me know if you get the same error or you will be able to get it to work.

Any help will be greatly appreciated.

Note:

You need to pip install setuptools in dir1 venv.


Solution

  • # app2.py
    from helloworld.hello import say_hello
    
    print(say_hello())
    

    After pip editable mode installation,

    (venv) C:\Users\TC\temp\editable\dir2>pip install -e C:\Users\TC\temp\editable\dir1
    

    the following error appears in app2.py.

    Import "helloworld.hello" could not be resolvedPylance(reportMissingImports)
    

    However, the app2.py runs fine. If pip install without editable mode, the error message disappears and IntelliSense works.

    I have tried many ways to get the IntelliSense to work under the editable mode without success.

    Therefore I conclude for some unknown reason, helloworld package is not installed under the editable mode. Instead the following folders are installed in venv\lib\site-packages

    2024-10-17  11:24 PM                91 __editable__.helloworld-0.1.0.pth
    2024-10-17  11:24 PM             3,436 __editable___helloworld_0_1_0_finder.py
    

    Since no helloworld package folder exists, Pylance therefore cannot resolve the import.

    Problem solved.

    1. Create a .env file in dir2.
    PYTHONPATH=C:/Users/TC/temp/editable/dir1
    
    1. Open settings.json in .vscode directory and make the following change.
    {
        "python.envFile": "${workspaceFolder}/.env"
    }