Parse repeated local labels with append

Repeated options are useful when a caller supplies several small labels without inventing a separator format. The action="append" setting tells argparse to add each --label value to a list. Given the synthetic arguments --label urgent --label backend, the parsed Namespace contains the list ["urgent", "backend"]. The assertions check both the full ordered list and the number of supplied labels; the program then joins the values to make the exact output easy to inspect.

append preserves occurrences supplied to this parse, but it does not validate label vocabulary, remove duplicates, or attach labels to files. A caller could repeat the same label, and this code would retain both entries. Add choices for a fixed vocabulary, a converter for a defined label grammar, or separate validation for domain-specific rules. If no --label is given, argparse's default here is None; choose default=[] only when an empty list is the desired semantic result and be mindful of how defaults are reused in a larger program.

The append action is supported by standard-library argparse, which has been available since Python 3.2. The official argparse action documentation specifies that it appends values to a list.

AI assistance disclosure: this article was drafted with AI assistance and should be checked in its target CLI context.

import argparse

parser = argparse.ArgumentParser(prog="label-local")
parser.add_argument("--label", action="append")

args = parser.parse_args(
    ["--label", "urgent", "--label", "backend"]
)
assert args.label == ["urgent", "backend"]
assert len(args.label) == 2

print("labels=" + ",".join(args.label))
labels=urgent,backend

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic