[Python] How to write a "non-type TypeVar" in python, similar to non-type template parameter...

Discussão em 'Python' iniciado por Stack, Abril 28, 2025.

  1. Stack

    Stack Membro Participativo

    To be short, I hope to write something like template<int N> of c++ in python. Here's a specific example

    from typing import TypeVar, Generic
    T = TypeVar("T", ...?) # an actual int value, not int type, as typevar, I'm wondering how to write such type var
    V = TypeVar("V", ...?) # an actual int value, not int type, as typevar
    class Foo(Generic[T, V]):
    def __init__(self, t: T, v: V) -> None:
    self.T, self.V = t, v

    def __call__(self, x: np.ndarray[tuple[T, V], np.dtype[np.float_]]):
    return x

    # e.g.
    foo = Foo(3, 2) # foo is expected to type-hint as Foo[3, 2] or Foo[Literal[3], Literal[2]]
    y = foo(np.zeors(3, 2)) # foo(...) is expected to hint a parameter type of np.ndarray[tuple[Literal[3], Literal[2]], np.dtype[np.float_]]


    So how should I configure the TypeVars to get what I want?

    Continue reading...

Compartilhe esta Página