Adding constant variables

In many other languages, you can create a constant variable, one that does not change, typically using const or constant. In Python, it is common for the name of constants to use an uppercase name (PI = 3.14 for example), but these are still changeable. I wouldn’t know, since I haven’t gone too deep with the C behind Python, but it shouldn’t be hard to implement, or you could add a const keyword to explicitly state the fact that a variable is constant.

EDIT:
I came up with a base idea for how it would work:

class Constant:
  def __init__(self, value):
    self.__value = value
  
  @property
  def value(self):
    return self.__value

pi = Constant(3.141592653589793)
pi.value += 1 # AttributeError: can't set attribute 'value'

There is typing.Final,

from typing import Final

PI: Final[float] = 3.14159
PI += 1   # Error in type checker.

but, as with anything from typing, it’s not enforced in runtime.

6 Likes

Oh, I did not know that. I don’t do a while lot with typing, so I’ll keep that in mind for when I do.

NOTE:

This has come up a lot in the past – see the archives of the python-ideas list for discussion.

This is a standard practice for making no-writable attributes, but it doesn’t help this problem at all. In the above the name pi is bound to an instance of your Constant type – but there is nothing at all that would prevent the name pi from bering rebound to another name.

Python already has immutable types (numbers, strings, tuples…) – so if you set, e.g. pi to a value, that value will never change, but the name can get rebound regardless.

On the other hand, if Python did have a “constant” – then the name could not be rebound, but the value it’s bound to, if mutable, could be mutated.

Anyway, make sure you “get” what name binding and immutability are on Python before going to much further with this discussion :slight_smile: