I am trying to compile this code and it keeps adding "Hello" when it shouldn't because it is a String and I made a Stack of integers. Following the example, in typing's docs, I noted that when they push "x" the stack is empty because they emptied the stack with a prior pop, which removes the number 2 from it. My end goal is to try to catch the type error that is supposed to be raised per the docs and to no avail, it hasn't been working. Is there something I am doing wrong in particular when declaring the Type Var leading for it to accept "Hello" in the Stack. Here is the source I am referencing in text
stack.push(2)
stack.pop()
stack.push('x') # Type error
This is code I wrote.
from typing import *
T = TypeVar('T')
class Stack(Generic[T]):
"""The generic stack class is a data structure that has many versatitle applications."""
def __init__(self) -> None:
self.__ult_ls: list[T] = []
def push(self, a: T) -> None:
"""
Add item to Stack.
"""
self.__ult_ls.append(a)
def pop(self) -> T:
"""
Remove and return last item from Stack.
"""
return self.__ult_ls.pop()
def isEmpty(self) -> bool:
"""
Is Stack Empty
"""
return not self.__ult_ls
def addAll(self, c: list[T]) -> None:
self.__ult_ls.extend(c)
if __name__ in "__main__":
a1 = Stack[int]()
for i in range(4):
a1.push(i)
a1.push('Hello')
while a1.isEmpty() != True:
print(a1.pop())
a2 = Stack[str]()
a2.addAll(['Peter', 'Antony', 'Jose'])
while a2.isEmpty() != True:
print("Nice to Meet you ", a2.pop(), "!")
Here is the output in the console:
Hello
3
2
1
0
Nice to Meet you Jose !
Nice to Meet you Antony !
Nice to Meet you Peter !
I even tried debugging the code and it verifies that shows that "Hello" gets added using Microsoft Visual Studio Code.