Skip to content

Cannot use non-string annotations for argparse._SubParsersAction parameters #7539

@OddBloke

Description

@OddBloke

In #6178, argparse._SubParsersAction was modified to be generic. This poses a problem when using this type to annotate a function, because argparse._SubParsersAction is not subscriptable but, being generic, it won't pass strict type-checking without subscripting. Consider this example file:

from typing import Any
import argparse


def example(subparser: argparse._SubParsersAction) -> None:
    subparser.add_parser("subexample")

Python will execute this code, but mypy --strict reports: example.py:5: error: Missing type parameters for generic type "_SubParsersAction".

If we add a type parameter to satisfy mypy:

from typing import Any
import argparse


def example(subparser: argparse._SubParsersAction[Any]) -> None:
    subparser.add_parser("subexample")

then mypy --strict is happy, but Python cannot execute the file because TypeError: 'type' object is not subscriptable.

This can be worked around with a string annotation (i.e. "argparse._SubParsersAction[Any]") but this can't be assigned to a type variable, which makes all of my helper function definitions much noisier and multi-lined.

(My usecase: I have common subcommands that I use helper functions to add: these all accept a _SubParsersAction.)

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