Student Login

Pythonic commas

A grizzled hacker asked me about this code:

  1. SECTIONS = [
  2. "elite",
  3. "premium",
  4. "main",
  5. ]

Doesn't matter what the code is for. His question was about a comma.

Specifically, after the string "main". I put a comma there. You see?

The question is: Why? Why put a comma there at all?

In fact, you don't have to, in Python. In the last element in a list, a trailing comma is not necessary. And as far as I can tell, most Python coders don't put it there. But I do, for a good reason:

It makes diffs more pinpointed.

Imagine we add a new category below "main", called "economy". And imagine I'm NOT using a comma after "main". Then SECTIONS changes from this:

  1. SECTIONS = [
  2. "elite",
  3. "premium",
  4. "main"
  5. ]

... to this:

  1. SECTIONS = [
  2. "elite",
  3. "premium",
  4. "main",
  5. "economy"
  6. ]

What's the diff for these two in version control? In Git, it looks something like:

  1. SECTIONS = [
  2. "elite",
  3. "premium",
  4. - "main"
  5. + "main",
  6. + "economy"
  7. ]

Basically, the change portion is 3 lines. But if instead I start with a trailing comma:

  1. SECTIONS = [
  2. "elite",
  3. "premium",
  4. "main",
  5. ]

... and add "economy" with its own trailing comma:

  1. SECTIONS = [
  2. "elite",
  3. "premium",
  4. "main",
  5. "economy",
  6. ]

... then the diff's change portion is only one line:

  1. SECTIONS = [
  2. "elite",
  3. "premium",
  4. "main",
  5. + "economy",
  6. ]

More-pinpointed diffs gives you benefits:

1) If you and I are working together on the same code base, in different feature branches, then we're less likely to have a merge conflict.

2) Code reviewers will have an easier time. They're less likely to make mistakes, because they don't have to think so hard to decipher the nature of the change you actually made.

3) It's more clear what actually changed in your code, if you skim the diff before merging in.

This "comma hack" applies not just to lists, but to sets, dictionaries, and other situations in Python. Use it.

For Teams Bootcamp