Python Packages and Virtual Environments

Python Packages, Virtual Environments and Project Structure

Learn how professional Python projects are organized and run. Split code into modules and packages and understand how Python finds what you import. Give every project its own virtual environment, install packages with pip and pin their versions so that anyone can rebuild the same setup. Describe a project in pyproject.toml, install it for development and give it a terminal command. Finish by building a command-line interface with argparse and recording what the program does with the logging module.

IntermediateLesson 7 of 9 in Intermediate Python Course

What you will learn

  1. 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 import
      Write modules, choose an import form, keep top-level code safe to import with the __name__ check, and use dir(), __all__ and __pycache__ with understanding.
    • Build packages and use absolute and relative imports
      Group 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 errors
      Trace how Python searches sys.modules and sys.path, and diagnose the usual import failures: the wrong interpreter, a different import name, a shadowing file and a circular import.
  2. 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 environment
      Explain 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 pip
      Use 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 reproduced
      Record exact versions with pip freeze and requirements files, separate direct dependencies from a pinned lock list, and upgrade pins deliberately with constraints, hashes and lock tools.
  3. Lay out a project the way professional teams do, describe it in a pyproject.toml file, and install it for development with a command of its own.
    • Lay out a project folder
      Arrange 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 file
      Read 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 command
      Install 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.
  4. 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 options
      Read 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 program
      Organize a command-line program around a testable main function, return exit codes, separate results from messages, and add subcommands and mutually exclusive options.
  5. Replace diagnostic print calls with the logging module: 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 levels
      Create 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 application
      Configure 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.

Python Packages and Virtual Environments study guide

5 chapters

1

