Basic Structure And Imports
- Wrap script entrypoints in
if __name__ == "__main__":so importing a helper function doesn’t accidentally run the whole script.
How it works
A .py file is both a runnable script and an importable module. Wrapping your entry point in if __name__ == "__main__": tells Python: “only run main() when I execute this file directly, not when another file imports from it.”
def greet(name: str) -> str:
return f"Hello, {name}"
if __name__ == "__main__":
print(greet("Matt"))
Always run tools from inside your virtual environment using python -m (for example, .venv/bin/python -m pytest). That puts the current directory on sys.path so imports like from app.semantic_retrieval import cosine_similarity work without PYTHONPATH hacks.
What can go wrong
ModuleNotFoundError: No module named 'app': Running.venv/bin/pytestdirectly failed inai-security-labbecause the script wrapper didn’t add the repo root tosys.path. Switching to.venv/bin/python -m pytestfixed it immediately.- Side effects on import: Code sitting at the top level outside
if __name__ == "__main__":executes the moment another file imports that module.
Referenced code
From tests/test_semantic_retrieval.py in ai-security-lab (run with .venv/bin/python -m pytest):
import pytest
from app.semantic_retrieval import cosine_similarity
from app.semantic_retrieval import retrieve_semantic
Evidence: Python 3 documentation (__main__ and sys.path) plus the observed ModuleNotFoundError → python -m pytest fix in ai-security-lab. Related: pytest unit and integration tests.