Aveek Das
PEP Workflow - Programming in Python

Best practices to follow while programming in Python

February 9, 2021 by

In this article, I am going to discuss some of the best practices that a programmer must follow while programming in python. Python as a language has evolved to a great extent over the last few decades and has gained popularity amongst a lot of software programmers, data enthusiasts, and system administrators. This is because of the ease of writing code in python and the large community behind it.

Programming Language Survey - Programming in Python

Figure 1 – Programming Language Survey (Source)

In the above figure, you can see the trend of python as compared to the other popular programming languages. This survey was conducted by Stack Overflow and reflects that developers love programming in python and the popularity is still rising.

Overview of PEP

As per the official documentation – “PEP stands for Python Enhancement Proposal. A PEP is a design document providing information to the Python community, or describing a new feature for Python or its processes or environment. The PEP should provide a concise technical specification of the feature and a rationale for the feature.” You can read more about PEP here. Basically, PEP enables the developers to propose new features to the python community, raise and track issues with the community and also document the design decisions for implementing a particular feature within python. If you are beginning to programming in python, I would suggest understanding how python and the community around it work for a better understanding of the community standards.

PEP Workflow - Programming in Python

Figure – PEP Workflow (Source)

In the above figure, you can see a workflow that describes how the PEP tasks are maintained and released. In this article, I might use PEP as a reference to some design and code guidelines.

Naming Styles in Python

When you start programming in python or any other language, a lot of the effort goes into deciding meaningful class names, variables, method names etc. Although it differs from developer to developer, it is often advised that we should follow a similar naming pattern while writing code. PEP-8 is a styling guideline offered by the community that tells us how we should choose and define our naming conventions for our python program. The PEP-8 is guide was developed by Guido van Rossum, Barry Warsaw, and Nick Coghlan in 2001 which primarily focuses to improve the readability and consistency of the python code. I am going to discuss a few of the major naming convention best practices from this guideline below.

Object Type

Naming Examples

Description

Variables

variable, short_variable, this_is_a_long_variable

Use meaningful words variables that describe the type of data that you are using the variable for. Long variables are advised to be separated using underscores, which helps in enhanced readability.

Classes

Class, LongClassName

While writing class names in python, you should use upper case alphabets for each of the words. This style of writing words is called CamelCase, popular while writing class names in many other programming languages as well. Do not use hyphens or underscores to separate the words in class names.

Methods

class_method(arg_a, arg_b), this_is_a_long_class_method()

A method is defined inside a class to get or set specific attributes of the class. While writing code for methods, the preferred way is to use all lowercase alphabets and separate the words by using underscore. Also, your method might take arguments, for which you can name your arguments in the same way you name of method names, by using underscores as separators between words.

Protected Methods

_protected_method(self, …)

Protected methods are used inside class objects within python. These methods are written with a starting underscore in front of the method name.

Private Methods

__private_method(self, …)

Private methods are also used inside class objects within python. These methods are written with a double underscore in front of the method name.

Functions

function(), short_function()

A function is something similar to a method, the only difference is that a function is not associated with a class. You can use the same naming conventions for functions and methods. Both can be separated by using underscores.

Constants

CONSTANT, THIS_IS_A_LONG_CONSTANT

Constants are values in python that have the same value throughout the execution flow and it is assigned once during the initialization. You should use uppercase letters to name a constant and separate those using underscores as well. You can define long or short constant names based on the purpose of the constant that is being used in the context.

Module

module.py, long_module_name.py

A module is a python that you can import into your code while writing programs. It is essentially imported as a python object into your code that you can use to refer and bind values to. You should use all lowercase letters for naming your modules and use underscores as separators.

Package

mypackage, shortpackage

A package is a collection of one or more python files that together serve a specific purpose. A package can also be a directory that contains a few python modules along with a __init__.py file.

Simple tips while programming in Python

Now that you are aware of the naming conventions and styles while programming in python, let us look into a few simple tips that will help you understand your code better.

Programming in Python

Figure – Programming in Python (Source)

Check the memory of your python objects

When you create variables or data frames in python, often it becomes challenging if you are allocating a lot of data into the variable. It is advised that you efficiently check the memory of your variables while writing your code, so that you know how to deal with those variables. You can use the following code to see the memory of your objects.

The above code will take all integers from 0 to 100000 and store them as a list to the variable test_list and output as 824464 bytes or roughly 800 KB.

Return multiple values from Functions

This is one of my most favorite tips that I have been using for a long time now. I was not aware of this functionality and often used it to wrap multiple variables into a list or dictionary before returning to the function. This significantly helps to write simpler code rather than combining all the variables to a list or dictionary. As a best practice, you can use this tip when you have at most three or four return variables. In case you have more variables to return, you can use a data class. Read more about python data classes here.

Joining strings in python

While programming in python or any other programming language, you might often come across situations wherein you would need to join one or more strings together to form a concatenated string. Fortunately, python offers a .join method using which you can concatenate all the strings from a given list. Alternatively, you can also do a loop to join the different strings in the list, however that is not considered a good design.

As you can see in the code above, you need to provide a space between quotes before the .join method, and as such the strings are concatenated.

Inline Documentation

While your program with python, sometimes it becomes essential to document the purpose of your code block. PEP-257 introduces a concept of using docstrings within your python code that helps you documents your methods and classes easily. You can use one-liners for your simple functions as below.

If you need to write multi-line documentation, you can follow this example.

Conclusion

In this article, I have explained a few ways to be a better programmer while programming in Python and follow best practices and guidelines. As a developer, your code should be easy to understand to anyone who reads it, well documented, and simple. You should always take special care while naming variables and methods as it helps a lot when any other developer tries to understand your code.

Table of contents

Setting up Visual Studio Code for Python Development
How to debug Python scripts in Visual Studio Code
Deploy Python apps to Azure Functions using Visual Studio Code
Getting started with Amazon S3 and Python
Getting started with Pandas in Python
Working with Pandas Dataframes in Python
Exploring databases in Python using Pandas
Best practices to follow while programming in Python
Exporting data with Pandas in Python
Create REST APIs in Python using Flask
Working with JSON data in Python
Understanding *args and *kwargs arguments in Python

Aveek Das
Python

About Aveek Das

Aveek is an experienced Data and Analytics Engineer, currently working in Dublin, Ireland. His main areas of technical interest include SQL Server, SSIS/ETL, SSAS, Python, Big Data tools like Apache Spark, Kafka, and cloud technologies such as AWS/Amazon and Azure. He is a prolific author, with over 100 articles published on various technical blogs, including his own blog, and a frequent contributor to different technical forums. In his leisure time, he enjoys amateur photography mostly street imagery and still life. Some glimpses of his work can be found on Instagram. You can also find him on LinkedIn View all posts by Aveek Das

956 Views