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

Try It Now

โœ… 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.