argparsing.py

Overview

The [argparsing.py](/projects/286/67331) file provides a custom command-line argument and ini-file option parsing framework built on top of Python’s standard `argparse` module. It is designed primarily for the pytest testing framework but can be adapted for other applications requiring complex command line and ini-file configuration management.

Key features include:

The module encapsulates the parsing logic in the `Parser` class, which is the main entry point to define options, groups, and parse command line inputs.


Classes and Functions

Class NotSet

A sentinel singleton class used to represent an unspecified default value distinct from `None`.

NOT_SET = NotSet()

Class Parser

Main class for defining and parsing command line and ini-file options.

Attributes

Methods

Usage Example

parser = Parser()
parser.addoption("--verbose", action="store_true", help="Increase verbosity")
group = parser.getgroup("Database Options", "Options related to database configuration")
group.addoption("--db-host", default="localhost", help="Database hostname")
args = parser.parse(["--verbose", "--db-host", "db.example.com"])
print(args.verbose)  # True
print(args.db_host)  # "db.example.com"

Function get_ini_default_for_type(type: Literal[...] | None) -> Any

Returns a sensible default value for the given ini-file option type when no explicit default is provided.


Class Argument

Represents a single command line option, mimicking `optparse.Option` behavior but compatible with `argparse`.

Attributes

Methods

Usage Example

arg = Argument("-v", "--verbose", action="store_true", help="Enable verbose output")
print(arg.names())  # ['-v', '--verbose']
print(arg.attrs())  # {'action': 'store_true', 'dest': 'verbose', 'help': 'Enable verbose output'}

Class ArgumentError(Exception)

Custom error raised when an `Argument` instance is created with invalid or inconsistent arguments.


Class OptionGroup

Represents a named group of related command line options for better help output organization.

Attributes

Methods

Usage Example

group = parser.getgroup("Output Options", "Options affecting output formatting")
group.addoption("--color", choices=["yes", "no"], default="yes", help="Colorize output")

Class MyOptionParser(argparse.ArgumentParser)

Subclass of `argparse.ArgumentParser` with customized behavior:


Class DropShorterLongHelpFormatter(argparse.HelpFormatter)

Custom help formatter that:


Important Implementation Details


Interaction with Other System Parts


Visual Diagram

classDiagram
    class Parser {
        +prog: str | None
        +extra_info: dict[str, Any]
        +__init__(usage: str | None, processopt: Callable[[Argument], None] | None, _ispytest: bool)
        +processoption(option: Argument) void
        +getgroup(name: str, description: str, after: str | None) OptionGroup
        +addoption(*opts: str, **attrs: Any) void
        +parse(args: Sequence[str | os.PathLike[str]], namespace: argparse.Namespace | None) argparse.Namespace
        +parse_setoption(args: Sequence[str | os.PathLike[str]], option: argparse.Namespace, namespace: argparse.Namespace | None) list[str]
        +parse_known_args(args: Sequence[str | os.PathLike[str]], namespace: argparse.Namespace | None) argparse.Namespace
        +parse_known_and_unknown_args(args: Sequence[str | os.PathLike[str]], namespace: argparse.Namespace | None) tuple[argparse.Namespace, list[str]]
        +addini(name: str, help: str, type: Literal | None, default: Any) void
    }

    class OptionGroup {
        +name: str
        +description: str
        +options: list[Argument]
        +addoption(*opts: str, **attrs: Any) void
    }

    class Argument {
        +_short_opts: list[str]
        +_long_opts: list[str]
        +dest: str
        +names() list[str]
        +attrs() Mapping[str, Any]
    }

    class MyOptionParser {
        +error(message: str) NoReturn
        +parse_args(args: Sequence[str] | None, namespace: argparse.Namespace | None) argparse.Namespace
    }

    class DropShorterLongHelpFormatter {
        +_format_action_invocation(action: argparse.Action) str
        +_split_lines(text: str, width: int) list[str]
    }

    Parser "1" o-- "*" OptionGroup : groups
    OptionGroup "1" o-- "*" Argument : options
    Parser "1" --> "1" MyOptionParser : creates
    MyOptionParser "1" --> "1" DropShorterLongHelpFormatter : uses formatter

Summary

The [argparsing.py](/projects/286/67331) file provides a pytest-tailored command line and ini-file parsing system that extends and customizes the Python standard `argparse` module. It supports grouping of options, advanced help formatting, ini-file option typing, and integration with pytest’s error handling and shell completion features. The core `Parser` class manages option groups and parsing, while utility classes like `Argument` and `OptionGroup` encapsulate option definitions. `MyOptionParser` and `DropShorterLongHelpFormatter` provide enhanced behavior and help output. Overall, this module is a critical part of pytest’s configuration subsystem enabling rich command line interfaces and configuration management.