From 38fbf14b1280733a6ac6ccb8d3f1c7e58201cdee Mon Sep 17 00:00:00 2001 From: RenChu Wang Date: Sun, 21 Jul 2024 21:03:26 -0700 Subject: [PATCH] =?UTF-8?q?=E2=8F=A9=20Forward=20reference=20in=20type=20b?= =?UTF-8?q?ound=20works.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This particular pattern can be useful in node type declaration. --- python/src/self.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 python/src/self.py diff --git a/python/src/self.py b/python/src/self.py new file mode 100644 index 0000000..342ada9 --- /dev/null +++ b/python/src/self.py @@ -0,0 +1,18 @@ +# Copyright (c) 2024 RenChu Wang - All Rights Reserved + +import abc +from collections.abc import Sequence +from typing import Protocol, TypeVar + +T = TypeVar("T", bound="HasChildren", covariant=True) + + +class HasChildren(Protocol[T]): + @abc.abstractmethod + def children(self) -> Sequence[T]: ... + + +class HasSelfAsChildren(HasChildren["HasSelfAsChildren"]): + # It does autocomplete. Seems fine. + def children(self) -> Sequence["HasSelfAsChildren"]: + return []