Skip to content

Fix subgroups typing#363

Open
Henri-J-Norden wants to merge 1 commit intolebrice:masterfrom
Henri-J-Norden:bugfix/subgroups_typing
Open

Fix subgroups typing#363
Henri-J-Norden wants to merge 1 commit intolebrice:masterfrom
Henri-J-Norden:bugfix/subgroups_typing

Conversation

@Henri-J-Norden
Copy link

Issue

With pyright, the subgroups function always produces a type error (reportArgumentType).

Example:

from dataclasses import dataclass
from simple_parsing import subgroups


@dataclass
class A:
    pass

subgroups({"a": A})
          ^^^^^^^^
          Argument of type "dict[str, type[A]]" cannot be assigned to parameter "subgroups" of type "dict[Key@subgroups, DataclassT@subgroups | type[DataclassT@subgroups] | partial[DataclassT@subgroups]]" in function "subgroups"

PS. In a different project, the error was reported as:

No overloads for "subgroups" match the provided arguments
subgroups.py: Overload 1 is the closest match

Solution

As noted in the pyright docs, the subgroups function argument should be typed as Mapping[...] instead of dict[...] due to type variance:

Use Sequence rather than list, Mapping rather than dict, etc. Immutable containers allow for more flexibility because their type parameters are covariant rather than invariant. A parameter that is typed as Sequence[str | int] can accept a list[str | int], list[int], Sequence[str], and a Sequence[int]. But a parameter typed as list[str | int] is much more restrictive and accepts only a list[str | int].

The only limitation is that Mapping is read-only, therefore the subgroups function must not modify the contents of its subgroups argument, but this appears to already be the case with the current implementation.

@Henri-J-Norden Henri-J-Norden changed the title Use Mapping for subgroups overloads (instead of dict) Fix subgroups typing Feb 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant