DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Advancing Robot Vision and Control
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Using Python Libraries in Java

Trending

  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Building a Real-Time Change Data Capture Pipeline With Debezium, Kafka, and PostgreSQL
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  1. DZone
  2. Coding
  3. Languages
  4. 10 Must-Know Patterns for Writing Clean Code With Python

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.

By 
Alex Omeyer user avatar
Alex Omeyer
·
Apr. 06, 22 · Analysis
Likes (7)
Comment
Save
Tweet
Share
21.0K Views

Join the DZone community and get the full member experience.

Join For Free

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:

Python
 
# 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.

Python
 
# 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.

Python
 
# 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.

Python
 
# 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 allow engineers to:

Tracking codebase issues in the editor allow 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 VSCode or JetBrains that integrate with Jira, Linear, Asana, and other project management tools.

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.

Python
 
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 the variables above, stick to a naming convention when naming functions. Using different naming conventions would confuse other developers.

Python
 
# 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.

Python
 
# 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.

Python
 
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)

Classes:

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

Python
 
# 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.

And in this article, you learned about clean code in general and some patterns to write clean code using the Python programming language. However, these patterns can be replicated in other programming languages too.

Lastly, I hope that by reading this article, you have learned enough about clean code and some useful patterns for writing clean code.

Coding best practices Python (language)

Opinions expressed by DZone contributors are their own.

Related

  • Advancing Robot Vision and Control
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Using Python Libraries in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!