Professional Python
Every script so far in this course has lived in one file, run with print() statements telling you what's happening, and assumed whatever packages were already installed on your machine. That's fine for learning. It falls apart the moment a script needs to run unattended, get shared with someone else's machine, or be installed instead of copy-pasted. This chapter covers the five practices that close that gap: isolating dependencies with virtual environments, organizing a project so it scales past one file, replacing print() with real logging, building a command-line interface with argparse instead of hand-parsing sys.argv, and packaging the result so it's genuinely pip install-able. Git and GitHub (Chapters 28-29) round out the picture but aren't retaught here.
ModuleNotFoundError — they don't have the package you installed eight months ago and forgot about. You fix that, then it fails silently in production at 3 AM with no log anywhere explaining why, because every diagnostic was a print() statement that nobody was watching a terminal to see. You fix that too, then a user runs it with the wrong arguments and gets a raw Python traceback instead of a helpful error message. None of these are bugs in your logic — they're the difference between a script that works "on my machine" and a tool built the way professionals actually ship Python. That gap is this entire chapter.
1. Virtual environments
- Installing packages globally (
pip installwith no virtual environment active) means every project on your machine shares the exact same package versions. - A virtual environment gives one project its own private copy of Python and its own installed packages, isolated from every other project.
requirements.txtrecords exactly what a project needs, so anyone (including future you) can recreate the same environment elsewhere.
ModuleNotFoundError-on-a-teammate's-machine scenario from the hook, and its uglier cousin — two of your own projects needing two different, incompatible versions of the same package — are both solved by the same fix: never install project dependencies globally.
Here's the trap in concrete terms. Say Project A needs requests version 2.28, and six months later Project B needs requests version 2.34 for a feature that only exists in the newer release. If both projects install packages globally, there is only ever one installed copy of requests on your machine — installing the version Project B needs silently breaks Project A the next time you run it.
site-packages directory for installed libraries, completely separate from your system-wide Python. Activating one tells your shell "use this Python and these packages until further notice" — every pip install you run while it's active goes into that folder, not your global install.
Python's standard library includes everything needed to create one — no extra install required. From inside a project folder:
$ python3 -m venv .venv
$ ls .venv/bin
Activate.ps1 activate activate.csh activate.fish pip pip3 pip3.14 python python3 python3.14
python3 -m venv .venv creates the environment in a folder named .venv (the leading dot is convention, not a requirement — it keeps the folder out of the way in file listings, and it's the name most .gitignore templates already exclude). Nothing changes yet, though — the environment exists but isn't active. Activating it is the step that actually redirects python3 and pip:
$ source .venv/bin/activate
$ which python3
$ python3 -m pip --version
/path/to/project/.venv/bin/python3
pip 25.1.1 from /path/to/project/.venv/lib/python3.14/site-packages/pip (python 3.14)
which python3 now points inside the project folder, not at the system Python — every package installed from here on is scoped to this project alone. On Windows, the equivalent is .venv\Scripts\activate instead of source .venv/bin/activate; the rest of the workflow is identical.
Thought process: the decision here isn't really "how do I run venv" — it's recognizing that global installs are a trap the moment a second project exists on the same machine. The habit to build is: every new project folder gets its own .venv before the first pip install, not after something breaks.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
I'm starting a new Python project in an empty folder and want every dependency isolated from my system-wide Python from day one. Give me the exact commands to create a virtual environment named .venv using the standard library's venv module, activate it on both macOS/Linux (bash) and Windows, and confirm it's active by checking which python3 is being used. Also explain in plain terms why installing packages without an active virtual environment is risky once I have more than one Python project on the same machine.
With the environment active, installing a package puts it only here:
$ python3 -m pip install requests
$ python3 -m pip freeze
certifi==2026.6.17
charset-normalizer==3.4.9
idna==3.18
requests==2.34.2
urllib3==2.7.0
requirements.txt is a plain text file listing a project's dependencies, one per line, usually with an exact version (requests==2.34.2). It's the file that lets anyone — a teammate, a server, future you on a new laptop — recreate the exact same environment with one command, instead of guessing which packages and versions a project needs by trial and error.
pip freeze prints every installed package in that exact format, which is why the standard workflow is to redirect it straight into the file:
$ python3 -m pip freeze > requirements.txt
$ cat requirements.txt
certifi==2026.6.17
charset-normalizer==3.4.9
idna==3.18
requests==2.34.2
urllib3==2.7.0
On a different machine, one command reinstalls everything at those exact pinned versions:
$ python3 -m venv .venv
$ source .venv/bin/activate
$ python3 -m pip install -r requirements.txt
That three-command sequence is the entire reason requirements.txt exists — it's what makes "clone the repo and get it running" take thirty seconds instead of a support ticket about missing packages.
- Global installs mean every project shares one set of package versions — a recipe for one project quietly breaking another.
python3 -m venv .venvcreates an isolated environment; activating it redirectspython3/pipto that environment until deactivated.requirements.txt, generated withpip freeze, is how a project's exact dependencies travel with it to any other machine.
Go Deeper: what does deactivate do, and is .venv committed to git?
Running deactivate (a command the activation script adds to your shell) exits the virtual environment and restores your normal system python3/pip. And no — .venv/ should never be committed to git: it's often hundreds of megabytes, entirely machine-specific (it contains an actual copy of the interpreter), and completely reproducible from requirements.txt alone. Add .venv/ to .gitignore; commit requirements.txt instead.
- Virtual environments isolate a project's Python packages from every other project on the same machine.
python3 -m venv .venvcreates one;source .venv/bin/activateactivates it.pip freeze > requirements.txtrecords exact dependencies;pip install -r requirements.txtrecreates them anywhere.
2. Project structure
- A one-file script doesn't scale — a real project separates source code, tests, and config into their own places.
- A package is a folder of Python files with an
__init__.py, importable as a single unit. - There's a widely recognized standard shape most Python projects converge on, which this section lays out directly.
.py file. This is the shape everything else in the chapter builds on top of.
Here's a genuine project layout for a small task-management tool, shown as a real directory tree:
tasktool/
├── .venv/ (not committed -- see Sub-topic 1)
├── .gitignore
├── pyproject.toml (Sub-topic 5)
├── requirements.txt
├── README.md
├── src/
│ └── tasktool/
│ ├── __init__.py
│ ├── cli.py (argparse entry point, Sub-topic 4)
│ ├── storage.py (business logic)
│ └── logging_config.py
└── tests/
├── __init__.py
└── test_storage.py
__init__.py file, which tells Python "treat this folder as one importable unit." A folder without __init__.py is just a folder — Python won't let you import it as a package. Inside a package, src/tasktool/cli.py becomes reachable as tasktool.cli, and src/tasktool/storage.py as tasktool.storage, from anywhere the package is installed or importable.
A few of the choices in that tree are deliberate, not arbitrary:
- The actual package lives under
src/tasktool/, not directly at the project root — this is the "src layout," and it exists specifically to stop accidental imports of an un-installed, half-finished package during testing. tests/is a sibling ofsrc/, not mixed inside it — test code is never something an installed user of the package needs, so it stays out of what actually ships.cli.pyholds only argument parsing and wiring;storage.pyholds the actual logic. Splitting "how the user invokes this" from "what it actually does" means the logic instorage.pycan be tested directly, without going through the command line at all.
Thought process: the judgment call in laying out a project is what to put in a separate module versus what to leave inline — the rule of thumb is: anything that could reasonably be unit-tested on its own (parsing, calculations, storage) gets its own module; anything that's just "glue" wiring the pieces together (the CLI entry point) stays thin and mostly delegates.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
I have a single-file Python script called tasktool.py that mixes argument parsing and task-storage logic in one file. I want to restructure it into a proper installable package using the "src layout" convention: a src/tasktool/ package directory with __init__.py, a cli.py for argument parsing only, and a storage.py for the actual task logic, plus a separate tests/ directory at the project root. Show me the exact folder tree and explain why storage logic should be separated from the CLI entry point specifically for testability.
Config also gets a defined home rather than being scattered through the code. For a small tool, that's usually either a dedicated module (like logging_config.py above) or a single settings file read once at startup — the goal is one obvious place to look, not one setting hardcoded in cli.py and another hardcoded three files away in storage.py.
- A package is a folder with
__init__.py, making it importable as a single unit. - The "src layout" (
src/yourpackage/) keeps the installable package separate from tests, config, and project metadata at the root. - Splitting CLI wiring (
cli.py) from actual logic (storage.py) makes the logic testable independent of the command line.
Go Deeper: is the src/ layout mandatory?
No — plenty of real projects put the package directly at the project root instead of under src/, and both are common in the wild. The src/ layout's specific advantage shows up once a project has both a package and a test suite: without it, it's easy for tests to accidentally import the local, uninstalled source folder instead of the actually-installed package, hiding bugs that would only appear after a real pip install. For small personal tools this risk is minor; for anything meant to be installed by others, src/ layout is the safer default.
- A package needs
__init__.py; without it, a folder can't be imported as one unit. - The standard shape:
src/yourpackage/for code,tests/as a sibling, config in one obvious place, metadata files at the root. - Separate "how it's invoked" (CLI) from "what it does" (logic) so the logic is testable on its own.
3. Logging
print()has no levels, no timestamps, and no way to turn it off without editing code — the standard library'sloggingmodule has all three.- Five standard log levels — DEBUG, INFO, WARNING, ERROR, CRITICAL — let you filter what's shown without deleting any code.
- A configured logger can send different levels to different places at once: warnings and errors to the console, everything to a file.
print() statements nobody was watching. Logging is what makes an unattended script's behavior reconstructable after the fact.
print() sends text to the console and nothing else. It can't be filtered by severity, it can't be redirected to a file without extra work, and turning it off means finding and deleting (or commenting out) every call by hand. The logging module, part of the standard library, solves all three:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger("inventory")
def restock(item, qty):
logger.info("Restocking %s by %d units", item, qty)
if qty < 0:
logger.error("Negative restock quantity for %s: %d", item, qty)
raise ValueError("quantity cannot be negative")
return qty
restock("widgets", 50)
try:
restock("gadgets", -5)
except ValueError:
logger.warning("Restock rejected, notifying supply team")
2026-07-11 15:54:45 [INFO] inventory: Restocking widgets by 50 units
2026-07-11 15:54:45 [INFO] inventory: Restocking gadgets by -5 units
2026-07-11 15:54:45 [ERROR] inventory: Negative restock quantity for gadgets: -5
2026-07-11 15:54:45 [WARNING] inventory: Restock rejected, notifying supply team
logging.getLogger(name) and call .info(), .error(), etc. on, instead of calling print() directly. The name (here, "inventory") shows up in every message it produces, which matters once a project has multiple modules each logging their own events — you can tell at a glance which part of the program a message came from. Note the messages also use %s/%d placeholders rather than an f-string — logging only builds the final string if the message actually gets emitted, which avoids wasted work for messages a low log level would filter out anyway.
Notice each call above used a different method — .info(), .error(), .warning() — rather than one generic "log this" call. That's the level system:
DEBUG detailed diagnostic info, useful only while actively debugging
INFO confirmation that things are working as expected
WARNING something unexpected happened, but the program can continue
ERROR something failed -- a specific operation could not complete
CRITICAL a serious error -- the program itself may be unable to continue
A logger is configured with a minimum level, and only messages at that level or higher actually get shown — lower-severity calls are silently skipped, not deleted, so they're still there the moment you need them again:
import logging
logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s")
logger = logging.getLogger("demo")
logger.debug("Debug detail: cache hit for key=42")
logger.info("Job started")
logger.warning("Disk usage at 85 percent")
logger.error("Failed to connect to database")
logger.critical("Out of memory, shutting down")
WARNING: Disk usage at 85 percent
ERROR: Failed to connect to database
CRITICAL: Out of memory, shutting down
Both logger.debug(...) and logger.info(...) ran, but produced no output — they're below the configured WARNING threshold. Change one line, level=logging.DEBUG, and all five lines print; no code needs to be touched or deleted either way.
Thought process: the design decision that matters is choosing the right level per message, not just calling logger.info() for everything — routine progress is INFO, something recoverable-but-suspicious is WARNING, and something that actually broke an operation is ERROR. Getting this right is what makes filtering by level (DEBUG during development, WARNING+ in production) actually useful instead of arbitrary.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
I have a Python function restock(item, qty) that currently uses print() for every message, including an error case when qty is negative (which raises ValueError). Rewrite it to use the logging module instead: configure logging.basicConfig with level=logging.INFO and a format that includes a timestamp, level name, and logger name, get a named logger called "inventory", and choose the correct log level (info/warning/error) for each message based on its actual severity. Explain why the log messages should use %s-style placeholders instead of an f-string.
A single basicConfig() call only sends output to the console. Real production code often needs both — warnings and errors visible immediately in the terminal, but a complete record of everything (including DEBUG) saved to a file for later. That needs two handlers on the same logger, each with its own level:
import logging
def configure_logger(name, log_file="app.log"):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
logger.addHandler(console_handler)
logger.addHandler(file_handler)
return logger
logger = configure_logger("orders")
logger.debug("Order payload validated")
logger.info("Order #4521 placed")
logger.error("Payment gateway timeout for order #4521")
INFO: Order #4521 placed
ERROR: Payment gateway timeout for order #4521
2026-07-11 15:57:45,071 DEBUG orders: Order payload validated
2026-07-11 15:57:45,072 INFO orders: Order #4521 placed
2026-07-11 15:57:45,072 ERROR orders: Payment gateway timeout for order #4521
The logger itself is set to DEBUG (accept everything), and each handler applies its own, stricter filter on top — the console only shows INFO and up, while the file keeps everything including DEBUG. This is exactly the shape a real unattended script needs: a clean console for a human watching it run, and a complete file record for reconstructing what happened after the fact.
print()can't be filtered or redirected without editing code;loggingcan, via levels and handlers.- DEBUG < INFO < WARNING < ERROR < CRITICAL — a logger's configured level hides everything below it, without deleting the calls.
- Multiple handlers on one logger send different levels to different destinations (console vs. file) at the same time.
Go Deeper: why %s placeholders instead of an f-string in a log call?
logger.info("Restocking %s by %d units", item, qty) only formats the final string if the message actually passes the logger's level filter — the arguments are kept separate and merged in lazily. An f-string, by contrast, is evaluated immediately, every time the line runs, even if the logger is configured to discard DEBUG or INFO messages entirely. For a single log call this difference is invisible; inside a hot loop logging thousands of DEBUG messages that are mostly filtered out in production, it's the difference between negligible overhead and real, measurable slowdown.
logging.getLogger(name)gives you a named logger; call.debug()/.info()/.warning()/.error()/.critical()based on actual severity.- A logger's configured level filters out anything below it, without deleting the calls — flip one setting to see everything again.
- Separate handlers let one logger send different levels to the console and to a file simultaneously.
4. Building a CLI with argparse
argparseturns command-line arguments into a clean, validated object instead of hand-parsingsys.argv.- Positional arguments are required and identified by order; optional arguments use a flag (
-f/--flag) and can have defaults. - Subcommands (like
git addvs.git commit) let one program expose several distinct actions, each with its own arguments.
argparse generates both validation and help text for free, from the same declarations.
A minimal parser declares its arguments, then parse_args() reads them and returns a namespace object with one attribute per argument:
import argparse
parser = argparse.ArgumentParser(
prog="wordcount",
description="Count words in a text file."
)
parser.add_argument("filename", help="path to the text file")
parser.add_argument("-l", "--lines", action="store_true", help="also count lines")
parser.add_argument("-e", "--encoding", default="utf-8", help="file encoding (default: utf-8)")
args = parser.parse_args(["report.txt", "--lines"])
print(args)
print(args.filename, args.lines, args.encoding)
Namespace(filename='report.txt', lines=True, encoding='utf-8')
report.txt True utf-8
filename is positional — no flag, required, and identified purely by where it appears (wordcount report.txt means report.txt is the filename). --lines and --encoding are optional — they start with -/--, can appear in any order or not at all, and (unlike positionals) can define a default for when they're omitted. action="store_true" makes --lines a flag with no value of its own — its mere presence sets args.lines to True.
parse_args() was called here with an explicit list (["report.txt", "--lines"]) rather than reading real command-line input — useful for testing a parser directly in code. In a real script, calling parser.parse_args() with no argument reads from sys.argv automatically. Either way, argparse also generates help text for free, straight from the help= strings already written above:
$ python3 argparse_basic.py --help
usage: wordcount [-h] [-l] [-e ENCODING] filename
Count words in a text file.
positional arguments:
filename path to the text file
options:
-h, --help show this help message and exit
-l, --lines also count lines
-e, --encoding ENCODING
file encoding (default: utf-8)
Thought process: the design decision is which arguments genuinely have to be positional (the thing the whole command is about, usually exactly one) versus which are optional settings with sensible defaults -- forcing something into a positional slot that's really an optional tweak makes the command harder to remember and easier to get wrong.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Build a Python CLI tool called "wordcount" using argparse. It needs one required positional argument, filename (the path to a text file), plus two optional arguments: -l/--lines as a boolean flag (default False) to also count lines, and -e/--encoding as a string with default "utf-8". Give every argument a clear help= string, set prog and description on the ArgumentParser, and show me what python3 wordcount.py --help prints.
Real CLI tools usually do more than one thing — git has add, commit, push; pip has install, freeze, list. argparse supports this with subparsers, each one a fully independent parser with its own arguments:
import argparse
def build_parser():
parser = argparse.ArgumentParser(prog="taskcli", description="Manage a simple task list.")
subparsers = parser.add_subparsers(dest="command", required=True)
add_parser = subparsers.add_parser("add", help="add a new task")
add_parser.add_argument("description", help="what the task is")
add_parser.add_argument("-p", "--priority", type=int, default=3,
help="priority 1 (high) to 5 (low), default 3")
done_parser = subparsers.add_parser("done", help="mark a task complete")
done_parser.add_argument("task_id", type=int, help="the task's numeric id")
return parser
def main(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
if args.command == "add":
print(f"Added task: {args.description!r} (priority {args.priority})")
elif args.command == "done":
print(f"Marked task {args.task_id} as done")
if __name__ == "__main__":
main()
$ python3 task_cli.py add "Write chapter 31" --priority 1
$ python3 task_cli.py done 7
Added task: 'Write chapter 31' (priority 1)
Marked task 7 as done
argparse is the standard library module that turns a declared set of arguments into parsing, type-conversion, validation, and help-text generation — all from the same add_argument() calls. type=int above means argparse itself converts "7" to 7 and rejects anything that isn't a valid integer, before your code ever sees it.
That validation is not optional or best-effort — it's enforced automatically, with a real error message and a nonzero exit code, exactly like a professional CLI tool should behave:
$ python3 task_cli.py done notanumber
usage: taskcli done [-h] task_id
taskcli done: error: argument task_id: invalid int value: 'notanumber'
-v/--verbose flag) and subcommands, the top-level flag must come before the subcommand name on the command line — taskcli -v add "task" works, but taskcli add "task" -v fails with unrecognized arguments: -v, because once argparse hands off to the add subparser, it no longer recognizes arguments that belong to the parent parser.
- Positional arguments are required and order-based; optional arguments use a flag and can define a default.
type=gives free validation and conversion; a bad value produces a clean error and exit code 2, not a traceback.- Subparsers (
add_subparsers()) give one program multiple independent subcommands, each with its own arguments — but a parent parser's own flags must be given before the subcommand name.
Go Deeper: what does required=True on add_subparsers() actually do?
Without required=True, running the program with no subcommand at all silently leaves args.command as None instead of raising an error — a script that then tries to compare args.command == "add" would just do nothing, with no explanation to the user about what went wrong. Setting required=True makes argparse itself reject a missing subcommand with a clear "the following arguments are required: command" error, the same way a missing positional argument is rejected.
argparsereplaces hand-parsingsys.argvwith declared arguments, automatic validation, and generated help text.- Positional = required, order-based; optional = flag-based, can have a default.
- Subparsers give a program multiple subcommands; global flags must precede the subcommand name on the command line.
5. Packaging basics
pyproject.tomlis the single, standard file that describes a Python project's metadata and how to build it.- A project is
pip install-able the moment it has a validpyproject.tomlalongside a proper package — no separate registration step needed for a local or private install. [project.scripts](also called entry points) turns a function into a real terminal command after install.
python3 cli.py from inside it" into "run pip install . once, then type tasktool from anywhere" — the difference between a script and an actual installed tool.
For the tasktool project structure from Sub-topic 2, here's a real, minimal pyproject.toml at the project root:
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "tasktool"
version = "1.0.0"
description = "A simple command-line task manager."
requires-python = ">=3.9"
[project.scripts]
tasktool = "tasktool.cli:main"
pyproject.toml is the modern, standardized file (replacing the older setup.py) that tells pip everything it needs to build and install a project: what build tool to use ([build-system]), the project's own metadata like name and version ([project]), and any command-line entry points it should create ([project.scripts]). It's plain TOML — Python's own standard library can read it directly with tomllib, no third-party parser required.
The [project.scripts] table is the piece that makes a package genuinely feel like a real CLI tool rather than "a script you have to remember the path to." Each entry is command-name = "module.path:function_name":
tasktool = "tasktool.cli:main"
^ ^ ^
| | `-- the function to call
| `-- the module it lives in
`-- the command a user types in their terminal
pyproject.toml, that pip uses to generate a real executable command when the package is installed. After pip install ., typing tasktool in any terminal (with the environment activated) runs the main() function from tasktool/cli.py — exactly as if you'd typed python3 -m tasktool.cli, but as its own standalone command.
Thought process: the thing to get right here isn't TOML syntax, it's picking a stable entry-point function signature — main() taking no required arguments (reading from sys.argv internally, same as Sub-topic 4's main(argv=None) pattern) — since that's what both pip's generated script and a plain "python3 -m yourpackage.cli" invocation both need to call identically.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
I have a package at src/tasktool/ with a cli.py containing a function main(argv=None) that parses arguments with argparse. Write a minimal, valid pyproject.toml using the setuptools build backend that: sets project name "tasktool", version "1.0.0", a one-line description, requires-python ">=3.9", and declares a console entry point so that after `pip install .`, running `tasktool` in the terminal calls tasktool.cli:main. Explain what each of the three top-level tables ([build-system], [project], [project.scripts]) is responsible for.
With pyproject.toml in place and the src/tasktool/ package it points to actually existing, installing locally is one command, run from the project root with a virtual environment active:
$ pip install .
$ tasktool add "Ship v1.0"
That's the whole leap from "script" to "installed tool": before, running it meant remembering the exact file path and typing python3 path/to/cli.py; after, it's a real command, callable from any directory, exactly like any other tool installed with pip.
pyproject.tomlis the single standard file describing a project's build system and metadata.- A valid
pyproject.tomlalongside a real package is all that's needed forpip install .to work — no publishing step required for a local install. [project.scripts]entry points turn a Python function into a real terminal command after install.
Go Deeper: what's the difference between pip install . and publishing to PyPI?
pip install . builds and installs directly from a local folder — perfect for your own machine, a teammate's clone of the repo, or a CI pipeline, and everything covered in this chapter is enough to make that work. Publishing to PyPI (so anyone in the world can run pip install tasktool without cloning anything) is an additional step on top: building a distributable artifact with a tool like build, then uploading it with twine. That publishing workflow is genuinely useful for open-source libraries but is a step beyond what most internal or personal tools ever need.
pyproject.tomlhas three key tables:[build-system],[project], and[project.scripts].- A valid
pyproject.tomlplus a real package is enough forpip install .to work locally. - Entry points map a terminal command name to a specific function, turning an installed package into a real CLI tool.
6. Putting it together: a shippable CLI tool
- None of the previous five sub-topics are independent — a shippable tool needs all of them working together, not any one in isolation.
- The same
cli.pycan wire up argparse and logging configuration in one place, keeping both concerns close to the entry point. - This is the shape of the professional project brief this chapter builds toward: a packaged CLI tool.
Here's every piece from Sub-topics 1-5 assembled into the real tasktool project, starting from src/tasktool/cli.py:
import argparse
import logging
logger = logging.getLogger(__name__)
def build_parser():
parser = argparse.ArgumentParser(prog="tasktool", description="Manage a simple task list.")
parser.add_argument("-v", "--verbose", action="store_true", help="show debug-level logging")
subparsers = parser.add_subparsers(dest="command", required=True)
add_parser = subparsers.add_parser("add", help="add a new task")
add_parser.add_argument("description")
return parser
def main(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(levelname)s: %(message)s",
)
if args.command == "add":
logger.debug("Validating description before saving")
logger.info("Added task: %s", args.description)
if __name__ == "__main__":
main()
$ python3 -m tasktool.cli -v add "Ship v1.0"
$ python3 -m tasktool.cli add "Ship v1.0"
DEBUG: Validating description before saving
INFO: Added task: Ship v1.0
---
INFO: Added task: Ship v1.0
Notice logging is configured inside main(), after arguments are parsed — not at import time. That ordering is deliberate: the -v/--verbose flag itself decides the logging level, so parsing has to happen first. This is also the same subparser gotcha from Sub-topic 4 in action: -v is declared on the top-level parser, so it must come before add on the command line.
With __init__.py in place and the pyproject.toml from Sub-topic 5 pointing [project.scripts] at tasktool.cli:main, the entire chapter collapses into one clean setup-to-ship sequence:
$ python3 -m venv .venv # Sub-topic 1: isolate dependencies
$ source .venv/bin/activate
$ pip install . # Sub-topic 5: install via pyproject.toml
$ tasktool -v add "Ship v1.0" # Sub-topic 4: real CLI, Sub-topic 3: real logging
Thought process: the integration decision -- not any single piece's syntax -- is where to configure logging relative to argument parsing. Configuring it too early (at import time) means it can't react to a --verbose flag that hasn't been parsed yet; configuring it inside main(), right after parse_args(), is what lets a command-line flag control logging behavior at all.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a Python CLI entry point, main(argv=None), for a package called tasktool. It needs: a top-level -v/--verbose flag, one subcommand "add" taking a required "description" positional argument, and logging configured via logging.basicConfig with level=DEBUG if --verbose was passed else level=INFO. Configure logging AFTER parsing arguments, not at import time, and explain why that ordering specifically matters for a --verbose flag to work. The add subcommand should log the description at DEBUG level (as a validation step) and INFO level (confirming it was added).
- A shippable CLI tool needs a virtual environment, a real package structure, logging, argparse, and packaging metadata working together, not any single piece alone.
- Logging configuration that depends on a command-line flag must happen after
parse_args(), inside the entry point function, not at import time. - The full path from source to shipped tool:
venv→ package structure →pip install .→ a real installed command.
Go Deeper: what's an "editable install," and when would you want one?
pip install -e . (the -e flag means "editable") installs the package as a live link to the source folder instead of copying it — edits to src/tasktool/cli.py take effect immediately, without reinstalling. This is the standard workflow while actively developing a package: install it once with -e, then iterate on the code and re-run the tasktool command to see changes instantly, exactly the workflow this chapter's exercises use.
- All five earlier sub-topics compose into one tool — venv isolates it, structure organizes it, logging observes it, argparse drives it, packaging ships it.
- Logging that depends on a parsed argument (like
--verbose) must be configured afterparse_args()runs. pip install -e .is the standard workflow for developing a package you're actively editing.
- Every professional Python project you'll encounter — at a company, in open source, in a serious side project — uses a virtual environment and a
requirements.txtorpyproject.toml; skipping this is one of the fastest ways to mark code as amateur in a code review. - Production systems live or die by their logs — when something breaks in an unattended script or server process at 3 AM, the log file (not a debugger, since nobody's watching) is the only record of what happened, which is exactly why "just use print()" doesn't scale past a personal script.
- Internal company tools are overwhelmingly built exactly this way: a small, well-structured Python package with an argparse-driven CLI, installed with
pip install -e .on a teammate's machine — this chapter's shape, not a special case.
Points to Remember
- Virtual environments (
python3 -m venv .venv) isolate a project's dependencies;requirements.txt(viapip freeze) lets that environment be recreated anywhere. - A standard project layout separates installable source code (
src/yourpackage/, with__init__.py) from tests, config, and project metadata. - The
loggingmodule replacesprint()with leveled, filterable, redirectable diagnostics — DEBUG through CRITICAL — essential for anything unattended. argparsedeclares positional and optional arguments (and subcommands) once, and gets validation, type conversion, and help text generated for free.pyproject.tomlis the standard file that makes a projectpip install-able, with[project.scripts]entry points turning a function into a real terminal command.- A genuinely shippable CLI tool needs all five working together — venv, structure, logging, argparse, and packaging aren't separate tricks, they're one coherent workflow.