Skip to content

[mypyc] Optimize TYPE_CHECKING to False at Runtime #16263

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -3705,3 +3705,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