Assume I have two classes Foo1 and Foo2 that implement a method bar():
- In
Foo1,bar()is a regular method - In
Foo2,bar()is a@classmethod
class Foo1:
def bar(self) -> None:
print("foo1.bar")
class Foo2:
@classmethod
def bar(cls) -> None:
print("Foo2.bar")
Now assume I have a function that accepts a list of "anything that has a bar() method" and calls it:
def foreach_foo_call_bar(foos):
for foo in foos:
foo.bar()
Calling this function works fine during runtime:
foreach_foo_call_bar([Foo1(), Foo2])
as both Foo1() and Foo2 has a bar() method.
However, how can I properly add type hints to foreach_foo_call_bar()?
I tried creating a PEP544 Protocol called SupportsBar:
class SupportsBar(Protocol):
def bar(self) -> None:
pass
and annotating like so:
def foreach_foo_call_bar(foos: Iterable[SupportsBar]):
...
But mypy says:
List item 1 has incompatible type "Type[Foo2]"; expected "SupportsBar"
Any idea how to make this properly annotated?