Black: auto-formatting
Overview
**Memorizable line:** Black is a tool that automatically fixes your code spacing and quotes to look perfect. When many people work on a project, everyone types differently. Some use single quotes, some use double quotes. Some use extra spaces. Here is messy code: ```python def add ( a ,b): return a+ b ``` If you run Black on this file, it automatically changes it to: ```python def add(a, b): return a + b ``` Black is `uncompromising`. This means it does not ask for your opinion. It has one strict set of rules, and it applies them to everyone's code. You run it from your terminal: `black my_file.py`. **Analogy:** Think of Black as a strict school uniform. You do not get to choose the colors, but everyone looks neat, and no one argues about fashion.
It stops arguments about code style. Developers save time because they never have to manually fix spaces again.
Where used: FastAPI, Django, pytest
Why learn this
- Makes your code look professional instantly without manual effort.
Code walkthrough
def run():
x = { 'a':1,'b':2 }
return x
print(run())
Focus: x = { 'a':1,'b':2 }
Aha moment
def func(): return 1
print(func())
Prediction: If Black formats this, how many lines will it become?
Common guess: One line.
Black expands one-liners. It will become two lines: one for `def func():` and one for `return 1`.
Common mistakes
- Fighting the formatter: Trying to manually fix spaces after Black runs. Just let Black do its job.
Recall questions
- Explain Black in your own words, as if to a classmate.
- What does it mean that Black is uncompromising?
Understanding checks
Which of these is true about Black? A: It finds logic bugs in your code. B: It only changes spacing and formatting.
B
Black is a formatter. It only changes how the code looks, not how it runs.
If you write `name = 'Rahul'` (with single quotes) and run Black, what happens?
Black changes it to `name = "Rahul"` (double quotes).
Black strictly prefers double quotes for strings.
Practice tasks
Format code mentally
Given this messy code, change it to match what Black would output (fix spaces and quotes).
Challenge
Format a dictionary
Write a dictionary called `data` with keys 'x' and 'y' mapping to 1 and 2. Format it exactly as Black would (spaces after colons, double quotes for keys).
Continue learning
Previous: Defining functions and return values