Organize 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
ImportName available afterwardExample call
import statsstatsstats.mean(values)
import statistics as ststst.mean(values)
from stats import meanmeanmean(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 statementCall to a function in summary
import csvstats.analysis.summarycsvstats.analysis.summary.describe(data)
from csvstats.analysis import summarysummary.describe(data)
from csvstats.analysis.summary import describedescribe(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 -m with a dotted module name to preserve package context.
  • A package uses __main__.py for python -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.executable and installation details in the same environment that runs the program.
  • A script command and a -m command 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.
2

Keep 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
ShellActivation command
bash or zshsource .venv/bin/activate
fishsource .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.executable and 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 pipPurpose
install requestsInstall if missing; keep an installed version that satisfies the request
install --upgrade requestsSeek a newer suitable release
show requestsShow version, location, and dependency metadata
list --outdatedShow installed distributions with newer releases available
checkReport missing or incompatible installed dependencies
uninstall requestsRemove 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.3 selects exactly one version.
  • !=2.32.0 excludes that version.
  • ==2.32.* selects the 2.32 series.
  • ~=2.31 combines a lower bound of 2.31 with the 2 series.
  • ~=2.31.0 combines 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 pip to 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.0 is 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
RecordWhat it expresses
Direct dependencies with rangesPackages the project itself needs and the releases it supports
Pinned requirements or lock fileA 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.
3

Describe, 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
LayoutPackage locationDevelopment consequence
srcsrc/csvstatsInstall the project so its package is importable normally
flatcsvstats beside configurationRunning 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
LocationAudience and purpose
project.dependenciesRuntime requirements for every installation
project.optional-dependenciesPublic extras users can request
dependency-groupsDevelopment dependency lists, absent from built project metadata
build-system.requiresTools 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; tomllib is 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 main function between the installed command and package execution.
  • Build locally, inspect the wheel, and check a clean install outside the source tree.
4

Make 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
SettingBehavior
action="store_true"Store True when present; otherwise False
action="count", default=0Count 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=2Require 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 Namespace attributes.
  • Positional arguments and options have different default requirements.
  • Use flag actions for booleans, and set a zero default when counting repetitions.
  • Match nargs to 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 SystemExit or 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.
5

Write 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.

LevelNumberTypical event
DEBUG10Detailed state used while investigating a bug
INFO20Normal progress, such as a completed load
WARNING30An unexpected condition the program can handle
ERROR40An operation failed
CRITICAL50A 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.exception inside 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=False when dictionary setup should preserve existing module loggers.

Python Packages and Virtual Environments examples

5 Walkthroughs

1

Turn a script into an importable package

15 steps
Separate reusable calculations from start-up actions, run a package correctly, and trace an import failure.
  1. 1
    IntroductionSeparate 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.

  2. 2
    ExplanationChoose the name the caller will use

    A file named stats.py has its own namespace. import stats binds that module, so callers write stats.mean(values). from stats import mean instead binds the function name directly.

    An alias gives the imported object a chosen local name: import statistics as st supports st.mean(values). A star import can replace names already present and makes their origin harder to read.

  3. 3
    ExamplePut 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__".

  4. 4
    Key InsightThe guard does not stop the whole import

    Python stores the module object in sys.modules before 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.

  5. 5
    ChallengePredict what an importer sees

    units.py prints "loaded" at top level. It also calls main() under its __name__ guard. In a fresh process, a caller imports units twice. 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.

  6. 6
    ExplanationFollow the package tree

    Place summary.py and helpers.py inside csvstats/analysis, with __init__.py in both package directories. The summary module’s name is csvstats.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.

  7. 7
    ExampleResolve 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_rows
    

    One dot starts at csvstats.analysis; two reach csvstats. The first import selects csvstats.analysis.helpers, and the second selects csvstats.loaders.readers. A bare import helpers would ask for a top-level name instead of the sibling file.

  8. 8
    TipUse a module name when starting package code

    From the directory containing csvstats, use python -m csvstats.analysis.summary. The dotted name gives relative imports the package context they need.

    A direct command such as python csvstats/analysis/summary.py runs the file without that parent context. To support python -m csvstats, put a small delegating entry point in the package’s __main__.py and leave the real work in an ordinary module.

  9. 9
    ChallengeFind the right parent

    Inside library.reports.weekly, what module supplies load in from ..storage import load? How would you execute weekly from the directory containing library?

    ---reveal---

    The import selects library.storage: the second dot moves up from library.reports. Run python -m library.reports.weekly. That command preserves package context; a direct source path would not supply the same context for the relative import.

  10. 10
    ExplanationCheck the running interpreter first

    A successful install in one terminal cannot supply packages to every Python process on the computer. Check sys.executable in the process that fails, then run python -m pip show NAME with 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.

  11. 11
    ExampleLet the loaded path reveal shadowing

    Suppose import json succeeds but json.loads is missing. Printing json.__file__ shows a project file called json.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.

  12. 12
    ChallengeDistinguish discovery from initialization

    billing.orders imports billing.users, which requests Order from billing.orders before that class is defined. Would adding the project root to sys.path repair 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.

  13. 13
    ConnectionStarting location changes the search

    For a file command, normal sys.path begins 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.append repairs whose meaning changes with the terminal’s starting folder.

  14. 14
    ChallengeRepair 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 -m and 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.

  15. 15
    RecapTrace 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.

2

Rebuild a project environment from recorded dependencies

15 steps
Choose an interpreter, isolate installs, read version limits, and record a dependency selection that can be rebuilt.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the setup another person can repeat
  2. 2
    ExampleCreate the environment with the intended Python
  3. 3
    ExplanationActivate or name the interpreter directly
  4. 4
    ChallengeVerify the editor’s Python
  5. 5
    TipTreat the environment as replaceable
  6. 6
    ExampleAsk for a suitable install, then inspect it
  7. 7
    ExplanationRead all limits together
  8. 8
    ChallengeChoose a release inside the series
  9. 9
    ExplanationSeparate supported ranges from tested pins
  10. 10
    ExampleFreeze a clean selection and rebuild
  11. 11
    Key InsightConstraints do not request packages
  12. 12
    ChallengeFind the missing hash requirement
  13. 13
    ConnectionA package list is not the whole runtime
  14. 14
    ChallengeRemove an experiment without breaking the project
  15. 15
    RecapKeep three setup decisions explicit
3

Install a src project and create its command

13 steps
Read project tables, install editable source, and verify a built wheel in a clean environment.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionConnect source code to an installed tool
  2. 2
    ExampleFind the import package
  3. 3
    Key InsightEditable success leaves one question open
  4. 4
    ChallengeChoose what another contributor needs
  5. 5
    ExampleSeparate build tools from runtime libraries
  6. 6
    ExplanationGive optional users and developers separate lists
  7. 7
    ChallengePlace each requirement where it belongs
  8. 8
    ExampleInstall for edits and refresh metadata
  9. 9
    ExampleDeclare a callable behind the command
  10. 10
    ChallengeRepair a command missing after an edit
  11. 11
    ExampleBuild the files another environment receives
  12. 12
    ChallengeConnect development setup to the missing command
  13. 13
    RecapRefresh the right layer
4

Build a CLI that parses, reports, and exits clearly

12 steps
Trace parsed values, structure main, and preserve usable result output and meaningful status codes.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive terminal strings a clear meaning
  2. 2
    ExampleDeclare the accepted input
  3. 3
    ExampleTrace values after parsing
  4. 4
    Key InsightUse actions for booleans and repetitions
  5. 5
    ChallengePredict a command without a flag
  6. 6
    ExampleForward the work result through main
  7. 7
    ExplanationSeparate invalid usage from operational failure
  8. 8
    ChallengeKeep redirected results usable
  9. 9
    ExplanationDispatch separate actions
  10. 10
    TipEncode conflicts in the parser
  11. 11
    ChallengeFollow a subcommand failure to the shell
  12. 12
    RecapKeep the CLI boundary narrow
5

Trace a log record from a module to its destinations

13 steps
Choose useful levels, follow logger admission and handler filtering, and configure logging once for the application.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow one event through logging
  2. 2
    ExampleName the module and describe the event
  3. 3
    ExplanationChoose a level from the event’s meaning
  4. 4
    ChallengePreserve the failure’s call history
  5. 5
    ExplanationSeparate admission from destination filtering
  6. 6
    ExampleAdmit detailed module records
  7. 7
    ExampleAdd a quiet console and detailed file
  8. 8
    ExampleGive destinations a readable format
  9. 9
    ChallengeDiagnose a detailed file that stays empty
  10. 10
    TipAvoid duplicate routes and hidden reconfiguration
  11. 11
    ConnectionConnect CLI verbosity to the log threshold
  12. 12
    ChallengeTrace a child with its own threshold
  13. 13
    RecapTrace the route before changing a threshold

Python Packages and Virtual Environments practice questions

50 Practice Questions in 5 sets

Set 1: Trace imports and choose the right environment10 Practice Questions

Question 1 of 10

A file named measure.py defines convert. A second module runs import measure as ms. How should it call the function on value?
  1. measure.convert(value)
  2. convert(value)
  3. ms.convert(value)
  4. ms.measure.convert(value)
Show answerHide answer
Answer: C
The alias binds the module to 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?
  1. The print runs once; the guarded call does not run.
  2. The print runs twice; the guarded call does not run.
  3. The print runs once; the guarded call runs once.
  4. The print stays silent; the guarded call does not run.
Show answerHide answer
Answer: A
The first import executes the top-level print and stores the loaded module for reuse. The second import normally retrieves that cached object, so it does not print again. The guard skips only its own body during import; it does not suppress the whole file.

Question 3 of 10

A module inside trail.analysis.report uses from .helpers import clean. What module supplies clean?
  1. trail.helpers
  2. helpers
  3. trail.analysis.report.helpers
  4. trail.analysis.helpers
Show answerHide answer
Answer: D
A single leading dot starts from the importing module’s package, which is 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?
  1. python atlas/cli.py
  2. python -m atlas.cli
  3. python -m atlas/cli.py
  4. python -m cli
Show answerHide answer
Answer: B
The -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

A program importing json reports a missing loads attribute. json.__file__ points to the project’s json.py. What should the developer change?
  1. Install json into the active virtual environment.
  2. Rename the project file and restart the program.
  3. Add the project directory to the end of sys.path.
  4. Repeat import json after the first import fails.
Show answerHide answer
Answer: B
The loaded path shows that the project file shadows the standard-library module. Renaming that file removes the competing name, and restarting clears the cached module. Installing another package does not fix which local source file the import system selects first.

Question 6 of 10

A bash terminal is in a project whose virtual environment already exists at .venv. What command activates it for that terminal?
  1. python -m venv .venv
  2. .venv\Scripts\activate.bat
  3. python -m pip install .venv
  4. source .venv/bin/activate
Show answerHide answer
Answer: D
The bash activation script changes that shell’s command search path to prefer the environment. Creating a venv is a separate operation, so running python -m venv .venv is not the activation step. The Scripts batch-file form belongs to Windows Command Prompt.

Question 7 of 10

An editor cannot import a library that works in an activated terminal. The two processes report different sys.executable paths. What is the most direct fix?
  1. Select the terminal’s environment interpreter in the editor.
  2. Activate the environment once more in the same terminal.
  3. Copy the library into the project’s source package.
  4. Recreate the editor’s imports by adding PYTHONPATH.
Show answerHide answer
Answer: A
The paths establish that the editor and terminal run different interpreters. Selecting the environment’s interpreter lets the editor use the packages already installed there. Repeating terminal activation changes that terminal again, but it does not select an interpreter for the editor process.

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?
  1. Add market’s folder to sys.path before importing either module.
  2. Reload market.orders from accounts before requesting Order.
  3. Move Order to a shared module that neither importer calls back into.
  4. Import accounts in market’s initializer before importing orders.
Show answerHide answer
Answer: C
The return import reaches the cached 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

An environment has 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?
  1. Keep the installed satisfying version.
  2. Upgrade to the newest version below 3.
  3. Downgrade to the lower bound 2.31.
  4. Install a second requests release beside it.
Show answerHide answer
Answer: A
A plain install request is already satisfied by 2.32.3, so pip normally leaves it in place. The range describes permitted releases; it is not an instruction to select its lower bound or seek a newer version. Seeking an upgrade requires an explicit upgrade request.

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?
  1. Stay in /work and run python -m run.py.
  2. Enter /work/ledger and run python -m ledger.run.
  3. Stay in /work and add helpers to sys.modules.
  4. Enter /work/ledger and run python -m run.
Show answerHide answer
Answer: D
The successful file command starts its path search in /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

A requirement is sensor-lib~=4.6.0. Does release 4.7.1 satisfy it, and why?
  1. Yes; every release below 5 is allowed.
  2. Yes; 4.7.1 is later than the lower bound.
  3. No; only release 4.6.0 is allowed.
  4. No; the allowed release series is 4.6.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A program needs package A with core>=3,<4 and package B with core>=4,<5. pip reports ResolutionImpossible. How should the dependency selection be repaired?
  1. Pin core to 4 and keep both parent requirements.
  2. Choose A and B releases whose core ranges overlap.
  3. Install both core releases into the same environment.
  4. Skip dependency installation for B and keep core 3.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A constraints file lists colorama==0.4.6, but neither the install request nor its dependencies needs colorama. What effect does that line have on installation?
  1. It does not cause colorama to be installed.
  2. It installs colorama at exactly version 0.4.6.
  3. It installs colorama only as a development tool.
  4. It removes any colorama already in the environment.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A team freezes an environment after experimenting with three unrelated libraries. The resulting file rebuilds successfully but is larger than the project needs. What should the team do before recording a new baseline?
  1. Delete every transitive dependency from the existing frozen file.
  2. Copy the frozen file directly into public library dependencies.
  3. Rebuild from project needs in a clean environment, then record versions.
  4. Keep only packages whose names match imports in the entry script.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A hash-checked requirements file pins 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?
  1. Add a hash to parsekit>=1 while leaving its version unrestricted.
  2. Add --no-deps so only the hashed viewkit wheel is installed.
  3. Resolve parsekit, then add its exact pin and allowed artifact hashes.
  4. Put parsekit>=1 in constraints and keep the requirements unchanged.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A contributor moves a project and its .venv to another directory. An installed command still refers to the old path. How should the environment be repaired?
  1. Edit only VIRTUAL_ENV to contain the new directory name.
  2. Recreate the venv at the new location and reinstall its requirements.
  3. Activate the moved venv so all embedded script paths are rewritten.
  4. Copy the project source into the environment’s site-packages.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A fresh Python release has no compatible wheel for an extension package. pip downloads its source archive and fails while looking for a compiler. Why did an install need a compiler?
  1. The available artifact needed a local source build.
  2. Every wheel must be compiled locally before installation.
  3. The virtual environment had selected the wrong import name.
  4. The resolver always compiles transitive dependencies first.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A library imports 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?
  1. In tool.setuptools as a package-discovery setting.
  2. In dependency-groups under a development-only group.
  3. In project.scripts as a second console command.
  4. In project.dependencies as a runtime requirement.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An application supports Python 3.11 or later. Its frozen file contains exact runtime pins and an editable reference to /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?
  1. Choose supported Python, retain the old editable path in the pins, then activate the newly created environment.
  2. Choose supported Python, install the pins without the old local reference, then install the local checkout editable.
  3. Keep Python 3.10, remove the old local reference from the pins, then install the local checkout editable.
  4. Choose supported Python, drop all transitive pins, then install the local checkout editable with the newest dependencies.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Two plugins require the same core library. One declares 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?
  1. 4.7.9
  2. 4.8.5
  3. 4.8.6
  4. 4.9.0
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

A project offers optional PDF export to users and uses ruff only during development. Where should those dependency lists go?
  1. PDF in dependency-groups; ruff in optional-dependencies.
  2. Both in build-system.requires as packaging requirements.
  3. Both in project.scripts as separately installed commands.
  4. PDF in optional-dependencies; ruff in dependency-groups.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An editable project gains a new console command in [project.scripts], but that command is absent from the environment. What step makes the installer create it?
  1. Restart Python without reinstalling the project.
  2. Compile the modified source with compileall.
  3. Run python -m pip install -e . again.
  4. Run python -m pip install --group dev.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A project uses a src layout. Where does the import package fieldnotes normally sit relative to pyproject.toml?
  1. In .venv/fieldnotes below the project root.
  2. In src/fieldnotes below the project root.
  3. In tests/fieldnotes below the project root.
  4. In dist/fieldnotes below the project root.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A TOML file contains version = 0.8.0. What correction makes this version value valid TOML?
  1. version = "0.8.0"
  2. version = [0.8.0]
  3. version: "0.8.0"
  4. version = (0, 8, 0)
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

The command scanlog should call main in scanlog.cli. What value belongs on the right side of its [project.scripts] entry?
  1. "src/scanlog/cli.py"
  2. "scanlog.cli.main()"
  3. "scanlog:cli.py"
  4. "scanlog.cli:main"
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An editable src install loads a helper module correctly, but the built wheel omits that helper. How can a release check expose the omission without the source tree masking it?
  1. Install the wheel in a fresh venv and run from outside the checkout.
  2. Run the same check from the checkout after reinstalling editable mode.
  3. Add src to PYTHONPATH before running checks against the wheel.
  4. Freeze the editable environment and run its installed command again.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

With pip 25.1 or later, a contributor runs 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?
  1. Install the local project, for example with pip install -e .
  2. Move the import package from src into the dev group definition.
  3. Rename the dev group to the project’s distribution name.
  4. Add the project’s version string to build-system.requires.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A console entry is 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?
  1. Keep main(path) and expect pip to pass the first shell argument.
  2. Use main(argv=None), then parse argv inside the function.
  3. Change the target to audit.cli:main(path) in the metadata.
  4. Make the wrapper call cli.py by its source-tree file path.
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?
  1. Move the constant into cli’s main function and keep both imports.
  2. Add the source directory to sys.path before importing cli.
  3. Put the constant in a lower-level module imported by both.
  4. Import calc with a star import so its constants load earlier.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A project supports Python 3.10 and reads TOML using tomli there, but uses tomllib on newer Python. What runtime requirement avoids installing tomli when the standard-library reader is available?
  1. "tomli>=2; python_version >= '3.11'"
  2. "tomllib>=2; python_version < '3.11'"
  3. "tomli>=2; sys_platform == 'linux'"
  4. "tomli>=2; python_version < '3.11'"
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

An argparse option is declared as parser.add_argument("--dry-run", action="store_true"). What attribute holds its parsed value?
  1. args.dry-run
  2. args.dryrun
  3. args.dry_run
  4. args.--dry-run
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A parser declares --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?
  1. "4", "west", 2
  2. 4, ["east", "west"], 2
  3. 4, ["east", "west"], 1
  4. 4, ["west"], None
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

An option declared with type=bool receives the text "False" and becomes True. What declaration suits a flag that should be false when absent and true when present?
  1. action="store_true"
  2. type=str, default=False
  3. type=bool, default=False
  4. action="count", default=0
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A CLI writes JSON results and must report a missing file while a user redirects standard output. What result preserves both usable output and a failure signal?
  1. Send the diagnostic to standard output and exit with 1.
  2. Send the diagnostic to standard error and exit with 0.
  3. Print an empty JSON object and exit with 0.
  4. Send the diagnostic to standard error and exit with 1.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A CLI sends JSON to standard output. On a missing file, main prints an error with plain 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?
  1. Send the error to standard error; keep the entry as a bare main() call.
  2. Keep the error on standard output; exit through SystemExit(main()).
  3. Send the error to standard error; make main return 0 after handling it.
  4. Send the error to standard error; exit through SystemExit(main()).
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?

  1. Integer 4 reaches cmd_list; the shell receives status 0.
  2. Integer 0 reaches cmd_list; the shell receives status 1.
  3. Integer 0 reaches cmd_list; the shell receives status 0.
  4. No handler runs; the parser exits with usage status 2.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A script uses an unambiguous --out abbreviation for --output. A new --outlier option makes the script fail. What parser setting requires stable declared spellings from now on?
  1. allow_abbrev=False
  2. add_help=False
  3. exit_on_error=False
  4. prefix_chars="-"
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An argparse parser has a required mutually exclusive group containing -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?
  1. WARNING; DEBUG; ERROR.
  2. Usage error; INFO; usage error.
  3. Usage error; DEBUG; usage error.
  4. WARNING; DEBUG; usage error.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A parser defines --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?
  1. 2, 2, and 1.
  2. 2, 1, and 1.
  3. 1, 2, and 2.
  4. 2, 2, and 0.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A parser declares --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?
  1. The output is 20; the exit status is 0.
  2. The output is 14; the exit status is 0.
  3. The output is 14; the exit status is 14.
  4. The output is "6 14"; the exit status is 0.
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

A logger’s effective level is INFO. What happens to an ordinary DEBUG call through that logger?
  1. It is rejected before handlers receive a record.
  2. It reaches handlers but always uses the INFO label.
  3. It appears on standard error through the last-resort handler.
  4. It reaches every handler whose own level is DEBUG.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Inside an except OSError block, a developer needs the message and the current traceback at ERROR level. What call provides both?
  1. logger.error(str(err))
  2. logger.warning("Could not open %s", path)
  3. logger.info("Could not open %s", path)
  4. logger.exception("Could not open %s", path)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A child logger and root each have a console handler. The child propagates records, and every warning appears twice. What change preserves one central console configuration?
  1. Lower both handler thresholds so all severities are admitted.
  2. Remove the child’s console handler and keep propagation to root.
  3. Call basicConfig again before each warning is logged.
  4. Raise the root level while keeping both warning handlers.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A module creates its logger before application start-up. A dictConfig setup names only root and omits disable_existing_loggers. The module then goes silent. What setting preserves those preexisting module loggers?
  1. "disable_existing_loggers": True
  2. "version": 2
  3. "disable_existing_loggers": False
  4. "propagate": False on the root logger
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Root is WARNING. A module logger is NOTSET and propagates to a root file handler at DEBUG. INFO messages are missing. The team wants this module to produce DEBUG for the file while retaining root’s inherited WARNING policy for other modules. What change fits?
  1. Set this module logger explicitly to DEBUG.
  2. Set the file handler explicitly to NOTSET.
  3. Set this module logger explicitly to ERROR.
  4. Call basicConfig(level=DEBUG) with existing root handlers.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Root is WARNING, 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?
  1. To both handlers.
  2. To neither handler.
  3. To the file only.
  4. To the console only.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A DEBUG message is filtered out. A developer replaces an f-string containing calculate_report() with logger.debug("Report %s", calculate_report()) and still observes the calculation. Why, and what prevents that work when DEBUG is off?
  1. Logging retries formatting; add a second DEBUG handler to stop retries.
  2. Percent templates force eager formatting; return to the f-string form.
  3. The root level is ignored everywhere; disable propagation on the logger.
  4. Arguments still run; guard the calculation with isEnabledFor(DEBUG).
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A new contributor can run an installed CLI, but its first optional chart operation fails because matplotlib is missing. The project declares a plot extra; the contributor installed only -e . and the dev group containing ruff. How should setup change while retaining editable development?
  1. Add matplotlib to build-system.requires and keep the same install command.
  2. Install the editable project with its plot extra, then record the tested selection.
  3. Rename the dev group to plot without adding its runtime dependencies.
  4. Copy matplotlib from another environment into the source package.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A wheel installs in a fresh venv and its command works there. A scheduled job starts the command by bare name without activating that venv and cannot find it. What deployment change selects the verified installation independently of shell activation?
  1. Rebuild the same wheel while the job is scheduled.
  2. Use the installed command’s full path inside that venv.
  3. Add a new script entry with the same command name.
  4. Move the wheel archive into the job’s working directory.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A reusable library calls basicConfig during import. Later, its host application calls basicConfig with a file destination, but logs still go to the console. What durable ownership change fixes this interaction?
  1. Let the application configure logging and let the library only create loggers.
  2. Have the library call basicConfig again before every message.
  3. Have the library clear root handlers whenever it is imported.
  4. Make the library set root to DEBUG and leave its handler installed.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

76 Key Terms, each with its definition

A

Absolute import
An absolute import identifies a module or object using a path that begins with a top-level package name instead of leading dots.
from csvstats.loaders import read_rows identifies the package explicitly wherever the import appears.
Activation
Activation changes a shell session so its command lookup prefers a virtual environment’s tools, without changing the environment’s Python version.
A new terminal may need activation even when another window already shows the (.venv) prompt.
argparse Namespace
An argparse Namespace is an object whose attributes store the parsed argument values, including conversions and defaults declared by the parser.
After parsing, code reads args.top as an integer and args.dry_run as a boolean flag value.
Argument action
An argument action specifies how argparse stores or handles an input, such as collecting repeated values or counting repeated flags.
Using action="append" retains each supplied column name instead of keeping only the final one.

B

basicConfig
basicConfig is a convenience function for configuring root logging, normally leaving existing root handlers unchanged unless forced to replace them.
An earlier root-level logging call can explain why a later basicConfig request has no visible effect.
Build backend
A build backend is the tool implementation that constructs a project’s distribution artifacts when called by a front end such as pip.
The value setuptools.build_meta tells pip which backend object handles the project’s build requests.
Build front end
A build front end coordinates a build by reading project configuration and invoking the declared backend through its build interface.
python -m build asks the backend to produce source and wheel distributions in the project’s output directory.
Bytecode cache
A bytecode cache stores a compiled form of imported source so Python can avoid recompiling unchanged code during a later program start.
The generated __pycache__ directory can be removed and rebuilt, so it belongs in Git ignore patterns.

C

Circular import
A circular import occurs when module dependencies loop back to a module still initializing, possibly requesting names it has not defined yet.
Moving shared definitions out of orders and customers can remove their initialization cycle.
Console script
A console script is an installed terminal command whose wrapper imports a declared callable, calls it, and forwards its result as an exit status.
The entry scan = "scan.cli:main" creates the command when the project is installed into its environment.
Constraints file
A constraints file limits versions of named packages requested elsewhere without requesting those packages for installation by itself.
A team can constrain a shared dependency while different applications request only the packages they need.

D

Dependency group
A dependency group is a named development dependency list in pyproject.toml that is excluded from the project’s built dependency metadata.
The dev group can include a test group and ruff without making them requirements for ordinary users.
Dependency resolver
A dependency resolver searches for a set of package versions that jointly satisfies the direct and transitive requirements of an install.
If two parents require nonoverlapping versions of the same dependency, pip reports that resolution is impossible.
dictConfig
dictConfig configures logging from a dictionary describing loggers, handlers, formatters, and settings for existing logger behavior.
Setting disable_existing_loggers to false keeps already-created module loggers active during setup.
Direct dependency
A direct dependency is a package the project itself requires, declared explicitly instead of being present only through another package.
If the project’s code imports rich for ordinary output, rich belongs in its runtime dependency list.
Dispatch
Dispatch selects and calls the function responsible for the parsed command, often using a handler stored by a subparser’s defaults.
Returning args.func(args) lets the selected subcommand pass its outcome through the main function.
Distribution name
A distribution name identifies an installable project to packaging tools and can differ from the name Python code uses to import it.
Installing Pillow provides the PIL import package; installing an assumed import name can target the wrong project.
Dynamic metadata
Dynamic metadata is a project field declared for the build backend to supply instead of providing its static value directly in [project].
A backend can obtain a version from one configured source when dynamic = ["version"] is declared.

E

Editable install
An editable install makes a project available through its development source tree so edits to existing source files affect the next run.
Changing a function needs no reinstall, but adding a script entry requires refreshing the installed metadata.
Effective level
A logger’s effective level is its own set threshold or, when its level is NOTSET, the nearest ancestor’s set threshold.
A module logger at NOTSET inherits root’s WARNING threshold until a closer level is explicitly configured.
Entry-point target
An entry-point target identifies an importable module and callable, using a colon to separate them in a console-script declaration.
The target csvstats.cli:main names a callable, while src/csvstats/cli.py names a file path.
Environment marker
An environment marker attaches a condition to a requirement so it applies only to matching Python versions, platforms, or other supported settings.
The marker sys_platform == "win32" can restrict a requirement to Windows installations.
Exit status
An exit status is a process result reported to the shell, with zero conventionally signaling success and nonzero values signaling failure.
Forwarding main() through SystemExit lets an automated job detect a missing-file failure.
Externally managed environment
An externally managed environment is a Python installation marked as controlled by a system package manager, restricting ordinary pip changes.
When pip reports external management, create a venv for project work instead of overriding the protection.
Extra
An extra is a named, user-selectable set of additional dependencies declared in a distribution’s public optional-dependency metadata.
Installing "csvstats[plot]" requests the plotting dependencies in addition to the base project.

F

Flag
A flag is an option whose presence changes a setting without taking an ordinary value, such as an on/off or counted-verbosity option.
A --dry-run store-true flag sets args.dry_run to true without requiring the word "True".
Flat layout
A flat layout places importable packages beside project configuration, allowing root-directory execution to discover local source directly.
A flat-layout check can pass locally even when a needed module is missing from the built distribution.
Formatter
A formatter converts a log record into display text using a chosen layout, often including time, severity, logger name, and message.
One formatter can give the console and file the same line structure while their thresholds differ.

G

Generated artifact
A generated artifact is an output that can be recreated from project inputs, such as bytecode, an environment directory, or a built wheel.
The project ignores dist/ and .venv/ while preserving its source and dependency lock in Git.

H

Handler
A handler routes log records to a destination such as a stream or file and can filter records using its own severity threshold.
A WARNING console handler can stay quiet while a DEBUG file handler preserves detailed records.
Hash checking
Hash checking verifies downloaded artifacts against recorded digests, with pip’s strict mode requiring complete pinned and hashed dependencies.
An artifact whose bytes differ from every permitted hash is rejected even when its version name matches the pin.

I

Import alias
An import alias is the local name chosen with as for an imported module or object, without renaming the original module itself.
After import statistics as st, the calling code uses st.mean(data) to calculate an average.
Interpreter
An interpreter is the Python executable running a process, whose version and environment help determine available modules and packages.
Comparing sys.executable in the editor and terminal can explain why only one can import a library.

L

Lazy import
A lazy import defers loading a module until an imported name is first used, with explicit module-level syntax available in Python 3.15.
A CLI can defer a large optional import so commands that never use it avoid its loading cost.
Lock file
A lock file records a resolved dependency selection for repeatable installation, often including exact versions and artifact information.
A deliberate dependency update regenerates the lock and checks the new selection in a clean environment.
Log level
A log level is a severity value that classifies an event and can also set a threshold admitting that level and higher severities.
An INFO threshold admits normal progress and errors while excluding DEBUG details used for investigation.
Log rotation
Log rotation limits continued growth of a log file by switching files at a configured threshold and retaining a bounded number of older files.
A rotating handler can use a 1 MB threshold and keep three backups instead of growing one file indefinitely.
Logger
A logger is a named object through which code reports events, checking its effective severity threshold before forwarding created records.
A logger named csvstats.loaders identifies file-loading events separately from calculation events.

M

Module
A module is an importable unit of Python code with its own namespace, commonly stored in a single source file ending in .py.
The file stats.py supplies reusable calculations through calls such as stats.mean(values).
Module cache
The module cache, sys.modules, maps import names to module objects so ordinary repeated imports can reuse modules already being loaded or loaded.
A circular import can find an object in the cache before that module has defined its requested class.
Module search path
The module search path is the ordered list in sys.path used by path-based import discovery to find packages and modules.
Starting with a script path puts that script’s directory at the front of the normal search path.
Mutually exclusive group
A mutually exclusive group permits at most one of its options, or exactly one when the group is required, and rejects conflicting members.
A verbose-or-quiet group can allow the default mode while preventing both flags in the same invocation.

N

Namespace
A namespace maps names to objects within a scope, allowing different modules to use the same local name without replacing one another’s objects.
A variable named mean in a command-line script does not overwrite the function available as stats.mean.
Namespace package
A namespace package can combine portions from multiple directories on the search path without a single regular package initializer.
Separate distributions can contribute modules under one shared top-level namespace package name.
nargs
The nargs setting defines how many values argparse consumes for one argument, with fixed counts and special forms for variable-length input.
Using nargs="+" accepts multiple filenames but rejects an invocation that provides none for that argument.

O

Option
An option is a named command-line input beginning with a prefix such as --, normally using a default value when it is omitted.
The option --top 3 can change a row limit while leaving the input path as a positional value.
Option abbreviation
An option abbreviation is a shortened long-option prefix accepted when it uniquely identifies an option and abbreviation is enabled.
An existing --for prefix becomes ambiguous if both --format and --force are later declared.

P

Package entry point
A package entry point in __main__.py supplies the code executed by python -m package, often delegating to an ordinary main function.
Running python -m csvstats can reach the same CLI function as the installed csvstats command.
PATH
PATH is the operating system’s ordered command-search setting, which activation changes to put a venv’s command directory first.
A scheduled job can bypass PATH lookup by invoking the environment’s Python through its full path.
Pinning
Pinning selects exact package versions so a later installation can request the same releases that were checked together for an application.
A pinned line such as requests==2.32.3 prevents a fresh install from silently selecting a newer requests release.
pip
pip is an installer that resolves package requirements and installs distributions into the environment associated with its Python interpreter.
python -m pip show requests checks the installed metadata using the same Python named in the command.
Positional argument
A positional argument is a command-line value identified by its place in the input, normally required unless its definition allows omission.
In scan records.csv, the filename can supply the parser’s required path positional argument.
Project metadata
Project metadata describes a distribution’s identity, supported Python versions, dependencies, and other information used by packaging tools.
A new runtime dependency changes metadata, so an editable install must be refreshed after that change.
Project root
The project root is the directory containing the whole development project, including configuration, documentation, tests, and source code.
The outer project folder contains pyproject.toml; its inner source package supplies Python’s import name.
Propagation
Propagation passes an accepted log record to ancestor handlers without rechecking ancestor logger levels, until the route is stopped.
One root handler can collect records from the application’s modules and from installed libraries.
PyPI
PyPI is the Python Package Index, a public repository of Python distributions from which installers can obtain package releases.
A normal pip request searches PyPI unless an index setting directs it to another package repository.

R

Regular install
A regular install installs a built copy of a project so later changes in the development source do not take effect until reinstallation.
A clean regular wheel install checks that all needed modules were included in the packaged result.
Regular package
A regular package is a package directory containing __init__.py, whose code initializes the package when it is first imported.
The initializer in csvstats/analysis runs before the first import of csvstats.analysis.summary finishes.
Relative import
A relative import uses leading dots in a from statement to locate another module from the current module’s known package context.
Inside csvstats.analysis.summary, from .helpers import clean selects a sibling module.
Requirements file
A requirements file supplies pip install requests and supported options, usually one per line, and can include pins, markers, or other files.
python -m pip install -r requirements.txt reads the committed package selection into a fresh environment.
Root logger
The root logger is the top of Python’s logger hierarchy, commonly configured once by an application to collect records through shared handlers.
A child explicitly set to DEBUG can send records to root handlers even when root’s own level is WARNING.

S

Shadowing
Shadowing occurs when a same-named local module is found before the intended file-based module, changing what an import loads.
A project file named json.py can hide the standard-library JSON module and cause missing attributes.
site-packages
The site-packages directory holds installed third-party Python packages for an interpreter or environment, separate from the standard library.
Using the wrong interpreter can select a different package directory from the one populated by pip.
Source distribution
A source distribution is an archive of a project’s source and build inputs that an installer must build before installing the resulting package.
When no suitable wheel exists, pip can download an sdist and ask the project’s backend to build it.
src layout
A src layout places importable project code inside a separate src directory, so normal root-directory imports require installation.
An editable install makes src/csvstats available without placing the project root’s other files on the import path.
Standard error
Standard error is a process stream conventionally used for diagnostics, keeping them separate from the result data sent to standard output.
A missing-file diagnostic remains visible when the user redirects only the program’s standard output.
Standard output
Standard output is a process’s normal result stream, which a shell can redirect to a file or connect to another program through a pipe.
A command can print JSON results to standard output for another program to read without log messages.
Subcommand
A subcommand selects one action within a command-line program and can have its own parser, arguments, defaults, handler, and help.
An inventory tool’s add and list subcommands can accept different inputs while sharing one installed command.
Submodule
A submodule is a module inside a package, named through its parent’s dotted path and exposed as an attribute of the parent after loading.
The code imports csvstats.analysis.summary before using its describe function through that path.

T

TOML
TOML is a configuration format with key-value pairs, tables, quoted strings, arrays, and comments, used by Python project configuration.
Writing version = "0.1.0" stores a version string; leaving that dotted value unquoted is invalid.
Traceback
A traceback records the sequence of calls leading to an exception, helping identify where an unexpected failure occurred in the code.
Inside an except block, logger.exception attaches that call history instead of logging only the error text.
Transitive dependency
A transitive dependency is a package required indirectly because another package in the project’s dependency tree needs it.
urllib3 enters an environment when requests needs it, even if the application never imports urllib3 directly.

V

Version specifier
A version specifier expresses a limit on acceptable distribution versions, with comma-separated conditions that must all be satisfied.
The requirement >=2.31,<3 accepts a suitable 2.x release while excluding version 3 and later.
Virtual environment
A virtual environment is a project-specific Python environment with its own installed third-party packages and a link to a base Python.
Separate venvs let two projects use different releases of the same library without replacing one another’s selection.

W

Wheel
A wheel is a built distribution archive that can be installed without first building its source, provided its compatibility requirements fit.
A matching wheel avoids a local source build that might otherwise need a compiler on the developer’s machine.

#

__name__ guard
The name guard is a conditional that runs its body when a module is executed as the program and skips that body during ordinary import.
A demonstration under if __name__ == "__main__": stays silent when another file imports the module.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started