pythonintermediate
Protocol
Advanced Python pattern: protocol
pythonPress ⌘/Ctrl + Shift + C to copy
from typing import Protocol
class SupportsLen(Protocol):
def __len__(self) -> int: ...
def has_items(x: SupportsLen) -> bool:
return len(x) > 0
print(has_items([1, 2, 3]))Use Cases
- advanced programming
- patterns
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Implement the Iterator Protocol
Create custom iterators using __iter__ and __next__ for lazy evaluation.
Best for: Batch processing
#python#iterator
pythonadvanced
Protocol Classes for Structural Typing
Define interfaces with Protocol for duck-typing that works with static type checkers.
Best for: dependency injection
#python#protocol
pythonbeginner
Type Hints
Advanced Python pattern: type-hints
Best for: advanced programming
#python#advanced
pythonintermediate
Dataclass
Advanced Python pattern: dataclass
Best for: advanced programming
#python#advanced