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.

7 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:

forum.micropython.org/viewtopic.php?t=450#p2555 recommends lambda:

const = lambda x: x
CONST = const(0)

Considering the myriad implementations, does anyone know what prevents this being added? I ask because the answers to the undermentioned, and their comments, are frequently contradictory: [1]


  1. stackoverflow.com/questions/17291791/why-no-const-in-python#comment62211014_17292194 ↩︎

I don’t see how a lambda solves the problem:

const = lambda x: x
CONST = const(0)

# ... later ...

CONST = 17

It’s just an overly complicated way to write CONST = 0.

3 Likes

It doesn’t do anything. The thread linked to is talking about Micropython, which (apparently - I haven’t looked into it) has an actual feature of constants. The lambda function makes the syntax const(1) behave correctly in other Python implementations, but without any actual constness.

This simply isn’t a feature of CPython, so you won’t get it in any way. The best way to go about it would be with an external tool, and as has been mentioned, type checkers are capable of doing this for you.

2 Likes