79558395

Date: 2025-04-06 15:40:42
Score: 0.5
Natty:
Report link

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

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Anuraj_R