I have a Python package (pyproject.toml setup with uv) and I would like to have unit-tests in the same file as the source code, leaving the tests/ directory exclusively for integration tests, similar to the way it is done in Rust with #[cfg(test)] modules. I can do: # add.py def add(a, b): return a + b def test_add(): assert add(1, 2) == 3 Then uv run pytest can handle this and run the assertions. However when I build the project, test_add is importable from module foo along with add. How can I prevent this ? Edit I realise I can do: if "pytest" in __import__("sys").modules: def test_add(): assert add(1, 2) == 3 However this seems a bit brittle. Continue reading...