键入提示。如何提示传递给函数的对象必须具有某些 method/attribute 访问权限?

Type hinting. How to hint that object passed to a function must have some method/attribute access?

请看一个使用 numpy docstring 进行类型提示的示例:

def my_function(obj):
    """Do some work.

    Parameters
    ----------
        obj : Any class with `do_work()` method
    Returns
    -------
    None
    """
    time.sleep(5)

我想知道是否有办法告诉调用者函数需要具有 do_work 方法的对象?有没有办法使用 python3/mypy 类型提示 or/and numpy 文档字符串来指定此类提示?

定义一个Protocol

import typing


class Worker(typing.Protocol):
    def do_work(self):
        pass


class SomeWorker:
    def do_work(self):
        print("Working...")


def my_function(obj: Worker):
    obj.do_work()


x = SomeWorker()
my_function(x)  # This will type check; `SomeWorker` doesn't have to inherit from Worker