Junior — Middle
Could you explain what a Protocol is in the typing module in Python?
sobes.tech AI
Answer from AI
Protocol in Python's typing module is a way to describe an interface (a set of methods and attributes) that an object must support, without needing to inherit from a specific class.
It is part of the concept of "structural typing," where what matters is not the object's belonging to a particular class, but the presence of the required methods and properties.
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 has a close method
Thus, Protocol allows describing requirements for objects for static type checking without forcing them to explicitly inherit from any base class.