Python Constants Concept
Python Constants Concept
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.
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.
Output:
host=localhost port=5432
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
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()
def my_function():
...
# Implementation will be added later
class MyClass:
def method(self):
...
# Placeholder for method logic
def main():
print("This is the main function.")
Output:
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:
Previous Next