From 6b7ff8a0f564df9ae3ff5db56e0af8ce4efbb712 Mon Sep 17 00:00:00 2001 From: JacobiusMakes Date: Fri, 4 Dec 2026 06:58:00 -0500 Subject: [PATCH] Teach Python readers to distinguish a goalless final from a missing score --- .github/workflows/starter.yml | 4 ++ README.md | 2 + examples/final-score/README.md | 22 ++++++++ examples/final-score/example.json | 23 +++++++++ examples/final-score/read_score.py | 68 +++++++++++++++++++++++++ examples/final-score/test_read_score.py | 60 ++++++++++++++++++++++ 6 files changed, 179 insertions(+) create mode 100644 examples/final-score/README.md create mode 100644 examples/final-score/example.json create mode 100644 examples/final-score/read_score.py create mode 100644 examples/final-score/test_read_score.py diff --git a/.github/workflows/starter.yml b/.github/workflows/starter.yml index a161b44..83f71b2 100644 --- a/.github/workflows/starter.yml +++ b/.github/workflows/starter.yml @@ -8,6 +8,7 @@ on: - 'examples/websocket-replay/**' - 'examples/support-report/**' - 'examples/nba-csv-report/**' + - 'examples/final-score/**' - 'examples/test_odds_workspace.py' - 'parlay_api/**' - 'tests/**' @@ -22,6 +23,7 @@ on: - 'examples/websocket-replay/**' - 'examples/support-report/**' - 'examples/nba-csv-report/**' + - 'examples/final-score/**' - 'parlay_api/**' - 'pyproject.toml' permissions: @@ -46,6 +48,8 @@ jobs: run: | python "$GITHUB_WORKSPACE/tests/test_installed_package.py" python -m pytest -q --import-mode=importlib "$GITHUB_WORKSPACE/tests/test_odds_coverage.py" "$GITHUB_WORKSPACE/tests/test_first_response.py" "$GITHUB_WORKSPACE/tests/test_migration_example.py" + - name: Check the saved final-score reader + run: python -B -m unittest discover -s examples/final-score - name: Exercise the offline support report run: python -B -m unittest discover -s examples/support-report -p test_support_repro.py - name: Replay fictional frames and exercise a loopback WebSocket diff --git a/README.md b/README.md index bb3bcab..e255d95 100644 --- a/README.md +++ b/README.md @@ -186,6 +186,8 @@ The freshness cutoff accepts 60 to 86,400 seconds and applies to each book's price. `total_games_covered` counts distinct events on the board before the per-book freshness cutoff. The response includes the server's `as_of` time. +[Read a final football score by event ID](examples/final-score/). Run the saved Portugal–U.S. 0–0 example locally, then try a pending match. The reader preserves zero and matches each score to the named team even when the away score arrives first. + The client includes sports, odds, events, scores, historical odds, player props, futures, usage and other endpoint methods. Check [current API documentation](https://parlay-api.com/docs) for parameters, plan requirements and coverage. If migrating from another API, diff --git a/examples/final-score/README.md b/examples/final-score/README.md new file mode 100644 index 0000000..4aee291 --- /dev/null +++ b/examples/final-score/README.md @@ -0,0 +1,22 @@ +# Read one final football score in Python + +Portugal and the United States finished 0–0 in the 2023 Women’s World Cup. An upcoming game can also have zero **score rows**. Only the first of those records gives you a final score. + +[Replay Group E in your browser](https://jacobiusmakes.github.io/parlayapi-notebooks/womens-world-cup-group-e/) · [Ver a tabela em português](https://jacobiusmakes.github.io/parlayapi-notebooks/womens-world-cup-group-e/pt-br/) + +From this directory, use Python 3.9 or newer. The example needs only the standard library and makes no network requests. + +```sh +python3 read_score.py example.json example-portugal-usa +python3 read_score.py example.json example-usa-vietnam +``` + +The first command returns Portugal 0, United States 0. The second returns United States 3, Vietnam 0, even though Vietnam’s score appears first in the file. The two final scores come from the [2023 match records](https://github.com/martj42/womens-international-results/blob/1102e60045cf3c1bc1d4651d0e76a72804ee2d25/results.csv). The IDs and API-shaped records are teaching examples. Harbor–Vale is fictional. + +Try `python3 read_score.py example.json example-pending`. It reports that the event has no confirmed final status, writes no score to standard output and exits with status 1. + +## Use a saved response + +Save the event list from your own authorized `client.scores(sport_key)` call as JSON. Pass its filename and the exact event ID to the same command. The reader requires a completed event, two distinct teams, and one nonnegative integer score for each named team. A rematch between the same teams has its own event ID. The output preserves the supplied scores; qualification, shoot-outs and betting settlement require their own records. + +For a new integration, [check archive coverage by sport and source](https://parlay-api.com/historical-coverage?utm_source=github&utm_medium=python_tutorial&utm_campaign=final_score_reader). Check current plan access and request cost before calling a keyed endpoint. The historical replay runs independently of current coverage. diff --git a/examples/final-score/example.json b/examples/final-score/example.json new file mode 100644 index 0000000..8fd9675 --- /dev/null +++ b/examples/final-score/example.json @@ -0,0 +1,23 @@ +[ + { + "id": "example-usa-vietnam", + "home_team": "United States", + "away_team": "Vietnam", + "completed": true, + "scores": [{"name":"Vietnam","score":"0"},{"name":"United States","score":"3"}] + }, + { + "id": "example-portugal-usa", + "home_team": "Portugal", + "away_team": "United States", + "completed": true, + "scores": [{"name":"United States","score":"0"},{"name":"Portugal","score":"0"}] + }, + { + "id": "example-pending", + "home_team": "Harbor", + "away_team": "Vale", + "completed": false, + "scores": null + } +] diff --git a/examples/final-score/read_score.py b/examples/final-score/read_score.py new file mode 100644 index 0000000..34d256c --- /dev/null +++ b/examples/final-score/read_score.py @@ -0,0 +1,68 @@ +"""Read a supplied final score by event ID, retaining zero and matching teams by name.""" + +import argparse +import json +import sys +from pathlib import Path + + +def goal_count(value): + """Accept the nonnegative whole numbers used in football scores.""" + if type(value) is int and value >= 0: + return value + if isinstance(value, str) and value.isascii() and value.isdigit(): + return int(value) + raise ValueError("A team score is missing or is not a nonnegative whole number.") + + +def final_score(events, event_id): + if not isinstance(events, list): + raise ValueError("Expected the list of events returned by scores().") + if not isinstance(event_id, str) or not event_id.strip(): + raise ValueError("Supply the exact event ID from the response.") + matches = [event for event in events if isinstance(event, dict) and event.get("id") == event_id] + if len(matches) != 1: + raise ValueError(f"Expected one event with the supplied ID, found {len(matches)}.") + event = matches[0] + if event.get("completed") is not True: + raise ValueError("The event has no confirmed final status.") + home, away = event.get("home_team"), event.get("away_team") + if not all(isinstance(name, str) and name.strip() for name in (home, away)) or home == away: + raise ValueError("Expected two distinct team names on the event.") + scores = event.get("scores") + if not isinstance(scores, list) or len(scores) != 2: + raise ValueError("Expected one final score for each of the two teams.") + by_team = {} + for row in scores: + if not isinstance(row, dict): + raise ValueError("Expected a named score for both teams.") + name = row.get("name") + if name not in (home, away) or name in by_team: + raise ValueError("The score rows do not identify the two event teams exactly once.") + by_team[name] = goal_count(row.get("score")) + return { + "event_id": event_id, + "home_team": home, + "home_score": by_team[home], + "away_team": away, + "away_score": by_team[away], + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("file", type=Path, help="Saved scores() response in JSON format") + parser.add_argument("event_id", help="Exact ID of one event in that response") + args = parser.parse_args() + try: + with args.file.open(encoding="utf-8-sig") as source: + result = final_score(json.load(source), args.event_id) + except (OSError, ValueError) as error: + print(error, file=sys.stderr) + return 1 + print(json.dumps(result, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/final-score/test_read_score.py b/examples/final-score/test_read_score.py new file mode 100644 index 0000000..d7947c4 --- /dev/null +++ b/examples/final-score/test_read_score.py @@ -0,0 +1,60 @@ +import json +import unittest +from copy import deepcopy +from pathlib import Path + +from read_score import final_score + + +class FinalScoreTests(unittest.TestCase): + def setUp(self): + self.games = json.loads(Path(__file__).with_name("example.json").read_text("utf-8")) + + def test_goalless_final(self): + result = final_score(self.games, "example-portugal-usa") + self.assertEqual((result["home_score"], result["away_score"]), (0, 0)) + + def test_matches_names_even_when_away_comes_first(self): + result = final_score(self.games, "example-usa-vietnam") + self.assertEqual((result["home_team"], result["home_score"], result["away_team"], result["away_score"]), + ("United States", 3, "Vietnam", 0)) + + def test_unfinished_or_unknown_is_not_a_final(self): + for status in (False, None, 1, "true"): + game = dict(self.games[0], completed=status) + with self.subTest(status=status), self.assertRaises(ValueError): + final_score([game], game["id"]) + + def test_missing_or_duplicate_id(self): + for records in ([], [self.games[0], self.games[0]]): + with self.assertRaises(ValueError): + final_score(records, self.games[0]["id"]) + + def test_incomplete_ambiguous_and_extra_scores(self): + for scores in (None, [], [{"name":"Vietnam","score":"0"}], self.games[0]["scores"] * 2, + [self.games[0]["scores"][0]] * 2, [None,{}], + [{"name":"Unlisted","score":1}, self.games[0]["scores"][1]]): + with self.subTest(scores=scores), self.assertRaises(ValueError): + final_score([dict(self.games[0], scores=scores)], self.games[0]["id"]) + + def test_rejects_non_scores(self): + for score in (None, True, -1, 0.5, "3.0", "", "3"): + game = deepcopy(self.games[0]) + game["scores"][0]["score"] = score + with self.subTest(score=score), self.assertRaises(ValueError): + final_score([game], game["id"]) + + def test_matching_an_id_does_not_select_a_rematch(self): + second = deepcopy(self.games[0]) + second.update(id="rematch") + second["scores"][0]["score"] = 2 + self.assertEqual(final_score([self.games[0],second],"rematch")["away_score"],2) + + def test_input_shape_and_team_identity(self): + for games in ({}, [dict(self.games[0], home_team="Vietnam")], [dict(self.games[0], away_team="")]): + with self.assertRaises(ValueError): + final_score(games, self.games[0]["id"]) + + +if __name__ == "__main__": + unittest.main()