Skip to content

optimise_fonts's return value could be better typed #2

@shmulvad

Description

@shmulvad

The main function optimise_fonts and the other exposed functions using it return dict[str, typing.Any]. This is inconvenient for the users of the library as they will have no autocomplete and type safety. There are two possible ways you can solve it. I would recommend 1 here, although it will break backwards compatibility. You can use 2 if you really prefer dictionaries and don't want to break the backwards compatibility.

1. Using a dataclass:

Returning a suitable dataclass instead will allow users to access the values with dot notation:

from dataclasses import dataclass, field

@dataclass
class FontResult:
    css: set[str] = field(default_factory=set)
    fonts: dict[str, str] = field(default_factory=dict)
    chars: set[str] = field(default_factory=set)
    uranges: str = ''

Then you can return an instance of this instead of your dictionary:

font_res = FontResult()
...
font_res.chars = characters  # etc
...
return font_res

2. Using TypedDict:

Return a typed dictionary. The code would be something along these lines:

from typing import TypedDict


class FontResult(TypedDict):
    css: set[str]
    fonts: dict[str, str]
    chars: set[str]
    uranges: str


def optimise_fonts(...) -> FontResult:
    font_res = {'css': set(), 'fonts': {}, 'chars': set(), 'uranges': ''}
    ...
    return font_res

Metadata

Metadata

Assignees

Labels

pythonicMaking the code more idiomatic Python

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions