A constant is a variable whose value should not change during program execution. Unlike other languages, Python does not enforce constants, but by convention, we use uppercase letters.
Defining Constants in Python
PI = 3.14159 GRAVITY = 9.8 APP_NAME = "My Python App" print(PI, GRAVITY, APP_NAME)
๐จ Python does not prevent changes to constants, but it is a good practice not to modify them.
Using a Class to Define Constants
class Constants: PI = 3.14159 GRAVITY = 9.8 SPEED_OF_LIGHT = 299792458 print(Constants.PI)
๐น This helps group related constants together.
Using a Separate File (constants.py
)
โ
Step 1: Create constants.py
PI = 3.14159 GRAVITY = 9.8
โ Step 2: Import and Use
import constants print(constants.PI) # Output: 3.14159 print(constants.GRAVITY) # Output: 9.8
This approach keeps the main code clean and organized.
Best Practices for Constants
โ Use UPPERCASE letters (APP_VERSION = "1.0.0"
).
โ Store constants in a separate module (constants.py
).
โ Use dataclass(frozen=True) or namedtuple for true immutability.
โ Never modify constants after defining them.