from dataclasses import dataclass from io import TextIOWrapper from json import loads from os import sep from typing import Any, Dict @dataclass class Article: id: str title: str summary: str content: str custom: Dict[str, str] @staticmethod def from_open_file(id: str, file: TextIOWrapper) -> "Article": kwargs = {'id': id} custom = {} for line in file: if line.strip() == 'content': break kv = line.strip().split(' ', 1) key = kv[0] value = kv[1] if len(kv) > 1 else '' if key in Article.__annotations__: kwargs[key] = value else: custom[key] = value content = file.read() return Article(content=content, custom=custom, **kwargs) @dataclass class Site: name: str url: str custom: Dict[str, str] @staticmethod def from_open_file(file: TextIOWrapper) -> "Site": kwargs = {} custom = {} data = file.read() data = loads(data) for key, value in data.items(): if key in Site.__annotations__: kwargs[key] = value else: custom[key] = value return Site(custom=custom, **kwargs)