Home > OS >  Python 3.8.x Intra and Extra Imports
Python 3.8.x Intra and Extra Imports

Time:04-27

When defining multiple python 3 packages in a project, I cannot determine how to configure the environment (using VS Code) such that I can run a file in any package with intra-package imports without breaking extra-package imports.

Example with absolute paths:

src/
  foo/
    a.py
    b.py
  goo/
    c.py

# b.py contents
from foo.a import *

# c.py contents
from foo.b import *

where PYTHONPATH="${workspaceFolder}\src", so it should be able to see the foo and goo directories.

I can run c.py, but running b.py gives a ModuleNotFoundError: "No module named 'foo'".

Modifying b.py to use relative paths:

# modified b.py contents
from a import *

Then allows me to run b.py, but attempting to then run c.py gives a ModuleNotFoundError: "No module named 'b'".

I have also added __init__.py files to foo/ and goo/ directories, but the errors still occurs.

I did set the cwd in the launch.json file to be the ${workspaceFolder} directory, if that is relevant.

CodePudding user response:

A solution I was trying to avoid, but does work in-case there are no better solutions, is putting each individual package-dependency onto the PYTHONPATH environment variable.

E.g., "${workspaceFolder}\src;${workspaceFolder}\foo" when running c.py.

But this is not an easily scalable solution and is also something that needs to be tracked across project changes, so I do not think it is a particularly good or pythonic solution.

CodePudding user response:

In fact, you can find it didn't work if you try to print the current path. It just add ".." to the path instead of the parent directory.

import sys
print(sys.path)
sys.path.append('..')
print(sys.path)

So, what we have to do is add the path of module we used to "sys" in path.

Here we have three ways:

  1. Put the written .py file into the directory that has been added to the system environment variable;
  2. Create a new .pth file under \Python\Python310\Lib\site-packages.

Write the path of the module in this new .pth file , one path per line.

  1. Using the pythonpath environment variable as upstairs said.

Then we can use this two ways to import :

sys. path. append ('a').
sys. path. insert (0, 'a')
  • Related