简体   繁体   中英

Python type hinting with constraint on type superclass

Is it possible to add type hint in Python with constraint on the type's superclass? For example, I want something that looks like this:

def foo(g: T(S)) -> T:
    pass

which would be a function that take in a parameter g of type T and T must be a subclass of a class S or S itself, and the function's return value is of type T .

The equivalent function in C# would be something like

public static void foo<T>(T g) where T : S
{
}

I have looked in PEP484 but there doesn't seem to be anything about this.

Per PEP484 , the syntax you want seems to be:

from typing import TypeVar

T = TypeVar('T', bound=S)

def foo(g: T) -> T:
    pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM