3b Lint

Read the tutorial. Build it yourself is the other way to read this part.

just setup

ruff finds code that works but could be better, such as a file that nobody closes. It fixes some of what it finds by itself, and leaves the rest to us.

The code before this part. The code after it.

3b.1 What ruff fixes

ruff check --fix fixes what it can, and lists the rest. It writes its fixes, and then exits with code 1, because one problem is left.

This change came from running uv run ruff check --fix.

In scripts/corpus.py, ruff wrote the list WORDS as a list of strings, in place of a string that the code split.

uv run ruff check --statistics

It fails, with exit code 1. It prints one line for the rule SIM115, open-file-with-context-handler, and then Found 1 error. main opens a file and never closes it, and ruff cannot fix that.

What changed

  • scripts/corpus.py: a list of words, as ruff writes it. 1 line added, 1 removed. It comes from uv run ruff check --fix. The file.
    • look at WORDS = ["the", "a", "word", "count", "text", "tally", "test", "step", "move", "commit", "tag", "note", "slide", "class", "shell", "file", "line", "code"]
The diff of scripts/corpus.py
@@ -3,7 +3,7 @@
 import sys
 from pathlib import Path
 
-WORDS = "the a word count text tally test step move commit tag note slide class shell file line code".split()
+WORDS = ["the", "a", "word", "count", "text", "tally", "test", "step", "move", "commit", "tag", "note", "slide", "class", "shell", "file", "line", "code"]
 
 
 def main() -> None:

This change on GitHub. The code after it.

3b.2 main closes its file

ruff cannot fix SIM115. A with block closes the file when the block ends.

A patch to src/tally/__init__.py.

main in src/tally/__init__.py reads the file in a with block, and reads the standard input when there is no file.

uv run ruff check

It prints All checks passed!.

What changed

  • src/tally/__init__.py: a with block, which closes the file. 5 lines added, 1 removed. The file.
    • look at with open(args[0]) as file:
The diff of src/tally/__init__.py
@@ -21,7 +21,11 @@ def main() -> None:
     args, n = [arg for arg in args if arg != "--table"], None
     if args[:1] == ["--top"]:
         n, args = int(args[1]), args[2:]
-    text = open(args[0]).read() if args else sys.stdin.read()
+    if args:
+        with open(args[0]) as file:
+            text = file.read()
+    else:
+        text = sys.stdin.read()
     counts = count(text)
     rows = top(counts, n) if n else sorted(counts.items())
     if as_table:

This change on GitHub. The code after it.