Analytics Vidhya
Published in

Analytics Vidhya

How to write beautiful python code.

Take care of the names, I will take care of the formatting

Photo by Clément Hélardot on Unsplash

In this blog, you will learn how to transform your python code and make it aesthetic, readable, and structured. The idea is, codes should flow like a story. Now, if this seems a little intimidating, hang in there because apart from writing the documentation and naming variables, everything else is automated.

Naming Convention

Now the naming convention in Python is a little messed up. This is not my interpretation, it is written in pep8 like this:

“The naming conventions of Python’s library are a bit of a mess, so we’ll never get this completely consistent — nevertheless, here are the currently recommended naming standards. New modules and packages (including third party frameworks) should be written to these standards, but where an existing library has a different style, internal consistency is preferred.” — [PEP 8]

Let me give you some simple rules to follow.

Rule 1 — Write your variable names, method names, and function names in lowercase, separated by an underscore.

Rule 2 — Keep these variable names short and simple, these are characters of your story. Avoid — “very_long_variable_names” instead use “short_names”

Tip: Humanize variables, think variables as your friend, and name them accordingly.


Rule 4 — CamelCase ClassNames

With these simple rules, you will not violate any of the pep8 principles. Also, don’t worry about remembering them all. Later in the auto-formatting section, I will share one great tool that will help you find the wrong variable names and rename them. Just make sure you keep the function and variable name as they are your friend.


Find your score out of 10

Do not feel bad about your first score, mine was a -4.5. Save your python file and do the following.

Step 1

Step 2

In your directory where your code is just run

Simple right? — this will give you a score out of 10 and will very nicely point out all the issues. Now before making any changes, just run the following command.

Step 3

Step 4

Step 5

Run pylint again and see if your score improved or not.

(Pylint takes white spaces very seriously!)

Step 6

Now that we are almost done making your code pretty, you can visually see the difference after autopep8. Try to attack every point in the pylint report. I feel a good code has a score above 8.5. This is not a hard and fast rule but based on my industry experience as a Data Science Engineer, we can live with it with no issues.

Let me also give some more tools which you can use for auto-formatting.

  1. autopep8 — discussed above
  2. Yapf
  3. Black

P.S. Pylint is also present as a VS code extension where it highlights the variable names and other deviations from pep8. Make sure you activate that as well.

Comments < Docstring < Standard Documentation

Now, if you have run the pylint and if you are writing non-documented code you will come across one very peculiar error in pylint — docstring missing. Docstrings are like a small writeup about your code, class, functions, and methods, its task (ideally, it should be in one line), and about its arguments i.e., input and return i.e. output.

The various docstrings are given in the snippet below.

Now we can take the documentation to the next level (as I have done above) by following set formats of docstrings and later on, use a module like the sphinx. I highly recommend reading about various standard formats of docstrings. I like to follow the NumPy format given in this link. [link]

If you are a VS code user, a very nice extension can help you automatically create the placeholder for your standard documentation format. The extension is “Python Docstring Generator” — linked here.

Importance of version control

Photo by Yancy Min on Unsplash

One thing that we often overlook while developing locally is version control. You can avoid a lot of headaches if you start using it. This is a slight deviation from how to write a beautiful python code but adds great value in terms of maintaining a long-term history of every file, branching and merging to test different features, high availability, and disaster recovery.

Bring it all together

Start your code with a docstring: the scope, goal, and how to use it. Add more details about additional documentation in this section. I know it’s too much to ask but trust me, it adds a lot of value. It’s like an introduction about your code where you are the author. Add a README file from the start.

We start with all imports, pylint will take care of all the import sequences and declare all the constants. Now declare all your functions and methods and add a standard docstring in every function. Maintain a flow of functions, each function should have one and only one task. Run any auto-formatting tool and get your pylint score, improve the score to go above 8 and you are done. A beautiful python code.

The Zen of Python.

No matter how many tips and tricks are discussed, it will always start with “import this.” If you haven’t tried it before, just type and execute “import this” in the python interpreter and you will see the 19 guiding principles written by Tim Peters. These are also mentioned in [PEP 20]

The principles are given below, I highly recommend reading about them and I have not covered that in this article.

  1. Beautiful is better than ugly.
  2. Explicit is better than implicit.
  3. Simple is better than complex.
  4. Complex is better than complicated.
  5. Flat is better than nested.
  6. Sparse is better than dense.
  7. Readability counts.
  8. Special cases aren’t special enough to break the rules.
  9. Although practicality beats purity.
  10. Errors should never pass silently.
  11. Unless explicitly silenced.
  12. In the face of ambiguity, refuse the temptation to guess.
  13. There should be one — and preferably only one — obvious way to do it.
  14. Although that way may not be obvious at first unless you’re Dutch.
  15. Now is better than never.
  16. Although never is often better than *right* now.
  17. If the implementation is hard to explain, it’s a bad idea.
  18. If the implementation is easy to explain, it may be a good idea.
  19. Namespaces are one honking great idea — let’s do more of those!

I hope your code is now more presentable, easy to read and understand. Later in life when you look at your code you will thank yourself that you documented it so well and it looks so elegant.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
prakshaal jain

prakshaal jain


MBA Business Analytics, NMIMS, Mumbai (21–23), Former Data Science Engineer at Utopia Global, Inc.