Reject Abbreviated Python CLI Options with argparse

A build script invokes an asset tool with --out build. It works while the tool has only --output, then breaks when a later version adds --outline. The caller was relying on an accepted prefix rather than a declared option name. For automation, requiring the full long name makes this contract easier to review and maintain.

These examples use Python 3.10 or later. The tool prints a proposed asset job without opening files or performing a conversion, so its parsing behavior can be tested independently.

Reproduce an Accepted Prefix

Run this short example:

1
2
3
4
5
6
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--output")
print(parser.parse_args(["--out", "build"]).output)
# build

The parser accepts the shortened name because it uniquely identifies --output. After adding an option such as --outline, that same prefix becomes ambiguous. A full --output invocation avoids depending on which other options happen to exist. The setting that controls this behavior is documented in Python’s allow_abbrev reference .

Require Declared Long Option Names

Save this as asset_cli.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import argparse
import json


def make_parser():
    parser = argparse.ArgumentParser(
        description="Describe an asset conversion job",
        allow_abbrev=False,
    )
    parser.add_argument("--output", required=True)
    parser.add_argument("--format", choices=("png", "webp"), default="png")
    parser.add_argument("input")
    return parser


def main(argv=None):
    args = make_parser().parse_args(argv)
    print(json.dumps({
        "input": args.input,
        "output": args.output,
        "format": args.format,
    }, sort_keys=True))


if __name__ == "__main__":
    main()

Run python asset_cli.py --output build --format webp hero.png. It prints:

1
{"format": "webp", "input": "hero.png", "output": "build"}

Now python asset_cli.py --output build --form webp hero.png fails instead of treating --form as --format. Keep parse_args() here: this command owns the complete argument list and should reject leftovers. parse_known_args() serves a different interface where another component handles the remaining arguments.

The setting governs long option abbreviation. It does not make a declared short option invalid or validate whether a path exists. Add explicit aliases only when you intend to support them as part of the command’s public interface.

Separate Option Values from Positional Filenames

A filename that starts with a hyphen can look like an option. After specifying the options, place -- before the positional filename:

1
2
3
4
5
6
7
from asset_cli import make_parser

args = make_parser().parse_args([
    "--output", "build", "--", "--draft.png",
])
print(args.input)
# --draft.png

The separator ends option parsing; it is not included in the filename. Put the options before it. For an option value that itself starts with hyphens, attach the value to the full option name: --output=--staging assigns --staging to output. It is an ordinary relative path string in this demonstration. The parser still does no filesystem access. See the documented argument syntax rules .

Test the Contract Without Launching a Shell

Save this as test_asset_cli.py beside the tool and run python test_asset_cli.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import contextlib
import io

from asset_cli import make_parser


def must_reject(argv):
    errors = io.StringIO()
    with contextlib.redirect_stderr(errors):
        try:
            make_parser().parse_args(argv)
        except SystemExit as exc:
            assert exc.code == 2
        else:
            raise AssertionError(f"accepted invalid arguments: {argv!r}")
    assert errors.getvalue()


parser = make_parser()
args = parser.parse_args(["--output", "build", "hero.png"])
assert (args.input, args.output, args.format) == ("hero.png", "build", "png")
args = parser.parse_args([
    "--output=--staging", "--format=webp", "--", "--draft.png",
])
assert (args.input, args.output, args.format) == (
    "--draft.png", "--staging", "webp",
)

for argv in [
    ["--output", "build", "--form", "webp", "hero.png"],
    ["--out", "build", "hero.png"],
    ["--output", "build", "--format", "gif", "hero.png"],
    ["--output", "build", "hero.png", "extra.png"],
    ["hero.png"],
    ["--output", "build"],
    ["--output"],
]:
    must_reject(argv)

print("Asset CLI parsing checks passed.")

The tests cover full names, defaults, the separator, an attached value, abbreviations, an unsupported format, extra arguments, and missing arguments. They check the error status and presence of diagnostics without depending on exact help wording, which can differ between Python releases.

Preserve Failures in the Calling Pipeline

Also test the actual entry point. Save this as test_asset_process.py in the same directory and run python test_asset_process.py from that directory:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import json
import subprocess
import sys

valid = subprocess.run(
    [sys.executable, "asset_cli.py", "--output", "build", "hero.png"],
    capture_output=True, text=True, check=True, timeout=10,
)
assert json.loads(valid.stdout) == {
    "input": "hero.png", "output": "build", "format": "png",
}

invalid = subprocess.run(
    [sys.executable, "asset_cli.py", "--output", "build",
     "--form", "webp", "hero.png"],
    capture_output=True, text=True, check=False, timeout=10,
)
assert invalid.returncode == 2
assert invalid.stdout == ""
assert invalid.stderr
print("Asset CLI process checks passed.")

Parsing finishes before the tool prints its job, so a malformed invocation produces no success output. A real converter should likewise finish argument validation before writing assets. Let the parser’s failure reach the process boundary so a build runner can stop. When introducing this setting to an existing command, first update callers that rely on abbreviated names and run these checks against the Python versions used by the pipeline.