Middle+
Have you worked with Protocol in Python? What are Generics?
sobes.tech AI
Answer from AI
Yes, Python has Protocol from the typing module, which allows describing structural types — that is, types defined by the presence of certain methods and attributes, rather than inheritance. This is the basis for duck typing with support for static typing.
Example of using Protocol:
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None:
...
class Resource:
def close(self) -> None:
print("Closed")
def cleanup(resource: SupportsClose) -> None:
resource.close()
r = Resource()
cleanup(r) # Works because Resource implements the close method
Generics are parameterized types that allow creating generic functions and classes that work with different data types while preserving type information.
Example of a generic with TypeVar:
from typing import TypeVar, Generic, List
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()
stack_int = Stack[int]()
stack_int.push(1)
value = stack_int.pop() # value has type int
Thus, Protocol helps describe interfaces by structure, and generics create versatile components with type safety.