Python Useful Tips — Variables, Part Two

Tony
8 min readSep 23, 2024

This is the part two of “Python Useful Tips — Variables”.

Define Variables Close to Their Usage

Many people had a habit when first learning to program: we liked to write all variable initialization definitions together and place them at the beginning of the function, like this:

def create_game_image(game):
"""
Generate a PNG image based on game data
"""
# Predefine all local variables
coordinates = []
image_markers, label_markers = [], []
total_markers = 0
    # Start initializing coordinates data
coordinates.append(...)
...
# After a few lines of code, start processing image_markers and label_markers
image_markers.append(...)
...
# After more code, start calculating total_markers
total_markers += ...

The reason we write code this way is that we think “variable initialization” statements are similar and should be grouped together at the beginning, making the code appear more organized. However, such code only looks tidy; it doesn’t improve readability and can actually make it worse.

When organizing code, we should always focus on its purpose and responsibilities, rather than anything else. Let’s re-write the above code to the following:

--

--

Tony
Tony

No responses yet