7
0
mirror of https://github.com/ChristianLight/tutor.git synced 2024-05-29 12:20:49 +00:00
tutor/tutor/types.py
Régis Behmo 33e4f33afe feat: strongly typed hooks
Now that the mypy bugs have been resolved, we are able to define more precisely
and cleanly the types of Actions and Filters.

Moreover, can now strongly type named actions and hooks (in consts.py). With
such a strong typing, we get early alerts of hooks called with incorrect
arguments, which is nothing short of awesome :)

This change breaks the hooks API by removing the `context=...` argument. The
reason for that is that we cannot insert arbitrary arguments between `P.args,
P.kwargs`: https://peps.python.org/pep-0612/#the-components-of-a-paramspec

> A function declared as def inner(a: A, b: B, *args: P.args, **kwargs:
> P.kwargs) -> R has type Callable[Concatenate[A, B, P], R]. Placing
> keyword-only parameters between the *args and **kwargs is forbidden.

Getting the documentation to build in nitpicky mode is quite difficult... We
need to add `nitpick_ignore` to the docs conf.py, otherwise sphinx complains
about many missing class references. This, despite upgrading almost all doc
requirements (except docutils).
2022-11-15 14:58:36 +01:00

52 lines
1.2 KiB
Python

# The Tutor plugin system is licensed under the terms of the Apache 2.0 license.
__license__ = "Apache 2.0"
import typing as t
from typing_extensions import TypeAlias
from . import exceptions
ConfigValue: TypeAlias = t.Union[
str,
float,
None,
bool,
t.List[str],
t.List[t.Any],
t.Dict[str, t.Any],
t.Dict[t.Any, t.Any],
]
Config: TypeAlias = t.Dict[str, ConfigValue]
def cast_config(config: t.Any) -> Config:
if not isinstance(config, dict):
raise exceptions.TutorError(
f"Invalid configuration: expected dict, got {config.__class__}"
)
for key in config.keys():
if not isinstance(key, str):
raise exceptions.TutorError(
f"Invalid configuration: expected str, got {key.__class__} for key '{key}'"
)
return config
T = t.TypeVar("T")
def get_typed(
config: t.Dict[str, t.Any],
key: str,
expected_type: t.Type[T],
default: t.Optional[T] = None,
) -> T:
value = config.get(key, default)
if not isinstance(value, expected_type):
raise exceptions.TutorError(
"Invalid config entry: expected {expected_type.__name__}, got {value.__class__} for key '{key}'"
)
return value