Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Python Constants Concept

This document provides an overview of constants in Python, explaining their definition, usage, and how to define them despite Python not having a dedicated syntax for constants. It highlights the benefits of using constants, such as improved code maintainability and readability, and outlines naming conventions and methods for handling constants in Python projects. Additionally, it discusses built-in constants and internal identifiers treated as constants within the Python programming language.

Uploaded by

myhy7p
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Python Constants Concept

This document provides an overview of constants in Python, explaining their definition, usage, and how to define them despite Python not having a dedicated syntax for constants. It highlights the benefits of using constants, such as improved code maintainability and readability, and outlines naming conventions and methods for handling constants in Python projects. Additionally, it discusses built-in constants and internal identifiers treated as constants within the Python programming language.

Uploaded by

myhy7p
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Home Resources Python Tutorial | Learn Python Language Python…

Python Constants: Uses, Rules, Examples


4 mins read Last updated: 25 Feb 2025 4637 views

Share 1.25%

Table of Contents

Introduction
What Are Constants in Python?
Why and When to Use Constants?
How to Define Constants in Python?
Rules for Naming Python Constants
How to Handle Python Constants?
Other Constants in Python

Introduction
In programming, constants are a fundamental concept referring to values
that don’t change throughout a program's execution. Developers use
constants often in various projects and cases.
Python doesn’t support constants and has no dedicated syntax to declare
them. It treats constants as variables that can’t be changed. The
programming language has a naming convention to prevent developers
from reassigning a name to hold a constant.
In this tutorial, we will define constant in Python, its uses, and more.

What Are Constants in Python?


We have studied the concept of constants in mathematics, which refers to a
value that never changes. When we talk about Python constants, it means a
value that never changes while executing a program.
Programming constants are different from math constants and include two
elements—a name and an associated value. The name defines what a
constant is about, whereas the value defines the concrete expression of the
constant. The value of a constant can be of any data type, which means our
constant can be an integer, character, floating-point, string, etc.
Once we define the constant, we can perform only a single operation on it.
Also, we can access its value but can’t change it. So, in programming, we
commonly use constants for values that can’t be modified. Some common
examples of constants include a project’s root folder name, total minutes in
an hour, etc.

Why and When to Use Constants?


Using constants ensures that we don’t accidentally change their values in
the code and encounter errors that are hard to fix. They also enhance code
readability and maintainability. Here are the top benefits of using constants
in Python programming:
Improved Code Maintainability
When we include constants in code, we can use one name to identify one
value throughout. So, whenever we need to change the value of that
constant, we can easily do that without changing every instance of the
value. We simply have to change the value in one place, i.e., where we
defined the constant. Hence, this makes the code moreQuiz
maintainable.
Enhanced Code Readability
Having a single descriptive name to represent a value throughout the code
makes it readable. So, rather than using a concrete speed value, we can use
the name MAX_SPEED for the constant, which is easier to read and
understand.
Reduced Bugs
The constant’s value is the same throughout the program, so there are
fewer errors and bugs. This is quite a useful feature for large projects that
have multiple developers and programmers working, as they don’t have to
spend time debugging the constant's value.
Clear Intent Communication
More than values, names, like pi, PI, or Pi, convey our intent clearly and
allow developers to understand the program accurately.
Thread-safe Data Storage
As we can only access constants and not write them, they are thread-safe
objects. So, multiple threads can simultaneously use a single constant
without higher risks of losing or corrupting data.
Reduced Risks
When a constant represents a value throughout a program, there are fewer
risks of errors than when we use explicit instances of a value. This is
because when we use different values and need to change them for a
particular set of calculations, we may end up changing the wrong value;
hence, causing an error.
Constants are values used to represent magnitude, quantity, parameter, or
object that remain unchanged throughout. We use constant values in
several situations. Here are some examples for you:
3,600- It shows the number of seconds in an hour, which is constant.
3.141592653589793- It represents Pi (π), the ratio of the circumference of
a circle to its diameter.
-273.15- This constant value shows absolute zero in degrees Celsius equal
to 0 kelvins on the Kelvin temperature scale.
2.718281828459045- It is an Euler’s number denoted by e. This constant
value is related to the natural logarithm and compound interest.
Although these are common examples of constants in life and science, they
are also used in Python programming. There are similar constant values
that we come across in day-to-day programming.

How to Define Constants in Python?


Now that you have gained a fair understanding of constants in
programming, let’s take a look at how to define Python constants.
Python doesn’t support constants and has no dedicated syntax to define
them. As the programming language is dynamic, it only contains variables.
So, to include constants in a program, you must define a variable in a way
that never changes, handling it as a variable.
However, how does a developer know that a given value is a constant? That
is why the Python community came up with a Python constants naming
convention to differentiate a constant from a variable.
User-Defined Constants
We use the naming convention to inform a developer that the given value is
a constant. We write the name in capital letters, separating words using
underscores.
Example
PI = 3.14159
EULER_NUMBER = 2.71828
GRAVITY = 9.8 # m/s^2

We create constants similarly to how we create variables. We use a


descriptive name, the assignment operator (=), and a specific value to
define a constant. Capital letters convey that the name must be treated as a
constant or a variable that remains unchanged. This will tell other
programmers not to change the value or perform assignment operations on
that variable.

Rules for Naming Python Constants


Python constants are basically variables that remain unchanged. Hence,
they both follow the same naming rules. However, unlike variables,
constants use only uppercase letters. The following points the Python
constants best practices that you must follow:

Must include uppercase letters only

Can be of any length

Underscore separates words or used as first characters

Digits from 0 to 9 can be included but not as first characters

When you name a constant using uppercase letters, it makes the name
stand out, and other programmers can know it’s a constant. Avoid using
abbreviations to define constants and ensure that the name aligns with the
meaning of the constant’s value so that it can be reused. Hence, the same
should be descriptive.

Don’t use single-letter names or generic names. Moreover, define constants


at the top of a .py file after the import statement. This will enable people
reading code to determine the purpose of the constant and expected
treatment.

How to Handle Python Constants?


Moving on, let’s see how to handle and organize constants in Python while
working on real-life projects. We use various methods and approaches for
this purpose. We can place constants in a configuration file, the same file
as the code using them, an environment variable, and a dedicated module.
Below, we have explained a few practical examples of using different tactics
to handle constants effectively:
Placing Constants With Related Code
This is the easiest and most natural method to handle constants in Python.
Define constants with code using them. This tactic lets you define
constants at the top of the module containing relevant code.
Example
# app.py
DB_HOST = "localhost"
DB_PORT = 5432
connection_string = f"host={DB_HOST} port={DB_PORT}"
print(connection_string )

Output:

host=localhost port=5432

Storing Constants in Configuration Files


If you want to externalize the constants of a project in detail, you can go for
this method. Keep all the constants out of the source code of the project by
using an external configuration file.
Example

#File Name :app.py


import configparser

config = configparser.ConfigParser()
config.read('config.ini')

DB_HOST = config['database']['host']
DB_PORT = config['database']['port']
connection_string = f"host={DB_HOST} port={DB_PORT}"
print(f"Connecting to database with: {connection_string}")

Output:
Connecting to database with: host=localhost port=5432

Creating a Dedicated Module for Constants


Creating a dedicated module for constants is a popular approach to
handling and organizing constants. This strategy is suitable for constants
used in different modules and packages across a project. This method aims
to offer constants a clear and distinct namespace.
Example

FIle Name : constants.py


DB_HOST = "localhost"
DB_PORT = 5432
API_KEY = "your-api-key-here"
Python code in another module (app.py):

app.py
from constants import DB_HOST, DB_PORT
def connect_to_database():
connection_string = f"host={DB_HOST} port={DB_PORT}"
print(f"Connecting to database with: {connection_string
# Code to connect to database

connect_to_database()

Handling Constants as Environment Variables


Lastly, you can define constants as environment variables for Linux and
macOS and as system variables on Windows. This is a useful method for
deployment configuration in different settings. We can store those
constants in environment variables that imply security concerns and are not
directly committed to the source code, such as API access tokens,
authentication credentials, etc.
If you are using environment variables for crucial or sensitive information,
be careful, as they may be exposed in logs or child processes. Cloud
service providers provide more secure secrets management. For this
technique, export constants as environment or system variables in the
operating system using either of the following two methods:

1. Export constants manually in the current shell session


2. Add constants to the shell’s configuration file
The first method is faster and is used to test code quickly. However, you
can access the code from the command-line session where constants are
defined. If you use Linux or macOS, you can access the configuration file in
the home folder.

Other Constants in Python


We have studied user-defined constants in Python. Apart from them,
several internal identifiers are treated as other types of constants in Python.
Some are strict constants, so you can’t change them once the interpreter
starts running.
In the following section, we will discuss internal Python names that you can
use as constants in the code.
Built-in Constants
Python documentation states that there are a few constants in the built-in
namespace. The first two built-in constants listed in Python documentation
are Boolean values True and False, which are also instances of int. The
value of True is 1, and the value of False is 0. They are strict constants, so
we can’t change or reassign them. If you try to do so, it will return
SyntaxError. Also, they are singleton objects, so each has one instance.
None is another commonplace constant value in Python with a null value.
We use this constant value to express nullability. Similar to Boolean values
True and False, None is also a strict constant and singleton, so it can’t be
reassigned. Moreover, we use None as a default argument value in
functions, class constructors, and methods. Using it, we can communicate
that a variable is empty. In Python, None is treated as an implicit return
value of functions with no explicit return statement.
Next is the ellipsis literal (...), a constant value in Python, which is also a
special value. It is the same as ellipsis and the only instance of the
types.EllipsisType type. We can use it as a placeholder for unwritten code
and to replace the pass statement. When we use …in type hints, it conveys
the idea of an unknown length of data collection with a uniform type. We
use the ellipsis constant value in various situations. Its semantic
equivalence to ellipsis punctuation in English makes the code more
readable.
Example

def my_function():
...
# Implementation will be added later
class MyClass:
def method(self):
...
# Placeholder for method logic

__debug__ is also a built-in constant in Python. It is a Boolean constant


value with a default value of True. It is also a strict constant, so we can’t
change its value once the interpreter is running. The assert statement and
__debug__ are closely related to each other. So, if __debug__ is True, the
assert statements will run. However, if the __debug__ value is False, the
assert statements will stop and won’t run. This enhances the code
performance.
Internal Dunder Names
Python comprises a range of internal dunder names that are considered
constants in programming. Let’s learn about __name__ and __file__ out of
various special names used in Python.
__name__ is an attribute in Python closely related to how a code is run.
While importing the module, Python sets __name__ internally to a string
containing the module name we are importing.
Example

def main():
print("This is the main function.")

# Checking the value of __name__


if __name__ == "__main__":
main()

Output:

This is the main function.

The __file__ attribute includes the path to the file Python is importing or
executing. We use it from inside the module to get the path to the module
Example

# script.py

import os
def show_file_path():
print("The file path is:", __file__)

def show_directory():
print("The directory containing this file is:", os.path

if __name__ == "__main__":
show_file_path()
show_directory()

Output:

# The file path is: /path/to/your/script.py


# The directory containing this file is: /path/to/your

FAQs About Python Constants

What is the difference between a variable, constant, and a


literal in Python?
A variable is a memory location where data is stored. A constant is
a variable whose value we can’t change. A literal is a raw value
stored in a variable or constant.
Variables are mutable, so we can change or update their values.
Constants are immutable, so their values can’t be changed or
updated. Literals can be mutable or immutable based on the type
of literal.

Does Python have constants?

What are the Python constant naming conventions?


Updated - 25 Feb 2025 4 mins read Published : 17 Sep 2024

Previous Next

Elevate Your Learning Journey with Cutting-Edge


Education Technology.
Company Our Programs
Contact Data
About Digital Marketing
WsCube Tech Blog Web Development
Self-Paced Courses Cyber Security
Events App Development

Support Telegram Community


Privacy Policy
Terms & Conditions
Refund Policy

© Copyright 2025, All Rights Reserved By WsCube Tech

You might also like