Reading a codebase

A real project can have thousands of files. Nobody reads them all. You read just enough to make your change.

A plan for a new project

  1. Read the README and CONTRIBUTING.md.
  2. Run it, and run the tests. If you cannot run it, you cannot check your change.
  3. Look at the folders. src/ (or a folder named after the project) holds the code, tests/ the tests, docs/ the documentation.
  4. Find the entry point: main(), or in Python if __name__ == "__main__":.
  5. Follow one feature from where its input comes in to where its output goes out.
  6. Search instead of scrolling.

Following a feature

def read_words(text):
    words = []
    for word in text.lower().split():
        word = word.strip(".,!?")
        if word:
            words.append(word)
    return words


def count(words):
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    return counts


def top(counts, n):
    pairs = sorted(counts.items(), key=lambda p: (-p[1], p[0]))
    return pairs[:n]


def main():
    text = "The cat saw the dog. The dog ran!"
    for word, times in top(count(read_words(text)), 2):
        print(word, times)


if __name__ == "__main__":
    main()
Open in compiler

This "project" prints the most common words of a text. Start at the bottom, at the entry point: main(). Its key line is top(count(read_words(text)), 2). Read it from the inside out: read_words runs first, its list goes to count, and count's dictionary goes to top. Step through it and watch each function's result become the next one's input. Each function does one job, which is what makes the code easy to follow.

Searching

To findUse
where a name is definedyour editor's Go to Definition (F12 in VS Code)
every place it is usedFind All References (Shift+F12)
any text in the projectgit grep "read_words"
why a line is the way it isgit blame wordfreq.py, then git show on that commit
the history of one filegit log -- wordfreq.py

Commit messages and old issues often explain why the code is the way it is. Write down what you learn as you go, and draw how the main parts connect.

Quick check

1. In top(count(read_words(text)), 2), which function runs first?
2. What does git blame show?
3. What should you do before changing anything in a new project?

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.