liveBook · Manning

Package

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

A Python package is an importable directory that organizes related Python modules and subpackages.

As an application grows, a single file can hide which functions belong together. A Python package gives related modules a named place in the directory hierarchy, making imports express the code’s purpose. section 2.3.2 section 7.3.1

To create a package in this layout, make a directory and add an `__init__.py` file. It can be empty, but code placed in it runs when the package is imported. Packages can contain other packages to form deeper, meaningful namespaces. section 2.3.2 section 7.3.1

Give a utility a clearer home

Move `utility.py` into a `utilities` directory, rename it `strings.py`, and add `utilities/__init__.py`. Then `from utilities import strings` lets `main.py` call `strings.add(12, 12)`. The directory and module names clarify which `add` function is being used. section 2.3.2

├── app
│   ├── __init__.py
│   ├── static
│   │   ├── css
│   │   │   └── base.css
│   │   ├── images
│   │   │   ├── myblog_banner.png
│   │   │   └── myblog_banner_50.png
│   │   └── js
│   │       └── index.js
│   └── templates
│       ├── base.html
│       └── index.html
└── myblog.py

The application layout places `__init__.py`, static files, and templates under an `app` package, with `myblog.py` at the top level. section 7.3.1

The same organization helps a Flask application grow beyond one feature-heavy file. Package code can participate in an application factory: `myblog.py` imports `create_app` from `app` and calls it to obtain the Flask app instance. Use packages when a named hierarchy makes related functionality easier to locate and extend. section 7.3.1

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Shows directory creation, `__init__.py` import behavior, nested packages, and an application-factory refactor without exploring package-loading internals.
Examples
Uses a `utilities/strings.py` refactor and a Flask application layout with an `app` package and `myblog.py`.
What it assumes
Assumes familiarity with Python modules and imports; introduces package creation directly and uses an existing Flask app for the larger refactor.
What you can do after
Build it from scratch by adding `__init__.py` to a directory, then use package imports to organize modules or a Flask app.
How it connects
Connects packages to modules, imports, namespaces, `__init__.py`, Flask app instances, and application factories.

Also explained in

Compare how 7 books explain package →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.