Skip to content

3.14+ argparse colorization makes sub-commands prog always colored if colored at creation time #139809

@gaborbernat

Description

@gaborbernat

Bug report

Bug description:

Here's an example script that replicates the problem:

from __future__ import annotations

import os
from argparse import ArgumentParser
from contextlib import suppress
from unittest.mock import patch

os.environ["FORCE_COLOR"] = "1"

parser = ArgumentParser(description="argparse tester", prog="complex")
parser.add_argument("--root", action="store_true", help="root flag")
sub = parser.add_subparsers(dest="command")
sub.add_parser("demo")

with suppress(SystemExit):
    parser.parse_args(["demo", "--help"])

with patch.dict(os.environ, {"NO_COLOR": "1"}, clear=False):
    parser.parse_args(["demo", "--help"])

You can see the first invocation prints everything in color, while the second only the sub-command:

Image

This is because https://github.com/python/cpython/blame/main/Lib/argparse.py#L1966 passes through the prog formatted and not as raw. This example is contrived a bit to have a minimal demonstration, the actual issue I'm facing is in https://github.com/tox-dev/sphinx-argparse-cli where I'm reading this value directly to generate Sphinx documentation from this.

CPython versions tested on:

3.14, 3.15

Operating systems tested on:

Linux, macOS

Linked PRs

Metadata

Metadata

Labels

3.14bugs and security fixes3.15new features, bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

Projects

Status

Doc issues

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions