[Python] TypeVar as dict key type hint "has no meaning in this context"

Discussão em 'Python' iniciado por Stack, Maio 11, 2025.

  1. Stack

    Stack Membro Participativo

    The context:


    I have a dict whose keys are arbitrary types, and whose values are Callables which take a string and return an instance of the same type as the key. For example:

    class Hero:
    def __init__(self, name):
    self.name = name


    all_heroes = {
    "deadpool": Hero("wade wilson"),
    "wolverine": Hero("james howlett")
    }

    REGISTERED_CONVERTERS = {
    Hero: all_heroes.get,
    int: int,
    }

    hero_lookup = REGISTERED_CONVERTERS[Hero]
    assert hero_lookup("deadpool").name == "wade wilson"

    int_lookup = REGISTERED_CONVERTERS[int]
    assert int_lookup("5") == 5

    The Problem:


    I want to properly type hint this dict of converter functions

    What's not Working:


    This was my first attempt:

    from typing import Callable, TypeVar

    T = TypeVar("T")
    TypeConverter = Callable[[str], T]
    REGISTERED_CONVERTERS: dict[type[T], TypeConverter] = {
    int: int,
    }


    Pylance is happy with the T in the TypeConverter alias, but complains about the T for the dict's key:

    Type variable "T" has no meaning in this context Pylance(reportGeneralTypeIssues)
    (constant) T: type[T]


    I thought maybe the TypeConverter alias was causing issues, so then I tried this:

    T = TypeVar("T")
    REGISTERED_CONVERTERS: dict[type[T], Callable[[str], T]] = {
    int: int,
    }


    This is seemingly worse as Pylance now raises the same complaint about both Ts

    What am I doing wrong, or is this a Pylance problem?

    Continue reading...

Compartilhe esta Página