Skip to content

Conversation

pre-commit-ci bot and others added 2 commits December 1, 2025 22:41
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.14.3 → v0.14.7](astral-sh/ruff-pre-commit@v0.14.3...v0.14.7)
- [github.com/rbubley/mirrors-prettier: v3.6.2 → v3.7.3](rbubley/mirrors-prettier@v3.6.2...v3.7.3)
- [github.com/pre-commit/mirrors-mypy: v1.18.2 → v1.19.0](pre-commit/mirrors-mypy@v1.18.2...v1.19.0)
- [github.com/henryiii/check-sdist: v1.2.0 → v1.3.0](henryiii/check-sdist@v1.2.0...v1.3.0)
- [github.com/henryiii/validate-pyproject-schema-store: 2025.11.02 → 2025.11.21](henryiii/validate-pyproject-schema-store@2025.11.02...2025.11.21)
- [github.com/python-jsonschema/check-jsonschema: 0.34.1 → 0.35.0](python-jsonschema/check-jsonschema@0.34.1...0.35.0)
- [github.com/scientific-python/cookie: 2025.11.10 → 2025.11.21](scientific-python/cookie@2025.11.10...2025.11.21)
Signed-off-by: Henry Schreiner <henryfs@princeton.edu>
@henryiii
Copy link
Collaborator

henryiii commented Dec 9, 2025

We aren't quite using TypeVar correctly, but I don't think there's another way to do this. Basically, we have something like this:

from __future__ import annotations

import typing
from collections.abc import Callable

T = typing.TypeVar("T", bound="str | list[str] | dict[str, str]")

def f(g: Callable[[str], str], inp: T) -> T:
    if isinstance(inp, str):
        return g(inp)
    if isinstance(inp, dict) and all(isinstance(v, str) for v in inp.values()):
        return {k: g(v) for k, v in inp.items()}
    if isinstance(inp, list) and all(isinstance(v, str) for v in inp):
        return [g(v) for v in inp]
    raise TypeError()

And we use it like this:

x: str | list[str]
y = f(str, x)

And we want y to have the type str | list[str]. We don't care about subclasses; list[str] really will be list[str] and not a subclass, which is why this is failing, I think, in mypy (it got much worse in 1.19, which seems to no longer narrow TypeVar at all). I think the correct way would be to expand out the bound, but that would be 63 possibilities in our case.

T = typing.TypeVar(
    "T",
    "str",
    "list[str]",
    "dict[str, str]",
    "str | list[str]",
    "list[str] | dict[str, str]",
    "str | dict[str, str]",
    "str | list[str] | dict[str, str]",
)

@henryiii henryiii merged commit 20153a1 into main Dec 9, 2025
68 checks passed
@henryiii henryiii deleted the pre-commit-ci-update-config branch December 9, 2025 15:29
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.

2 participants