• About   |
  • Write For Us   |
  • Contact Us   |
  • हिंदी
Saturday, January 28, 2023
  • Login
  • Register
No Result
View All Result
The Second Angle
Advertise
  • Infotainment
    • Sports
  • Entertainment
    • Lifestyle
      • Home & Decoration
  • People
    • Inspiring
  • Education
  • Travel
  • Finance
  • Healthcare
  • Technology
  • World
The Second Angle
  • Infotainment
  • Entertainment
  • People
  • Education
  • Travel
  • Finance
  • Healthcare
  • Technology
  • World
Advertisement
ADVERTISEMENT
Home Technology

9 Must-Know Patterns For Writing Clean Code With Python

Python developers still need to learn python best practices and design patterns in order to write clean code. Here are the 9 Must-know Patterns for Writing Clean Code with Python.

TSA Desk by TSA Desk
December 2, 2022
in Technology
Reading Time: 5 mins read
A A
9 Must-Know Patterns For Writing Clean Code With Python

The University Of Texas

Share on FacebookShare on WhatsApp
Advertisement Advertisement Advertisement
ADVERTISEMENT

Python is one of the most elegant and clean programming languages available, yet having a beautiful and clean syntax does not imply creating clean code. Surprisingly, Python has surpassed Java in the list of top programming languages and is now the most learned! In this blog, we’ve compiled a list of must-know patterns for Writing Clean Code with Python.

It is the second most used language after JavaScript and is gradually edging out of the competition to take the top spot. It is widely used in a variety of disciplines, including web development using popular frameworks such as Django and Flask, web scraping, automation, system administration, DevOps, testing, network programming, data analysis, data science, machine learning, and artificial intelligence.

RelatedPosts

5 Best Google Cloud Print Alternatives To Use

5 Best Google Cloud Print Alternatives To Use

Java Programmer

How to become a Better Java Programmer In 2023

What is a Clean Code?

This quote from Bjarne Stroustrup, the creator of the C++ programming language, elucidates what clean code entails:

“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.”

We may derive some of the characteristics of clean code from the quote:

  • Clean code is focused. Each function, class, or module should do one thing and do it well.
  • 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.
  • Clean code is easy to debug.
  • Clean code is easy to maintain. That is it can easily be read and enhanced by other developers.
  • Clean code is highly performant.

9 Must-Know Pattern For Writing Clean Code with Python: 

1. Use descriptive names that are lengthy and simple to read.

9 Must-know Patterns for Writing Clean Code With Python
Image Source: blog. galvanize

As a result, there will be no need to write needless remarks, 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 to reveal names.

9 Must-know Patterns for Writing Clean Code With Python
Image Source: ehsangazar

From the name, other developers should be able to deduce what your variable holds. In a nutshell, your code should be simple to read and understand.

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

9 Must-know Patterns for Writing Clean Code With Python
Image Source: javacodegeeks

A variable’s name should be lengthy and descriptive rather than short and confusing.

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

9 Must-know Patterns for Writing Clean Code With Python
Image Source: medium

Maintain consistency in your naming convention. Maintaining a consistent naming convention is critical to avoiding misunderstanding when working with other developers on your code. This is true when it comes 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. Don’t use magic numbers.

9 Must-know Patterns for Writing Clean Code With Python
Image Source: StackOverflow

Magic numbers are numbers that exist in code but have no meaning or explanation because they have specific, hard-coded meanings. Typically, these numbers exist as literals in several places 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)

6. Be consistent with your function naming convention.

9 Must-know Patterns for Writing Clean Code With Python
Image Source: medium

When naming functions, as with variables, follow a naming standard. Other developers might be confused if you used various naming standards.

# 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

7. Functions should do one thing and do it well.

9 Must-know Patterns for Writing Clean Code With Python
Image Source: medium

Write a brief, straightforward functions that do a single thing. A good rule of thumb to remember is that if your function name contains the word “and,” you should consider splitting 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)

8. Do not use flags or Boolean flags.

9 Must-know Patterns for Writing Clean Code With Python
Image Source: proxy curl

Variables that carry a boolean value — true or false — are known as boolean flags. These flags are supplied to a function, which uses them to define 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)

9. Do not add redundant context.

9 Must-know Patterns for Writing Clean Code With Python
Image Source: NASA

This can happen while dealing with classes and adding extra variables to variable names.

# 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

Split your logic into multiple files or classes called modules to keep your code tidy and manageable. In Python, a module is just a file with the.py suffix. And each module should be laser-focused on performing one thing well. You can adhere to basic object-oriented — OOP concepts such as encapsulation, abstraction, inheritance, and polymorphism.

Writing clean code has several benefits, including increased software quality, code maintainability, and the elimination of technical debt. Hope this article on must-know patterns for writing clean code with python was helpful to you.

Also Checkout: A Guide to Understanding How a 10GBASE-SR Optical Module Works

ShareSendTweet
TSA Desk

TSA Desk

Related Posts

5 Best Google Cloud Print Alternatives To Use
Technology

5 Best Google Cloud Print Alternatives To Use

Are you yet to discover the best Google Cloud Print alternatives? Don't worry; we've compiled a list of the best...

Read more
Java Programmer
Technology

How to become a Better Java Programmer In 2023

Let us discuss some important tips that you need to remember for becoming a good Java programmer in 2023.

Read more
How To Clear Cookies On Android
Technology

How To Clear Cookies On Android

If you use the internet on a regular basis, you've undoubtedly visited a website that employs cookies. However, you may...

Read more
Java Programmer
Technology

10 Must Have Apps for Entrepreneurs

Is the only reason you go to work each day simply to get your paycheck? Do you find that you...

Read more
INFINIX INBook X1 Pro Review: Parameters And Features
Technology

INFINIX INBook X1 Pro Review: Parameters And Features

The need for portable computing continues to rise as the year 2021 draws to a close. Interest is high worldwide,...

Read more
How To Reinstall Windows 10 Without Losing Data?
Technology

How To Reinstall Windows 10 Without Losing Data?

Following the cancellation of plans for a spin-off in Windows 10X, Microsoft determined that 2021 would be the time for...

Read more
Load More
Next Post
Java Programmer

U.S. discussing “social challenges” with India: Ambassador Elizabeth Jones 

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Facebook Twitter Instagram Telegram

About

The Second Angle

A platform providing diverse views on various issues, providing an in-depth understanding of important developments happening around us. It offers you true journalism amidst the cacophony. Discover the latest news, opinions, analysis and a lot more here.

Important Links

  • About
  • Career
  • Write for us | The Second Angle
  • Support Us
  • Privacy Policy
  • Terms
  • Contact Us
  • Newsletter
  • हिंदी

Subscribe to Our Newsletter

We don’t spam! Read our privacy policy for more info.

Check your inbox or spam folder to confirm your subscription.

© 2017-22. The Second Angle. All Rights Reserved. Developed and Maintenance by SquareBase.io

No Result
View All Result
  • Infotainment
    • Sports
  • Entertainment
    • Lifestyle
      • Home & Decoration
  • People
    • Inspiring
  • Education
  • Travel
  • Finance
  • Healthcare
  • Technology
  • World
  • Login
  • Sign Up

© 2017-22. The Second Angle. All Rights Reserved. Developed and Maintenance by SquareBase.io

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms below to register

All fields are required. Log In

Retrieve your password

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

Log In
This website uses cookies. By continuing to use this website you are giving consent to cookies being used. Visit our Privacy and Cookie Policy.
Go to mobile version