Every repository eventually grows a scripts/ folder: a shell script that regenerates fixtures, another that versions a wheel, a third that nobody dares delete because the release notes depend on it. The usual fix is a Makefile nobody reads or a YAML file that only the CI server understands. Both hide their logic behind a syntax you cannot step through in a debugger.

pydoit takes the other road. You describe work in ordinary Python functions in a file called dodo.py, and doit figures out what actually needs to run. If nothing changed, nothing runs. If a single input file moved, only the tasks that consume it are rebuilt. All of that bookkeeping lives in one database file, and the engine that performs it is small enough to read in an afternoon.

This tour walks the real master tree of pydoit/doit. The package holds 29 Python modules and about 7,558 lines of code, which makes it one of the few orchestration tools compact enough to audit end to end. We will follow a task from the moment its function is discovered to the moment its subprocess exits, and we will look at the state machine that decides whether it should have run at all.

doit architecture overview: CLI, task loading, dependency planning, execution and state storage

Overview: DoitMain dispatches commands; task loading builds Task objects; planning orders them; the runner executes actions while the dependency module records state.

Reading the overview from left to right:

  • DoitMain, L156 registers eleven core commands in DOIT_CMDS and layers plugin commands on top, so every subcommand shares one dispatch path.
  • DoitCmdBase, L432 merges database, loader and command-specific options into a single option list, then hands the parsed values to a signature-based execute.
  • task_params, L114 decorates a task creator so command-line parameters are validated once and inherited by every task the generator produces.
  • Task, L107 is the model object: actions, file_dep, task_dep, calc_dep, uptodate, getargs, values and targets all pass through a 20-entry attribute whitelist.
  • TaskControl, L25 validates that every dependency name exists, adds implicit dependencies from targets, and expands wildcard task names.
  • Runner.select_task, L111 asks the dependency manager whether a task is current, then decides between running, skipping and erroring.
  • MD5Checker, L385 compares a saved (timestamp, size, md5) tuple against the file on disk, short-circuiting on the first mismatch.
  • CmdAction, L101 runs a shell command through subprocess, captures both streams and converts a non-zero exit code into a typed failure.
  • ConsoleReporter, L12 turns those results into the familiar . task, -- task and !! task lines, while JSON and quiet reporters implement the same callbacks.
doit detailed module map across commands, loading, planning, execution and state storage

Detail: twenty modules and their import edges, with the six command files that wrap the core engine.

The dodo.py contract and how it becomes Task objects

A task creator is just a function whose name starts with task_; the prefix constant is declared in loader.py and stripped to form the task name. The loader scans a namespace, keeps only functions or objects exposing create_doit_tasks, and sorts creators by the line number where they were defined so task order matches reading order in the file.

Each creator may return a dictionary, yield dictionaries, or return a Task instance directly. When a generator yields several dictionaries, any dict containing a name field becomes a subtask and is registered under the composite identifier basename:name; the parent becomes a group task with no actions but with dependency entries pointing at its children. A group with no children at all is still created, which is how a conditionally empty generator stays listable.

@task_params sits above that mechanism. It attaches a parameter definition list to the function as _task_creator_params, and the loader parses those options from the command line before the generator runs. Because the parameters are attached to the creator rather than the task, the loader raises an explicit error when a task also declares a params attribute, since the two definitions would silently disagree.

Delayed creation is the third variant. A creator decorated with create_after stores a DelayedLoader, and the loader records a placeholder task whose real contents are produced only after a named task has executed. That is how doit supports tasks that are themselves generated by earlier build steps without forcing every generation to happen up front.

The same model carries cleanup and output policy. Setting clean to True makes doit delete the task’s declared targets, while a list of clean actions is executed instead; if a clean callable names dryrun in its signature, doit injects the flag so the action can report what it would remove without removing it. Teardown actions are collected as tasks execute and then run in reverse order once the run finishes, which gives long-lived resources a predictable shutdown order. Verbosity is handled with the same explicit tables: level 0 captures both streams, level 1 captures stdout and leaves stderr live, and level 2 passes both through untouched.

From a dodo.py dictionary to a running subprocess

The build facts in this section are what make the engine predictable. The Task constructor validates all twenty attributes against a whitelist of accepted types and values, so a typo such as file_deps fails immediately with the offending key named rather than being ignored. file_dep entries are normalised into a set, task_dep entries containing * are split into a separate wildcard list, and uptodate entries are wrapped into (callable, args, kwargs) triples or plain booleans.

