Skip to content

Commit dce8e1c

Browse files
[mypyc] fix: inappropriate Nones in f-strings (#19846)
if a variable is Final but the value is not yet known at compile-time, and that variable is used as an input to an f-string, the f-string will incorrectly contain "None" Fixes [mypyc#1140](mypyc/mypyc#1140)
1 parent 73affc0 commit dce8e1c

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

mypyc/irbuild/specialize.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -719,7 +719,9 @@ def get_literal_str(expr: Expression) -> str | None:
719719
if isinstance(expr, StrExpr):
720720
return expr.value
721721
elif isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_final:
722-
return str(expr.node.final_value)
722+
final_value = expr.node.final_value
723+
if final_value is not None:
724+
return str(final_value)
723725
return None
724726

725727
for i in range(len(exprs) - 1):

mypyc/test-data/run-strings.test

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,9 +412,16 @@ def test_basics() -> None:
412412
[case testFStrings]
413413
import decimal
414414
from datetime import datetime
415+
from typing import Final
415416

416417
var = 'mypyc'
417418
num = 20
419+
final_known_at_compile_time: Final = 'hello'
420+
421+
def final_value_setter() -> str:
422+
return 'goodbye'
423+
424+
final_unknown_at_compile_time: Final = final_value_setter()
418425

419426
def test_fstring_basics() -> None:
420427
assert f'Hello {var}, this is a test' == "Hello mypyc, this is a test"
@@ -451,6 +458,8 @@ def test_fstring_basics() -> None:
451458
inf_num = float('inf')
452459
assert f'{nan_num}, {inf_num}' == 'nan, inf'
453460

461+
assert f'{final_known_at_compile_time} {final_unknown_at_compile_time}' == 'hello goodbye'
462+
454463
# F-strings would be translated into ''.join[string literals, format method call, ...] in mypy AST.
455464
# Currently we are using a str.join specializer for f-string speed up. We might not cover all cases
456465
# and the rest ones should fall back to a normal str.join method call.

0 commit comments

Comments
 (0)