7 Best python coding practices

7 Best python coding practices

7 Best python coding practices - With Python now a recognized language applied in diverse development arenas, it is more than expected for there to be some set of practices that would make for the foundation of good coding in it.

7 Best python coding practices - With Python now a recognized language applied in diverse development arenas, it is more than expected for there to be some set of practices that would make for the foundation of good coding in it.

To take advantage of the numerous third-party libraries, one would definitely have to put together a streak of applying the industry recognized python coding practices.

It is here that we turn and present you with some Python coding practices that you will come to treasure as they will greatly enhance your Python code output.

1. Set Out Consistent Indentation within a Python File

Indentation can’t be emphasized enough and its importance in Python is really high. However, there is the tendency to mix tabs and spaces which is deemed unwise and highly discouraged. Using a mix of indents and spaces will leave you pretty confused as you execute your code. You will be left wondering at which indentation level a particular line is being considered.

Always go for PEP-8 to avoid possible confusion in the event your code is used or read by someone else.

Avoid messing up your code and allow IDEs to do their part in formatting your code. Avoid tabs like the plague altogether as under defined tab semantics prevail in the computer world. The diverse systems editors out there will display tabs differently with tabs getting destroyed or wrongly interpreted when copy paste functions are applied in markup codes or web pages.

2. Utilize the Python Dictionary

The Python dictionary data structure is a means of data storage that is quite easy to use and effective. You will find that other languages do have dictionaries as well as coming in the form of associative arrays. A dictionary in Python represents a set of unordered pairs of key: value where the requirement is that each key is unique. The dictionary is indeed meant for everyday use. Some common scenario examples will show us how:

One scenario could be when we need a default value for a key:

def count_duplicates(numbers):
   result = {}
   for number in numbers:
       if number not in result:  # No need for if here
           result[key] = 0
       result[number] += 1
   return result

By using setdefault, we achieve a much cleaner code:
>>> def count_duplicates(numbers):
   result = {}
   for number in numbers:
       result.setdefault(number, 0)  # this is clearer
       result[number] += 1
   return result

3. Don’t Skip Inline Comments or Writing of Documentation

It may seem like you are saving on time when you skip writing comments in those complex code sections of your project. As you pat yourself on the back for having met a client’s deadline you will soon be pulling your hair as you read your own code and not be able to remember why and what you did in a particular section. It all trickles down well for those to whom you will either leave or handover your project in the event you decide to leave a company. It will be less traumatizing or haunting to go through the well-documented code.

You have no reason not to have documentation or comment in your code as it really doesn’t take much time to do so. Also strive “self-document” your code by naming your methods, functions, and variables to indicate the purpose of components.

4. Tap into Python Logic Operands

The logical operations found in Python are not just meant for giving the usual True or False values. They also have the capability to return the actual value of the operations and this reveals how powerful the operand can be for you. With the powerful logic operands at your disposal, you can easily speed up your coding process as well as enhance the readability of your code.

Let’s see some examples of this powerful logic at work; we have an object to be fetched from the cache and if it is missed it will alternatively fetch from the database.

# check_in_cache returns object or None
def get_obj(): 
return check_in_cache() or pull_from_db()

The above code snippet would have been written in an ordinary way an appear as follows;

def get_obj():
result = check_in_cache()
if result is None:
        result = pull_from_db()
    return result

Here four lines of code are required to achieve the same result as our first snippet which is only one expressive readable line of code.

However, as you tap into the power of Python logic operands stay sharp and remember returning objects that have the logical equivalent of False for example empty list. When for example you have the check_in_cache() function giving you that particular object, it will be handled as missing resulting in your application giving a pull_from_db function. In this case, you will have to consider using an additional explicit is None check.

5. Have a Properly Structured Repository

As a developer today regardless of the language you use, all new projects begin with setting up of a code repository and a form of version control.

A proper project structure accompanied by a suitably crafted repository is a must for any developer and there is no way around it. With Python, it is considered best practice to have key components present in your repository. Emphasis is also placed upon taking time to generate each component of your repository even in a basic structure form before beginning the coding process.

  • License – [root]: The first file you should add to your project. Not sure how to go about creating this file, take a look at choosealicense.com to help you on this path.

  • README – [root]: This file is where you get to talk about your project; what it is about, what it does and what it is designed for. Your basic README file may take the form of plain text, reStructuredText or Markdown.

  • Module Code – [root] or [/module]: Despite this not being critical if you have no worthwhile code being created still make sure you put all your actual code in a suitable named subdirectory (maybe /module) and in case yours is a single file project, place it within root itself.

  • setup.py – [root]: this is a basic script found in a majority of Python projects. It works to enable Distutils’ proper building and distribution of modules needed by your project. For more information on setup.py visit the official documentation.

  • requirements.txt – [root]: This file is used to detail the development modules and additional dependencies needed to properly work on the project. However, you may note that some projects may lack the requirements.txt file. For further details, you may visit the official PIP page.

  • Documentation – [/docs]: For you to have a well-structured project having documentation is fundamental. You will typically place your documentation in the /docs directory.

  • Tests – [/tests]: Another typical part of most projects the tests should be put in their corresponding directory.

With all the above in mind your basic Python repository would look like this:

6. Apply Python Properties and avoid Explicit Getters and Setters

The result of constantly using Python properties (@property)  is that you get much cleaner code as compared when using getters and setters.

A comparison is detailed below to show you how well Python properties will work for you. We will use an example of a Java-style written code snippet that has getters and setters:

class A:

  def __init__(self, some)

    self._b = some

  def get_b(self):

    return self._b

  def set_b(self, val):

    self._b = val

a = A('123')



We now compare this with code that has been written using the Python style properties:

class A:

  def __init__(self, some)

    self._b = some


  def b(self):

    return self._b


  def b_setter(self, val):

    self._b = val

a = A('123')


a.b = '123'

Take caution and avoid encapsulating any heavy calculations or complicated logic behind the property as this may confuse other developers who come across or use your code.

7. Leave No Broken Windows Unrepaired

For the long term benefit of your project and others who shall use it, it is important to recognize, accept and repair any broken code (broken windows) immediately. Neglecting to do this more often than not snowballs down into complex and much greater problems later on. An example from Microsoft who adopted the “zero defects methodology” to their great benefit when they faced challenges in fixing bugs and errors found in their original version of Microsoft Word. Clearing away a poor production cycle will ave you from many issues down the line and you will be very grateful that you repaired your broken windows before anything else gets lost or goes out of hand.

In conclusion

While Python presents you with an outrightly powerful development platform, you are tasked with the great responsibility of using it well. The above list of best practices may not be entirely exhaustive it is still your duty to implement them and many more that you come across. This will help you in your quest towards tapping into everything that Python has to offer.


What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...

Python Hello World Program - Create & Run Your First Python Program in PyCharm

Python Hello World Program - Your first step towards Python world. Learn how to create the Hello World Python program in PyCharm.

Standard Data Types in Python - Python Tutorial - Python Training

This video on 'Standard Data Types in Python' will help you establish a foothold on Python by helping you learn basic concepts.

Python Libraries You Must Learn in 2020-Learn Python-Python Training

This LIVE session on 'Python Libraries' will help you understand the topmost trending Python libraries toy must learn.