[Introduction to Python Tutorial] 6 Tips for Optimizing and Refactoring Python Code

Writing clean Pythonic code is all about making it as concise and understandable as possible. So when you learn programming to a certain stage, it is necessary to refactor the code.

However, many inexperienced learners want to refactor the lengthy code they wrote but have no idea. Today we will share a few tips for refactoring and optimizing python code to help you.

The point of this article is to discuss why these refactorings are good ideas, not just how to do them.

  1. Combine nested if conditions

Too much nesting can make code difficult to understand, especially in Python, which doesn't have parentheses to help separate different levels of nesting.

Reading deeply nested code can be frustrating because you have to sort out which conditions belong to which level. Therefore, we should reduce nesting as much as possible, if two conditions can be combined with and, it will be more readable than nesting.

Before merging:

After merging:

  1. Move duplicate code outside of conditional statements

We should always look for ways to remove duplicate code. This is a great way to improve your coding skills.

Sometimes, duplicate code occurs on both branches of a condition, which means that this code will always execute. So this repetitive code can be moved out of the condition and executed outside the condition.

By moving the assignment to the label variable outside the condition, we removed the duplicate lines of code and made it clear what the condition actually controls, which is calculating the total.

  1. Replace yield in inner loop with yield from

A little trick that is often overlooked is that Python's yield keyword has a corresponding yield from for collections. So there is no need to use a for loop to iterate over the collection. This keeps the code shorter and removes the extra variable in the for. And after eliminating the for loop, yield from makes the program run about 15% more efficient.

Before refactoring:

After refactoring:

  1. use any() instead of for loop

A common pattern is that we need to find if one or more items in a collection meet certain conditions. This can be done with a for loop, for example:

A more concise approach is to use Python's any() and all() built-in functions to clearly show the intent of the code.

any() will return True when at least one element evaluates to True, and all() will return True only if all elements evaluate to True.

If the call to any() finds an element with the value True, it can return immediately.

  1. replace list() with [ ]

The most concise and Pythonic way to create a list is to use [].

This has the added advantage of being a great way to improve program performance.

Here's a comparison of the time before and after the change:

For the same reason and performance, use { } instead of dict().

  1. Move repeated statements out of for/while loops

Move the "invariant" statement out of the loop. If a statement just sets some variables for the loop to use, it doesn't need to be in the loop. Loops are inherently complex, so keep them in mind when writing them to make them shorter and easier to understand.
In this example, the city variable is assigned a value in the loop, but it is only read and not changed.

So it's safe to move it out, which makes it more clear that the same city value will be applied to every building variable.

This also improves program performance because if any statements in the loop will be executed each time the loop runs. The time spent on these multiple executions is wasted because it only needs to be executed once. This savings can be significant if the statement involves calls to the database or other time-consuming tasks.
Recommended articles in the past:
Can you really learn Python by yourself? If
you want to easily get started with Python programming, you must read these 10 classic cases, and you can find a job after
learning Python learning: quickly build a python environment

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326831010&siteId=291194637