如何获取属性返回类型注解?

0 投票
1 回答
41 浏览
提问于 2025-04-13 00:55

我想找到一种方法,从一个类的属性中提取返回类型的注解,比如:

class Test:
    @property
    def foo(self) -> int:
        return 1

print(return_type_extract(Test, 'foo')) # <class 'int'>

对于普通的方法,可以这样做:

import inspect
class Test:
    def foo(self) -> int:
        return 1

def return_type_extract(cls: type, method_name: str) -> type:
    method = getattr(cls, method_name)
    return inspect.signature(method).return_annotation

print(return_type_extract(Test, 'foo')) # <class 'int'>

不过,这种方法对使用了 @property 装饰器的属性不管用,因为在 inspect.signature 里面会报错。我查过 inspect 库中与属性相关的内容,但到现在为止还没有找到合适的方法。

1 个回答

2

如果我们获取到的属性是一个属性对象,我们可以通过它的获取方法(.fget)来得到底层的函数。接着,我们使用 get_type_hints() 来提取这个底层函数的返回类型注解。

像这样:

from typing import get_type_hints

class Test:
    @property
    def foo(self) -> int:
        return 1

def return_type_extract(cls: object, property_name: str) -> type:
    property_obj = getattr(cls, property_name)
    if isinstance(property_obj, property):
        property_obj = property_obj.fget
    return get_type_hints(property_obj).get('return')

print(return_type_extract(Test, 'foo'))  # <class 'int'>

撰写回答