Fundamentals 13 min read

Mastering Python Variable Naming: Boost Code Readability

This article explores why descriptive variable names are crucial for Python code quality, presents practical naming principles, discusses type‑hinting through names, introduces Hungarian notation, and offers actionable tips for defining, using, and cleaning up variables to write clearer, more maintainable code.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Python Variable Naming: Boost Code Readability

Variable and Code Quality

As the first article in the "Python Craftsman" series, it focuses on variables, a fundamental skill for any programming language, and explains how good variable naming directly impacts code quality.

How to Name Variables

Good names improve readability. The article lists several core principles:

1. Descriptive and specific

Use names that precisely describe the value within an acceptable length. Examples of good names: day_of_week, hosts_to_reboot, expired_cards. Bad examples: day, host, cards, temp.

2. Hint the type when possible

Although Python is dynamically typed, certain prefixes convey expected types. Boolean‑like names start with is or has (e.g., is_superuser, has_error, allow_vip, debug). Numeric names often include words like port, age, radius, or end with _id, _count, _length. Avoid plain plurals for numbers; prefer number_of_apples or apples_count.

3. Hungarian notation (optional)

Prefixing with an abbreviation of the logical type can help when many variables of the same kind appear, e.g., pl_students for a list of Person objects.

4. Keep names short but meaningful

A good name should be about two to three words. Overly long names like how_much_points_need_for_level2 are discouraged; a concise alternative is points_level2. Avoid one‑ or two‑letter names such as i, j, k unless the context is obvious.

5. Other considerations

Do not use overly similar names in the same scope (e.g., users, users1, user3).

Prefer positive naming: use is_special instead of is_not_normal.

Better Variable Usage

1. Consistency

Use the same name for the same concept throughout the codebase; avoid mixing photo and image for the same variable.

2. Avoid globals()/locals()

Do not rely on locals() to pass variables to templates; it obscures which variables are used. Instead, pass an explicit dictionary.

def render(request, user_id, trip_id):
    user = User.objects.get(id=user_id)
    trip = get_object_or_404(Trip, pk=trip_id)
    is_suggested = is_suggested(user, trip)
    return render(request, 'trip.html', {
        'user': user,
        'trip': trip,
        'is_suggested': is_suggested
    })

3. Define variables close to their use

Instead of declaring many variables at the top of a function, place each definition near where it is first needed.

def generate_trip_png(trip):
    path = []
    markers = []
    photo_markers = []
    text_markers = []
    marker_count = 0
    point_count = 0
    # ... further logic ...

4. Return dicts for flexible multiple values

When a function may need to add return values later, returning a dictionary avoids breaking existing callers.

def latlon_to_address(lat, lon):
    return {
        'country': country,
        'province': province,
        'city': city
    }

addr_dict = latlon_to_address(lat, lon)

5. Limit variable count per function

Human short‑term memory can handle about ten items; split overly long functions into smaller ones.

6. Remove unused variables

Delete variables that are never read to keep the code clean.

def fancy_func():
    # reader expects to see usage of fancy_vars
    fancy_vars = get_fancy()
    # ... many lines ...
    return result

7. Avoid unnecessary temporary variables

When a variable is only used once, return the expression directly.

def get_best_trip_by_user_id(user_id):
    return {
        'user': get_user(user_id),
        'trip': get_best_trip(user_id)
    }

Conclusion

Thoughtful variable naming and disciplined usage significantly improve code readability and maintainability. This is the first article of the "Python Craftsman" series, inviting readers to share feedback.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonbest practicescode qualityvariable namingprogramming fundamentals
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.