Skip to content

Expression dependant generic types #840

Answered by plannigan
plannigan asked this question in Q&A
Discussion options

You must be logged in to vote

Thanks to @sobolevn's comment, I was able to come up with the answer I was looking for. The key is to annotate the self argument to the chain() method, despite that rarely being necessary. The following code say that for a call to chain() to be valid _Return_T == Tree[_Child_U], but does not require that all Transformers produce a Tree.

from typing import Generic, List, TypeVar, Union

_Child_T = TypeVar("_Child_T")
_Child_U = TypeVar("_Child_U")
_Return_T = TypeVar("_Return_T")
_Return_V = TypeVar("_Return_V")


class Tree(Generic[_Child_T]):
    children: "List[Union[Tree[_Child_T], _Child_T]]"


class Transformer(Generic[_Child_T, _Return_T]):
    def transform(self, tree: Tree[_Child_T]…

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
3 replies
@plannigan
Comment options

@sobolevn
Comment options

@plannigan
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by plannigan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants