DEV Community

Anuraj R
Anuraj R

Posted on

Python Doesn’t Have True Constants—So I Built setconstant

If you’ve ever worked with languages like C or Java, you know the value of constants—those fixed values that should never change. They help keep code clean, prevent accidental modifications, and make debugging easier.

But here’s the thing: Python doesn’t have built-in constants.

There’s no const keyword, and nothing stops you (or your teammates) from accidentally reassigning an important value. That’s fine for some use cases, but sometimes you need immutability.

So, I built setconstant—a lightweight Python package that finally brings real constants to Python. No more accidental overwrites. No more scattered hardcoded values. Just clean, immutable constants, the way they should be.

Why setconstant?

Sure, Python developers pretend to have constants by writing variables in ALL_CAPS. But let’s be honest—that doesn’t actually prevent changes. setconstant fixes that by introducing true immutability into your Python projects.

Key Features:

-> Define Constants Easily – Create integers, floats, or strings in seconds.
-> Immutability – Once set, a constant cannot be changed or reassigned.
-> Simple – No complex setup—just import and use.
-> Error Handling – Get instant feedback if you try to redefine a constant.

How It Works

Let’s jump right in with a quick example:

import setconstant

Defining constants

setconstant.const_i("PI", 3)
setconstant.const_f("GRAVITY", 9.81)
setconstant.const_s("APP_NAME", "CodeHaven")

Accessing constants

print(setconstant.get_constant("PI")) # Output: 3
print(setconstant.get_constant("GRAVITY")) # Output: 9.81
print(setconstant.get_constant("APP_NAME")) # Output: CodeHaven

Attempting to change a constant raises an error

setconstant.const_i("PI", 4) # Raises ValueError_

That’s it! Define a constant once, and Python won’t let you modify it later. If you try, setconstant will throw an error—saving you from unexpected bugs.

Why You’ll Love It

-> No More Accidental Changes – Your constants stay truly constant.
-> Cleaner, More Organized Code – No more magic numbers scattered everywhere.
-> Better Error Handling – If something goes wrong, you’ll know immediately.

Installation

Start using setconstant in seconds:

pip install setconstant

Once installed, just import it and start defining constants in your Python projects.

*Try It & Share Your Thoughts
*

I built setconstant to fix a gap in Python, and I’d love for you to try it out. Whether you're working on a small script or a large-scale application, true constants can make your life easier.

What do you think? Would you find this useful in your projects? Let me know in the comments.

Happy coding!
Anuraj R

Top comments (0)