Skip to content

Commit 26744f4

Browse files
committed
Fix type annotations for stack.py
1 parent ccff4c1 commit 26744f4

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

data_structures/stacks/stack.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
from __future__ import annotations
22

3+
from typing import Generic, TypeVar
4+
5+
T = TypeVar("T")
6+
37

48
class StackOverflowError(BaseException):
59
pass
@@ -9,7 +13,7 @@ class StackUnderflowError(BaseException):
913
pass
1014

1115

12-
class Stack:
16+
class Stack(Generic[T]):
1317
"""A stack is an abstract data type that serves as a collection of
1418
elements with two principal operations: push() and pop(). push() adds an
1519
element to the top of the stack, and pop() removes an element from the top
@@ -19,7 +23,7 @@ class Stack:
1923
"""
2024

2125
def __init__(self, limit: int = 10):
22-
self.stack: list[int] = []
26+
self.stack: list[T] = []
2327
self.limit = limit
2428

2529
def __bool__(self) -> bool:
@@ -28,13 +32,13 @@ def __bool__(self) -> bool:
2832
def __str__(self) -> str:
2933
return str(self.stack)
3034

31-
def push(self, data):
35+
def push(self, data: T) -> None:
3236
"""Push an element to the top of the stack."""
3337
if len(self.stack) >= self.limit:
3438
raise StackOverflowError
3539
self.stack.append(data)
3640

37-
def pop(self):
41+
def pop(self) -> T:
3842
"""
3943
Pop an element off of the top of the stack.
4044
@@ -47,7 +51,7 @@ def pop(self):
4751
raise StackUnderflowError
4852
return self.stack.pop()
4953

50-
def peek(self):
54+
def peek(self) -> T:
5155
"""
5256
Peek at the top-most element of the stack.
5357
@@ -71,7 +75,7 @@ def size(self) -> int:
7175
"""Return the size of the stack."""
7276
return len(self.stack)
7377

74-
def __contains__(self, item) -> bool:
78+
def __contains__(self, item: T) -> bool:
7579
"""Check if item is in stack"""
7680
return item in self.stack
7781

@@ -80,7 +84,7 @@ def test_stack() -> None:
8084
"""
8185
>>> test_stack()
8286
"""
83-
stack = Stack(10)
87+
stack: Stack[int] = Stack(10)
8488
assert bool(stack) is False
8589
assert stack.is_empty() is True
8690
assert stack.is_full() is False

0 commit comments

Comments
 (0)