• About   |
  • Submit Guest Post |
  • Contact Us
No Result
View All Result
The Second Angle (TSA Magazine)
Advertise
  • Infotainment
    • Sports
    • People
    • Inspiring
  • Entertainment
    • Lifestyle
    • Home & Decoration
  • Buzz
  • Education
  • Travel
  • Finance
  • Healthcare
  • Technology
The Second Angle
No Result
View All Result
  • Infotainment
  • Entertainment
  • Buzz
  • Education
  • Travel
  • Finance
  • Healthcare
  • Technology
Advertisement
ADVERTISEMENT
Lexitoto
Slot Demo
RTP SLOT
Lexitoto
Aplikasi Lexitoto
RTP Lexitoto
RTP IDN Slot
RTP PG Soft
RTP Habanero
RTP Microgaming
RTP TopTrend Gaming
RTP GMW
RTP Nolimit City
RTP Booster
Slot Demo Bambu4d
Slot Demo PG Soft
Slot Demo Habanero
Situ Togel Online
Situs Togel Amanah
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Prediksi Togel Lexitoto
Slot Demo PG Soft
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Lexitoto
Vietnam Lottery
Syair HK
Octagon Lottery
Bandar Situs Togel
Situs Slot Gacor
Bocoran Slot Gacor
Lexitoto
Togel Toto Macau
Situs Togel Macau
Prediksi Macau
Bambu4d
Prediksi Togel Bambu4d
Slot Gacor Bet Kecil
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Situs Togel Online
Aplikasi Bambu4d
Aplikasi RTP Slot
Aplikasi RTP Booster
Aplikasi Slot Demo
Aplikasi Prediksi Togel
RTP Bambu4d
RTP IDN Slot
RTP PG Soft
RTP Habanero
RTP Microgaming
RTP TopTrend Gaming
RTP GMW
RTP Nolimit City
RTP Playstar
RTP Booster
Slot Demo Bambu4d
Slot Demo PG Soft
Slot Demo Habanero
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Bambu4d
Prediksi Togel Bambu4d
Bambu4d
RTP Slot
Live Draw HK
Live Draw SDY
Lexitoto Togel
Prediksi Syair Macau
Data SDY
Bandar Togel
https://bluewaveslogistics.com/
Situs Toto
Prediksi Syair Taiwan
RTP Slot
Situs Toto
Prediksi Syair Macau
Slot Gacor
RTP Slot Gacor
Prediksi Syair HK
Prediksi Syair HK
Prediksi Syair SGP
Prediksi SGP
Prediksi Syair Cambodia
Prediksi Cambodia
Prediksi Cambodia
Prediksi Syair China
Prediksi Syair China
Prediksi Syair SDY
Prediksi PCSO
Syair SDY
SYAIR HK
Situs Togel
Paito SGP
Paito HK
Paito SDY
Prediksi Macau
Live Draw Cambodia
Prediksi Jepang
Situs Togel
Live Draw Macau
Live Draw Cambodia
Live SGP
lexitoto
Live Macau
Live RTP Slot
RTP SLOT
hinterlaces.com RTP Slot
Rtp Slot
showfactory.in
https://tuniversity.tn/
situs toto
lexitoto
slot deposit pulsa
lexitoto
Data Pengeluaran HK
Prediksi China
Prediksi Cambodia
Toto Slot
Slot Thailand
Situs Toto
Rtp Slot
Slot Pulsa
SYAIR SDY
PREDIKSI SDY
Live Draw HK
Prediksi Macau
Prediksi Cambodia
PREDIKSI SDY
Prediksi Macau
Slot Pulsa
Prediksi Cambodia
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
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.

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

RelatedPosts

7 Conspiracy Theories That You Would Definitely Want To Believe In

Can You Download Videos From Facebook?

7 Most Futuristic Concept Cars in the World

7 Most Futuristic Concept Cars in the World

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.
Table of Contents
    • What is a Clean Code?
  • 9 Must-Know Pattern For Writing Clean Code with Python: 
    • 1. Use descriptive names that are lengthy and simple to read.
    • 2. Use descriptive intention to reveal names.
    • 3. Avoid using ambiguous shorthand.
    • 4. Always use the same vocabulary.
    • 5. Don’t use magic numbers.
    • 6. Be consistent with your function naming convention.
    • 7. Functions should do one thing and do it well.
    • 8. Do not use flags or Boolean flags.
    • 9. Do not add redundant context.

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

Related Posts

7 Conspiracy Theories That You Would Definitely Want To Believe In
Technology

Can You Download Videos From Facebook?

500 million people view millions of videos on Facebook every day. Some Facebook users wish to save their favorite videos...

Read moreDetails
7 Most Futuristic Concept Cars in the World
Technology

7 Most Futuristic Concept Cars in the World

Concept cars are no longer only a showpiece to draw attention to an automotive company. This is true technological brilliance....

Read moreDetails
What Makes GPT-4 Unique From ChatGPT And How Is It Different?
Technology

What Makes GPT-4 Unique From ChatGPT And How Is It Different?

With inception of new versions and other competitive AI chatbots, there arises a question — What makes GPT-4 Unique From...

Read moreDetails
20 Most Amazing And Genius Product Packaging Designs Ever Created
Technology

20 Most Amazing And Genius Product Packaging Designs Ever Created

The majority of our items are packaged in some style. Certain products don't require as much packing because customers will...

Read moreDetails
7 Most Expensive Cars In The World
Listicles

7 Most Expensive Cars In The World

Cars have been defined as a symbol of both luxury and status. While most of us are using our cars...

Read moreDetails
Top Examples Of Interactive Marketing & How Brands Can Make The Most Of It
Business

Top Examples Of Interactive Marketing & How Brands Can Make The Most Of It

In today's fast-paced digital age, companies must continually find new ways to engage with consumers. One increasingly popular approach is...

Read moreDetails
Load More

Leave a Reply Cancel reply

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

Latest

Luxury Getaways: 10 Most Exclusive Resorts In India For A Lavish Retreat

Luxury Getaways: 10 Most Exclusive Resorts In India For A Lavish Retreat

Exploring New Delhi’s Timeless Relics: 7 Ancient Ruins And Historical Sites In New Delhi

Exploring New Delhi’s Timeless Relics: 7 Ancient Ruins And Historical Sites In New Delhi

6 Instances When Best Books Were Turned Into Bollywood Movies

6 Instances When Best Books Were Turned Into Bollywood Movies

ADVERTISEMENT

About

The Second Angle

The Second Angle (TSA) Magazine covers a broad spectrum of topics including Entertainment, Lifestyle, education, Crypto, iGaming, Technology, fashion, beauty, relationships, celebrities, wellness, travel, and food. It also features user-generated content in the form of tips, guest post, forums, polls, contests and other interactive articles.

Important Links

  • About
  • Guest Post
  • Privacy Policy
  • Terms
  • Contact Us
  • Newsletter
ADVERTISEMENT

© 2017-23. The Second Angle. All Rights Reserved. Developed and Managed 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
No Result
View All Result
  • Infotainment
    • Sports
    • People
    • Inspiring
  • Entertainment
    • Lifestyle
    • Home & Decoration
  • Buzz
  • Education
  • Travel
  • Finance
  • Healthcare
  • Technology

© 2017-23. The Second Angle. All Rights Reserved. Developed and Managed by SquareBase.io

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