当参数可以是类型提示以及裸类型时,如何输入提示其返回类型由参数指定的函数?

问题描述 投票:0回答:1

我有一个函数,它接受类型(或类型提示)并返回与该类型(或提示)匹配的对象。例如:

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:
  ...
python python-3.x type-hinting
1个回答
0
投票

这看起来就像你在 .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''
© www.soinside.com 2019 - 2024. All rights reserved.