Skip to content

Commit

Permalink
Speed up recursive type check (#14326)
Browse files Browse the repository at this point in the history
Use a faster type query visitor and reuse visitor across calls.

This should speed up type checking slightly. My measurements show a
~0.5% improvement, but it may be below the noise floor.
  • Loading branch information
JukkaL authored Dec 20, 2022
1 parent b5fc748 commit 7ed4f5e
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3321,17 +3321,22 @@ def has_type_vars(typ: Type) -> bool:
return typ.accept(HasTypeVars())


class HasRecursiveType(TypeQuery[bool]):
class HasRecursiveType(BoolTypeQuery):
def __init__(self) -> None:
super().__init__(any)
super().__init__(ANY_STRATEGY)

def visit_type_alias_type(self, t: TypeAliasType) -> bool:
return t.is_recursive or self.query_types(t.args)


# Use singleton since this is hot (note: call reset() before using)
_has_recursive_type: Final = HasRecursiveType()


def has_recursive_types(typ: Type) -> bool:
"""Check if a type contains any recursive aliases (recursively)."""
return typ.accept(HasRecursiveType())
_has_recursive_type.reset()
return typ.accept(_has_recursive_type)


def flatten_nested_unions(
Expand Down

0 comments on commit 7ed4f5e

Please sign in to comment.