1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Method with Generic Type that Accesses External Structure of Same Generic Type

Discussão em 'Python' iniciado por Stack, Setembro 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm sure the title is plenty cryptic, so let me explain with an example.

    Given a simple inheritance structure, e.g.:

    class S:
    ...

    class A(S):
    ...

    class B(S):
    ...


    I'd like to conceptually do something like the following:

    class Foo:
    T = TypeVar('T', bound=S)

    items: dict[type[T], T] = dict()

    def get(self, t: type[T]) -> T:
    return self.items[t]


    In other words, have the return type of a method depend on the input type (with a bound of a specific supertype) that refers to a container providing that same generic (but with a bound) mapping.

    I can't quite figure out how to do it; any ideas how to approach this? I've tried to keep the example succinct, please let me know if more detail is necessary.

    My use case is the following: I have a map that maps from one of the subtypes (A, B) to instances of the respective type (A(), B()). That map is to be used by a method that is parameterized with one of these same subtype (of S). So, for instance, a call to that method, given type B, should access the map at key B and retrieve an instance of B() and the method should ultimately be able to type hint that the same type is returned as requested, but it needs to reach out into an outer context.

    Any pointer would be much appreciated! May thanks.

    Continue reading...

Compartilhe esta Página