picture

Translator |
Reviewer | Sun Shujuan

Do you often look back at code you wrote 6 months ago and wonder what the hell is going on with that code? Or take over a project from someone else and don't know where to start? This is a relatively common situation for developers. Common.

There are many ways in Python to help us understand the inner workings of code, so it should be easier to pick up where you left off when you look at or write code from the beginning.

Here I will give you an example, we may get the code as shown in the following figure. It's not the worst, but there are a few things we need to confirm, such as:

  • What do f and d stand for in the load_las_file function?
  • Why do we check the result in the clay function?
  • What type do these functions expect? Float or DataFrames?
picture
In this article, I'll cover 5 basic tips on how to improve the readability of your app/script through documentation, prompting for input, and proper variable names.
  PAR T 01  

 Notes 

The first thing we can do with the code is to add comments to certain lines, but be careful not to overcomment them. Comments need to explain why the code works, or why something is done a certain way, not how it is implemented.

Comments in Python are usually done using the pound sign (#) and can span one line or multiple lines.
# Comment using the hashtag
# Another comment using the hashtag
For multi-line comments, we can also use double quotes.
"""
This is an example of
a multi-line comment
"""

In the example below, some comments have been added to the code to explain the workflow and why of certain lines of code:

picture
  PAR T 02  

 explicit type 

The Python language is dynamically typed, which means that variable types are only checked at runtime. Also, variables can change type during code execution. On the other hand, static typing involves explicitly declaring variable types and cannot be changed during code execution.
In 2014, PEP 484 introduced the concept of type hints, which was subsequently introduced into Python 3.5. This allows you to explicitly declare variable types.

By adding type hints, you can significantly improve the readability of your code. In the example below, we can see that:

  • requires two parameters
  • The type of the parameter filename is a string
  • The type of the parameter start_depth is float, and the default value of this parameter is None
  • The function will return a pandas DataFrame object
picture
With type hints, we can know exactly what the function needs, and what it will return.

  PAR T 03  

 docstring 

A docstring is a string that immediately follows a function or class definition. Docstrings are a great way to explain in detail what a function does, what arguments are required, what exceptions will be thrown, return values, and more.

Also, if a tool like Sphinx is used to create online documentation for the code, the docstrings will be automatically extracted and converted to the appropriate documentation.

The following example shows the docstring for a function named clay_volume. Here we can specify the meaning of each parameter. This makes it more verbose than basic type hints. You can also include more information about the methodology behind the function, such as academic references or equations.

picture
Docstrings are also very helpful when we call functions elsewhere in the code. For example, when writing code in Visual Studio, you can hover over a function call and see a popup showing what the function does and what it needs.
picture
If you use Visual Studio Code (VS Code) to edit your Python code, you can use extensions like autoDocstring to make the process of creating docstrings easier. You can enter three double quotes, and the rest of the template will autofill. You just need to fill in the details.
picture
Tip: If you have declared types in parameters, they will be picked up automatically.

  PAR T 04  

 Human-readable variable names 

Sometimes, when you're writing code, you don't care too much about variable names, especially when time is tight. However, if you look back at the code and find a series of variables named x1 or var123, you may not understand at a glance what they mean.

In the example below, there are two variables f and d. We can guess what such variables mean by looking at other parts of the code, but this can take time, especially if the code is long.

picture
If we give these variables appropriate names, we will be able to know that one of the variables is the data_file read by the lasio.read() call, and most likely the raw data. The data variable tells us that this is the actual data we are dealing with.

picture
  PAR T 05  

 Avoid magic numbers 

Magic numbers are values ​​in code that have an unexplained meaning behind them and can be constants. Using these in code can lead to ambiguity, especially if you're not familiar with using numbers in calculations. Also, if we have the same magic number in multiple places, when it needs to be updated, we have to update every instance of it. However, if such numbers are assigned a suitably named variable, the substitution process is much easier.

In the example below, we have a function that computes a value called result and multiplies it by 0.6. What does this mean? Is it a conversion factor? Is it a scalar?

picture
If we declare a variable and assign that value to it, then we have a better chance of knowing what it is. In this case, the ratio of clay to shale is used to convert the gamma ray index to clay volume.

picture

  PAR T 06  

 final code 

After applying the tricks above, our final code now looks cleaner and easier to understand.

picture

  PAR T 07  

 Summarize 

Adding instructions to your code through comments and docstrings helps you and others understand what the code is doing. It might feel like a chore at first, but with tool use and regular practice, it becomes second nature.

Original link:

https://towardsdatascience.com/5-essential-tips-to-improve-the-readability-of-your-python-code-a1d5e62a4bf0




Translator introduction

Zhao Qingyu, 51CTO community editor, has been engaged in driver development for many years. His research interests include secure OS and network security, and he has published network-related patents.


51CTO technical community is recruiting


Get to know tech giants and improve IT skills
Talk about developing dreams and expanding human resources
Participate in topic discussions and win interactive gifts
Scan the code to add a small assistant and join the community immediately

picture

picture

The highest salary increase! It turned out to be this programming language that is about to "go to the ground"

Zhang Chaoyang, who insisted on "involution", let Sohu "lie down"...

Compared with C++ concurrent libraries, Rust is not too similar!



Click here to " read the full text " to see more exciting content
picture