A brief guide to Python programming best practices

Tauseef Malik
2 min readJun 28, 2021


Photo by Chris Ried on Unsplash

As a software developer, we should always strive to maintain good code quality by following best practices or standards. This is to ensure that the code delivered to solve a problem is readable and maintainable in the long run. To quote Guido van Rossum, “Code is read much more often than it is written.” which pretty much sums up a software developer’s day! 😄

Here, I will try to summarize some of the practices which I have learnt & followed while working with Python programming language

One of the utmost important thing in any programming language is naming. From naming variable, methods and pretty much everything, It sometimes takes a good amount of time just to come up with a good name!

Naming conventions (PEP-8)

  1. Variables, functions, methods, packages, modules: this_is_a_variable (Snake-case)
  2. Classes and exceptions: CapWords (Pascal case)
  3. Protected methods and internal functions: _single_leading_underscore
  4. Private methods: __double_leading_underscore
  5. Constants: CAPS_WITH_UNDERSCORES (All caps)

General best practices

  1. Maintain all dependencies in requirement.txt file for the lambda
  2. Maintain all constants in constants.py file for the lambda
  3. Null check before accessing values and Checking against None (very important). For e.g.
bad practice:
if data["state"] == "fixed":
good practice:
if data and data["state"] == "fixed":

4. Method annotation with expected return type to enforce types. For e.g.

def circumference(radius: float) -> float:

5. Do not use hard-coded strings.use constants instead.

bad practice:
"google.com" in link:
good practice:
google_link in link:

6. Avoid using messy nested if-else. Use switcher instead if possible.

7. Use constants or enums in-place of magic numbers.

8. Never Ignore the Exceptions you catch! Errors should never pass silently.

bad practice:
catch Exception as ex:

9. Cache/Store frequently used values.

10. Use conditional checks to check against whitelist of conditions.

11. Document __init__ methods in the doc-string for the class.

12. Use getters and setters instead of directly accessing globals and privates

>>> class C:
… def x(self):
… return self.__x
… def x(self, value):
… self.__x = value

13. Use String interpolation or String Templating library to avoid security issues.

14. use ‘in’ and == cautiously for string comparisons.

15. For Reading and Writing to a File, Use With Statement Context Managers as it manages the closing the file handle for you.

These are just some of the practices and there are so much more, if you want to learn more then I recommend to go through the PEP-8 styling guide mentioned in the good reads below. Hope you find this article helpful. Thanks for reading! 😃

Some other good reads -