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
- Read the README and
CONTRIBUTING.md. - Run it, and run the tests. If you cannot run it, you cannot check your change.
- Look at the folders.
src/(or a folder named after the project) holds the code,tests/the tests,docs/the documentation. - Find the entry point:
main(), or in Pythonif __name__ == "__main__":. - Follow one feature from where its input comes in to where its output goes out.
- 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()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 find | Use |
|---|---|
| where a name is defined | your editor's Go to Definition (F12 in VS Code) |
| every place it is used | Find All References (Shift+F12) |
| any text in the project | git grep "read_words" |
| why a line is the way it is | git blame wordfreq.py, then git show on that commit |
| the history of one file | git 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
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.