Python lesson

Build a Python notification sorter

Build an app that sorts JSON notifications by their reasons. Read a local file, select each primary reason and create a new report.

1. Create the product folder

You are building a report that shows which reasons take priority in demo notifications. JSON is a text format with named fields. An issue is a task record here; a pull request proposes merging a code change. The examples are invented.

Python 3 and a text editor are enough. Check your installation with python3 --version. If the command is unavailable, install Python 3 and reopen the terminal. The actual checks used Python 3.14.4. No extra package or account is needed.

Create bildiris-sirasi-v1. The tree below shows the three files to create; do not save the tree itself. Choose UTF-8 and avoid hidden .txt extensions. Do not create report.json manually: the program only creates a new output file.

Text
bildiris-sirasi-v1/
  app.py
  demo.json
  test_app.py

2. Implement the reason rule in app.py

Save the complete code as app.py. ORDER lists reasons in priority order: mention means being mentioned, and assign means being assigned a task. rank moves assign first for an issue. prioritize validates each record and places its selected reason in primary.

The app then sorts separate notifications by their primary priority, breaking ties with id. That global sort is our product decision, not a claim about GitHub inbox order. The GitHub announcement describes priority among reasons within one notification.

main reads only a local file. After checking all records, it opens a new output using x mode; existing input and output files are not replaced. We do not authenticate who created the input, so work with demo data you created yourself.

Pythonapp.py
"""Sort synthetic notifications offline."""
import argparse
import json
import re
import sys
from pathlib import Path

ORDER = "mention team_mention assign review_requested comment manual author state_change subscribed".split()
LIMIT = 1024 * 1024


def reject_nan(value):
    raise ValueError("Invalid JSON constant")


def fields(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("Duplicate JSON field")
        result[key] = value
    return result


def rank(kind, reason):
    return -1 if kind == "issue" and reason == "assign" else ORDER.index(reason)


def prioritize(data):
    if not isinstance(data, list) or len(data) > 500:
        raise ValueError("Expected a list of at most 500 records")
    seen, rows = set(), []
    for row in data:
        if not isinstance(row, dict) or set(row) != {"id", "type", "reasons"}:
            raise ValueError("Expected exactly id, type, reasons")
        ident, kind, reasons = row["id"], row["type"], row["reasons"]
        if not isinstance(ident, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}", ident):
            raise ValueError("id: 1-64 ASCII letters/digits/._-; start alphanumeric")
        if ident in seen:
            raise ValueError("Duplicate id")
        seen.add(ident)
        if kind not in ("issue", "pull_request"):
            raise ValueError("type must be issue or pull_request")
        if not isinstance(reasons, list) or not reasons:
            raise ValueError("Expected a nonempty reasons list")
        if any(not isinstance(r, str) or r not in ORDER for r in reasons):
            raise ValueError("Unknown reason; see ORDER")
        if len(set(reasons)) != len(reasons):
            raise ValueError("Duplicate reason")
        ordered = sorted(reasons, key=lambda r: rank(kind, r))
        rows.append(dict(id=ident, type=kind, primary=ordered[0], reasons=ordered))
    rows.sort(key=lambda r: (rank(r["type"], r["primary"]), r["id"]))
    return dict(total=len(rows), notifications=rows)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    try:
        with args.input.open("rb") as source:
            raw = source.read(LIMIT + 1)
        if len(raw) > LIMIT:
            raise ValueError("Input exceeds 1 MiB")
        data = json.loads(raw.decode("utf-8"), parse_constant=reject_nan,
                          object_pairs_hook=fields)
        report = prioritize(data)
        with args.output.open("x", encoding="utf-8") as target:
            target.write(json.dumps(report, indent=2, ensure_ascii=False) + "\n")
        return 0
    except (OSError, ValueError, RecursionError) as error:
        print("Error:", error, file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())

3. Save three notifications in demo.json

Save the complete list below as demo.json. id uniquely identifies a record. type identifies the task type, while reasons lists the causes of the notification. Keep these field names and values unchanged: the code expects them. Do not add personal names, emails or real account data.

Although pr-3 comes first in the input, issue-1 will lead the output. Its primary reason is assign; pr-3 gets mention and pr-2 gets review_requested. All three records remain. Their order and the order within reasons change, and primary is added to each record. The report wraps them in total and notifications fields.

JSONdemo.json
[
  {"id":"pr-3","type":"pull_request","reasons":["comment","assign","mention"]},
  {"id":"issue-1","type":"issue","reasons":["mention","assign"]},
  {"id":"pr-2","type":"pull_request","reasons":["review_requested"]}
]

4. Create a report and correct an error

Open a terminal in the folder: python3 app.py demo.json report.json. Success prints nothing. Open report.json: expect total 3 and notifications ordered issue-1, pr-3, pr-2. Reusing the output name causes an error and preserves the file. Choose report-2.json for another run.

Create empty.json containing only []. Run python3 app.py empty.json empty-report.json. Expect total 0 and an empty notifications list. This is valid: there are no records to process. A completely blank text file is not valid JSON and is rejected.

In a copy of demo.json, replace one reasons list with ["urgent"]. Run the copy with a new output filename. Expect Error: Unknown reason; see ORDER and no output file. Replace urgent with mention and try again. Missing commas or wrong quotes also stop the file from being accepted.

5. Verify the rule with test_app.py

Save the complete tests as test_app.py and run python3 -m unittest -v test_app.py. The supplied product passed 3 test groups. Expect the ending Ran 3 tests and OK. No separate testing package is needed.

Tests cover reason order, the issue exception, id tie-breaking, empty input and invalid fields. They also launch the actual program to check preservation of input and existing output, malformed JSON and excessive nesting. If you do not get OK, check filenames and that the code was copied completely.

Pythontest_app.py
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from app import ORDER, prioritize


def row(id="a", type="pull_request", reasons=None):
    return dict(id=id, type=type, reasons=reasons or ["mention"])


class Tests(unittest.TestCase):
    def test_order(self):
        rows = [row(str(i), reasons=[r]) for i, r in enumerate(ORDER)]
        rows += [row("issue", "issue", ["mention", "assign"]), row("00")]
        result = prioritize(rows[::-1])["notifications"]
        self.assertEqual([r["id"] for r in result], ["issue", "0", "00"] + list("12345678"))
        self.assertEqual(prioritize([]), dict(total=0, notifications=[]))

    def test_invalid(self):
        cases = [None, {}, [1], [dict(row(), extra=1)], [{"id":"a"}],
                 [row("")], [row("x"*65)], [row("../x")], [row(1)],
                 [row(type=[])], [row(reasons=["bad"])], [dict(row(), reasons=[])],
                 [row(reasons=[1])], [dict(row(), reasons="mention")],
                 [row(reasons=["mention"]*2)], [row(), row()], [row()]*501]
        for data in cases:
            with self.assertRaises(ValueError):
                prioritize(data)

    def test_cli(self):
        with tempfile.TemporaryDirectory() as folder:
            src, out = Path(folder)/"in", Path(folder)/"out"
            def run(target=out):
                return subprocess.run([sys.executable, str(Path(__file__).with_name("app.py")),
                                       str(src), str(target)], capture_output=True)
            src.write_text(json.dumps([row()]))
            self.assertEqual(run().returncode, 0)
            saved = out.read_bytes()
            self.assertNotEqual(run().returncode, 0)
            self.assertEqual(out.read_bytes(), saved)
            self.assertNotEqual(run(src).returncode, 0)
            self.assertEqual(src.read_bytes(), json.dumps([row()]).encode())
            out.unlink()
            for bad in (b"{", b"[NaN]", b"["*2000,
                        b" "*(1024*1024+1), b"[{}]", b"\xff"):
                src.write_bytes(bad)
                result = run()
                self.assertNotEqual(result.returncode, 0)
                self.assertFalse(out.exists())


if __name__ == "__main__":
    unittest.main()

6. Add a notification and understand the limits

Exercise: add {"id":"pr-0","type":"pull_request","reasons":["mention"]} as the fourth element in a copy of demo.json. Add a comma after the previous element. In the new report expect total 4 and issue-1, pr-0, pr-3, pr-2. pr-0 precedes pr-3 because their primary priorities tie and id decides.

Input is limited to 1 MiB and 500 records. id uses 1–64 ASCII characters, starting with a letter or digit; dots, underscores and hyphens are also accepted. Reasons must be nonempty and unique, and every reason must appear in ORDER. The app does not fetch new GitHub notifications or change delivered ones.

The primary source is GitHub’s November 24, 2026 announcement, which describes a staged transition. We are not testing that service’s rollout here. We test the input, selection and output of our own program. Other Python versions and network integration were not separately tested.

Recommended reading

All articles