summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEddy Pedroni <epedroni@pm.me>2024-09-23 12:27:10 +0200
committerEddy Pedroni <epedroni@pm.me>2024-09-23 12:27:10 +0200
commit513e102fc92aabfeffc441c75c4f87c31cdc4cc6 (patch)
tree4b8e0cfe024c895c29c0f7801c5499a6921b45c0
parent2c8b068fe2e5241a4c96d2284eddebeb4b526c05 (diff)
Parser returns dict instead of list
-rw-r--r--src/parser.py17
-rw-r--r--src/parser_unittest.py13
2 files changed, 14 insertions, 16 deletions
diff --git a/src/parser.py b/src/parser.py
index db05089..69718e5 100644
--- a/src/parser.py
+++ b/src/parser.py
@@ -3,15 +3,16 @@ from collections import namedtuple
from enum import Enum
from typing import TextIO, Iterator
-Card = namedtuple('Card', ['id', 'front', 'back'])
+Card = namedtuple('Card', ['front', 'back'])
-def _getCard(front_lines: list[str], back_lines: list[str]) -> Card:
+def _getCard(front_lines: list[str], back_lines: list[str]) -> tuple[int, Card]:
front_text = "".join(front_lines).strip()
back_text = "".join(back_lines).strip()
- id = hash(front_text + back_text)
- return Card(id, front_text, back_text)
+ card = Card(front_text, back_text)
+ id = hash(card)
+ return id, card
-def _getCards(f: TextIO) -> Iterator[Card]:
+def _getCards(f: TextIO) -> Iterator[tuple[id, Card]]:
class State(Enum):
PARSE_FRONT = 1,
PARSE_BACK = 2
@@ -62,7 +63,7 @@ def _getCards(f: TextIO) -> Iterator[Card]:
yield _getCard(front_lines, back_lines)
-def parse(path: Path) -> list[Card]:
+def parse(path: Path) -> dict[int, Card]:
"""
Parse a .fcard file and return a list of Card instances.
@@ -89,7 +90,7 @@ def parse(path: Path) -> list[Card]:
"""
if not path.is_file():
print(f"[Warning] Not a file: {path}")
- return []
+ return {}
with open(path, "r") as f:
- return [card for card in _getCards(f)]
+ return {id : card for id, card in _getCards(f)}
diff --git a/src/parser_unittest.py b/src/parser_unittest.py
index 02638e6..9ada265 100644
--- a/src/parser_unittest.py
+++ b/src/parser_unittest.py
@@ -32,10 +32,10 @@ Another back
"""
- expected = [
+ expected = {
("Foo\n\nBar", "Fizz\n\nBuzz"),
("Another card", "Another back")
- ]
+ }
path = tmp_path / "valid_file.fcard"
with open(path, "w") as f:
@@ -43,10 +43,7 @@ Another back
cards = parser.parse(path)
- assert expected == [(c.front, c.back) for c in cards]
-
- # Cards have unique IDs
- assert len(set([c.id for c in cards])) == len(cards)
+ assert expected == set(cards.values())
# Edge cases
def test_emptyFile(tmp_path):
@@ -55,11 +52,11 @@ def test_emptyFile(tmp_path):
f.write("")
cards = parser.parse(path)
- assert cards == []
+ assert cards == {}
def test_missingFile(tmp_path):
cards = parser.parse(tmp_path / "missing_file.fcard")
- assert cards == []
+ assert cards == {}
def checkException(tmp_path, file_contents):
path = tmp_path / "invalid_file.fcard"