For Standards Track; PEP 890 or any free in 8xx
Author: Aveyzan <aveyzan at gmail.com>
Created 20th August 2025
De facto almost every variable in Python is re-assignable, and sometimes we would want, as in JavaScript, to prevent this. JavaScript already offers it with the
const
keyword:
$k[const] $v[value] $o[=] $n[72];
$v[value] $o[=] $n[84]; // TypeError: Assignment to constant variable
In Python, especially in typing, there is special class
typing.Final
to prohibit variable re-assignment. Well,
PEP 591 doesn't work completely, it is only on need
for typing.
The closest to this approach in normal coding are presumably descriptors, or using
__setattr__()
and
__delattr__()
to emit an error,
for example: tuples and
enum.Enum class subclasses.
Because it is difficult to make a variable constant not being a class attribute, the
const
keyword would find place
only in classes... and their names would be assigned to
an internal attribute preferably being a tuple to make it work.
Syntax with the
const
keyword will be practically the same as in JavaScript, just without semicolon:
$k[const] <constant_name> $o[=] <value>
It is an error without the
=
operator. In C this would be equal to:
$k[const] <type/$k[auto]> <constant_name> $o[=] <value>;
and just like in JavaScript, attempt to re-assign a constant raises an error. Macro definition in C:
$o[#]$k[define] $con[PyAPI_Const]($p[name], $p[value]) $k[const] $p[name] $o[=] $p[value]
In C type of the value would be simply evaluated from Python's
type
class constructor as
type(value)
.