Skip to content

Commit

Permalink
[mypyc] Optimize TYPE_CHECKING to False at Runtime (#16263)
Browse files Browse the repository at this point in the history
Fixes [mypyc/mypyc#902](mypyc/mypyc#902)

This PR finds references of `typing.TYPE_CHECKING` or
`typing_extensions.TYPE_CHECKING` and optimizes them to `False` in
mypyc.
  • Loading branch information
srilman authored Feb 28, 2024
1 parent a91151c commit 5a8cd80
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
6 changes: 6 additions & 0 deletions mypyc/irbuild/expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ def transform_name_expr(builder: IRBuilder, expr: NameExpr) -> Value:
return builder.true()
if fullname == "builtins.False":
return builder.false()
if fullname in ("typing.TYPE_CHECKING", "typing_extensions.TYPE_CHECKING"):
return builder.false()

math_literal = transform_math_literal(builder, fullname)
if math_literal is not None:
Expand Down Expand Up @@ -185,6 +187,10 @@ def transform_name_expr(builder: IRBuilder, expr: NameExpr) -> Value:


def transform_member_expr(builder: IRBuilder, expr: MemberExpr) -> Value:
# Special Cases
if expr.fullname in ("typing.TYPE_CHECKING", "typing_extensions.TYPE_CHECKING"):
return builder.false()

# First check if this is maybe a final attribute.
final = builder.get_final_ref(expr)
if final is not None:
Expand Down
30 changes: 30 additions & 0 deletions mypyc/test-data/irbuild-basic.test
Original file line number Diff line number Diff line change
Expand Up @@ -3688,3 +3688,33 @@ def f(arg):
arg :: __main__.A
L0:
return arg

[case testTypeCheckingFlag]
from typing import TYPE_CHECKING, List

def f(arg: List[int]) -> int:
if TYPE_CHECKING:
from collections.abc import Sized
s: Sized = arg
return len(s)

[out]
def f(arg):
arg :: list
r0 :: bool
r1 :: int
r2 :: bit
s :: object
r3 :: int
L0:
r0 = 0 << 1
r1 = extend r0: builtins.bool to builtins.int
r2 = r1 != 0
if r2 goto L1 else goto L2 :: bool
L1:
goto L3
L2:
L3:
s = arg
r3 = CPyObject_Size(s)
return r3

0 comments on commit 5a8cd80

Please sign in to comment.