{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"project-layout","title":"Laying out a project so the imports keep working","url":"https://addaly.com/learn/python-for-ai/project-layout","position":27,"of":89,"minutes":8,"answer":"Run a module inside a package with python3 -m package.module rather than by path, and build file paths from __file__ rather than the current working directory.","keyIdea":"Run a module inside a package with `python3 -m package.module` rather than by path, and build file paths from `__file__` rather than the current working directory."},"body":{"format":"markdown","text":"## A layout that survives contact with reality\n\nFor anything past two files:\n\n```\nbilling/\n├── README.md\n├── requirements.txt\n├── .gitignore\n├── run.py\n├── billing/\n│   ├── __init__.py\n│   ├── money.py\n│   └── report.py\n└── tests/\n    └── test_money.py\n```\n\nThe outer `billing` is the project folder. The inner one is the **package**: a folder Python can import as a unit. `run.py` at the top is the entry point:\n\n```python\nfrom billing.money import with_tax\n```\n\n## `__init__.py`\n\nA folder becomes a package when it contains `__init__.py`. Since Python 3.3 a folder without one can still be imported, as a namespace package, but the rules are subtler and the failure modes are worse. Create the empty file. It costs nothing and removes a category of confusion.\n\n`__init__.py` runs when the package is first imported, so it is where you re-export the public names:\n\n```python\n# billing/__init__.py\nfrom .money import with_tax\nfrom .report import format_report\n```\n\nNow users write `from billing import with_tax` and you are free to move `money.py` later without breaking them. Keep it short; anything slow in `__init__.py` is paid by everyone who imports anything from the package.\n\n## Relative and absolute imports\n\nInside the package, one module refers to a sibling:\n\n```python\nfrom .money import with_tax        # relative: the dot means this package\nfrom billing.money import with_tax # absolute: from the top\n```\n\nRelative imports keep working if the package is renamed. Absolute ones read more clearly from outside. Pick one per project; the common convention is absolute imports everywhere except inside `__init__.py`.\n\nA relative import only works **inside a package**, run as part of a package. This is the origin of a message thousands of people have met:\n\n```\nImportError: attempted relative import with no known parent package\n```\n\nIt means you ran `python3 billing/money.py` directly. Run it as a module instead:\n\n```bash\npython3 -m billing.money\n```\n\n`-m` imports the module properly, with the package context intact, and it also puts the current directory at the front of `sys.path`. When a project's imports work for everyone else and not for you, `-m` from the project root is the first thing to try.\n\n## Where tests go, and the argument about `src`\n\nTests live in a `tests/` folder outside the package, and `pytest` from the project root finds them. Keeping them out of the package means they are not shipped to users and not imported by accident.\n\nYou will also see this variant:\n\n```\nproject/\n├── src/\n│   └── billing/\n└── tests/\n```\n\nThe `src` layout exists for one specific reason: without it, running Python from the project root puts your package on `sys.path` automatically, so your tests import the **source folder** rather than the installed package. Everything passes locally and fails after installation, because a missing file in the packaging configuration is invisible while the source is right there. With `src`, the only way to import your package is to install it, so the tests exercise what users get.\n\nFor a script, it is overhead. For anything you publish, it is the safer default.\n\n## Files that should not be in version control\n\n`.gitignore` at minimum:\n\n```\n__pycache__/\n*.pyc\n.venv/\n.env\n*.sqlite3\n.DS_Store\n```\n\n`.venv` is machine-specific and large. `.env` holds secrets and is covered in its own lesson. `__pycache__` is compiled output. Committing any of them creates merge conflicts nobody can resolve and, in the case of `.env`, a key that has to be rotated.\n\n## Configuration belongs in one place\n\nScatter file paths and thresholds through ten modules and changing one becomes an archaeology exercise. A single `config.py` holding constants, or a small function reading environment variables, keeps every knob in one file:\n\n```python\n# billing/config.py\nfrom pathlib import Path\nDATA_DIR = Path(__file__).parent.parent / \"data\"\nTAX_RATE = 0.18\n```\n\n`Path(__file__)` is the location of the module itself, so the path is correct regardless of which folder the program was started from. Paths built from the current working directory break the moment someone runs the script from somewhere else, and that gets its own lesson shortly.\n\n## The README is part of the code\n\nFour things, and it can be twenty lines: what this does, how to install it, how to run it, how to run the tests. Written the day the project starts, not the day somebody else needs it. Future you is somebody else."},"check":{"question":"A package works when a teammate runs `python3 -m billing.report` and fails for you with `ImportError: attempted relative import with no known parent package` when you run `python3 billing/report.py`. What is the difference?","options":[{"text":"Running the file by path makes it a top-level script with no package context, so `from .money import ...` has no parent package to resolve against.","correct":true},{"text":"The `__init__.py` file is missing from the package, which is why the relative import cannot find its parent.","correct":false,"tempting":"A missing `__init__.py` causes real trouble, but it would fail for the teammate too rather than only for the path-based invocation."},{"text":"`-m` installs the package into the environment first, which is what creates the parent package.","correct":false,"tempting":"Mistakes `-m` for an installation step; it only imports the module with the package context intact."},{"text":"The two commands use different Python interpreters, so one of them lacks the package on its path.","correct":false,"tempting":"Plausible for ModuleNotFoundError, but the message here is specifically about relative imports having no parent."}]},"prev":{"slug":"modules-and-imports","title":"Modules: splitting a script across files without breaking it","url":"https://addaly.com/learn/python-for-ai/modules-and-imports"},"next":{"slug":"pure-functions","title":"Side effects, and why some functions are easy to test","url":"https://addaly.com/learn/python-for-ai/pure-functions"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Laying out a project so the imports keep working', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/project-layout (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Laying out a project so the imports keep working","courseTitle":"Python, from Zero, for AI","module":{"index":3,"slug":"functions-and-structure","title":"Functions, modules, and code you can read again in March"},"answer":null,"keyIdea":"Run a module inside a package with `python3 -m package.module` rather than by path, and build file paths from `__file__` rather than the current working directory.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"a-layout-that-survives-contact-with-reality","runs":[{"text":"A layout that survives contact with reality"}]},{"t":"p","runs":[{"text":"For anything past two files:"}]},{"t":"code","lang":"","label":"Text","text":"billing/\n├── README.md\n├── requirements.txt\n├── .gitignore\n├── run.py\n├── billing/\n│   ├── __init__.py\n│   ├── money.py\n│   └── report.py\n└── tests/\n    └── test_money.py"},{"t":"p","runs":[{"text":"The outer "},{"text":"billing","code":true},{"text":" is the project folder. The inner one is the "},{"text":"package","b":true},{"text":": a folder Python can import as a unit. "},{"text":"run.py","code":true},{"text":" at the top is the entry point:"}]},{"t":"code","lang":"python","label":"Python","text":"from billing.money import with_tax"},{"t":"h2","id":"init-py","runs":[{"text":"__init__.py","code":true}]},{"t":"p","runs":[{"text":"A folder becomes a package when it contains "},{"text":"__init__.py","code":true},{"text":". Since Python 3.3 a folder without one can still be imported, as a namespace package, but the rules are subtler and the failure modes are worse. Create the empty file. It costs nothing and removes a category of confusion."}]},{"t":"p","runs":[{"text":"__init__.py","code":true},{"text":" runs when the package is first imported, so it is where you re-export the public names:"}]},{"t":"code","lang":"python","label":"Python","text":"# billing/__init__.py\nfrom .money import with_tax\nfrom .report import format_report"},{"t":"p","runs":[{"text":"Now users write "},{"text":"from billing import with_tax","code":true},{"text":" and you are free to move "},{"text":"money.py","code":true},{"text":" later without breaking them. Keep it short; anything slow in "},{"text":"__init__.py","code":true},{"text":" is paid by everyone who imports anything from the package."}]},{"t":"h2","id":"relative-and-absolute-imports","runs":[{"text":"Relative and absolute imports"}]},{"t":"p","runs":[{"text":"Inside the package, one module refers to a sibling:"}]},{"t":"code","lang":"python","label":"Python","text":"from .money import with_tax        # relative: the dot means this package\nfrom billing.money import with_tax # absolute: from the top"},{"t":"p","runs":[{"text":"Relative imports keep working if the package is renamed. Absolute ones read more clearly from outside. Pick one per project; the common convention is absolute imports everywhere except inside "},{"text":"__init__.py","code":true},{"text":"."}]},{"t":"p","runs":[{"text":"A relative import only works "},{"text":"inside a package","b":true},{"text":", run as part of a package. This is the origin of a message thousands of people have met:"}]},{"t":"code","lang":"","label":"Text","text":"ImportError: attempted relative import with no known parent package"},{"t":"p","runs":[{"text":"It means you ran "},{"text":"python3 billing/money.py","code":true},{"text":" directly. Run it as a module instead:"}]},{"t":"code","lang":"bash","label":"Bash","text":"python3 -m billing.money"},{"t":"p","runs":[{"text":"-m","code":true},{"text":" imports the module properly, with the package context intact, and it also puts the current directory at the front of "},{"text":"sys.path","code":true},{"text":". When a project’s imports work for everyone else and not for you, "},{"text":"-m","code":true},{"text":" from the project root is the first thing to try."}]},{"t":"h2","id":"where-tests-go-and-the-argument-about-src","runs":[{"text":"Where tests go, and the argument about "},{"text":"src","code":true}]},{"t":"p","runs":[{"text":"Tests live in a "},{"text":"tests/","code":true},{"text":" folder outside the package, and "},{"text":"pytest","code":true},{"text":" from the project root finds them. Keeping them out of the package means they are not shipped to users and not imported by accident."}]},{"t":"p","runs":[{"text":"You will also see this variant:"}]},{"t":"code","lang":"","label":"Text","text":"project/\n├── src/\n│   └── billing/\n└── tests/"},{"t":"p","runs":[{"text":"The "},{"text":"src","code":true},{"text":" layout exists for one specific reason: without it, running Python from the project root puts your package on "},{"text":"sys.path","code":true},{"text":" automatically, so your tests import the "},{"text":"source folder","b":true},{"text":" rather than the installed package. Everything passes locally and fails after installation, because a missing file in the packaging configuration is invisible while the source is right there. With "},{"text":"src","code":true},{"text":", the only way to import your package is to install it, so the tests exercise what users get."}]},{"t":"p","runs":[{"text":"For a script, it is overhead. For anything you publish, it is the safer default."}]},{"t":"h2","id":"files-that-should-not-be-in-version-control","runs":[{"text":"Files that should not be in version control"}]},{"t":"p","runs":[{"text":".gitignore","code":true},{"text":" at minimum:"}]},{"t":"code","lang":"","label":"Text","text":"__pycache__/\n*.pyc\n.venv/\n.env\n*.sqlite3\n.DS_Store"},{"t":"p","runs":[{"text":".venv","code":true},{"text":" is machine-specific and large. "},{"text":".env","code":true},{"text":" holds secrets and is covered in its own lesson. "},{"text":"__pycache__","code":true},{"text":" is compiled output. Committing any of them creates merge conflicts nobody can resolve and, in the case of "},{"text":".env","code":true},{"text":", a key that has to be rotated."}]},{"t":"h2","id":"configuration-belongs-in-one-place","runs":[{"text":"Configuration belongs in one place"}]},{"t":"p","runs":[{"text":"Scatter file paths and thresholds through ten modules and changing one becomes an archaeology exercise. A single "},{"text":"config.py","code":true},{"text":" holding constants, or a small function reading environment variables, keeps every knob in one file:"}]},{"t":"code","lang":"python","label":"Python","text":"# billing/config.py\nfrom pathlib import Path\nDATA_DIR = Path(__file__).parent.parent / \"data\"\nTAX_RATE = 0.18"},{"t":"p","runs":[{"text":"Path(__file__)","code":true},{"text":" is the location of the module itself, so the path is correct regardless of which folder the program was started from. Paths built from the current working directory break the moment someone runs the script from somewhere else, and that gets its own lesson shortly."}]},{"t":"h2","id":"the-readme-is-part-of-the-code","runs":[{"text":"The README is part of the code"}]},{"t":"p","runs":[{"text":"Four things, and it can be twenty lines: what this does, how to install it, how to run it, how to run the tests. Written the day the project starts, not the day somebody else needs it. Future you is somebody else."}]}],"check":{"question":[{"text":"A package works when a teammate runs "},{"text":"python3 -m billing.report","code":true},{"text":" and fails for you with "},{"text":"ImportError: attempted relative import with no known parent package","code":true},{"text":" when you run "},{"text":"python3 billing/report.py","code":true},{"text":". What is the difference?"}],"options":[{"text":[{"text":"Running the file by path makes it a top-level script with no package context, so "},{"text":"from .money import ...","code":true},{"text":" has no parent package to resolve against."}],"correct":true,"tempting":null},{"text":[{"text":"The "},{"text":"__init__.py","code":true},{"text":" file is missing from the package, which is why the relative import cannot find its parent."}],"correct":false,"tempting":[{"text":"A missing "},{"text":"__init__.py","code":true},{"text":" causes real trouble, but it would fail for the teammate too rather than only for the path-based invocation."}]},{"text":[{"text":"-m","code":true},{"text":" installs the package into the environment first, which is what creates the parent package."}],"correct":false,"tempting":[{"text":"Mistakes "},{"text":"-m","code":true},{"text":" for an installation step; it only imports the module with the package context intact."}]},{"text":[{"text":"The two commands use different Python interpreters, so one of them lacks the package on its path."}],"correct":false,"tempting":[{"text":"Plausible for ModuleNotFoundError, but the message here is specifically about relative imports having no parent."}]}],"order":[1,0,3,2],"why":null},"prev":{"slug":"modules-and-imports","title":"Modules: splitting a script across files without breaking it","minutes":8},"next":{"slug":"pure-functions","title":"Side effects, and why some functions are easy to test","minutes":8}}}