|
4 | 4 | """Utilities to deal with configuration."""
|
5 | 5 |
|
6 | 6 | from collections.abc import Mapping
|
7 |
| -from typing import Any, TypeVar, cast |
| 7 | +from typing import Any, ClassVar, Protocol, TypeVar, cast |
8 | 8 |
|
9 | 9 | from marshmallow import Schema
|
10 | 10 | from marshmallow_dataclass import class_schema
|
11 | 11 |
|
12 |
| -T = TypeVar("T") |
| 12 | + |
| 13 | +# This is a hack that relies on identifying dataclasses by looking into an undocumented |
| 14 | +# property of dataclasses[1], so it might break in the future. Nevertheless, it seems to |
| 15 | +# be widely used in the community, for example `mypy` and `pyright` seem to rely on |
| 16 | +# it[2]. |
| 17 | +# |
| 18 | +# [1]: https://github.com/python/mypy/issues/15974#issuecomment-1694781006 |
| 19 | +# [2]: https://github.com/python/mypy/issues/15974#issuecomment-1694993493 |
| 20 | +class Dataclass(Protocol): |
| 21 | + """A protocol for dataclasses.""" |
| 22 | + |
| 23 | + __dataclass_fields__: ClassVar[dict[str, Any]] |
| 24 | + """The fields of the dataclass.""" |
| 25 | + |
| 26 | + |
| 27 | +DataclassT = TypeVar("DataclassT", bound=Dataclass) |
13 | 28 | """Type variable for configuration classes."""
|
14 | 29 |
|
15 | 30 |
|
16 | 31 | def load_config(
|
17 |
| - cls: type[T], |
| 32 | + cls: type[DataclassT], |
18 | 33 | config: Mapping[str, Any],
|
19 | 34 | /,
|
20 | 35 | base_schema: type[Schema] | None = None,
|
21 | 36 | **marshmallow_load_kwargs: Any,
|
22 |
| -) -> T: |
| 37 | +) -> DataclassT: |
23 | 38 | """Load a configuration from a dictionary into an instance of a configuration class.
|
24 | 39 |
|
25 | 40 | The configuration class is expected to be a [`dataclasses.dataclass`][], which is
|
@@ -56,4 +71,4 @@ def load_config(
|
56 | 71 | instance = class_schema(cls, base_schema)().load(config, **marshmallow_load_kwargs)
|
57 | 72 | # We need to cast because `.load()` comes from marshmallow and doesn't know which
|
58 | 73 | # type is returned.
|
59 |
| - return cast(T, instance) |
| 74 | + return cast(DataclassT, instance) |
0 commit comments