Here is a different approach.
The structural pattern matching requires Python 3.10.
The dataclass is a convenient way to create classes which contains data.
TypeHints are optional. Nothing is checked during runtime.
The structural pattern matching requires Python 3.10.
The dataclass is a convenient way to create classes which contains data.
from __future__ import annotations from collections.abc import Generator from dataclasses import dataclass, field from pathlib import Path from typing import Any @dataclass(order=True) class Step: ident: str = field(compare=False) number: int = field(compare=True) name: str = field(compare=False) result: str = field(compare=False) progress: str = field(compare=False) def parse(file: str | Path | None = None, text: str | None = None) -> Generator[Step, None, None]: data : dict[str, Any] = {} if file and text: raise TypeError("text and file are mutually exclusive") if not (file or text): raise TypeError("text or file must be given") if file: text = Path(file).read_text() if not text: return for line in text.splitlines(): try: step, assignment = map(str.strip, line.split("=", maxsplit=1)) except ValueError: continue elements = step.split(".", maxsplit=3) match len(elements): case 2: if data: try: yield Step(**data) except TypeError: pass data.clear() data["number"] = int(elements[1]) data["ident"] = assignment case 3: data[elements[2].lower()] = assignment if data: try: yield Step(**data) except TypeError: pass text = """ garbage90832.rtzwrtzwrt.ztzwrtz = gg Step.0 = Foo !!!!ยง$252346"$%/ Step.1 = Task1 Step.1.Name = My first Task Step.1.Result = good Step.1.Progress = finished Step.2 = Task2 Step.2.Name = My second Task Step.2.Result = good Step.2.Progress = finished Step.3 = FOO Step.3.Name = My thrid Task Step.3.Result = xx Step.3.Progress = waiting garbage $%&)(/= """ result = sorted(parse(text=text)) for step in result: print(step)Result from for-loop:
Quote:Step(ident='Task1', number=1, name='My first Task', result='good', progress='finished')
Step(ident='Task2', number=2, name='My second Task', result='good', progress='finished')
Step(ident='FOO', number=3, name='My thrid Task', result='xx', progress='waiting')
TypeHints are optional. Nothing is checked during runtime.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!