如何在模块中使用typing.Protocol?

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

我想定义一个可以由对象满足的协议,该对象可能是一个模块:

from typing import Protocol

class MyType(Protocol):
    def foo(self) -> int:
        ...


class MyClass:
    def foo(self) -> int:
        return 1

# this is OK
a = MyClass()  # type: MyType

import mymodule
# mymodule.py just contains 
# def foo() -> int:
#     return 42

# but this is not.
b = mymodule  # type: MyType
# mypy complains saying
# Incompatible types in assignment (expression has type Module, variable has type "MyType")


import inspect
print(inspect.signature(a.foo))
print(inspect.signature(b.foo))
# both print: () -> int

要点:https://gist.github.com/hjwp/e322c86d14ce0b11f08b27d7b17f7791

python python-typing mypy
1个回答
1
投票

我不使用 mypy,但我确实检查 VSCode 中的类型,这对我有用:

from typing import Protocol

class MyType(Protocol):
    @staticmethod
    def foo() -> int:
        ...


import mymodule
# mymodule.py just contains 
# def foo() -> int:
#     return 42

def test(something: MyType):
    print(something.foo())  # prints 42

test(mymodule)  # type checking OK here!
© www.soinside.com 2019 - 2024. All rights reserved.