Skip to content

Commit

Permalink
(minor) Short circuit call to can_be_type_alias when using PEP 613
Browse files Browse the repository at this point in the history
When debugging python#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.
  • Loading branch information
hauntsaninja committed Jan 5, 2022
1 parent b0c4461 commit b5b4ad1
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
#
Expand All @@ -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)):
Expand Down

0 comments on commit b5b4ad1

Please sign in to comment.