Python Constants

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)

Try It Now

🚨 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)

Try It Now

🔹 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

Try It Now

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.