In Python, constants are variables whose values are intended to remain unchanged throughout a program. They are typically defined using uppercase letters to signify their fixed nature, often with words separated by underscores (e.g., MAX_LIMIT).
Let's understand with the help of example:
# Mathematical constant
PI = 3.14159
# Acceleration due to gravity
GRAVITY = 9.8
print(PI)
print(GRAVITY)
Output
3.14159 9.8
Table of Content
Rules while declaring a Constant
- Python constant and variable names can include:
- Lowercase letters (a-z)
- Uppercase letters (A-Z)
- Digits (0-9)
- Underscores (_)
- Naming rules for constants:
- Use UPPERCASE letters for constant names (e.g.,
CONSTANT = 65). - Do not start a constant name with a digit.
- Only the underscore (_) is allowed as a special character; other characters (e.g., !, #, ^, @, $) are not permitted.
- Use UPPERCASE letters for constant names (e.g.,
- Best practices for naming constants:
- Use meaningful and descriptive names (e.g.,
VALUEinstead ofV) to make the code clearer and easier to understand.
- Use meaningful and descriptive names (e.g.,
Example of Constant
There are multiple use of constants here are some of the examples:
1. Mathematical Constant:
PI = 3.14159
E = 2.71828
GRAVITY = 9.8
2. Configuration settings:
MAX_CONNECTIONS = 1000
TIMEOUT = 15
3. UI Color Constants:
BACKGROUND_COLOR = "#FFFFFF"
TEXT_COLOR = "#000000"
BUTTON_COLOR = "#FF5733"
These examples are valid and align with the described naming conventions.
How to create immutable constants?
The example using namedtuple is correct and demonstrates how to create immutable constants. Here's why this works:
- A namedtuple creates a lightweight, immutable object where fields can be accessed like attributes.
- While you can access values using constants.PI, you cannot modify them.
from collections import namedtuple
Constants = namedtuple('Constants', ['PI', 'GRAVITY'])
constants = Constants(PI=3.14159, GRAVITY=9.8)
# constants.PI = 3.14
print(constants.PI)
Output
3.14159