Python Constants
In Python, constants are typically variables that hold fixed values, and their values cannot be changed during the execution of a program. Although Python doesn’t have a built-in constant type, developers often use variables with uppercase names to represent constants as a convention. By convention, these variables are not meant to be modified after their initial assignment.
Here’s an example of defining constants in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Define constants PI = 3.14159 GRAVITY = 9.81 MAX_CONNECTIONS = 100 DEFAULT_TIMEOUT = 10 # Using constants radius = 5 area = PI * radius * radius print(area) # Attempting to change a constant will result in an error (although it's just a convention, not enforced by the language) PI = 3.14 # This will raise an error since PI is a constant and should not be reassigned. |
Keep in mind that Python doesn’t have a built-in mechanism to enforce constant behavior. The uppercase naming convention is just a way to indicate to other developers that the variable’s value is not meant to be changed. If someone ignores the convention and reassigns the value of a “constant,” Python won’t prevent it.
However, if you want to enforce immutability strictly, Python has a module called enum
(since Python 3.4) that allows you to create enumerations with constant values. Enumerations are immutable, and they are treated as constants in practice.
Here’s an example using an enumeration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from enum import Enum class Constants(Enum): PI = 3.14159 GRAVITY = 9.81 MAX_CONNECTIONS = 100 DEFAULT_TIMEOUT = 10 # Using an enumeration constant radius = 5 area = Constants.PI.value * radius * radius print(area) # Attempting to change a constant (enum) will result in an error Constants.PI = 3.14 # This will raise an error since enums are immutable. |
Using the enum
module is a more robust way to define constants and enforce their immutability, but it’s not as widely used as the uppercase naming convention.