Python
Constants
Programming
Coding
Python3

How do I create a constant in Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Python, the concept of a "constant" isn't formally defined or enforced by the language as it is in some other programming languages like C++ or Java. However, Python developers use conventions to indicate that a variable is intended to be immutable and should not be changed. In this article, we'll explore how to create and use constants in Python, including technical explanations and examples.

Why Use Constants?

Using constants in your code can greatly improve readability and maintainability. It signifies to other developers or your future self that a particular value should remain unchanged throughout the program's lifecycle. This can prevent accidental value changes and help in understanding the code's logic.

Defining Constants in Python

While Python lacks a built-in constant type, the community follows certain conventions to implement the concept of constants:

  1. Naming Conventions: Use uppercase letters with words separated by underscores to declare a constant. This naming style is a widely respected convention in Python to denote an immutable object.
python
   PI = 3.14159
   MAX_CONNECTIONS = 100
   DEBUG_MODE = False
  1. Modules: Since everything in a module is considered as part of the module's namespace, constants are often placed in a separate module file.
python
   # constants.py
   GRAVITY = 9.81
   SPEED_OF_LIGHT = 299792458

Import these constants into other Python scripts:

python
   from constants import GRAVITY, SPEED_OF_LIGHT

Enforcing Constants

Although Python does not enforce immutability, you can use some workarounds to enforce constant behavior:

Using Custom Classes

Create a class with read-only properties.

python
1class _Constants:
2    @property
3    def PI(self):
4        return 3.14159
5
6    @property
7    def MAX_CONNECTIONS(self):
8        return 100
9
10CONSTANTS = _Constants()

Attempting to change the value will lead to an AttributeError.

python
# Will raise an AttributeError
# CONSTANTS.PI = 3

Using the enum Module

You can use the enum module to define constants.

python
1from enum import Enum
2
3class Constants(Enum):
4    PI = 3.14159
5    MAX_CONNECTIONS = 100
6
7# Access the constants
8print(Constants.PI.value)
9print(Constants.MAX_CONNECTIONS.value)

Pitfalls and Caveats

  • Variable Mutability: If a constant is a mutable object such as a list or dictionary, the object itself can still be modified even if the variable is intended to be constant:
python
1  CONFIG = {'debug': True}
2
3  # This is allowed
4  CONFIG['debug'] = False
  • Enforcement: The enforcement of constant behavior should be done through discipline and adherence to conventions, as Python doesn't enforce constant values.

Summary Table

FeatureDescription
Syntax ConventionUse uppercase letters
Module UsagePlace constants in a separate module
Enforced ImmutableUse custom classes or enum module
Mutable ConstantsMutable types can have their contents modified
Enforcing ChangesPython does not enforce immutability

Conclusion

Python may not have a built-in mechanism for defining constants, but through community conventions and creative use of its flexibility, you can effectively employ constants in your programming projects. By maintaining good coding practices and using Python's capabilities strategically—such as through naming conventions, modules, and classes—you can create clean, maintainable, and reliable code. While Python relies on programmer discipline rather than enforced rules, this practice promotes better code quality and program stability.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.