我有一个函数,它接受类型(或类型提示)并返回与该类型(或提示)匹配的对象。例如:
def get_object_of_type(typ):
...
x = get_object_of_type(int)
# x is now guaranteed to be an int
y = get_object_of_type(str | bytes)
# y is now guaranteed to be either a string or a bytes object
如何输入提示此函数以使静态分析器清楚此行为?
以下解决方案(使用 Python 3.12 语法)适用于类型,但不适用于类型联合表达式:
def get_object_of_type[T](typ: type[T]) -> T:
...
这看起来就像你在 .net 框架中使用 C# 看到的东西,我不确定你是否可以在 python 中做到这一点,但也许这可以帮助......
from typing import TypeVar
AnyType = TypeVar('AnyType', int, str, bytes)
def get_object_of_type(typ: AnyType) -> AnyType:
if isinstance(typ, int):
"""rune some code"""
return 0
if isinstance(typ, str):
"""rune some code"""
return ''
if isinstance(typ, bytes):
"""rune some code"""
return b''