Skip to content

Commit 9c05d3d

Browse files
authored
(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 <>
1 parent ba0e9d6 commit 9c05d3d

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

mypy/semanal.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2666,7 +2666,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool:
26662666
lookup = self.lookup(s.unanalyzed_type.name, s, suppress_errors=True)
26672667
if lookup and lookup.fullname in ("typing.TypeAlias", "typing_extensions.TypeAlias"):
26682668
pep_613 = True
2669-
if s.unanalyzed_type is not None and not pep_613:
2669+
if not pep_613 and s.unanalyzed_type is not None:
26702670
# Second rule: Explicit type (cls: Type[A] = A) always creates variable, not alias.
26712671
# unless using PEP 613 `cls: TypeAlias = A`
26722672
return False
@@ -2693,7 +2693,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool:
26932693
return False
26942694

26952695
non_global_scope = self.type or self.is_func_scope()
2696-
if isinstance(s.rvalue, RefExpr) and non_global_scope and not pep_613:
2696+
if not pep_613 and isinstance(s.rvalue, RefExpr) and non_global_scope:
26972697
# Fourth rule (special case): Non-subscripted right hand side creates a variable
26982698
# at class and function scopes. For example:
26992699
#
@@ -2706,7 +2706,7 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool:
27062706
# annotations (see the second rule).
27072707
return False
27082708
rvalue = s.rvalue
2709-
if not self.can_be_type_alias(rvalue) and not pep_613:
2709+
if not pep_613 and not self.can_be_type_alias(rvalue):
27102710
return False
27112711

27122712
if existing and not isinstance(existing.node, (PlaceholderNode, TypeAlias)):

0 commit comments

Comments
 (0)