Would it be possible for the compiler to make use of type hints, such as Final
, to perform some optimisations? For example, consider this snippet
import typing as t
CONST: t.Final[str] = "World"
print(f"Hello, {CONST}!")
The bytecode generated by Python 3.13 is
5 LOAD_NAME 6 (print)
PUSH_NULL
LOAD_CONST 4 ('Hello, ')
LOAD_NAME 2 (CONST)
FORMAT_SIMPLE
LOAD_CONST 5 ('!')
BUILD_STRING 3
CALL 1
POP_TOP
RETURN_CONST 1 (None)
which shows how the interpreter will effectively perform a string formatting at runtime, instead of compile-time.
I appreciate a type hint is just a hint, so if that would be a problem (one potential problem is that the expression on the RHS would have to be a literal, with at most references to other constants), perhaps there could be outright support for final values in the compiler itself, with dedicated syntax to declare a “variable” as final (i.e. a constant) and related exceptions:
class FinalAssignmentError(SyntaxError):
...
CONST ::= "World" # Inferred type is Final[str]
CONST = "Hello" # raises FinalAssignmentError