From 76c464946d01073b8bcb757345d0d42b9a8207e4 Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Sat, 28 Jan 2023 03:16:45 +0300 Subject: auth: rework dictify Define a Protocol type to use with the `dictify` function and implement the `dictify` methods for the various classes. --- gn3/auth/dictify.py | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) (limited to 'gn3/auth/dictify.py') diff --git a/gn3/auth/dictify.py b/gn3/auth/dictify.py index 274ebb0..f9337f6 100644 --- a/gn3/auth/dictify.py +++ b/gn3/auth/dictify.py @@ -1,17 +1,12 @@ """Module for dictifying objects""" -from typing import Any +from typing import Any, Protocol -# TYPE = TypeVar("TYPE") +class Dictifiable(Protocol):# pylint: disable=[too-few-public-methods] + """Type annotation for generic object with a `dictify` method.""" + def dictify(self): + """Convert the object to a dict""" -__dictifiers__ = {}#: dict[TYPE, Callable[[TYPE], dict[str, Any]]] = {} - -# def register_dictifier(obj_type: TYPE, dictifier: Callable[[TYPE], dict[str, Any]]): -def register_dictifier(obj_type, dictifier): - """Register a new dictifier function""" - global __dictifiers__ # pylint: disable=[global-variable-not-assigned] - __dictifiers__[obj_type] = dictifier - -def dictify(obj: Any) -> dict[str, Any]: +def dictify(obj: Dictifiable) -> dict[str, Any]: """Turn `obj` to a dict representation.""" - return __dictifiers__[type(obj)](obj) + return obj.dictify() -- cgit v1.2.3