Skip to content

Advice for type checking Unions of recursively defined TypedDicts #9362

Answered by erictraut
clause asked this question in Q&A
Discussion options

You must be logged in to vote

Recursive nodes require a static type checker to employ bidirectional type inference to infer a result that is compatible with the return type (Core). When the "expected type" for bidirectional type inference involves a union, it succeeds only if the expression can be evaluated using one of the subtypes of the union. Your code is creating a situation where the expression must evaluate to more than one subtype.

def func(t1: Literal["+"], t2: Literal["+", "-"]):
    # This works because the dictionary expression evaluates
    # to `Add[Core, Core]`, which is one of the subtypes of the
    # expected type union.
    x1: Add[Core, Core] | Subtract[Core, Core] = {
        "tag": t1,
        "o…

Replies: 1 comment 3 replies

Comment options

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

@erictraut
Comment options

@clause
Comment options

Answer selected by clause
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants