Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I create a constant in Python?
In Python, there's no built-in data type for constants like other programming languages. However, Python follows naming conventions and provides several approaches to create constants that signal to other developers that a value shouldn't be changed.
Built-in Constants in Python
Python has six built-in constants: False, True, None, NotImplemented, Ellipsis (...), and __debug__. These cannot be reassigned ?
# Trying to reassign a built-in constant raises SyntaxError
try:
False = 100
except SyntaxError as e:
print(f"Error: {e}")
File "<stdin>", line 2
False = 100
^^^^^
SyntaxError: cannot assign to False
Using Naming Conventions
According to PEP 8, constants should be written in ALL_CAPS with underscores separating words. This signals that the value shouldn't be changed ?
# Mathematical constants
PI = 3.14159
SPEED_OF_LIGHT = 299792458 # meters per second
GOLDEN_RATIO = 1.618
# Application constants
MAX_CONNECTIONS = 100
DEFAULT_TIMEOUT = 30
API_VERSION = "v1.2"
print(f"PI: {PI}")
print(f"Speed of Light: {SPEED_OF_LIGHT} m/s")
print(f"API Version: {API_VERSION}")
PI: 3.14159 Speed of Light: 299792458 m/s API Version: v1.2
Creating a Constants Module
For larger projects, create a separate module to store all constants. This keeps them organized and easily accessible ?
constants.py
# constants.py - Store all application constants # Mathematical constants PI = 3.141592653589793 E = 2.718281828459045 # Physics constants SPEED_OF_LIGHT_IN_VACUUM = 299792458 GRAVITATIONAL_CONSTANT = 6.67430e-11 # Application settings MAX_FILE_SIZE = 1024 * 1024 # 1 MB DEFAULT_PORT = 8080 DATABASE_URL = "localhost:5432"
main.py
import constants
# Calculate circle area
radius = 5
area = constants.PI * radius ** 2
print(f"Circle area: {area}")
# Display physics constant
print(f"Speed of light: {constants.SPEED_OF_LIGHT_IN_VACUUM} m/s")
# Use application settings
print(f"Server running on port: {constants.DEFAULT_PORT}")
Circle area: 78.53981633974483 Speed of light: 299792458 m/s Server running on port: 8080
Using Enum for Related Constants
For related constants, use the enum module for better organization and type safety ?
from enum import Enum
class Colors(Enum):
RED = "#FF0000"
GREEN = "#00FF00"
BLUE = "#0000FF"
class Status(Enum):
PENDING = 1
APPROVED = 2
REJECTED = 3
# Usage
print(f"Red color code: {Colors.RED.value}")
print(f"Status: {Status.APPROVED.name}")
Red color code: #FF0000 Status: APPROVED
Important Notes
Convention, Not Enforcement: Python's constant naming is purely by convention. Values can still be reassigned, but developers understand they shouldn't be changed.
Immutable Types: Use immutable types like strings, numbers, and tuples for constants. Avoid mutable types like lists or dictionaries.
Conclusion
Python creates constants using ALL_CAPS naming convention and modules for organization. While not enforced by the language, this approach clearly communicates intent to other developers and maintains code readability.
