Created
January 20, 2020 20:02
-
-
Save vlad-bezden/b034673b05dd2da66f9393f8710f1947 to your computer and use it in GitHub Desktop.
Example on how to use Iterable type instead of List to make mypy happy :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Static type checking using Iterable | |
show function receives List[Base]. However, if I specify type as List[Base] | |
mypy will return following error: | |
error: Argument 1 to "show" has incompatible type "List[Double]"; expected "List[Base]" | |
To fix it use Iterable[Base] instead | |
Output: | |
Base(0) | |
Base(1) | |
Base(2) | |
Base(3) | |
Base(4) | |
Double(20) | |
Double(22) | |
Double(24) | |
Double(26) | |
Double(28) | |
Double(30) | |
""" | |
from typing import Iterable | |
class Base: | |
def __init__(self, x: int) -> None: | |
self.x = x | |
def __repr__(self) -> str: | |
return f"Base({self.x})" | |
class Double(Base): | |
def __init__(self, x: int) -> None: | |
super().__init__(x * 2) | |
def __repr__(self) -> str: | |
return f"Double({self.x})" | |
def show(items: Iterable[Base]) -> None: | |
print("\n".join(str(x) for x in items)) | |
a = [Base(i) for i in range(5)] | |
b = [Double(i) for i in range(10, 16)] | |
show(a) | |
show(b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment