- Learn
- Computer Science & IT
- Programming
- Intermediate Python
- Python Packages and Virtual Environments
Python Packages and Virtual Environments
Python Packages, Virtual Environments and Project Structure
IntermediateLesson 7 of 9 in Intermediate Python Course
What you will learn
- Split a growing program into modules and packages, import their names in the right form, and find and fix the problems that make imports fail.
- Split a program into modules and control what runs on importWrite modules, choose an import form, keep top-level code safe to import with the
__name__check, and usedir(),__all__and__pycache__with understanding. - Build packages and use absolute and relative importsGroup modules into packages and subpackages, qualify nested names correctly, choose between absolute and relative imports, and run modules that live inside a package.
- Understand how Python finds modules and fix import errorsTrace how Python searches
sys.modulesandsys.path, and diagnose the usual import failures: the wrong interpreter, a different import name, a shadowing file and a circular import.
- Split a program into modules and control what runs on import
- Give each project its own isolated environment, install and inspect packages with pip, and record exact versions so that anyone can rebuild the same environment.
- Create, activate and use a virtual environmentExplain why projects need separate environments, create one with
venv, activate it on macOS, Linux and Windows, check which interpreter runs, and recreate an environment instead of moving it. - Install, inspect and remove packages with pipUse pip to install, upgrade, inspect and uninstall packages from PyPI, write version specifiers correctly, and understand dependencies, conflicts, wheels and source distributions.
- Pin dependencies so installs can be reproducedRecord exact versions with
pip freezeand requirements files, separate direct dependencies from a pinned lock list, and upgrade pins deliberately with constraints, hashes and lock tools.
- Create, activate and use a virtual environment
- Lay out a project the way professional teams do, describe it in a
pyproject.tomlfile, and install it for development with a command of its own.- Lay out a project folderArrange source code, tests and configuration in a clear folder structure, choose between the src and flat layouts, name packages correctly and decide what goes into version control.
- Write the pyproject.toml fileRead and write the TOML syntax of
pyproject.toml, and fill in its build-system, project metadata, dependency, extra, dependency-group and tool tables. - Install your project for development and give it a commandInstall a project in editable and regular mode, define console commands with
[project.scripts], run the program in the right way and build its distribution files locally.
- Lay out a project folder
- Turn a script into a dependable command-line tool that parses its arguments, explains itself with
--help, reports errors clearly and returns meaningful exit codes.- Define positional arguments and optionsRead arguments with
argparse, define positional arguments and options with types, defaults, choices and actions, and predict the resulting values, help text and error messages. - Structure a command-line programOrganize a command-line program around a testable
mainfunction, return exit codes, separate results from messages, and add subcommands and mutually exclusive options.
- Define positional arguments and options
- Replace diagnostic
printcalls with theloggingmodule: write messages at the right level from each module, and configure in one place where they go and how they look.- Write log messages with loggers and levelsCreate a logger per module, choose the right level for each message, pass values the logging way, record exceptions and understand the default behavior and the logger hierarchy.
- Configure handlers and formats for an applicationConfigure logging once at start-up with handlers, levels and formats, send messages to the terminal and to a file, connect verbosity options to log levels, and keep library code free of configuration.
- Write log messages with loggers and levels
Python Packages and Virtual Environments study guide
1Organize reusable code and make imports work
A growing program needs clear places for its calculations, file handling, and start-up code. Modules and packages give these parts names that other code can import. Learn what an import runs, how a dotted name follows a package tree, and why the command used to start Python changes where it searches. These connections make import errors easier to diagnose without adding machine-specific paths to the program.
1.1 Modules that are safe to import
A module groups related code under one name. A file named stats.py provides the module stats; its global names live in its own namespace. Another module can use a variable named mean without changing stats.mean.
Choose how to bind a name
| Import | Name available afterward | Example call |
|---|---|---|
import stats | stats | stats.mean(values) |
import statistics as st | st | st.mean(values) |
from stats import mean | mean | mean(values) |
from stats import * brings public names into the current namespace. It makes their origin harder to see and can replace an existing name. Explicit imports keep dependencies readable.
Separate definitions from actions
For an ordinary eager import, Python creates a module object, puts it in sys.modules, and executes its top-level code. Later imports normally reuse that object. A top-level print("loading stats") therefore appears on the first import, even if several files import stats.
Function definitions also run at import time, creating functions, but their bodies run only when called. Put prompts, file processing, and other actions inside functions:
# stats.py
def mean(values):
return sum(values) / len(values)
def main():
print(mean([2, 4, 9]))
if __name__ == "__main__":
main()
Running python stats.py or python -m stats sets __name__ to "__main__", so main() prints 5.0. Importing stats sets its name to "stats"; the functions become available and the demonstration stays silent. Putting input() above the guard would still prompt every first importer. The guard protects only the code inside it.
Public names and inspection
A name such as _parse_row is internal by convention. Python still permits direct access. With no __all__, a star import omits underscore-prefixed names; __all__ = ["mean", "median"] instead chooses exactly the exported names. It controls star imports, not access permissions.
dir(stats) lists the module's attributes, including names Python supplies. dir() with no argument lists names in the current scope. For a file-based module, stats.__file__ identifies the loaded source location. In an interactive session, importlib.reload(stats) deliberately executes the module again; a repeated ordinary import does not refresh edited code.
Bytecode and delayed loading
Python normally caches imported source as bytecode in __pycache__, using an interpreter tag such as stats.cpython-315.pyc. Reusing valid bytecode saves compilation work on later starts; it does not speed up the function's calculations. The directly executed script is not cached this way. The cache can be recreated and should be ignored by Git.
Python 3.15 adds lazy import json and lazy from pathlib import Path. They delay loading until the bound name is first used, so a missing-module error can appear at that use. Explicit lazy imports belong at module level, outside function, class, and try blocks, and cannot use *. Ordinary imports use eager loading in the default mode. The lazy syntax requires Python 3.15.
Key Takeaways
- Each module has its own namespace; the import form determines which local names are bound.
- Top-level code runs during the first eager import; later imports normally use
sys.modules. - The
__name__guard keeps program actions from running when the module is imported. - Underscores and
__all__describe an interface; they do not enforce privacy. - Bytecode caching saves compilation work; Python 3.15 lazy imports delay module loading.
1.2 Package names, relative imports, and module execution
A package is a module that can contain other modules. A regular package has an __init__.py file in its directory. That file may be empty; any code it contains runs when the package is first imported.
Read a dotted name from a tree
csvstats/
__init__.py
cli.py
analysis/
__init__.py
helpers.py
summary.py
loaders/
__init__.py
readers.py
The file analysis/summary.py has the import name csvstats.analysis.summary. Importing it first loads csvstats, then csvstats.analysis, then the requested module. The parent initializers run in that order.
| Import statement | Call to a function in summary |
|---|---|
import csvstats.analysis.summary | csvstats.analysis.summary.describe(data) |
from csvstats.analysis import summary | summary.describe(data) |
from csvstats.analysis.summary import describe | describe(data) |
Plain import takes a module or package name. import csvstats.analysis.summary.describe asks Python to find a module called describe; it does not import the function.
Importing only csvstats need not load analysis. A loaded submodule becomes an attribute of its parent, but an unloaded one may be absent. A package can offer a shorter interface by putting from .analysis.summary import describe in its initializer. Keep this file light: its imports affect everyone importing the package.
Locate another module inside a package
An absolute import starts from the top-level package, as in from csvstats.loaders.readers import read_rows. An explicit relative import starts from the current module's package. Inside csvstats.analysis.summary:
from .helpers import clean
from ..loaders.readers import read_rows
One dot means csvstats.analysis; two dots move up to csvstats. The dots describe package relationships, not the terminal's current folder. Relative imports require the from form. import helpers searches for a top-level module, so it does not mean the neighboring helpers.py. Absolute imports are the usual readable choice; explicit relative imports are useful inside nested packages.
Run the module with its package context
Running python csvstats/analysis/summary.py treats the file as a script with no known parent package. Its relative imports then fail. From the directory containing csvstats, run:
python -m csvstats.analysis.summary
The -m option takes a dotted name with no .py ending. It preserves the module's package context while giving its executed code the name "__main__".
To support python -m csvstats, add csvstats/__main__.py:
from csvstats.cli import main
raise SystemExit(main())
This small entry file delegates the work to cli.main and forwards its exit status.
A directory without __init__.py can form a namespace package. Several directories on the search path may contribute portions of one namespace. This supports separately distributed parts of a shared package name. For an ordinary self-contained project, include __init__.py in each regular package directory so its boundaries and initialization are explicit.
Key Takeaways
- A regular package contains
__init__.py; nested module names follow the package tree. - An import binds either the package, a module, or a selected name according to its form.
- One leading dot starts from the current package; each additional dot moves up one level.
- Use
python -mwith a dotted module name to preserve package context. - A package uses
__main__.pyforpython -m package; namespace packages can span directories.
1.3 Find the cause of an import error
An import error often comes from the program's environment or starting location. Before reinstalling anything, identify the interpreter and the module Python actually found.
Follow the search
Python checks sys.modules first. If the requested module is absent, the usual finders look for built-in modules, frozen modules, and then modules on sys.path. Built-ins such as sys do not lose to a same-named source file. In the path search, the first matching location wins.
At normal start-up, sys.path begins with the script's directory for a file command, or the current directory for -m, -c, and interactive use. Entries from PYTHONPATH follow, then standard-library and environment package locations. Python 3.11's -P option suppresses the potentially unsafe initial path entry.
Suppose /home/sam/report contains main.py and helpers.py, with import helpers in main.py. From /home/sam, python report/main.py finds the neighboring helper because the script directory is searched. From there, python -m main cannot find main.py; it searches /home/sam. Inside /home/sam/report, either python main.py or python -m main works.
Check the interpreter and installed distribution
For a missing installed library, run these in the terminal that starts the program:
python -c "import sys; print(sys.executable)"
python -m pip show requests
If the editor uses another interpreter, a successful terminal install does not fix its imports. Select the environment's interpreter there as well. python -m pip install requests installs through the named Python, avoiding a bare pip attached to another installation.
Distribution names and import names can differ: Pillow supplies PIL, beautifulsoup4 supplies bs4, scikit-learn supplies sklearn, and python-dateutil supplies dateutil. Use the library's documented installation name.
Check for shadowing
A project file named random.py can be found before the standard-library module. Then random.randint(...) may fail because Python loaded your file. Inspect random.__file__, rename the local file, and restart the program. File-based modules such as json, csv, and logging have the same risk. A missing attribute alone is not enough to identify the cause; the loaded location supplies the evidence.
Break a circular dependency
Suppose shop.orders imports shop.customers, which immediately asks shop.orders for Order. If Order has not been defined yet, the second import sees a partly initialized module. The cache entry exists before execution finishes. The resulting error can mention a partially initialized module; exact wording varies with Python version and execution context.
Move shared definitions into a third module or make the imports point one way. A local import inside a function can delay access when restructuring is impractical. Reordering lines may hide a cycle without removing the dependency.
Avoid repairing a reusable project with sys.path.append("../lib"): that relative path depends on where the process starts. Package the code and install it, or run it with -m from the appropriate directory. For a module name supplied as text at run time, importlib.import_module("csvstats.analysis.summary") returns the module object; a relative name also needs a package argument.
Key Takeaways
- Check
sys.executableand installation details in the same environment that runs the program. - A script command and a
-mcommand can start with different search directories. - Inspect
__file__to identify shadowing; distribution names can differ from import names. - A circular import can expose a module before its definitions exist; move shared code or simplify dependencies.
2Keep project dependencies separate and repeatable
Two projects can need incompatible releases of the same library. A virtual environment gives each project its own installed packages, while pip manages those packages for a chosen interpreter. Version ranges express what the code supports; a pinned dependency list records a tested selection. Learn how these pieces work together so a new terminal, contributor, or deployment can use the intended setup.
2.1 Create and check a virtual environment
A virtual environment gives a project its own interpreter entry point and site-packages directory. It uses a base Python installation and normally shares that installation's standard library. Separate environments let one project use an older library while another uses a newer release.
Create the environment with the intended Python
From the project folder, run python -m venv .venv. On Windows, py -m venv .venv is also common. To select a particular interpreter, use a command such as python3.13 -m venv .venv or py -3.13 -m venv .venv.
The resulting directory contains pyvenv.cfg, interpreter and tool commands, and a package directory. Commands live in bin on macOS and Linux and Scripts on Windows. pip is included by default; new environments on Python 3.12 and later do not include setuptools by default.
Activate for your shell
| Shell | Activation command |
|---|---|
| bash or zsh | source .venv/bin/activate |
| fish | source .venv/bin/activate.fish |
| Windows Command Prompt | .venv\Scripts\activate.bat |
| Windows PowerShell | .venv\Scripts\Activate.ps1 |
Activation puts the environment's command directory first on PATH, sets VIRTUAL_ENV, and usually adds (.venv) to the prompt. deactivate reverses these session changes. A new terminal has its own state.
If PowerShell blocks activation, you can run the environment's interpreter directly. On a computer you manage, the documented user-level policy command is Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser; it changes that user's script policy, not the environment itself.
Activation is optional. These commands select the environment without changing the shell:
.venv/bin/python report.py
On Windows, use .venv\Scripts\python.exe report.py. Direct paths are useful for scheduled jobs and automation because the interpreter choice is explicit.
Verify the running process
python -c "import sys; print(sys.executable); print(sys.prefix != sys.base_prefix)"
The path identifies the executable; True identifies a virtual environment. An activated terminal and an editor can still use different interpreters. If an editor reports a missing dependency that works in the terminal, select .venv in the editor and compare the paths.
Activation does not switch the Python version recorded in pyvenv.cfg. To change versions, create an environment using the new base interpreter and reinstall the requirements. By default, base-installed third-party packages are hidden. --system-site-packages exposes them and reduces that isolation.
Rebuild instead of moving
Keep source code outside .venv and ignore the environment in Git. Its scripts can contain absolute paths, so copying or renaming it is unreliable. After moving a project, recreate the environment from its dependency files. Python 3.13 and later also place a Git ignore file inside a new venv.
An externally-managed-environment error means a system package manager controls that Python. Create a venv for project dependencies; pipx is useful for a stand-alone application. Avoid bypassing the protection with --break-system-packages, which risks the system's tools. uv, Poetry, and PDM can manage venvs; Conda also manages environments that can contain their own Python installation.
Key Takeaways
- Create the environment with the Python version the project needs.
- Activation changes one shell session; a direct interpreter path works without activation.
- Use
sys.executableand the prefix comparison to verify the running environment. - Keep environments disposable and recreate them after moving the project.
- Use a venv when system Python is externally managed.
2.2 Use pip and read version requirements
pip installs distributions into the environment belonging to its interpreter. PyPI, the Python Package Index, is its usual public source. Run pip as python -m pip so installation and program execution use the same Python.
Choose the command for the job
Command after python -m pip | Purpose |
|---|---|
install requests | Install if missing; keep an installed version that satisfies the request |
install --upgrade requests | Seek a newer suitable release |
show requests | Show version, location, and dependency metadata |
list --outdated | Show installed distributions with newer releases available |
check | Report missing or incompatible installed dependencies |
uninstall requests | Remove the named distribution |
list shows installed packages; freeze prints requirements-style entries suitable for recording versions. An ordinary install is not an upgrade request if the installed version already satisfies it.
Read specifiers as limits
A comma means that all listed conditions must hold. For example, "requests>=2.31,<3" allows releases from 2.31 up to, but excluding, 3.
==2.32.3selects exactly one version.!=2.32.0excludes that version.==2.32.*selects the 2.32 series.~=2.31combines a lower bound of 2.31 with the 2 series.~=2.31.0combines a lower bound of 2.31.0 with the 2.31 series.
Thus 2.32.3 fits ~=2.31 but fails ~=2.31.0. Versions compare numeric components: 1.10 follows 1.9. pip normally prefers final releases; --pre permits prereleases, and explicit prerelease requirements also affect eligibility.
Quote requirement strings and extras:
python -m pip install "requests>=2.31,<3"
python -m pip install "csvstats[plot]"
In bash, zsh, and Windows Command Prompt, an unquoted > redirects output. Square brackets also have shell meanings, especially in zsh. Quoting keeps the intended requirement intact across shells.
Resolve the whole dependency tree
Installing requests also installs packages it needs, including urllib3, idna, certifi, and charset-normalizer. These are transitive dependencies. Uninstalling requests leaves them installed; pip does not know that no other project work needs them. Recreate a clean environment from the project requirements to remove experimental leftovers.
The resolver searches for a combination satisfying all requirements. If one dependency requires urllib3<2 and another requires urllib3>=2, no version fits both. A ResolutionImpossible report calls for compatible parent-package versions or a justified requirement change. Skipping dependencies with --no-deps does not solve the incompatibility.
Understand installation files
A wheel is built and ready to install. Its tags identify interpreter and platform compatibility; py3-none-any identifies a pure Python wheel without a platform-specific binary tag. The package's metadata still sets supported Python versions. A source distribution, usually a .tar.gz file, must be built first and may require a compiler. pip prefers a compatible wheel when available.
Distribution-name matching ignores case and treats runs of -, _, and . as equivalent. Scikit_Learn and scikit-learn name the same distribution. Python import names remain case-sensitive identifiers and can have a different spelling.
Key Takeaways
- Use
python -m pipto bind installation to the intended interpreter. - An install keeps a satisfying installed release; an upgrade explicitly seeks a newer one.
- All comma-separated specifiers apply;
~=2.31.0is narrower than~=2.31. - Resolve conflicting requirements together and account for transitive dependencies.
- Wheels are ready to install; source distributions need a build first.
- Distribution-name normalization does not change Python import-name rules.
2.3 Record and rebuild a tested dependency selection
A version range describes acceptable releases, but a fresh install later can choose different versions. Pinning records exact selections, including transitive dependencies, so another setup can request the same releases.
Capture a clean environment
python -m pip freeze > requirements.txt
Index-installed packages appear as lines such as requests==2.32.3. freeze records the installed environment; it does not decide which packages the project truly needs. An unrelated experiment can enter the file. It normally omits pip itself; on Python 3.11 and earlier it also omits setuptools and wheel. --all includes these tools.
Editable installs and local or URL-based installs can appear as -e entries or direct references. Review those lines for paths that exist only on your computer. --exclude-editable omits editable projects when that is appropriate.
On another machine, create an environment using a supported Python, activate it, and run:
python -m pip install -r requirements.txt
python -m pip check
The file records packages, not the interpreter or operating system. An exact release may lack support for a new Python or platform. Record requires-python and check the supported environments as part of the project's validation.
Separate requirements from a selected environment
| Record | What it expresses |
|---|---|
| Direct dependencies with ranges | Packages the project itself needs and the releases it supports |
| Pinned requirements or lock file | A complete tested choice of dependency versions for an application |
Libraries use compatible ranges in their metadata so they can coexist with other projects. Applications also keep and commit a pinned selection. Copying an entire freeze result into public library dependencies can impose unrelated packages and unnecessary exact-version conflicts.
A requirements file accepts comments, -r other.txt to include another file, and environment markers. For example, pywin32>=306; sys_platform == "win32" applies only on Windows. A development requirements file can include the runtime file and add pytest and ruff.
Constraints and hashes solve different problems
With python -m pip install -r requirements.txt -c constraints.txt, constraints limit versions of packages requested elsewhere. A line naming urllib3 does not request its installation by itself. Constraints must name packages and cannot contain editable entries or extras.
Hash checking verifies downloaded files against recorded hashes. --require-hashes requires all dependencies to be pinned and hashed, including transitive ones. A tool can generate the file and its allowed artifact hashes; a wrong hash blocks that artifact. Hashes detect changed bytes, not whether the chosen package is trustworthy.
Update the selection deliberately
pip-tools compiles ranges in requirements.in to pinned requirements; uv uses uv.lock, while Poetry and PDM use their own locks. The standard pylock.toml format comes from PEP 751. pip's pip lock command is experimental and currently guarantees its generated lock only for the current Python and platform.
For an update, change the intended range or run a targeted upgrade command, rebuild in a fresh environment, run the project checks, and commit the updated lock with related code changes. Version numbers often use major, minor, and patch components, but projects choose their own compatibility policies; read their release notes before relying on that convention.
Key Takeaways
- Freeze a clean environment and review local or editable references before sharing it.
- Keep direct dependency ranges separate from an application’s complete pinned selection.
- Constraints limit a requested package; they do not request it.
- Hash checking requires a complete pinned, hashed dependency list.
- Rebuild and validate after deliberate upgrades; pins do not record the Python runtime or platform.
3Describe, install, and build a Python project
A project combines source code, dependency choices, documentation, and commands that users can run. A clear folder layout makes those roles visible, and pyproject.toml describes the package to build tools and installers. Learn how editable installs support development, why a changed command needs reinstallation, and how a clean wheel install checks the files that another environment actually receives.
3.1 Give source code and configuration clear places
The project root holds the whole development project. The import package holds the Python code other programs load. They may share a name, but they have different roles.
Read a src layout
csvstats/
pyproject.toml
README.md
LICENSE
.gitignore
src/
csvstats/
__init__.py
__main__.py
cli.py
loaders.py
summary.py
tests/
test_summary.py
The outer csvstats is the project directory. The inner src/csvstats is the import package. pyproject.toml describes how it is built and installed; README.md explains its use; LICENSE records its licensing terms. Tests sit outside the package so they exercise its public imports.
Choose a layout with its import behavior in mind
| Layout | Package location | Development consequence |
|---|---|---|
| src | src/csvstats | Install the project so its package is importable normally |
| flat | csvstats beside configuration | Running from the root can expose local source before installation |
Both layouts work. The src layout makes it harder for a successful import to hide a missing installation. In a flat layout, the current directory on sys.path can expose files that never entered the built package.
An editable src install still loads source files directly. The wheel may still omit a needed module. To inspect what users receive, build the package, install its wheel into a clean environment, and run checks from outside the source tree. This separates a packaging check from ordinary development feedback.
Split by responsibility
loaders.py reads the data. summary.py calculates results. cli.py parses arguments and coordinates these functions. __main__.py starts the application. A calculation function should receive values, not ask a command-line parser to obtain them.
Keep imports pointing from the CLI toward the reusable work. If summary.py imports cli.py while cli.py imports summary.py, the dependency direction has become a cycle. Put a shared definition in a lower-level module used by both. This also lets a notebook or another program reuse the calculations without starting the command-line interface.
Name the two kinds of package correctly
An import package name must be a valid identifier, such as csv_stats. A distribution can be named csv-stats in project metadata, but import csv-stats is invalid Python syntax. Avoid names such as logging or json for your package because they can shadow the standard library.
Tests should import through the installed package, for example from csvstats.summary import describe. Adding private source paths in each test can hide the same installation problems the layout was meant to reveal.
Keep the rebuild inputs in Git
Commit source, tests, configuration, documentation, the license, and the application's pinned requirements or lock file. Ignore generated material: .venv/, __pycache__/, *.pyc, dist/, build/, and *.egg-info/. Another contributor can recreate those outputs from the committed inputs. Keeping local environment directories in Git would also preserve machine-specific paths and large amounts of replaceable data.
Key Takeaways
- The project root and import package serve different roles.
- A src layout requires normal installation; a flat layout can expose uninstalled local code.
- A clean regular install checks built files; editable imports still use the source tree.
- Group modules by responsibility and keep imports pointing toward reusable code.
- Commit rebuild inputs and ignore environments, caches, and build outputs.
3.2 Write project metadata and dependency tables
pyproject.toml is the standard home for build configuration, project metadata, and supported tool settings. It uses TOML: headers create tables, strings need quotes, arrays use square brackets, booleans are true or false, and # starts a comment. Keys are case-sensitive. Write version = "0.1.0"; an unquoted 0.1.0 is invalid.
Start with a complete project description
[build-system]
requires = ["setuptools>=77.0.3"]
build-backend = "setuptools.build_meta"
[project]
name = "csvstats"
version = "0.1.0"
description = "Summarize the numeric columns of a CSV file"
readme = "README.md"
requires-python = ">=3.10"
license = "MIT"
authors = [{ name = "Ana Lima", email = "ana@example.com" }]
dependencies = ["rich>=13.7"]
[project.optional-dependencies]
plot = ["matplotlib>=3.8"]
[project.scripts]
csvstats = "csvstats.cli:main"
[dependency-groups]
test = ["pytest>=8"]
dev = [{ include-group = "test" }, "ruff"]
[tool.pytest.ini_options]
testpaths = ["tests"]
[build-system] tells a front end such as pip which backend builds the package. Its requires list contains build dependencies. Here, pip calls setuptools through setuptools.build_meta. Hatchling, Flit, PDM, and uv also provide backends. Runtime libraries such as rich belong in [project] dependencies, because they are needed when the installed program runs.
Distinguish the dependency lists
| Location | Audience and purpose |
|---|---|
project.dependencies | Runtime requirements for every installation |
project.optional-dependencies | Public extras users can request |
dependency-groups | Development dependency lists, absent from built project metadata |
build-system.requires | Tools needed to build the project |
python -m pip install "csvstats[plot]" requests the project plus its plotting extra. From the project root, python -m pip install --group dev installs the development group with pip 25.1 or later. A group may include another using { include-group = "test" }. Installing a group does not by itself install the local project.
Runtime requirements use supported ranges, for example "requests>=2.31,<3". Keep an application's exact tested selection in a lock or pinned requirements file. A marker such as "tomli>=2; python_version < '3.11'" selects a dependency only in the matching Python versions.
Read the remaining metadata
name is required and cannot be dynamic. version must be supplied or listed under dynamic for the backend to calculate. requires-python restricts supported interpreter versions; it is not the project's own version. Modern license values are SPDX expressions, such as "MIT"; license-files can select license files by pattern. Description, authors, keywords, classifiers, and [project.urls] help describe the distribution.
For one version source, keep a static version here or use a backend's dynamic-version configuration. With setuptools, [tool.setuptools.dynamic] can read an attribute such as csvstats.__version__ when dynamic = ["version"] is declared. At run time, importlib.metadata.version("csvstats") reads the installed distribution's version.
Each [tool.NAME] table follows that tool's documented keys. The standard library's tomllib, available since Python 3.11, can read TOML using tomllib.load with a binary file opened as "rb". A Python 3.10 program needs an alternative TOML reader. Older setup.py projects remain supported by setuptools; new declarative metadata normally lives here.
Key Takeaways
- Use valid TOML, including quoted version strings and lowercase booleans.
- Build requirements and runtime dependencies belong in different tables.
- Extras are public optional features; dependency groups support development.
- Declare the supported Python range and one source for the project version.
- Use
[tool.NAME]for tool-specific settings;tomllibis available from Python 3.11.
3.3 Install source for development and build a wheel
Installing your own project teaches Python where its package lives and creates the commands declared in its metadata. Choose an editable install during development and a regular install to check the packaged result.
Install the local project
From the project root, using its virtual environment:
python -m pip install -e .
The dot means the current project. pip asks its backend for an editable installation, installs runtime dependencies, and makes the source package available. Changes to existing Python source files appear on the next run without rebuilding the installed copy.
Metadata changes need another install. If you add a dependency, define an extra, change a command, or rename the package, run the command again. python -m pip install -e ".[plot]" requests the local project's plotting extra while keeping the editable install.
Without -e, python -m pip install . builds and installs a regular copy. Later source edits do not affect that copy until you reinstall it. This is useful when checking that package discovery and included files match what an installer receives.
Turn a function into a terminal command
[project.scripts]
csvstats = "csvstats.cli:main"
The left side names the command. The right side names an importable module and a callable, separated by a colon. It is not a source-file path and has no parentheses. Installation creates a command in the environment's bin directory or Scripts directory on Windows.
The wrapper imports csvstats.cli, calls main() with no required arguments, and passes its return value to sys.exit. A signature such as main(argv=None) works because it can be called without arguments. Returning 0 signals success; returning 1 signals failure. A new script entry does not appear until the project is reinstalled.
Support package execution too
Keep __main__.py small:
from csvstats.cli import main
raise SystemExit(main())
Now python -m csvstats data.csv and csvstats data.csv reach the same function. Running python src/csvstats/cli.py data.csv directly loses package context for relative imports and can select different import paths.
A new contributor gets the source, enters the project root, creates and activates .venv, and runs python -m pip install -e .. With pip 25.1 or later, python -m pip install --group dev adds development tools. csvstats --help checks that the installed command can start.
Build and inspect installable artifacts
python -m pip install build
python -m build
The build front end writes a source distribution and wheel under dist/. For this pure Python project at version 0.1.0, typical names are csvstats-0.1.0.tar.gz and csvstats-0.1.0-py3-none-any.whl.
A wheel is a ZIP archive containing the files to install. Inspect its contents to see whether the expected modules are present. Install the wheel with python -m pip install dist/csvstats-0.1.0-py3-none-any.whl in a clean environment. Then run the command from outside the source checkout. An editable run can succeed even when a required module was left out of the wheel; this clean install catches that packaging failure.
Key Takeaways
- Editable installs use source files; regular installs use a built copy.
- Reinstall after metadata changes, including new dependencies and console commands.
- A script target uses
module.path:function, and the callable must accept a call without arguments. - Share one
mainfunction between the installed command and package execution. - Build locally, inspect the wheel, and check a clean install outside the source tree.
4Make a command-line tool clear and dependable
A command-line interface turns strings from the terminal into values the program can use. argparse handles the routine parsing, help, and usage errors, while a small main function connects those values to reusable work. Learn to design flags and subcommands, report expected failures clearly, and keep result output separate from diagnostics so other programs can use the tool’s output safely.
4.1 Parse arguments, options, and flags
Arguments arrive as strings. For python report.py sales.csv --top 3, sys.argv contains the script name and the strings "sales.csv", "--top", and "3". argparse reads those strings, converts declared types, applies defaults, and returns a Namespace whose attributes hold the values.
Build and use a parser
import argparse
parser = argparse.ArgumentParser(
prog="csvstats",
description="Summarize the numeric columns of a CSV file.",
allow_abbrev=False,
)
parser.add_argument("path", help="CSV file to read")
parser.add_argument("--top", type=int, default=5,
help="rows to show (default: %(default)s)")
parser.add_argument("--format", choices=["table", "json"], default="table")
parser.add_argument("-c", "--column", action="append")
parser.add_argument("-v", "--verbose", action="count", default=0)
parser.add_argument("--dry-run", action="store_true")
path is positional and normally required. An option begins with dashes and normally uses a default when absent; without an explicit default, an ordinary value-taking option gets None. Options can have both short and long names. A value essential to every run is often clearer as a positional argument than as an option marked required=True.
Trace a parsed command
args = parser.parse_args([
"sales.csv", "--top", "3", "-c", "price", "-c", "qty", "-vv"
])
args.path is "sales.csv". type=int makes args.top the integer 3. The repeated -c options produce args.column == ["price", "qty"]; -vv produces args.verbose == 2. The omitted format keeps "table", and args.dry_run is False.
Long-option dashes become underscores in attribute names: use args.dry_run. Python reads args.dry-run as subtraction. dest="name" can select a different destination attribute.
Choose an action and number of values
| Setting | Behavior |
|---|---|
action="store_true" | Store True when present; otherwise False |
action="count", default=0 | Count flag occurrences from zero |
action="append" | Collect repeated values in a list |
nargs="+" | Require one or more values |
nargs="*" | Accept zero or more values |
nargs="?" | Accept zero or one value |
nargs=2 | Require exactly two values and return a list |
Avoid type=bool: bool("False") is True because the string is nonempty. Use a flag or BooleanOptionalAction, which creates paired forms such as --color and --no-color.
Let errors stop invalid input
--help and -h print help and exit successfully with status 0. An invalid integer, missing required positional argument, or invalid choice prints usage and an error to standard error and exits with status 2. Choices are checked after type conversion.
With default abbreviation enabled, an unambiguous --for can mean --format. Adding --force would make that spelling ambiguous. allow_abbrev=False makes scripts use the declared spellings. Python 3.15 enables close-match suggestions by default for mistyped choices and subcommands; the underlying validation still rejects invalid values.
Key Takeaways
- argparse converts terminal strings into
Namespaceattributes. - Positional arguments and options have different default requirements.
- Use flag actions for booleans, and set a zero default when counting repetitions.
- Match
nargsto the number of values and use underscores in option-derived attributes. - Help exits with 0; usage errors go to standard error and exit with 2.
- Disable abbreviation when stable long-option spellings matter.
4.2 Keep parsing, work, and exit status separate
A command-line program needs a small entry function that coordinates work. Reusable functions should accept ordinary values so that other code can call them without constructing an argparse namespace.
Return a status from main
import sys
def main(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
if args.top < 1:
parser.error("--top must be at least 1")
try:
rows = read_rows(args.path)
except FileNotFoundError:
print(f"csvstats: file not found: {args.path}", file=sys.stderr)
return 1
print(summarize(rows, top=args.top))
return 0
if __name__ == "__main__":
raise SystemExit(main())
Here, build_parser, read_rows, and summarize are the parser builder and the application's work functions. With argv=None, parsing uses sys.argv[1:]. Passing a list, such as main(["sales.csv", "--top", "3"]), makes the input explicit. The installed script wrapper can also call main() with no arguments.
A return value alone does not tell the shell anything unless the entry point forwards it. raise SystemExit(main()) and sys.exit(main()) do that. Status 0 means success; argparse uses 2 for usage errors, and applications commonly use 1 for an expected operational failure. sys.exit("message") prints the message to standard error and exits with 1.
Keep result data usable
Send normal results to standard output. Send error messages and logging to standard error. Then csvstats sales.csv --format json > out.json redirects only the result stream. A plain error print would put text into the JSON output and make it invalid.
Catch expected failures near the place where the application can explain them, such as a file that does not exist. Let unexpected bugs raise a traceback or record them with logger.exception. Catching every exception and returning success would hide failures from automation. Use parser.error(...) for invalid argument combinations or value rules that parsing alone cannot express.
Add commands with separate argument sets
parser = argparse.ArgumentParser(prog="inventory")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", help="add an item")
add.add_argument("name")
add.add_argument("--qty", type=int, default=1)
add.set_defaults(func=cmd_add)
lst = sub.add_parser("list", help="list items")
lst.add_argument("--low", action="store_true")
lst.set_defaults(func=cmd_list)
After parse_args, call args.func(args) inside main and return its result. The handler functions must exist when assigned. inventory add stapler --qty 3 selects cmd_add; inventory list --low selects cmd_list. Each subparser supplies its own help, and required=True rejects a missing command.
Reject conflicting flags and improve help
Put verbose and quiet flags in parser.add_mutually_exclusive_group(). The default permits neither or one; required=True requires exactly one. Giving both causes a usage error.
Use a specific description, an epilog example, and a metavar such as "N" for a displayed value name. An option with action="version" prints a version and exits; importlib.metadata.version("csvstats") keeps that version tied to installed metadata.
Key Takeaways
- Let
main(argv=None)parse inputs and pass plain values to reusable work functions. - Forward the returned status through
SystemExitor the installed script wrapper. - Send results to standard output and diagnostics to standard error.
- Use subparsers for separate actions and mutually exclusive groups for conflicting options.
- Handle expected failures clearly while preserving unexpected bug information.
5Write useful logs and control where they go
Logs explain what a program did without mixing diagnostic text into its results. Module loggers identify the code that produced each message, and severity levels let an application choose how much to show. Follow a message from its logger through the hierarchy to its handlers, then configure a quiet terminal and a detailed file. Keep that configuration at application start-up so reusable modules remain easy to use elsewhere.
5.1 Choose levels and write messages from each module
The logging module separates the place that reports an event from the configuration that displays or saves it. A module can report detailed progress while an application chooses to show only warnings. The same record can include the logger name, severity, and timestamp.
Name the source and select a level
Create a logger at module level:
import logging
logger = logging.getLogger(__name__)
In csvstats.loaders, that gives the logger the name "csvstats.loaders". Calling getLogger again with the same name returns the same logger object. Module-level functions such as logging.warning instead use the root logger and may automatically configure it when no root handlers exist.
| Level | Number | Typical event |
|---|---|---|
| DEBUG | 10 | Detailed state used while investigating a bug |
| INFO | 20 | Normal progress, such as a completed load |
| WARNING | 30 | An unexpected condition the program can handle |
| ERROR | 40 | An operation failed |
| CRITICAL | 50 | A failure prevents continued operation |
A threshold includes its own level and more severe levels. At INFO, DEBUG is filtered out. Use the event's meaning, not how often you want to see it, to choose the level.
Pass values through the message template
logger.info("Loaded %d rows from %s", 120, "sales.csv")
The message becomes "Loaded 120 rows from sales.csv" when it is formatted. Logging delays this %-style substitution until formatting is needed. An f-string also produces valid text, but it is formatted before the logger decides to drop a message. Argument expressions themselves still run when the logging call is made. To skip an expensive calculation when DEBUG is disabled, guard it explicitly:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Report %s", calculate_report())
The template needs a placeholder for each formatting argument. logger.info("Loaded", 120) has no placeholder and can produce a logging error report when a handler formats it. Keep context specific, such as "Skipped row 17: price 'n/a' is not a number". Never record passwords, access tokens, or complete personal data; use a suitable identifier instead.
Understand a quiet logger
The root logger starts at WARNING. Named loggers normally start at NOTSET and inherit an effective level from their nearest configured ancestor. Without application configuration, a built-in last-resort handler can write warnings and higher messages to standard error as message text only.
Calling logging.basicConfig(level=logging.INFO) in the application makes INFO visible using the default level, logger name, and message format. Its output might be "INFO:csvstats.loaders:Loaded 120 rows".
Preserve the traceback when needed
Inside an except block:
except OSError:
logger.exception("Could not read %s", path)
exception records an ERROR and the current exception traceback. logger.error(..., exc_info=True) has the same effect. Logging only an exception's string loses the call stack that helps locate the failure.
Logger names form a tree: csvstats.loaders belongs under csvstats, then the root. Records normally propagate to ancestor handlers, letting one application setup collect messages from many modules. Setting a noisy library logger such as urllib3 to WARNING can suppress its lower-level messages without silencing your own INFO records.
Key Takeaways
- Use
getLogger(__name__)so messages identify their module. - A severity threshold includes that level and all more severe levels.
- Pass values as separate logging arguments; placeholder substitution is delayed.
- Use
logger.exceptioninside an exception handler to preserve the traceback. - NOTSET loggers inherit an effective level, and records normally propagate to ancestor handlers.
5.2 Configure destinations, formats, and verbosity
A logger decides whether to create a record. A handler sends that record to a destination, and a formatter turns it into display text. Both the originating logger's effective threshold and a destination handler's threshold matter.
Start with one application setup
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
This configures the root logger and a standard-error stream handler. A filename argument selects a file instead. basicConfig does nothing when root handlers already exist; force=True removes and replaces them. Configure once in the entry point, before normal application logging, so an earlier root-level logging call does not choose the setup accidentally.
Give the terminal and file different thresholds
root = logging.getLogger()
root.setLevel(logging.DEBUG)
fmt = logging.Formatter("%(levelname)s %(name)s: %(message)s")
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
console.setFormatter(fmt)
logfile = logging.FileHandler("csvstats.log", encoding="utf-8")
logfile.setLevel(logging.DEBUG)
logfile.setFormatter(fmt)
root.addHandler(console)
root.addHandler(logfile)
A module logger at NOTSET inherits DEBUG from root. Its DEBUG record reaches both handlers, but only the file accepts it. WARNING reaches both. If root stayed at WARNING, that same inheriting module logger would drop DEBUG before either handler could receive it.
A child logger explicitly set to DEBUG behaves differently: it creates the DEBUG record even if root is at WARNING. During propagation, ancestor logger levels are not checked again; ancestor handler levels are checked. Lowering only a file handler cannot rescue a record already rejected by the originating logger.
Keep configuration out of reusable libraries
Applications choose destinations. A library creates named loggers and reports events; it should not add console or file handlers or call basicConfig. It may add a NullHandler to its top-level logger. A duplicate line often comes from attaching handlers to both a child and an ancestor, or running setup twice. Configure handlers in one place; use propagate=False only when that logger deliberately owns its separate output.
Connect verbosity and manage files
For a counted -v flag with default 0:
level = max(logging.WARNING - 10 * args.verbose, logging.DEBUG)
No flag selects WARNING, -v selects INFO, and -vv or more selects DEBUG. A quiet flag can select ERROR. Keep diagnostic streams on standard error so redirected results stay clean.
FileHandler appends by default. Specify UTF-8 so the encoding is consistent. For bounded files, RotatingFileHandler("csvstats.log", maxBytes=1_000_000, backupCount=3) rotates near 1 MB and retains three older files.
For data-driven setup, logging.config.dictConfig accepts a dictionary with version: 1, formatters, handlers, and root or named loggers. Its disable_existing_loggers default is True; existing non-root loggers can be disabled unless they or an ancestor are named in the configuration. Set it to False when existing module loggers should remain active.
Key Takeaways
- Logger admission comes before handler filtering; ancestor logger levels are not rechecked during propagation.
- A handler chooses a destination and a formatter chooses the line layout.
- Configure once at application start-up; libraries report events without choosing output destinations.
- Avoid duplicate handlers along a propagation path.
- Connect verbosity to levels and rotate growing files.
- Use
disable_existing_loggers=Falsewhen dictionary setup should preserve existing module loggers.
Python Packages and Virtual Environments examples
1Turn a script into an importable package
15 steps
- 1IntroductionSeparate the calculation from the command
A reporting script has grown large enough that another program needs its calculations. Move those calculations into a module, then organize related modules into a package.
Follow what Python does at each import: it binds names, executes initialization code, and searches particular locations. Each of those steps explains a different kind of failure when a script becomes reusable code.
- 2ExplanationChoose the name the caller will use
A file named
stats.pyhas its own namespace.import statsbinds that module, so callers writestats.mean(values).from stats import meaninstead binds the function name directly.An alias gives the imported object a chosen local name:
import statistics as stsupportsst.mean(values). A star import can replace names already present and makes their origin harder to read. - 3ExamplePut the demonstration behind a guard
Keep a reusable calculation separate from the demonstration:
def mean(values): return sum(values) / len(values) def main(): print(mean([2, 4, 9])) if __name__ == "__main__": main()Running the file prints
5.0. Importing it creates the functions but skips the guarded call because the module's import name is not"__main__". - 4Key InsightThe guard does not stop the whole import
Python stores the module object in
sys.modulesbefore executing its code. Later ordinary imports normally reuse it. This means a top-level prompt outside the guard still runs on the first import.The guard controls a block of actions; it does not turn module loading off. Python 3.15’s explicit lazy imports provide a different mechanism: they delay loading until first use of the imported name.
- 5ChallengePredict what an importer sees
units.pyprints"loaded"at top level. It also callsmain()under its__name__guard. In a fresh process, a caller importsunitstwice. What runs?---reveal---
The top-level print runs once; the guarded
main()call does not run. The first import executes initialization, while the second normally uses the cached module. Moving only the print under the guard would make both imports silent. - 6ExplanationFollow the package tree
Place
summary.pyandhelpers.pyinsidecsvstats/analysis, with__init__.pyin both package directories. The summary module’s name iscsvstats.analysis.summary.Importing that name loads the top-level package, then the analysis package, then the module. Initializer code runs along the way. Keep those initializers small so importing one function does not unexpectedly start unrelated work.
- 7ExampleResolve a sibling and a parent import
Inside
csvstats.analysis.summary, these imports have different starting points:from .helpers import clean from ..loaders.readers import read_rowsOne dot starts at
csvstats.analysis; two reachcsvstats. The first import selectscsvstats.analysis.helpers, and the second selectscsvstats.loaders.readers. A bareimport helperswould ask for a top-level name instead of the sibling file. - 8TipUse a module name when starting package code
From the directory containing
csvstats, usepython -m csvstats.analysis.summary. The dotted name gives relative imports the package context they need.A direct command such as
python csvstats/analysis/summary.pyruns the file without that parent context. To supportpython -m csvstats, put a small delegating entry point in the package’s__main__.pyand leave the real work in an ordinary module. - 9ChallengeFind the right parent
Inside
library.reports.weekly, what module suppliesloadinfrom ..storage import load? How would you executeweeklyfrom the directory containinglibrary?---reveal---
The import selects
library.storage: the second dot moves up fromlibrary.reports. Runpython -m library.reports.weekly. That command preserves package context; a direct source path would not supply the same context for the relative import. - 10ExplanationCheck the running interpreter first
A successful install in one terminal cannot supply packages to every Python process on the computer. Check
sys.executablein the process that fails, then runpython -m pip show NAMEwith that interpreter.If the editor points elsewhere, select the environment there too. Also verify the documented import name: the installed distribution Pillow supplies
PIL, so install and import names are not always identical. - 11ExampleLet the loaded path reveal shadowing
Suppose
import jsonsucceeds butjson.loadsis missing. Printingjson.__file__shows a project file calledjson.py. That local file won the path search before the standard-library source.Rename the local file and restart. Reinstalling packages cannot fix the conflicting source name. Built-in modules are found differently, but file-based modules and installed libraries can be shadowed this way.
- 12ChallengeDistinguish discovery from initialization
billing.ordersimportsbilling.users, which requestsOrderfrombilling.ordersbefore that class is defined. Would adding the project root tosys.pathrepair this failure? Explain a better change.---reveal---
No. The module was found, but its initialization is incomplete. Move the shared definition into a lower-level module that both can import, or make dependencies point one way. Path changes do not make an unfinished definition available.
- 13ConnectionStarting location changes the search
For a file command, normal
sys.pathbegins with the script’s directory. For-m, it begins with the current directory. A working file command and a failing module command may therefore be searching different places.Once the package is installed, its environment can discover it through installation. Avoid scattered
sys.path.appendrepairs whose meaning changes with the terminal’s starting folder. - 14ChallengeRepair the launch and keep imports quiet
A package module uses a relative import and has an unguarded demonstration call at top level. Direct source execution fails, while importing it starts the demonstration. What two changes address these separate problems?
---reveal---
Launch it with
python -mand its dotted module name from a location where the package is discoverable. Move the demonstration call under the__name__guard. The first change supplies package context; the second controls actions during import. - 15RecapTrace the kind of failure
Ask three different questions when reusable code misbehaves: which names did the import bind, which initialization actions ran, and where did this interpreter search?
The answers lead to specific changes: qualify the right name, guard program actions, select the intended environment, or correct a package dependency. A cached module can still be initializing, so finding its object does not mean all its definitions are ready.
2Rebuild a project environment from recorded dependencies
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the setup another person can repeat
- 2ExampleCreate the environment with the intended Python
- 3ExplanationActivate or name the interpreter directly
- 4ChallengeVerify the editor’s Python
- 5TipTreat the environment as replaceable
- 6ExampleAsk for a suitable install, then inspect it
- 7ExplanationRead all limits together
- 8ChallengeChoose a release inside the series
- 9ExplanationSeparate supported ranges from tested pins
- 10ExampleFreeze a clean selection and rebuild
- 11Key InsightConstraints do not request packages
- 12ChallengeFind the missing hash requirement
- 13ConnectionA package list is not the whole runtime
- 14ChallengeRemove an experiment without breaking the project
- 15RecapKeep three setup decisions explicit
3Install a src project and create its command
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionConnect source code to an installed tool
- 2ExampleFind the import package
- 3Key InsightEditable success leaves one question open
- 4ChallengeChoose what another contributor needs
- 5ExampleSeparate build tools from runtime libraries
- 6ExplanationGive optional users and developers separate lists
- 7ChallengePlace each requirement where it belongs
- 8ExampleInstall for edits and refresh metadata
- 9ExampleDeclare a callable behind the command
- 10ChallengeRepair a command missing after an edit
- 11ExampleBuild the files another environment receives
- 12ChallengeConnect development setup to the missing command
- 13RecapRefresh the right layer
4Build a CLI that parses, reports, and exits clearly
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive terminal strings a clear meaning
- 2ExampleDeclare the accepted input
- 3ExampleTrace values after parsing
- 4Key InsightUse actions for booleans and repetitions
- 5ChallengePredict a command without a flag
- 6ExampleForward the work result through main
- 7ExplanationSeparate invalid usage from operational failure
- 8ChallengeKeep redirected results usable
- 9ExplanationDispatch separate actions
- 10TipEncode conflicts in the parser
- 11ChallengeFollow a subcommand failure to the shell
- 12RecapKeep the CLI boundary narrow
5Trace a log record from a module to its destinations
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow one event through logging
- 2ExampleName the module and describe the event
- 3ExplanationChoose a level from the event’s meaning
- 4ChallengePreserve the failure’s call history
- 5ExplanationSeparate admission from destination filtering
- 6ExampleAdmit detailed module records
- 7ExampleAdd a quiet console and detailed file
- 8ExampleGive destinations a readable format
- 9ChallengeDiagnose a detailed file that stays empty
- 10TipAvoid duplicate routes and hidden reconfiguration
- 11ConnectionConnect CLI verbosity to the log threshold
- 12ChallengeTrace a child with its own threshold
- 13RecapTrace the route before changing a threshold
Python Packages and Virtual Environments practice questions
Set 1: Trace imports and choose the right environment10 Practice Questions
Question 1 of 10
measure.py defines convert. A second module runs import measure as ms. How should it call the function on value?Show answerHide answer
ms, so the function is reached through ms.convert. It does not also bind the original name measure or bring convert directly into the importing namespace. The call must follow the name actually bound by the import.Question 2 of 10
labels.py prints "ready" at top level and calls main() only under its __name__ guard. In a fresh process, another file imports labels twice. What runs from labels.py?Show answerHide answer
Question 3 of 10
trail.analysis.report uses from .helpers import clean. What module supplies clean?Show answerHide answer
trail.analysis. It does not start from the module name trail.analysis.report. Reaching trail.helpers would require moving up one package level with two leading dots.Question 4 of 10
atlas/cli.py uses from .reader import load. From the directory containing atlas, what command runs the CLI with its package context?Show answerHide answer
-m form locates atlas.cli through the import system and preserves its parent package for the relative import. A direct file command executes the file without that parent context. The argument after -m is a dotted module name, with no slash or .py ending.Question 5 of 10
json reports a missing loads attribute. json.__file__ points to the project’s json.py. What should the developer change?Show answerHide answer
Question 6 of 10
.venv. What command activates it for that terminal?Show answerHide answer
python -m venv .venv is not the activation step. The Scripts batch-file form belongs to Windows Command Prompt.Question 7 of 10
sys.executable paths. What is the most direct fix?Show answerHide answer
Question 8 of 10
market.orders first imports market.accounts and only afterward defines Order. During its import, market.accounts runs from market.orders import Order, which fails. Moving that import below other imports in accounts still fails. What dependency change addresses the cause?Show answerHide answer
market.orders object before its Order definition executes. A shared lower-level module removes that initialization cycle. Changing search paths cannot create the missing definition, and importing the same cycle through the initializer still leaves the dependency in place.Question 9 of 10
requests 2.32.3 installed. A developer runs python -m pip install "requests>=2.31,<3". The installed version satisfies the requirement. What does this request normally do?Show answerHide answer
Question 10 of 10
/work/ledger contains run.py and helpers.py; run.py imports helpers. From /work, python ledger/run.py works but python -m run fails. What change makes module execution work without altering paths or source?Show answerHide answer
/work/ledger, where both files live. Module execution instead starts from the current directory, so entering that folder makes run discoverable. Adding .py to a -m argument does not convert it to a source-file command.Set 2: Resolve requirements and rebuild installations10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
sensor-lib~=4.6.0. Does release 4.7.1 satisfy it, and why?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
core>=3,<4 and package B with core>=4,<5. pip reports ResolutionImpossible. How should the dependency selection be repaired?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
colorama==0.4.6, but neither the install request nor its dependencies needs colorama. What effect does that line have on installation?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
viewkit==2.4 and hashes its wheel. viewkit requires parsekit>=1, but parsekit is absent from the file. The team wants a complete hash-checked rebuild. What must change?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
.venv to another directory. An installed command still refers to the old path. How should the environment be repaired?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
httpx whenever its main feature runs, but httpx appears only in build-system.requires. Installation finishes and a clean runtime cannot import httpx. Where should its supported range be declared?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
/home/jo/code/app. A colleague has Python 3.10 and a checkout elsewhere. What setup plan retains the tested runtime versions and supports local editable development?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
core~=4.8.0; the other declares core>=4.8.2,!=4.8.5. Candidate releases are 4.7.9, 4.8.5, 4.8.6, and 4.9.0, all interpreter-compatible. What core release satisfies both plugins?Show answerHide answer
Save this lesson to see this answer.
Set 3: Configure projects and check installed commands10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
[project.scripts], but that command is absent from the environment. What step makes the installer create it?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
fieldnotes normally sit relative to pyproject.toml?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
version = 0.8.0. What correction makes this version value valid TOML?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
scanlog should call main in scanlog.cli. What value belongs on the right side of its [project.scripts] entry?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
python -m pip install --group dev in an uninstalled src project. The group contains pytest and ruff only. What else is needed for normal imports of the local project?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
audit = "audit.cli:main". The callable is def main(path): ..., with no default, and the generated command fails before processing input. What design supports both the installed command and explicit argument-list calls?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
mapkit.cli imports mapkit.calc; mapkit.calc imports DEFAULT_SCALE from mapkit.cli, creating an initialization cycle. Both need the constant. How should responsibilities be changed?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Parse commands and report outcomes10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
parser.add_argument("--dry-run", action="store_true"). What attribute holds its parsed value?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
--size with type=int, default=4, --tag with action="append", and -v with action="count", default=0. It parses --tag east --tag west -vv. What are size, tag, and v?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
type=bool receives the text "False" and becomes True. What declaration suits a flag that should be false when absent and true when present?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
print and returns 1; the entry point calls main() and discards the result. The user redirects standard output. What two changes preserve a clean result stream and a shell-visible failure?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
A required list subparser declares --limit with type=int, default=4 and func=cmd_list. Its handler is:
def cmd_list(args):
return 0 if args.limit > 0 else 1
Main parses input and returns args.func(args); the entry uses raise SystemExit(main()). For list --limit 0, what value reaches the handler and what status reaches the shell?
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
--out abbreviation for --output. A new --outlier option makes the script fail. What parser setting requires stable declared spellings from now on?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
-v with action="count", default=0 and -q with action="store_true". After parsing, -q selects ERROR; otherwise verbosity maps through max(WARNING - 10 * v, DEBUG). What happens for no flags, -vvv, and -v -q, in that order?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
--limit with type=int. Main then calls parser.error if the value is below 1; only afterward does it open the input file, catching FileNotFoundError and returning 1. The entry forwards main’s status. With a nonexistent input file, what statuses result from --limit zero, --limit 0, and --limit 2?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
--range with nargs=2, type=int and --mode with choices "sum" or "last", defaulting to "sum". Main computes sum(args.range) in sum mode, otherwise args.range[-1], prints that result, and returns 0. What result and status follow --range 6 14 --mode last when the entry forwards main’s result?Show answerHide answer
Save this lesson to see this answer.
Set 5: Diagnose logging and complete project setups10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
except OSError block, a developer needs the message and the current traceback at ERROR level. What call provides both?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
disable_existing_loggers. The module then goes silent. What setting preserves those preexisting module loggers?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
worker.io is explicitly DEBUG, and propagation is enabled. Root has a console handler at ERROR and a file handler at INFO; worker.io has no handlers. Where does its WARNING record go?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
calculate_report() with logger.debug("Report %s", calculate_report()) and still observes the calculation. Why, and what prevents that work when DEBUG is off?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
plot extra; the contributor installed only -e . and the dev group containing ruff. How should setup change while retaining editable development?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Absolute import
from csvstats.loaders import read_rows identifies the package explicitly wherever the import appears.Activation
(.venv) prompt.argparse Namespace
args.top as an integer and args.dry_run as a boolean flag value.Argument action
action="append" retains each supplied column name instead of keeping only the final one.B
basicConfig
Build backend
setuptools.build_meta tells pip which backend object handles the project’s build requests.Build front end
python -m build asks the backend to produce source and wheel distributions in the project’s output directory.Bytecode cache
__pycache__ directory can be removed and rebuilt, so it belongs in Git ignore patterns.C
Circular import
orders and customers can remove their initialization cycle.Console script
scan = "scan.cli:main" creates the command when the project is installed into its environment.Constraints file
D
Dependency group
pyproject.toml that is excluded from the project’s built dependency metadata.Dependency resolver
dictConfig
disable_existing_loggers to false keeps already-created module loggers active during setup.Direct dependency
Dispatch
args.func(args) lets the selected subcommand pass its outcome through the main function.Distribution name
Pillow provides the PIL import package; installing an assumed import name can target the wrong project.Dynamic metadata
[project].dynamic = ["version"] is declared.E
Editable install
Effective level
Entry-point target
csvstats.cli:main names a callable, while src/csvstats/cli.py names a file path.Environment marker
sys_platform == "win32" can restrict a requirement to Windows installations.Exit status
main() through SystemExit lets an automated job detect a missing-file failure.Externally managed environment
Extra
"csvstats[plot]" requests the plotting dependencies in addition to the base project.F
Flag
--dry-run store-true flag sets args.dry_run to true without requiring the word "True".Flat layout
Formatter
G
Generated artifact
dist/ and .venv/ while preserving its source and dependency lock in Git.H
Handler
Hash checking
I
Import alias
as for an imported module or object, without renaming the original module itself.import statistics as st, the calling code uses st.mean(data) to calculate an average.Interpreter
sys.executable in the editor and terminal can explain why only one can import a library.L
Lazy import
Lock file
Log level
Log rotation
Logger
csvstats.loaders identifies file-loading events separately from calculation events.M
Module
.py.stats.py supplies reusable calculations through calls such as stats.mean(values).Module cache
sys.modules, maps import names to module objects so ordinary repeated imports can reuse modules already being loaded or loaded.Module search path
sys.path used by path-based import discovery to find packages and modules.Mutually exclusive group
N
Namespace
mean in a command-line script does not overwrite the function available as stats.mean.Namespace package
nargs
nargs="+" accepts multiple filenames but rejects an invocation that provides none for that argument.O
Option
--, normally using a default value when it is omitted.--top 3 can change a row limit while leaving the input path as a positional value.Option abbreviation
--for prefix becomes ambiguous if both --format and --force are later declared.P
Package entry point
__main__.py supplies the code executed by python -m package, often delegating to an ordinary main function.python -m csvstats can reach the same CLI function as the installed csvstats command.PATH
Pinning
requests==2.32.3 prevents a fresh install from silently selecting a newer requests release.pip
python -m pip show requests checks the installed metadata using the same Python named in the command.Positional argument
scan records.csv, the filename can supply the parser’s required path positional argument.Project metadata
Project root
pyproject.toml; its inner source package supplies Python’s import name.Propagation
PyPI
R
Regular install
Regular package
__init__.py, whose code initializes the package when it is first imported.csvstats/analysis runs before the first import of csvstats.analysis.summary finishes.Relative import
from statement to locate another module from the current module’s known package context.csvstats.analysis.summary, from .helpers import clean selects a sibling module.Requirements file
python -m pip install -r requirements.txt reads the committed package selection into a fresh environment.Root logger
S
Shadowing
json.py can hide the standard-library JSON module and cause missing attributes.site-packages
Source distribution
src layout
src directory, so normal root-directory imports require installation.src/csvstats available without placing the project root’s other files on the import path.Standard error
Standard output
Subcommand
Submodule
csvstats.analysis.summary before using its describe function through that path.T
TOML
version = "0.1.0" stores a version string; leaving that dotted value unquoted is invalid.Traceback
logger.exception attaches that call history instead of logging only the error text.Transitive dependency
V
Version specifier
>=2.31,<3 accepts a suitable 2.x release while excluding version 3 and later.Virtual environment
W
Wheel
#
__name__ guard
if __name__ == "__main__": stays silent when another file imports the module.- 1Python Classes
- 2Python Comprehensions and Generators
- 3Python Functions and Decorators
- 4Python Regular Expressions
- 5Python JSON and CSV Files
- 6Testing with pytest
- 7Python Packages and Virtual Environments
- 8Python Type Hints
- 9Python Concurrency
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.