pyright icon indicating copy to clipboard operation
pyright copied to clipboard

exponential slowdown when using `yield from` with type alias

Open pinterior opened this issue 1 year ago • 1 comments

Describe the bug

if multiple function use yield from with a type alias type, processing time grows almost exponentially with the number of such functions.

Code or Screenshots

#!/usr/bin/env python

from collections.abc import Iterator

class A[T]:
    def __iter__(self) -> Iterator[T]: ...

class B[T]:
    def __iter__(self) -> Iterator[T]: ...

type C[T] = A[T] | B[T]

def g() -> C[int | str]: ...

def f_0(): yield from g()
def f_1(): yield from g()
def f_2(): yield from g()
def f_3(): yield from g()
def f_4(): yield from g()
def f_5(): yield from g()
def f_6(): yield from g()
def f_7(): yield from g()
def f_8(): yield from g()
def f_9(): yield from g()
$ time pyright po.py
0 errors, 0 warnings, 0 informations

real    25m25.431s
user    25m24.261s
sys     0m3.227s
# of f_N seconds
5 8
6 29
7 98
8 278
9 711
10 1524

if g is declared as def g() -> A[int | str] | B[int | str]: ..., the problem does not occur.

VS Code extension or command-line

command-line tool, 1.1.407

pinterior avatar Oct 28 '25 12:10 pinterior

the problem seems to in the following:

  • UniqueNameMap.build: self recursion reaches recursionCount > maxTypeRecursionCount condition even when there is only a single f_0
  • Generator's first type argument (int | str): its typeAliasSources growing with repeated def f_N(): yield from g()

both can be fixed as follows, but I'm not sure whether this is the correct approach.

diff --git a/packages/pyright-internal/src/analyzer/typePrinter.ts b/packages/pyright-internal/src/analyzer/typePrinter.ts
index d57ba7521..29667913c 100644
--- a/packages/pyright-internal/src/analyzer/typePrinter.ts
+++ b/packages/pyright-internal/src/analyzer/typePrinter.ts
@@ -1494,9 +1505,10 @@ class UniqueNameMap {
             }
         }
 
+        if (recursionTypes.find((t) => t === type)) return;
+
         try {
             recursionTypes.push(type);
 
             switch (type.category) {
                 case TypeCategory.Function: {
                     type.shared.parameters.forEach((_, index) => {
diff --git a/packages/pyright-internal/src/analyzer/types.ts b/packages/pyright-internal/src/analyzer/types.ts
index 99fc9b0d3..50639b4e0 100644
--- a/packages/pyright-internal/src/analyzer/types.ts
+++ b/packages/pyright-internal/src/analyzer/types.ts
@@ -2847,7 +2847,9 @@ export namespace UnionType {
                 }
 
                 sourcesToAdd.forEach((source) => {
-                    unionType.priv.typeAliasSources!.add(source);
+                    if ([...unionType.priv.typeAliasSources!].every(t => !isTypeSame(t, source))) {
+                        unionType.priv.typeAliasSources!.add(source);
+                    }
                 });
             }
         }

pinterior avatar Sep 22 '26 09:09 pinterior