How do I declare python constants in Python?
In Java, we declare constants like this:
public static final String CONST_NAME = "Name";
How can I do something similar in Python to create a constant?
How do I declare python constants in Python?
In Java, we declare constants like this:
public static final String CONST_NAME = "Name";
How can I do something similar in Python to create a constant?
Ah, this is a classic question when transitioning to Python! Python doesn’t enforce immutability for constants like Java does. Instead, it’s all about convention. By convention, developers use uppercase variable names to signal that a value should be treated as constant.
While this doesn’t prevent someone from reassigning the variable (Python doesn’t have built-in constant types), it serves as a clear visual cue to others working on the code.
Example:
MY_CONSTANT = 10
Simple and effective!
Great point, Ian! If you’re looking for something more robust than a naming convention to mimic true immutability, you might consider using collections.namedtuple
. Namedtuples are immutable by nature, so once you set their values, they can’t be altered.
Here’s how you can use it to define python constants:
from collections import namedtuple
Constants = namedtuple('Constants', ['MY_CONSTANT'])
constants = Constants(MY_CONSTANT=10)
print(constants.MY_CONSTANT)
This approach adds an extra layer of safety by making the value immutable.
These are both solid approaches, but if you’re working with a set of constants and want to make the whole structure immutable, Python has another tool: types.MappingProxyType
. It’s like a read-only dictionary. You can use it to store multiple python constants in a single, immutable dictionary-like structure.
Here’s an example:
from types import MappingProxyType
constants = MappingProxyType({'MY_CONSTANT': 10})
print(constants['MY_CONSTANT'])
# Attempting to modify this will raise a TypeError:
# constants['MY_CONSTANT'] = 20
This is great when you have a group of constants and want a completely read-only view.