(Neither this question nor this question are duplicates - they are all resolved by setting the PYTHONPATH correctly.)
I have the basic file structure of a Python package, located in ~/github/mypackage:
. └── mypackage/ ├── __init__.py ├── main.py └── mysubmodule/ ├── __init__.py └── calc.py where mypackage/__init__.py contains a global variable (or anything I need to define there, like a pint unit registry):
myglobalvariable = 42 and mypackage/mymodule/calc.py uses an absolute import to get the global variable from the package __init__.py:
from mypackage import myglobalvariable Unforuntately, this does not seem to work. When I run main.py:
import mypackage.mymodule.calc as calc I get a ModuleNotFoundError:
{ "name": "ModuleNotFoundError", "message": "No module named 'mypackage'", "stack": "--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) File /Users/myusername/Downloads/test/mypackage/main.py:3 1 # %% ----> 3 import mypackage.mymodule.calc as calc ModuleNotFoundError: No module named 'mypackage'" } I did check the PYTHONPATH of the current interpreter using sys.path... and it should capture the mypackage directory:
[ '/Users/myusername/github/mypackage/src', '/Users/myusername/github/mypackage', '/opt/homebrew/Caskroom/miniconda/base/envs/mycondaenv/lib/python311.zip', '/opt/homebrew/Caskroom/miniconda/base/envs/mycondaenv/lib/python3.11', '/opt/homebrew/Caskroom/miniconda/base/envs/mycondaenv/lib/python3.11/lib-dynload', '', '/opt/homebrew/Caskroom/miniconda/base/envs/mycondaenv/lib/python3.11/site-packages', '/Users/myusername/github/test_wasm_platform_specific_dependencies/src' ] ...so what am I doing wrong?
EDIT:
I am using the VS Code Jupyter Interactive Window with the # %% magic command to run the main.py file. The src directory is most likely added to the interpreter PYTHONPATH by the VS Code Jupyter extension. Ultimately, the result is the same when I just run the main.py file using python in the command line.
sys.pathoutput. -- So where ismain.py? Is it at/Users/myusername/Downloads/test/mypackage/main.py? Where does thesrcdirectory come from? Where ismypackage/__init__.py? Is it as/Users/myusername/Downloads/test/mypackage/mypackage/__init__.py? -- Which commands do you use to run the code?main.py? Is it at/Users/myusername/github/mypackage/main.py, or at/Users/myusername/github/mypackage/mypackage/main.py? What command did you run? I do not know what# %%is. Can you reproduce the issue on the normal command line?