Skip to content

Instantly share code, notes, and snippets.

@1271
Created September 2, 2020 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1271/ad806c997ff5c8de40ffbe1de4a5e3d1 to your computer and use it in GitHub Desktop.
Save 1271/ad806c997ff5c8de40ffbe1de4a5e3d1 to your computer and use it in GitHub Desktop.
Python generic example
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