Junior — Middle
Do you use the Protocol from the typing module in your Python projects?
sobes.tech AI
Answer from AI
Yes, I use Protocol from the typing module in Python to define interfaces without inheritance. Protocol allows describing a set of methods and attributes that a class must implement, which is convenient for static typing and interface compliance checking.
Example of using Protocol:
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None:
...
class Resource:
def close(self) -> None:
print("Resource closed")
def cleanup(resource: SupportsClose) -> None:
resource.close()
res = Resource()
cleanup(res) # Works because Resource implements the close method
Thus, Protocol helps write more flexible and type-safe code.