python / python/typing

TypeVar substitution in get_type_hints

Open
#776 10 comments 9 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

When it comes to generic classes, type annotations retrieved with get_type_hints are not really easy to use, as in the following example:

from typing import Generic, TypeVar, get_type_hints

T = TypeVar("T")
class A(Generic[T]):
    a: T

U = TypeVar("U")
class B(A[U]):
    b: U

assert get_type_hints(B) == {"a": T, "b": U}

It could be useful to add a TypeVar substitution to get_type_hints, for example with an additional substitute_type_vars parameter (with a False default)
By the way, get_type_hints could also allow to pass generic alias in order to substitute directly TypeVars with their related argument.

It would give for the example above:

assert get_type_hints(B, substitute_type_vars=True) == {"a": U, "b": U}  # typevars are consistent
assert get_type_hints(B[T], substitute_type_vars=True) == {"a": T, "b": T}
assert get_type_hints(B[int], substitute_type_vars=True) == {"a": int, "b": int}  # ready to use

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the get_type_hints API and the generic-class examples in the issue, then review how generic aliases and TypeVar relationships are currently represented. Done means defining and implementing the proposed substitution behavior, including the default-disabled parameter and alias inputs, with tests covering B, B[T], and B[int].

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.