Created
September 2, 2020 07:59
-
-
Save 1271/ad806c997ff5c8de40ffbe1de4a5e3d1 to your computer and use it in GitHub Desktop.
Python generic example
This file contains 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
from typing import TypeVar, Generic, List | |
import json | |
T = TypeVar('T') | |
class Stack(Generic[T]): | |
def __init__(self) -> None: | |
self.__items: List[T] = [] | |
def push(self, item: T) -> None: | |
self.__items.append(item) | |
def pop(self) -> T: | |
return self.__items.pop() | |
def empty(self) -> bool: | |
return not self.__items | |
def __str__(self): | |
return json.dumps(self.__items) | |
a = Stack[int]() | |
a.push(3) | |
a.push(2) | |
a.push(1) | |
a.push('123') | |
a.push(123) | |
print(a) | |
# mypy generic.py | |
# generic.py:28: error: Argument 1 to "push" of "Stack" has incompatible type "str"; expected "int" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment