• Latest
  • Trending
10 must-know patterns for writing clean code with Python

10 must-know patterns for writing clean code with Python

April 29, 2022
Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023
Co-Creation Hub’s edtech accelerator puts $15M towards African startups

Co-Creation Hub’s edtech accelerator puts $15M towards African startups

February 20, 2023
Data Leak Hits Thousands of NHS Workers

Data Leak Hits Thousands of NHS Workers

February 20, 2023
EU Cybersecurity Agency Warns Against Chinese APTs

EU Cybersecurity Agency Warns Against Chinese APTs

February 20, 2023
How Your Storage System Will Still Be Viable in 5 Years’ Time?

How Your Storage System Will Still Be Viable in 5 Years’ Time?

February 20, 2023
The Broken Promises From Cybersecurity Vendors

Cloud Infrastructure Used By WIP26 For Espionage Attacks on Telcos

February 20, 2023
Instagram and Facebook to get paid-for verification

Instagram and Facebook to get paid-for verification

February 20, 2023
YouTube CEO Susan Wojcicki steps down after nine years

YouTube CEO Susan Wojcicki steps down after nine years

February 20, 2023
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Thursday, 16 July, 2026
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

10 must-know patterns for writing clean code with Python

by ITECHNEWS
April 29, 2022
in Data Science, Leading Stories
0 0
0
10 must-know patterns for writing clean code with Python

Python is one of the most elegant and clean programming languages, yet having a beautiful and clean syntax is not the same as writing clean code.

Developers still need to learn Python best practices and design patterns to write clean code.

YOU MAY ALSO LIKE

French Telco Orange Hit by Cyber-Attack

ATC Ghana supports Girls-In-ICT Program

What is clean code?🛁✨

This quote from Bjarne Stroustrup, inventor of the C++ programming language clearly explains what clean code means:

“I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well.”

From the quote we can pick some of the qualities of clean code:

1. Clean code is focused. Each function, class, or module should do one thing and do it well.
2. Clean code is easy to read and reason about. According to Grady Booch, author of Object-Oriented Analysis and Design with Applications: clean code reads like well-written prose.
3. Clean code is easy to debug.
4. Clean code is easy to maintain. That is it can easily be read and enhanced by other developers.
5. Clean code is highly performant.

 

Well, a developer is free to write their code however they please because there is no fixed or binding rule to compel him/her to write clean code. However, bad code can lead to technical debt which can have severe consequences on the company. And this, therefore, is the caveat for writing clean code.

In this article, we would look at some design patterns that help us to write clean code in Python. Let’s learn about them in the next section.

Patterns for writing clean code in Python

Naming convention:

Naming conventions is one of the most useful and important aspects of writing clean code. When naming variables, functions, classes, etc, use meaningful names that are intention-revealing. And this means we would favor long descriptive names over short ambiguous names.

Below are some examples:

1. Use long descriptive names that are easy to read. And this will remove the need for writing unnecessary comments as seen below:

# Not recommended
# The au variable is the number of active users
au = 105

# Recommended 
total_active_users = 105

2. Use descriptive intention revealing names. Other developers should be able to figure out what your variable stores from the name. In a nutshell, your code should be easy to read and reason about.

# Not recommended
c = [“UK”, “USA”, “UAE”]

for x in c:
print(x)

# Recommended
cities = [“UK”, “USA”, “UAE”]
    for city in cities:
        print(city)

3. Avoid using ambiguous shorthand. A variable should have a long descriptive name than a short confusing name.

# Not recommended
fn = 'John'
Ln = ‘Doe’
cre_tmstp = 1621535852

# Recommended
first_name = ‘JOhn’
Las_name = ‘Doe’
creation_timestamp = 1621535852

4. Always use the same vocabulary. Be consistent with your naming convention.
Maintaining a consistent naming convention is important to eliminate confusion when other developers work on your code. And this applies to naming variables, files, functions, and even directory structures.

# Not recommended
client_first_name = ‘John’
customer_last_name = ‘Doe;

# Recommended
client_first_name = ‘John’
client_last_name = ‘Doe’

Also, consider this example:
#bad code
def fetch_clients(response, variable):
    # do something
    pass

def fetch_posts(res, var):
    # do something
    pass

# Recommended
def fetch_clients(response, variable):
    # do something
    pass

def fetch_posts(response, variable):
    # do something
    pass

5. Start tracking codebase issues in your editor.

A major component of keeping your python codebase clean is making it easy for engineers to track and see issues in the code itself. Tracking codebase issues in the editor allows engineers to:

Tracking codebase issues in the editor allows engineers to:

  • Get full visibility on technical debt
  • See context for each codebase issue
  • Reduce context switching
  • Solve technical debt continuously

You can use various tools to track your technical debt but the quickest and easiest way to get started is to use the free Stepsize extensions for VSCodeor JetBrains that integrate with Jira, Linear, Asana and other project management tools.

 

Image description

 

6. Don’t use magic numbers. Magic numbers are numbers with special, hardcoded semantics that appear in code but do not have any meaning or explanation. Usually, these numbers appear as literals in more than one location in our code.

import random

# Not recommended
def roll_dice():
    return random.randint(0, 4)  # what is 4 supposed to represent?

# Recommended
DICE_SIDES = 4

def roll_dice():
    return random.randint(0, DICE_SIDES)

Functions

7. Be consistent with your function naming convention.
As seen with variables above, stick to a naming convention when naming functions. Using different naming conventions would confuse other developers.

# Not recommended
def get_users(): 
    # do something
    Pass

def fetch_user(id): 
    # do something
    Pass

def get_posts(): 
    # do something
    Pass

def fetch_post(id):
    # do something
    pass

# Recommended
def fetch_users(): 
    # do something
    Pass

def fetch_user(id): 
    # do something
    Pass

def fetch_posts(): 
    # do something
    Pass

def fetch_post(id):
    # do something
    pass

8. Functions should do one thing and do it well. Write short and simple functions that perform a single task. A good rule of thumb to note is that if your function name contains “and” you may need to split it into two functions.

# Not recommended
def fetch_and_display_users():
users = [] # result from some api call

    for user in users:
        print(user)


# Recommended
def fetch_usersl():
    users = [] # result from some api call
        return users

def display_users(users):
for user in users:
        print(user)

9. Do not use flags or Boolean flags. Boolean flags are variables that hold a boolean value — true or false. These flags are passed to a function and are used by the function to determine its behavior.

text = "Python is a simple and elegant programming language."

# Not recommended
def transform_text(text, uppercase):
    if uppercase:
        return text.upper()
    else:
        return text.lower()

uppercase_text = transform_text(text, True)
lowercase_text = transform_text(text, False)


# Recommended
def transform_to_uppercase(text):
    return text.upper()

def transform_to_lowercase(text):
    return text.lower()

uppercase_text = transform_to_uppercase(text)
lowercase_text = transform_to_lowercase(text)

Image description

Classes:

10. Do not add redundant context. This can occur by adding unnecessary variables to variable names when working with classes.

# Not recommended
class Person:
    def __init__(self, person_username, person_email, person_phone, person_address):
        self.person_username = person_username
        self.person_email = person_email
        self.person_phone = person_phone
        self.person_address = person_address

# Recommended
class Person:
    def __init__(self, username, email, phone, address):

        self.username = username
        self.email = email
        self.phone = phone
        self.address = address

In the example above, since we are already inside the Person class, there’s no need to add the person_ prefix to every class variable.

Bonus: Modularize your code:

To keep your code organized and maintainable, split your logic into different files or classes called modules. A module in Python is simply a file that ends with the .py extension. And each module should be focused on doing one thing and doing it well.

You can follow object-oriented — OOP principles such as follow basic OOP principles like encapsulation, abstraction, inheritance, and polymorphism.

Conclusion

Writing clean code comes with a lot of advantages: improving your software quality, code maintainability, and eliminating technical debt.

Source: Alex Omeyer
Via: dev.to
Tags: 10 must-know patterns for writing clean code with Python
ShareTweet

Get real time update about this post categories directly on your device, subscribe now.

Unsubscribe

Search

No Result
View All Result

Recent News

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025

Recent News

  • Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa July 29, 2025
  • French Telco Orange Hit by Cyber-Attack July 29, 2025
  • ATC Ghana supports Girls-In-ICT Program April 25, 2023
  • Vice President Dr. Bawumia inaugurates ICT Hub April 2, 2023
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Add New Playlist

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
Go to mobile version