fbpx

5 ways to start writing better Python code

Writing better Python code

ARTICLE SUMMARY

How many times did you face badly written Python code? How much did you struggle while going through the 300 lines of function and trying to understand what it does? Magic numbers, multiple nested if-else conditions… there are so many ways to spoil the code!

In this article, there are 5 simple tricks that you can start using right now. Let’s move together toward a better code!

KISS 

The first step is to inspect your code for duplications. Duplication is not simply repeating lines of code, it means duplication of efforts. So let’s say you have an average calculation function implemented in different ways – it will be an effort duplication. Two classes doing a similar job are also efforts and code duplication.

Here I also want to mention one crucial programming principle: KISS. It stands for Keep It Simple, Stupid. So you should treat your code as a whole system and aim to keep this system as simple as possible. 

For example, instead of having 100 lines function try to split it into smaller logical parts and then convert these parts to separate functions. By doing so, you not only increase the code readability but also open a possibility to reuse some smaller functions. 

UNIT TESTS

Unit tests are a vast and popular topic, there are many tutorials and best practices on how to implement them. But here let’s focus on their purpose. Having them is not just a fine option, but it is crucial if the project is a long-term one. So, every time when you add a feature or change something in code, running unit tests will let you know that everything is okay: your code is alive and works as designed. Also, you will definitely appreciate them during the refactoring: it requires a lot of code changes, and tests speed up the project health check significantly.

Here we come to an important software development method: TDD. It stands for Test-Driven Development. It is simple and effective. If you need to create a function or class, take the following approach:

  1. Write unit tests for your future code
  2. Make sure that they fail
  3. Work on code logic, then make sure that tests pass

By doing the first step, you define what are the main parameters of your code, and what should be tested first. The second step is to check the reliability of your tests: if they never fail, something is definitely wrong! The final step is the code implementation, you can get working code and then gradually make it prettier.

DOCSTRINGS

A Python docstring is a string used to document a Python module, class, function, or method. It is an easy way for programmers to understand what it does without reading the code details. They are useful for all programmers including the code author.

To have an idea of how to write them, let’s take a look at PEP standards. PEP (Python Enhancement Proposal) is a document that describes new features proposed for Python and documents aspects of Python, like design and style, for the community. In some way, it is a collection of best practices. Although not all cases are covered by PEP documents, it is good to follow their guide whenever possible. We suggest taking a look at PEP 257, it is specifically dedicated to docstrings.

Also, it is a common practice to generate online documentation automatically from docstrings. There are several API tools like pdoc or pydoctor, you can have a precise look here.  

TYPE HINTING

Having docstrings in the project is certainly a great practice, but developers tend to forget about them, especially when time is short. Type hinting is a way to indicate the type of value within your Python code. It was specified in PEP 484 and introduced in Python 3.5. Their purpose is similar to docstrings: type hints increase the code readability and their presence has no runtime effect. So if you don’t have enough time to add a complete docstring to a function, at least do the type hinting. 

Take a look at the example below: 

extract of Python code

Although it can be guessed from the function itself, variable and return types are really helpful when the function is bigger or more complicated. It can also prevent function misusing: imagine that a certain function is designed to take and work with integers only but fails with floats. Having int indicated as an input variable type would save debugging time.

LINTER

When checking code quality, generally it is a good idea to use automated tools like linters. Linters are programs that highlight syntactical and stylistic problems in your Python code, which often helps to identify programming errors or unconventional coding practices. So they save time and developers’ efforts. 

There are several linters for Python, the most popular two are pylint and flake8. They have their advantages and drawbacks, so the advice is to try each option and choose which one is better for certain project needs. You can also check others like autopep8

What can linters help with? They are a good tool to check if variable names are meaningful, whether your code contains docstrings, if the length of code lines is good, etc. Linter will help to identify unused code and redundant imports. You can adjust linter settings according to your project. The only thing to keep in mind is that any linter is not a silver bullet: it will check the ‘spelling’ and ‘grammar’ of your code, but cannot figure out if the code makes sense or does what it should do.

In conclusion, the article highlights five simple tricks that can help improve the quality of Python code. These include avoiding code duplication, implementing unit tests, using docstrings, type hinting, and using linters to remove unused code. By following these practices, developers can make their code more readable, maintainable, and scalable, which ultimately leads to a better software development experience.

RELATED ARTICLES

Join SheCanCode for a day of ideation and coding at our Financial Inclusion Power Hack! Spend the day coding solutions that will help tackle financial...
Join SheCanCode for a day of ideation and coding at our International Women’s Day Power Hack! Spend the day coding solutions that will directly help...
The article delves into the extensive capabilities of NumPy, a critical numerical computing library in Python. It provides a comprehensive NumPy cheat sheet, covering essential...
The article provides a comprehensive dictionary of common coding languages, offering insights into their key features and diverse applications. From Python's versatility to Swift's role...

This website stores cookies on your computer. These cookies are used to improve your website and provide more personalized services to you, both on this website and through other media. To find out more about the cookies we use, see our Privacy Policy.