HOW TO: Run Tests, main.py and Notebook in Python | NO IMPORT ERRORS

Опубликовано: 05 Май 2026
на канале: chinamatt
466
6

Github Repo: https://github.com/ikitcheng/python_p...

1. Create the following folder structure: my_pkg/, tests/, .env, pytest.ini, my_notebook.ipynb
2. Make ‘my_pkg’ a package with the following files:
a. __init__.py: The __init__.py file makes this folder a package then the python files inside modules.
b. Main.py which uses your module files to create your main program
c. The module files ‘my_script.py’, ‘my_sciprt_2.py’
3. In the tests folder, create your tests. Remember to also add __init__.py so you can use relative imports. We will explain how later.
4. If we don't want to keep writing the package name when importing our own scripts in your module files (e.g. in my_script.py), then create a pytest config file `pytest.ini` file in the root directory. We need to write: pythonpath = . my_pkg
5. This allows pytest to locate module files in `my_pkg`.
6. In the test files, you would still need to import your scripts prefixed with the package name if that file is inside a package.
7. You may now run `python -m pytest` or `pytest` in the root directory.
8. You can see the test in `test_myscript.py` was ran successfully.
9. If the root directory is also a package itself (i.e. there is an `__init__.py` file) and contains module files, then in your tests you could use relative imports. Let’s see `test_multiply.py`, here we are using `..multiply` to import the `multiply` module.
10. Looking back at the pytest config file, the `--doctest-modules` argument lets you performs doctest on modules. In `my_script_2.py`, you can see we wrote a doctest. That’s why pytest was also able to discover it, as seen in the collected items.
11. That’s all for the tests.
12. Now for main.py, since it is located inside the package, we can simply import other module files as we would normally do. To run in root, we do `python my_pkg/main.py`.
13. For the notebook, located outside of `my_pkg` folder, it cannot see the modules inside. To solve this, we create a `.env` file to add ./my_pkg to the `PYTHONPATH` variable, so VsCode can locate files inside `./my_pkg`.
14. Without this, you would be facing `ModuleNotFoundError`.
15. And that’s how to run tests, main.py and jupyter notebooks in python without import errors.