How to properly annotate a generic factory function?

Viewed 67

I have the following custom factory function:

def converter(cls, data):
    if isinstance(data, cls):
        return data
    else:
        return cls(**data)

After some trial and error, I came across the following solution, which works but seems a bit verbose:

import typing as t
from typing_extensions import Protocol


class _T(Protocol):
    def __init__(self, *args: t.Any, **kwargs: t.Any): ...


_TDict = t.Dict["str", t.Any]


def converter(cls: t.Type[_T], data: t.Union[_T, _TDict]) -> _T:
    if isinstance(data, cls):
        return data
    else:
        return cls(**data)

Before landing in that solution, I tried with generics (_T = t.TypeVar("_T")), but mypy complained about Too many arguments for "Object".

Is there a betterâ„¢ way to type a class accepting kwargs?

0 Answers
Related