In programming, a constant is a value that remains unchanged throughout the execution of a program. Constants improve code readability, maintainability, and reduce the chances of accidental modifications. Unlike some programming languages, such as C, C++, and Java, Python does not have built-in support for true constants. However, Python developers follow certain conventions to represent constant values. This article explains constants in Python, their characteristics, declaration methods, types, and best practices.
Table of Contents
What are Constants?
A constant is a variable whose value is intended to remain fixed during program execution. Once assigned, it should not be changed. Constants are used to store fixed values such as API keys, database URLs, or mathematical constants like pi, or other data that should not be modified.
1. Stores Fixed Values: The primary characteristic of a constant is that it stores a value that is intended to remain unchanged throughout the execution of a program. Constants are used for values that should stay the same, such as mathematical constants, tax rates, or configuration values.2. Naming Convention: The most defining characteristic of a Python constant is that it exists by convention rather than compulsion. Python does not have a built-in const keyword. Therefore:
- Developers use PEP 8 style guidelines to indicate a constant.
- Constants are written in ALL CAPS with underscores separating words (e.g., MAX_CONNECTIONS, PI).
- This tells other developers, "This value should not be changed," even though the Python interpreter will perfectly allow a change.
3. Global Scope Placement: Constants are typically defined at the module level (at the very top of a Python file, outside of any functions or classes). This makes them easily accessible throughout the entire script or to be imported into other files as configuration values.
4. Dynamic Re-assignability: Because Python lacks true language-level enforcement for constants, they behave exactly like normal variables under the hood.
Example:
# Intended as a constant
TOTAL_RETRY_LIMIT = 3
# Python allows this change without any runtime errors or warnings
TOTAL_RETRY_LIMIT = 10
Unless you use external tools, Python will not crash or throw an error if a constant is overwritten during execution.
5. Storage of Literal Values: Python constants are usually assigned to immutable literal values (like integers, floats, strings, or tuples). Assigning a constant to a mutable object like a list or a dictionary can be misleading:
Example:
# The reference cannot be safely called "constant" if the contents change
ALLOWED_ROLES = ["admin", "editor", "viewer"]
ALLOWED_ROLES.append("hacker") # The list changed!
Creating Constants in Python
1. Using Uppercase Variable Names: The simplest and most widely accepted method of creating constants in Python is to write the variable name in uppercase letters. This follows the PEP 8 style guide, which recommends using uppercase names for values that should not change.Although Python does not prevent modification, uppercase names serve as a clear warning to programmers that the value should remain constant.
Example:
# Python program for Calculating the Area of a Circle
# Constant value
PI = 3.14159
radius = 7
area = PI * radius * radius
print("Radius:", radius)
print("Area:", area)
Output:
Explanation:Radius: 7
Area: 153.93791
- PI = 3.14159 creates a constant named PI that stores the mathematical value of pi.
- radius = 7 stores the radius of the circle.
- area = PI * radius * radius uses the constant PI to calculate the area using the formula
- print(area) displays the calculated area.
2. Using a Separate Constants Module: In large applications, constants are often stored in a separate Python file (module). This allows all parts of the program to access the same constant values without repeating them.
If a constant needs to be updated, it only needs to be changed in one place.
Example:
Step 1: Create constants.py
# Python file containing all constants SCHOOL_NAME = "ABC Public School" PASS_MARK = 40 MAX_STUDENTS = 500Step 2: Create main.py
# Python program for displaying school results
# using constant from another file
import constants
marks = 40
print("School:", constants.SCHOOL_NAME)
if marks == constants.PASS_MARK:
print("Result: Pass")
else:
print("Result: Fail")
Output:
Explanation:School: ABC Public School
Result: Pass
- In constants.py file, fixed values are stored once: SCHOOL_NAME = "ABC Public School", PASS_MARK = 40, MAX_STUDENTS = 500
- main.py file, import constants, Imports all constants from the module.
- constants.PASS_MARK accesses the constant stored in another file.
Example:
# Python program to create constants using frozen data class
from dataclasses import dataclass
@dataclass(frozen=True)
class AppConfig:
APP_NAME: str = "Student Portal"
VERSION: str = "1.0"
MAX_USERS: int = 1000
config = AppConfig()
print(config.APP_NAME)
print(config.VERSION)
print(config.MAX_USERS)
Output:
Explanation:Student Portal
1.0
1000
- @dataclass(frozen=True) creates an immutable data class.
- config = AppConfig() creates an instance containing the constant values.
- Accessing values using print(config.APP_NAME)
Attempting to modify an attribute like: config.MAX_USERS = 2000 raises an error: dataclasses.FrozenInstanceError: cannot assign to field 'MAX_USERS' because the data class is frozen.
Types of Constants in Python(IMAGE MENTIONING ALL TYPES OF CONSTANTS)
In Python, constants can be categorized based on the type of value they store. The major types of constants in Python are:1. Numeric Constants: Numeric constants are fixed numerical values used in a program. They can be integers, floating-point numbers, or complex numbers.
- Integer Constants: Integer constants are whole numbers without a decimal point. For example, MIN_AGE = 18, MAX_USERS = 100
- Floating-Point Constants: Floating-point constants contain decimal values. For example: PI = 3.14, PRICE = 90.80
- Complex Constants: Complex constants contain real and imaginary parts. For example, COMPLEX_NUMBER = 1 + 2j
Example:
3. Boolean Constants: Boolean constants represent logical values. Python has only two Boolean constants:COUNTRY = "India"
COMPANY_NAME = 'TutorialforGeeks'
ADDRESS = ''' Knowledge Park
Greater Noida,
Gautam Buddha Nagar,
Uttar Pradesh '''
- True: True represents a Boolean value that indicates a condition has been satisfied or an expression evaluates to true.
- False: False represents a Boolean value that indicates a condition has not been satisfied or an expression evaluates to false.
4. Special Constants: Special constants have predefined meanings in Python. Special constant None represents the absence of a value.IS_ADMIN = True
IS_VERIFIED = False
Example:
5. Collection Constants: Collection constants store groups of fixed values. Since lists, dictionaries, and sets are mutable, Python programmers generally use immutable collections as constants.RESULT = None
USER_DATA = None
- Tuple Constants: Tuples are immutable sequences. They cannot be modified after creation. That's why they are commonly used to store fixed collections. For example: WEEK_DAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
- Frozen Set Constants: A frozenset is an immutable set. In a frozenset, elements cannot be added or removed after initialization. It is useful when storing fixed groups of unique values. For example: VOWELS = frozenset({'a', 'e', 'i', 'o', 'u'})
Advantages of Using Constants in Python
- Improves Code Readability: Constants make the code easier to read and understand because they replace unclear numeric or text values with meaningful names. This helps programmers quickly understand the purpose of a value without additional explanation.
- Simplifies Code Maintenance: If a fixed value needs to be changed, it only has to be updated in one place rather than throughout the entire program. This reduces maintenance effort and minimizes the risk of introducing errors.
- Improves Code Consistency: Using constants ensures that the same value is used consistently throughout the application. This prevents accidental differences caused by manually entering values multiple times.
- Easier to Debug: When errors occur due to incorrectly fixed values, developers only need to check the constant declaration rather than searching through the entire codebase. This simplifies the debugging process.
- Encourages Better Programming Practices: Constants promote clean coding standards and encourage developers to organize their programs properly. Following the uppercase naming convention also makes the code more professional and easier to maintain.
- Prevents Accidental Modification: Although Python does not enforce constants, using naming conventions and immutable objects signals that certain values should not be changed. This helps prevent unintended modifications by programmers.
- Improves Program Reliability: Using constants reduces the likelihood of introducing errors caused by inconsistent or incorrect values. Programs become more predictable and reliable because important values remain fixed.
- Simplifies Large Project Management: In large applications, constants can be stored in separate modules or configuration files. This centralizes important values and makes managing large codebases more efficient.
- Makes Code Reusable: Constants can be reused across multiple functions, classes, and modules without redefining them repeatedly. This reduces code duplication and improves overall program organization.
- Supports Easy Configuration Management: Constants are often used for configuration settings such as file paths, URLs, tax rates, and application limits. Changing these settings becomes simple because they are stored in a single location.
Conclusion
Constants are values that are intended to remain unchanged throughout a program. Although Python does not provide true constant support through a special keyword, developers follow the convention of writing constant names in uppercase letters. Constants make programs easier to read, maintain, and debug by eliminating hardcoded values and centralizing important information. Using constants effectively is considered a good programming practice in Python development.Frequently Asked Questions
1. Does Python have a built-in const keyword?2. What happens if I modify a constant in Python?No. Unlike languages like JavaScript (const) or Java (final), Python does not have a native keyword to restrict a variable from being changed. Instead, Python relies on a community naming convention: writing the variable name in ALL_CAPS to signal that it should be treated as a constant.
3. How do I make a truly immutable constant in Python?Python will allow it without throwing an error. Because Python is dynamically typed, a constant is just a regular variable under the hood.
4. Where should I store my constants?To strictly prevent any changes at runtime, you can use a frozenset or frozen dataclass. If anyone tries to modify an attribute of a frozen object, Python will instantly raise an error.
5. What is the difference between a variable and a constant?For small scripts, constants should be placed at the very top of the file (module level), right after your imports.
For larger applications, the best practice is to isolate them. You can create a dedicated file to hold them, or store them externally in a .env or .toml file and load them into your script.
Variables can change during program execution, whereas constants are intended to remain fixed.
0 Comments