Skip to content

Add contextmanager interface to argparse.ArgumentParser for better sub-command declarations #132041

@makukha

Description

@makukha

Feature or enhancement

Proposal:

Currently, every sub-command requires separate local variable for sub-parser, leading to

  • Pollution of module namespace
  • Need to think about variable names
  • Visually unaligned code when sub-parser names have different length

The above-mentioned downsides can be avoided if argparse.ArgumentParser implements trivial context manager protocol:

class ArgumentParser:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

Having this, the respective example from argparse documentation

parser_a = subparsers.add_parser('a', help='a help')
parser_a.add_argument('bar', type=int, help='bar help')

parser_b = subparsers.add_parser('b', help='b help')
parser_b.add_argument('--baz', choices=('X', 'Y', 'Z'), help='baz help')

could be re-written as

with subparsers.add_parser('a', help='a help') as p:
    p.add_argument('bar', type=int, help='bar help')

with subparsers.add_parser('b', help='b help') as p:
    p.add_argument('--baz', choices=('X', 'Y', 'Z'), help='baz help')

The benefits become more obvious when there are more sub-commands and sub-commands have more arguments added.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions