Clean Code - Variable

Using meaningful and pronounceable variable names

Bad:

import datetime

ymdstr = datetime.date.today().strftime("%y-%m-%d")

Good:

import datetime

current_date: str = datetime.date.today().strftime("%y-%m-%d")

Use searchable names

Bad:

import time

# What is the number 86400 for again?
time.sleep(86400)

Good:

import time

# Declare them in the global namespace for the module.
SECONDS_IN_A_DAY = 60 * 60 * 24
time.sleep(SECONDS_IN_A_DAY)

Use explanatory variables

Bad:

import re

address = "One Infinite Loop, Cupertino 95014"
city_zip_code_regex = r"^[^,\\\\]+[,\\\\\\s]+(.+?)\\s*(\\d{5})?$"

matches = re.match(city_zip_code_regex, address)
if matches:
    print(f"{matches[1]}: {matches[2]}")

Not bad:

It's better, but we are still heavily dependent on regex.

import re

address = "One Infinite Loop, Cupertino 95014"
city_zip_code_regex = r"^[^,\\\\]+[,\\\\\\s]+(.+?)\\s*(\\d{5})?$"
matches = re.match(city_zip_code_regex, address)

if matches:
    city, zip_code = matches.groups()
    print(f"{city}: {zip_code}")

Good:

Decrease dependence on regex by naming subpatterns.

import re

address = "One Infinite Loop, Cupertino 95014"
city_zip_code_regex = r"^[^,\\\\]+[,\\\\\\s]+(?P<city>.+?)\\s*(?P<zip_code>\\d{5})?$"

matches = re.match(city_zip_code_regex, address)
if matches:
    print(f"{matches['city']}, {matches['zip_code']}")

Avoid Mental Mapping

Bad:

seq = ("Austin", "New York", "San Francisco")

for item in seq:
    # do_stuff()
    # do_some_other_stuff()

    # Wait, what's `item` again?
    print(item)

Good:

locations = ("Austin", "New York", "San Francisco")

for location in locations:
    # do_stuff()
    # do_some_other_stuff()
    # ...
    print(location)

Don’t add unneeded context

Bad:

class Car:
    car_make: str
    car_model: str
    car_color: str

Good:

class Car:
    make: str
    model: str
    color: str

Use default arguments instead of short circuiting or conditionals

Tricky

import hashlib

def create_micro_brewery(name):
    name = "Hipster Brew Co." if name is None else name
    slug = hashlib.sha1(name.encode()).hexdigest()
    # etc.

Good:

import hashlib

def create_micro_brewery(name: str = "Hipster Brew Co."):
    slug = hashlib.sha1(name.encode()).hexdigest()
    # etc.


Click here to share this article with your friends on X if you liked it.