From 9c05d3d19de74fc10a51aa5b663e6a38bc6abc73 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Wed, 5 Jan 2022 01:44:28 -0600 Subject: [PATCH] (minor) Short circuit call to `can_be_type_alias` when using PEP 613 (#11904) 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. Co-authored-by: hauntsaninja <> --- mypy/semanal.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mypy/semanal.py b/mypy/semanal.py index 29dfc96c24229..933ba54c358f6 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)):