Introduction

In Python, we often use variables to store data that can be changed over the course of our program. However, there are cases where we want to define values that should never be modified - these are known as constants. Constants are useful for defining values that shouldn’t change, such as mathematical constants or configuration settings for a program.

Python doesn’t have a built-in way to define constants, but there are several approaches you can use to create values that can’t be modified. In this post, we’ll explore some of the most common techniques for creating constant values in Python. Whether you’re a beginner or an experienced Python developer, understanding how to declare constants can help you write more maintainable and reliable code.

Solutions

Private property

In Python, private properties can be used to define a constant value because they cannot be modified from outside the class, which helps ensure that the value remains constant throughout the program.

When you define a private property in Python, you prefix its name with two underscores (e.g., __my_private_property). This tells Python to name-mangle the property, which means that it is stored with a name that includes the class name to prevent collisions with properties of the same name in other classes.

Here’s an example of how you can define a constant using a private variable in Python:

1
2
3
4
5
6
7
8
9
10
11
class Constants:
_MY_CONSTANT = 42

@property
def MY_CONSTANT(self):
return self._MY_CONSTANT

# Usage:
c = Constants()
print(c.MY_CONSTANT) # Output: 42
c.MY_CONSTANT = 43 # Raises an AttributeError: can't set attribute

In this example, we define a class called Constants that contains a private variable _MY_CONSTANT with a value of 42. We use the @property decorator to define a getter method called MY_CONSTANT that returns the value of _MY_CONSTANT.

Note that the _MY_CONSTANT variable is private, which means it’s not meant to be accessed directly from outside the class. Instead, we access the constant value using the getter method MY_CONSTANT, which can be called like any other instance method.

Also, note that trying to set the value of MY_CONSTANT directly will raise an AttributeError because the getter method only returns the value of _MY_CONSTANT, and doesn’t allow you to modify it. This ensures that the value of the constant remains unchanged throughout the program.

Singleton pattern

The Singleton pattern can be used to define a constant value in Python because it ensures that only one instance of a class can exist at any given time. By creating a Singleton class with a private variable that represents the constant value, we can ensure that the value remains consistent throughout the program.

Here’s an example of using the Singleton pattern to define a constant value in Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Singleton:
__instance = None

def __init__(self):
if Singleton.__instance is None:
Singleton.__instance = self
self._MY_CONSTANT = 42

@property
def MY_CONSTANT(self):
return self._MY_CONSTANT

# Usage:
s1 = Singleton()
print(s1.MY_CONSTANT) # Output: 42
s2 = Singleton()
print(s2.MY_CONSTANT) # Output: 42 (same instance as s1)
s1.MY_CONSTANT = 43 # Doesn't raise an error, but won't change the value
print(s2.MY_CONSTANT) # Output: 42 (unchanged)

In this example, we define a class called Singleton that uses the Singleton pattern to ensure that only one instance of the class can exist at any given time. We define a private variable _MY_CONSTANT with a value of 42, and use a getter method called MY_CONSTANT to access its value.

When we create a new instance of Singleton using s1 = Singleton(), the __init__() method checks if an instance of the class already exists. If it does not, it creates a new instance and initializes the private variable _MY_CONSTANT to 42. When we create a second instance of Singleton using s2 = Singleton(), it returns the same instance as s1 because the __init__() method determines that an instance of the class already exists.

Note that even though we can access _MY_CONSTANT from outside the class using the MY_CONSTANT getter method, we can’t modify its value. This is because _MY_CONSTANT is a private variable, and cannot be accessed directly from outside the class. Additionally, since the Singleton pattern ensures that only one instance of the class exists, any changes to _MY_CONSTANT made by one instance will be reflected in all other instances.

Read-only property

In Python, read-only properties can be used to define a constant value because they provide a way to access a value that cannot be modified from outside the class.

When you define a read-only property in Python, you are creating a property that can be read like any other property, but cannot be written to. This means that once you set the value of a read-only property, you cannot modify it. If you try to modify the value of a read-only property, Python will raise an exception.

To define read-only properties in Python, you can use the @property decorator and the @<property name>.setter decorator. Here’s an example:

Here’s an example of how you can define a constant value with a read-only property in Python:

1
2
3
4
5
6
7
8
9
10
11
class MyClass:
def __init__(self):
self._my_property = 42

@property
def my_property(self):
return self._my_property

@my_property.setter
def my_property(self, value):
raise AttributeError("my_property is read-only")

In this example, we define a class MyClass with a read-only property my_property. We start by initializing the value of _my_property to 42 in the constructor.

We then define a getter method for my_property using the @property decorator. This getter simply returns the value of _my_property.

Next, we define a setter method for my_property using the @my_property.setter decorator. This setter raises an AttributeError whenever an attempt is made to set the value of my_property, effectively making it read-only.

To use this class, we can create an instance of MyClass and access the value of my_property using the . notation, like this:

1
2
3
obj = MyClass()
print(obj.my_property) # Output: 42
obj.my_property = 100 # Raises AttributeError: my_property is read-only

Conclusion

In conclusion, there are several ways to define a constant value in Python, including using private properties, the singleton pattern, and read-only properties. Private properties are a good choice when you want to define a constant value within a class and make sure that it cannot be accessed or modified from outside the class. The singleton pattern is a good choice when you want to define a constant value that is globally accessible and only needs to be created once. Read-only properties are a good choice when you want to define a constant value that can be accessed from outside the class, but cannot be modified. By using these techniques, you can define constant values in Python that are easy to use, maintain, and understand.