如何根据参数推断对象的返回类型?

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

假设我们有一个函数

def get_attr_wrapper(obj: object, attr: str) -> ???:
    return getattr(obj, attr)

如何根据给定的参数推断

get_attr_wrapper
的返回类型?

也许可以用通用的方式?

例如,如果我通过了

from dataclasses import dataclass

@dataclass
class Foo:
    bar: str

foo = Foo(bar="baz")

rv = get_attr_wrapper(foo, "bar")

rv
会被 Python 的类型检查器推断为
string
类型。

python python-typing
1个回答
0
投票

您可以使用 TypeVar 使用泛型类型来实现此目的。

示例:

from typing import TypeVar


T = TypeVar('T')


def get_attr_wrapper(obj: object, attr: str) -> T:
    return getattr(obj, attr)

© www.soinside.com 2019 - 2024. All rights reserved.