Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Last active February 7, 2024 00:17
Show Gist options
  • Save CodeByAidan/88ba6d6bdf9794fef5559fc0ee355031 to your computer and use it in GitHub Desktop.
Save CodeByAidan/88ba6d6bdf9794fef5559fc0ee355031 to your computer and use it in GitHub Desktop.
Stack Implemention using Generics in mypy/Python with typing lib. Python 3.10+ required.
"""
A simple stack implementation using Generics.
This is a simple stack implementation using Generics. It is based on the
example from the Python docs:
https://docs.python.org/3/library/typing.html#user-defined-generic-types
"""
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
"""
A simple stack implementation using Generics.
Args:
Generic (T): The type of the items in the stack.
Attributes:
items (list[T]): The items in the stack.
"""
def __init__(self) -> None:
# Create an empty list with items of type T
self.items: list[T] = []
def push(self, item: T) -> None:
"""
Push an item onto the stack.
Args:
item (T): The item to push onto the stack.
"""
self.items.append(item)
def pop(self) -> T:
"""
Pop an item off the stack.
Returns:
T: The item popped off the stack.
Raises:
IndexError: If the stack is empty.
"""
return self.items.pop()
def empty(self) -> bool:
"""
Check if the stack is empty.
Returns:
bool: True if the stack is empty, False otherwise.
"""
return not self.items
if __name__ == '__main__':
stack = Stack[int]()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # 3
print(stack.pop()) # 2
print(stack.pop()) # 1
print(stack.empty()) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment