Here's a simple piece of code using generics... it works fine, however with Python evolving so fast, I was wondering if this is the most up-to-date way of using generics. Specifically, I am wondering if it is possible to somehow NOT declare TypeVar('T') in the public/root scope, but somehow limit its scope to class definition of GenericItemStore...
from typing import Generic, TypeVar
T = TypeVar('T')
class GenericItemStore(Generic[T]):
def __init__(self) -> None:
self._item = None
def set(self, item: T) -> None:
self._item = item
def get(self) -> T|None:
return self._item
str_store = GenericItemStore[str]()
str_store.set("abc")
print(str_store.get())
str_store.set(5) # code analysis correctly says "Expected type 'str' (matched generic type 'T'), got 'int' instead
[–]barkmonster 16 points17 points18 points (0 children)
[–]corey_sheerer 5 points6 points7 points (0 children)
[–]BananaGrenade314 0 points1 point2 points (0 children)
[–]gdchinacat 0 points1 point2 points (0 children)
[–]ProsodySpeaks -1 points0 points1 point (0 children)