Skip to Content
Course content

10: Auto-Formatting Code with black

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Look, we've all been there. You're deep in the zone, cranking out logic, and you don't care if your indentation is slightly off or if your lists are sprawling across three lines in a way that makes your eyes bleed. When you finally look back at your code, it's a mess. You could spend twenty minutes manually fixing the whitespace and aligning your brackets, but that's a waste of your brainpower.

That's where black comes in. I call it "the uncompromising code formatter." It doesn't give you a hundred options to tweak; it just decides how the code should look and enforces it. This is actually a blessing because it ends the "tabs vs. spaces" or "single vs. double quotes" arguments in a team instantly. If Black says it looks like this, it looks like this.

Creating a formatting nightmare

To see this in action, I'm going to write a quick script that calculates some basic stats for a small group of employees. I'm intentionally going to write this as poorly as possible—mixing quote styles, adding random whitespace, and letting lines run way too long.

def calculate_bonus( employees):
    results = {}
    for emp in employees:
        # This line is way too long and inconsistent
        bonus = emp['salary'] * 0.1 if emp['performance'] == 'Excellent' else emp['salary']*0.05 if emp['performance'] == 'Good' else 0
        results[emp['name']] = bonus
    return results

staff = [
    {"name":"Alice", "salary": 80000, "performance" : 'Excellent'},
    {"name": 'Bob', "salary":60000,"performance": "Good"},
    {"name": "Charlie", "salary":50000, "performance":'Poor'}
]

print(calculate_bonus( staff))

It works, but it's ugly. The bonus calculation is a readability disaster, and the dictionary formatting is all over the place. I could fix this by hand, but I'd rather let a tool do it.

The "Wait, why isn't this working?" moment

First, I'll install it via pip: pip install black. Now, here is where I usually trip up when I'm tired. I remember that Black is a Python package, so my first instinct is to try and call it from inside my script like a library.

# My mistaken attempt
import black
black.format_file("my_script.py") # This isn't how we actually use it!

I quickly realize I'm overcomplicating things. Black is designed to be a Command Line Interface (CLI) tool. You don't import it into your logic; you run it against your files from the terminal. I'll scrap that import and head back to my shell.

Letting Black take the wheel

Now, I'll run the command on my file. Assuming my file is named bonuses.py, I just run:

black bonuses.py

When I open the file again, the transformation is immediate. Black didn't change a single line of logic, but it completely restructured the visual layout. Here is what it looks like now:

def calculate_bonus(employees):
    results = {}
    for emp in employees:
        # This line is way too long and inconsistent
        bonus = (
            emp["salary"] * 0.1
            if emp["performance"] == "Excellent"
            else emp["salary"] * 0.05
            if emp["performance"] == "Good"
            else 0
        )
        results[emp["name"]] = bonus
    return results


staff = [
    {"name": "Alice", "salary": 80000, "performance": "Excellent"},
    {"name": "Bob", "salary": 60000, "performance": "Good"},
    {"name": "Charlie", "salary": 50000, "performance": "Poor"},
]

print(calculate_bonus(staff))

Notice how it standardized all the quotes to double quotes (") and broke that long ternary operator into a readable block. It also added the proper spacing around the dictionary keys and values. Now, instead of squinting at the code, I can actually see the logic.




📋 Practical Task

Refactoring the Messy Inventory System

I've provided a snippet of code below that manages a warehouse inventory. It is logically correct, but it is a complete eyesore with inconsistent spacing, trailing commas, and long lines that would make any senior dev cringe.

Your goal: Copy this code into a file named inventory.py, install black, and run it against the file. Then, submit the final, formatted version of the code.

def update_stock(items,new_arrivals):
    for item,qty in new_arrivals.items():
        if item in items:
            items[item] += qty
        else:
            items[item] = qty
    return items

current_stock = {"apples":10,   "bananas": 20, "oranges":15}
shipment = {"apples": 5, "pears": 12,  "bananas": 10}

# This line is an absolute mess of spacing
updated_inventory = update_stock(current_stock,shipment)
print(f"The current inventory is now: {updated_inventory}")
Rating
0 0

There are no comments for now.

to be the first to leave a comment.