Recursive protocols

Protocols can be recursive (self-referential) and mutuallyrecursive. This is useful for declaring abstract recursive collectionssuch as trees and linked lists:

  1. from typing import TypeVar, Optional
  2. from typing_extensions import Protocol
  3.  
  4. class TreeLike(Protocol):
  5. value: int
  6.  
  7. @property
  8. def left(self) -> Optional['TreeLike']: ...
  9.  
  10. @property
  11. def right(self) -> Optional['TreeLike']: ...
  12.  
  13. class SimpleTree:
  14. def __init__(self, value: int) -> None:
  15. self.value = value
  16. self.left: Optional['SimpleTree'] = None
  17. self.right: Optional['SimpleTree'] = None
  18.  
  19. root: TreeLike = SimpleTree(0) # OK