Option parsing is generated rather than hand-written. DoitCmdBase.get_options concatenates the database, loader and command option lists, and CmdParse turns them into an argument parser whose defaults can be overridden from INI or TOML configuration. The final _execute call is built by inspecting that method’s signature and pulling only the parameter names it asks for from the parsed namespace, which keeps command implementations ordinary Python functions.

Execution proper is a short loop. The runner receives ExecNode objects from the dispatcher, calls select_task, and on approval calls task.execute(stream), which walks the task’s actions in order. Each action returns None, a value, or a BaseFail subclass; the first failure aborts the remaining actions. CmdAction treats exit codes above 125 as a task error and other non-zero codes as a task failure, a distinction the reporter prints differently.

Parallelism reuses the same loop. With -n greater than zero, MRunner serialises tasks into process queues and collects result dictionaries; MThreadRunner swaps in daemon threads. A recent change pins the multiprocessing start method to fork when Python 3.14 would default to forkserver, because the newer default pickles the runner and breaks dodo files containing lambdas or nested functions. On the scheduling side, the dispatcher keeps a ready deque and a waiting set, detects cycles by walking each node’s ancestor chain, and answers multiprocessing workers with a hold on sentinel when all remaining tasks are blocked.

Deciding what is up to date

Up-to-date checking lives entirely in dependency.py. Dependency.get_status runs any uptodate callables, treats a string entry as a shell command whose exit status is the verdict, and stops early when a check returns false. If a task declares neither file dependencies nor uptodate entries, it is never considered current — an honest default that prevents silent skips.

For file dependencies the default checker stores a timestamp, a size and an md5 digest. The check order matters for speed: an unchanged mtime returns immediately, a changed size returns “modified” without hashing, and only the ambiguous case pays for a full md5. Blocks are read at 128 times the hash block size. If the configured checker class differs from the one recorded in the database, all saved values for that task are discarded, which avoids reusing an md5 from a timestamp-based run.

Successful tasks write a compact record: saved values under _values_:, a result digest under result:, the checker name, one state tuple per dependency, and the ordered list of dependency paths. Three storage backends are available — dbm, JSON and SQLite — and the DBM backend keeps a dirty set so only modified task ids are re-encoded at shutdown. That small detail is why a large build with hundreds of up-to-date tasks touches very little of the database file.

Value passing is a second, quieter dependency channel. A getargs entry maps an action argument name to a (task_id, key_name) pair, and the task constructor converts each pair into an implicit result dependency: if the producer’s stored result changed, the consumer reruns. Before execution the runner resolves those pairs through the dependency manager, reading either a single value or, for a group task, a dictionary assembled from every subtask. Group aggregation happens at read time rather than write time, so subtasks never need to know that a consumer exists.

Extending doit without forking it

Four plugin categories are recognised: commands, loaders, backends and reporters. PluginDict reads them from configuration sections or from setuptools entry points, and deliberately defers importing a plugin until get_plugin is called, so a broken optional dependency cannot break the default path. A custom reporter only has to implement the handful of status callbacks the console reporter already exposes.

The tools.py module shows how much can be expressed without subclassing anything. config_changed hashes a dictionary of settings with sorted keys and compares it to the value saved on the last successful run; timeout stores a completion timestamp and returns false once a configured number of seconds has elapsed; check_timestamp_unchanged accepts a comparison operator so a reverted file can count as unchanged. These are ordinary callables, so they compose with each other and with user code.

If your daily loop already leans on pytest for tests and tox for environments, doit fills the remaining gap: the ad-hoc generation and packaging steps that neither tool models. It reads as a natural extension of that toolchain rather than a separate platform to learn.

Honest Limits

doit is a single-machine task runner, not a distributed scheduler. There is no central coordinator, no retry policy with backoff, and no built-in notion of a worker pool spread across hosts; parallel execution means subprocesses or threads on the machine invoking it. Teams that need cross-machine orchestration will outgrow it, and that is a scope decision rather than a defect.

The file-state database is a local file. Two doit processes pointed at the same .doit.db will not coordinate, and the recoverable failure mode is a corrupted database that the code tells you to delete. The DBM backend is fast but its format depends on the platform’s available dbm module, which is why JSON and SQLite exist as alternatives and why dumpdb is a first-class command.

Finally, Python-level flexibility is the design centre. Actions are shell strings or functions, and the engine does not sandbox them, hash their source, or cache their outputs. Comparing action bodies across runs is left to extensions, much like the trade-offs pre-commit makes when it trusts hooks to be deterministic. For a task runner named after the simplest possible instruction, that restraint is also the reason the whole package still fits in a source tour.

Watch PyShine on YouTube

Contents