如何类型提示 __getattr__ 方法的返回类型?

rv.*_*tch 11 python getattr python-3.x python-typing

我很好奇Python 3 中是否有一种方法可以提示__getattr__()Python 中方法的返回类型。

我有以下用于测试目的的虚拟代码:

class MyClass:

    def __getattr__(self, item: str) -> str:
        return 'test'

    def __getattribute__(self, item: str) -> str:
        return 'test'


c = MyClass()

print(c.hello, type(c.hello))  # test <class 'str'>
Run Code Online (Sandbox Code Playgroud)

不幸的是,Pycharm 无法解析hello上面的属性类型。我不确定,但我认为它目前是按Any类型处理的。

我还对上述代码提出了以下变体,但仍然无法使类型提示按预期工作:

from typing import Callable

ReturnsString = Callable[[], str]


class MyClass:

    my_test_fn: ReturnsString = lambda self: 'hello'
    __getattr__: ReturnsString = lambda self, _item: 'test'
    __getattribute__: ReturnsString


c = MyClass()

# type hinting works as expected - return type is `str`
print(c.my_test_fn())

# type hinting doesn't work here still - help?
print(c.hello, type(c.hello))  # test <class 'str'>
Run Code Online (Sandbox Code Playgroud)

我很想知道是否有人知道一种解决方法,我们可以__getattribute()__在 Python 3.x 中键入提示返回类型,也许使用键入泛型或其他方式。

附加信息

只是为了澄清一下,我的用例是我正在尝试构建一个dict支持属性(点)访问的子类。所以我注意到类型提示和特定于类型的建议适用于__getitem__工作,但不适用于__getattr__. 例如:

from typing import Callable

ReturnsString = Callable[[], str]


class MyClass(dict):
    __getattr__: ReturnsString = lambda self, _item: 'test'
    __getattribute__: ReturnsString
    __getitem__: ReturnsString


c = MyClass(hello=123)

# works as expected - return type of c['hello'] is `str`
print(c['hello'], type(c['hello']))  # test <class 'str'>

# type hinting doesn't work here still - help?
print(c.hello, type(c.hello))  # test <class 'str'>
Run Code Online (Sandbox Code Playgroud)