[Python] Type annotation for a subclass of Mapping + dataclass

Discussão em 'Python' iniciado por Stack, Julho 10, 2025.

  1. Stack

    Stack Membro Participativo

    Ultimately, I wanted to extend the dataclasses.dataclass and collections.Mapping because I wanted to make dataclasses that I can use ** operator on with some additional functions.

    Since dataclass is a function, not a class, I couldn't use inheritance. So I made a new wrapping function

    from dataclasses import dataclass as original_dataclass, fields
    from collections import Mapping
    from typing import Any, Generator, Type

    def __iter__(self) -> Generator[str, None, None]:
    for field in fields(self):
    yield field.name

    def __len__(self) -> int:
    return len(fields(self))

    def __getitem__(self, item: Any) -> Any:
    return getattr(self, item)

    def additional_function(self):
    print("Yes")

    def dataclass(cls: Type) -> Type:
    cls.additional_function = additional_function
    cls.__iter__ = __iter__
    cls.__len__ = __len__
    cls.__getitem__ = __getitem__

    # If `cls` has these methods, then it counts as a Mapping in the python world
    for method in ("__contains__", "keys", "items", "values", "get", "__eq__", "__ne__"):
    setattr(cls, method, getattr(Mapping, method))

    return original_dataclass(cls)

    @dataclass
    class MyNewClass:
    hello: str

    # usage

    def usecase_function(hello:str):
    pass

    new_class = MyNewClass("hi")
    usecase_function(**new_class) # <- vs-code complains here
    new_class.hello # <- vs-code complains here


    The python interpreter(3.8.13) does not throw an error. However, my editor, vs-code is complaining that this is not a Mapping. I assume because I return a mere Type as the return of the new dataclass function.

    So I annotate the return as Type[Mapping]. Now, vs-code complains that new_class doesn't have the attribute hello. I assume because dataclass returns a Type[Mapping] which doesn't have a hello attribute.

    But I don't know how to annotate the function dataclass in this situation. Does anyone know how to annotate in this situation?

    Thank you.

    Continue reading...

Compartilhe esta Página