Best practices to write python code:

Pranjal Goyal
3 min readApr 10, 2022

--

Writing code is an art, it is not just writing something that works (Also if it works don't touch it (just kidding)😅). A quality code should be understood by anyone and its description should be clear about what it does and how it does that.

Python Language

Some best-practice for writing code in python:

Writing proper names and following conventions:

Naming variables and functions with enough description help others and yourself in a later stage to review the code and understand how the code functions and works.

The variable and function names are generally written in snake_case and global variables and Classname are written in CamelCase in python.

Naming Convention

Passing parameter type, return type, DocString in the function:

Specifying parameter type, return type and docstring(“documenting a function body”) helps in better visibility of code like if a person is calling the function in another file.

It could be easily understood what parameters the function takes and its return type without actually going inside the function.

Also, following PEP-8 guidelines will make your code look better, you can just use any IDE and format code with just one command.

Using Python inbuilt looping and methods:

One of the most powerful features of python is the support of libraries and inbuilt functions. Therefore it is always better to use the inbuilt function wherever possible since it gives the best-optimized version of that method.

Also, people tend to use index-based looping which can be avoided in python.

Inbuilt looping

Structure code into different directories:

Writing the whole code in a single python file can create readability and maintainability issues (+ stress to developers).

So it is better to structure code into different files and directories and it can be easily imported wherever it is needed.

Specifying Exception and its alternative path:

It is generally not a good practice to just write pass in case of an Exception, because as the codebase will expand we need to provide an alternative way once the exception occurs or just log it.

Exception Handling

I have written a dedicated Medium Article about Exception handling:

Till next time keep exploring keep learning…

“Sometimes it’s better to leave something alone, to pause, and that’s very true of programming.”Joyce Wheeler

Connect with me:
Wanna talk about something let’s connect?

Linkedin | Twitter | Github

--

--

Pranjal Goyal

Coding is ❤ | Computer Graduate | Learning New Things Everyday… | I write good stuff