Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use typing.Protocol with modules?

I'd like to define a protocol which could be satisfied by an object, which might be a module:

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

gist here: https://gist.github.com/hjwp/e322c86d14ce0b11f08b27d7b17f7791

like image 759
hwjp Avatar asked May 03 '26 09:05

hwjp


1 Answers

I don't use mypy but I do check types in VSCode and this works for me:

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!
like image 97
Flávio Fonseca Avatar answered May 05 '26 22:05

Flávio Fonseca