From b5b4ad19365d9ffce7cc6e1e708ffa81de937fd9 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Tue, 4 Jan 2022 23:14:36 -0800 Subject: [PATCH] (minor) Short circuit call to `can_be_type_alias` when using PEP 613 When debugging #11887 I realised `can_be_type_alias` can do non-trivial amounts of work. It's unlikely to ever show up on a profile, but reordering the check means we do less work. Changed the order of some other checks for consistency. --- mypy/semanal.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mypy/semanal.py b/mypy/semanal.py index 29dfc96c2422..933ba54c358f 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -2666,7 +2666,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: lookup = self.lookup(s.unanalyzed_type.name, s, suppress_errors=True) if lookup and lookup.fullname in ("typing.TypeAlias", "typing_extensions.TypeAlias"): pep_613 = True - if s.unanalyzed_type is not None and not pep_613: + if not pep_613 and s.unanalyzed_type is not None: # Second rule: Explicit type (cls: Type[A] = A) always creates variable, not alias. # unless using PEP 613 `cls: TypeAlias = A` return False @@ -2693,7 +2693,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: return False non_global_scope = self.type or self.is_func_scope() - if isinstance(s.rvalue, RefExpr) and non_global_scope and not pep_613: + if not pep_613 and isinstance(s.rvalue, RefExpr) and non_global_scope: # Fourth rule (special case): Non-subscripted right hand side creates a variable # at class and function scopes. For example: # @@ -2706,7 +2706,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: # annotations (see the second rule). return False rvalue = s.rvalue - if not self.can_be_type_alias(rvalue) and not pep_613: + if not pep_613 and not self.can_be_type_alias(rvalue): return False if existing and not isinstance(existing.node, (PlaceholderNode, TypeAlias)):