Use type hints/dedicated support to optimise for constants?

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
1 Like

Type hints should remain optional, (though they’re used by dataclasses and pydantic).
Using syntax for this would be a better idea. You could also use a soft keyword:

const CONST: str = "World"

Related previous thread:

That’s (related to) one of the goals of mypyc, mypy’s lesser known (and less developed) sibling.

One of the advantages of the specialising adaptive interpreter is that it actually doesn’t really need these sorts of hints, because it can detect this itself. The tier one interpreter first detects variables that haven’t changed and caches info to speed up further lookups. Then when tier 2’s JIT compiles, it will already convert those into constants, and then be able to optimise from there. I don’t think there are many optimisations using this yet, but there’s definitely plans. Importantly a lot of the constants you want to detect are going to be things like classes and functions.

2 Likes