Advertisement
Advanced Python, Command-Line Interfaces (argparse)

How do you group related arguments visually in the generated --help output using argument groups?

Short answer

add_argument_group() creates a labeled section within the parser's help output, letting you organize related arguments (like all authentication-related flags) together for readability, WITHOUT changing how the arguments are actually parsed — it's purely a --help display…

Save Python mock interview
Advertisement
AModel answer
add_argument_group() creates a labeled section within the parser's help output, letting you organize related arguments (like all authentication-related flags) together for readability, WITHOUT changing how the arguments are actually parsed — it's purely a --help display organization feature.
parser = argparse.ArgumentParser()
auth_group = parser.add_argument_group("authentication")
auth_group.add_argument("--username")
auth_group.add_argument("--password")

output_group = parser.add_argument_group("output options")
output_group.add_argument("--format", choices=["json", "csv"])
# --help now shows these grouped under their respective section headers
Real-world example
Organizing a CLI tool's --help output into clear, logical sections (authentication, output, filtering) for a large number of flags.
Likely follow-ups
  • Does argument grouping have any effect on argument PARSING behavior, or is it purely cosmetic for --help?
Related topics