Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Write Better Python Code Today

Julie Perilla Garcia
Level Up Coding
Published in
8 min readJan 8, 2020

--

Photo by Artem Sapegin on Unsplash

One of Python’s greatest attributes is readability. So, it is often painful when you open another programmer’s code and have no idea what she was trying to accomplish.

As developers, we often tackle a new problem head-on with brute force, manipulating our code until we get it to work. We look at our terminals, browsers, or applications in delight as they do just what we set out for them to do.

Then, we look at the code mess we created — time to refactor.

Wouldn’t it be better to tackle the structure and readability of your code as you go? Here are a few simple steps to start cleaning up your Python code today. Try this out on just one of your scripts, and you will see immediate results in readability, maintainability, and testability. The next time you receive a new assignment, try implementing these tactics as you go. It will make coding a lot more fun.

Setup Your Text Editor to Format Your Code to PEP8

The first step to clean code in Python is to format your code according to PEP8. While it’s worth reading the PEP8 specification, you certainly are not going to edit every line of your existing code to be formatted to PEP8. That would take forever and might make you cry.

Luckily, there are tools to help with PEP8 formatting. Some common Python packages used to autoformat to PEP8 are autopep8, black, and yapf.

You can even use these packages to setup autoformatting on Save of your Python files within your chosen text editor. Here is a list of some common text editors with links on how to setup autoformatting.

I use PyCharm, which defaults to the PEP8 coding style for Python, and will highlight violations in your editor with tooltips on how to fix them. This method is a great way to learn PEP8. You can also run the Code > Reformat Code tool that does the reformatting for you. In PyCharm, you can use the File Watcher feature to run formatting automatically on Save.

--

--

Written by Julie Perilla Garcia

Founder of The Developer Experience 👩🏻‍💻 How to Code Better, Work Better, Be Better, Stand Out in the Crowd 🤖 JavaScript, Python, React, GraphQL

Responses (6)

Write a response