I'm attempting to use real constants in Python—values which cannot be modified once defined.
I realize Python has no native support for constants like certain other languages (e.g., final in Java or const in C++), but I want the most Pythonic or safest manner of achieving this behavior.
class Constants:
PI = 3.14159
GRAVITY = 9.8
Constants.PI = 3 # This still allows reassignment
I want something that raises an error or prevents the value from being changed. I’ve also heard of using custom classes or metaclasses, but I’m not sure what the best practice is.
What’s the best way to implement unchangeable constants in Python?
You're correct—Python natively supports neither true constants like C, C++, nor Java. There is no const keyword, and even the hack of creating variables in all caps (PI = 3.14) is completely dependent on developer discipline.
Although workarounds such as metaclasses or special classes can be used to mimic immutability, none are able to prevent reassignment at the module level, or prevent an astute user from simply overwriting your values.
Therefore, I created something that does.
Introducing setconstant: Immutability in Python Constants
Python is not immutable, and that can have unintended value mutations—particularly in big codebases. So I made setconstant, a light Python package allowing you to define true constants that cannot be mutated after declaration.
How It Works
import setconstant
setconstant.const_i("PI", 3)
setconstant.const_f("GRAVITY", 9.81)
setconstant.const_s("APP_NAME", "CodeHaven")
print(setconstant.get_constant("PI")) # Output: 3
print(setconstant.get_constant("GRAVITY")) # Output: 9.81
print(setconstant.get_constant("APP_NAME")) # Output: CodeHaven
# Try to change the value
Once declared, constants are locked. Any attempt to overwrite them throws a ValueError, protecting your code from bugs or unintended logic changes.
Why Not Just Use a Class or Metaclass?
class Constants:
PI = 3.14
def __setattr__(self, name, value):
raise AttributeError("Cannot reassign constants")
Or even using metaclasses like:
class ConstantMeta(type):
def __setattr__(cls, name, value):
if name in cls.__dict__:
raise AttributeError(f"Cannot modify '{name}'")
super().__setattr__(name, value)
But these solutions have their limitations:
They can be circumvented with sufficient effort.
They are not intuitive to beginners.
They need boilerplate or more advanced Python functionality such as metaclasses.
setconstant circumvents that. It's simple, strict, and does what constants are supposed to do.
Installation
pip install setconstant
Feedback is always welcome!
Anuraj R, Creator of setconstant