Interview frequency: …
Short answer
Putting the code inside a src folder prevents it from being imported accidentally from the current working directory, so tests are forced to use the installed package and packaging errors appear early.
Explanation
In the flat layout the package folder sits next to the tests, so the tests work even if the built package is missing files. With the src layout you need to install (usually editable) before running, in exchange for more confidence that what you test is what will be published. This suits published libraries especially, while the flat layout may be enough for simple applications.
Code example
my-lib/
├── pyproject.toml
├── src/
│ └── my_lib/
│ ├── __init__.py
│ └── core.py
└── tests/
└── test_core.py
# pip install -e . Then pytestCommon mistakes
- Tests pass locally while the published package fails because the data files were not included.
- Editing sys.path by hand in tests instead of installing the package.