Open In App

How to create constant in Python

Last Updated : 07 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python lacks built-in constant support, but constants are typically represented using all-uppercase names by convention. Although they can technically be reassigned, it’s best practice to avoid modifying their values. This convention helps indicate that such variables should remain unchanged throughout the code, promoting clarity and consistency in programming.

Here's an example of how we can define the constant in Python:

Python
pi = 3.14159
gravity = 9.8
speed = 299792458

There are also multiple ways to create constants in Python:

Using typing.Final

Starting with Python 3.8, you can annotate a constant using Final from the typing module, which helps tools like mypy catch reassignment issues:

Python
from typing import Final
pi = 3.14159
gravity= 9.8
# Attempting to reassign these constants will raise an error in static type checkers
# pi = 3.14  # mypy will raise an error

Using namedtuple

We can use Python's namedtuple to create immutable constants. A namedtuple provides a convenient way to define constants that are grouped logically and cannot be easily modified.

Python
from collections import namedtuple

# Define a namedtuple for constants
c = namedtuple('Constants', ['pi', 'gravity', 'speed'])

# Create an instance of the namedtuple with constant values
c = Constants(pi=3.14159, gravity=9.8, speed=299792458)

# Access constants
print(f"PI: {constants.pi}")
print(f"Gravity: {constants.gravity}")
print(f"Speed of Light: {constants.speed}")

# Attempting to modify a value will raise an AttributeError
# constants.PI = 3.14  

Output
PI: 3.14159
Gravity: 9.8
Speed of Light: 299792458

Next Article
Article Tags :
Practice Tags :

Similar Reads