给Mypy开心的抽象班级构造函数的正确方法是什么?

发布于 01-17 23:51 字数 936 浏览 3 评论 0原文

我有一个抽象基类 BsaeFoo,我的数据类(例如 ChildFoo)继承自它。

from abc import ABCMeta
from typing import Dict, Any, TypeVar, Type
from dataclasses import dataclass

Foo = TypeVar("Foo", bound="BaseFoo")


class BaseFoo(metaclass=ABCMeta):
    @classmethod
    def from_dict(cls: Type[Foo], data: Dict[str, Any]) -> Foo:
        init_data = {key: data.get(key, None) for key in cls.__annotations__}
        return cls(**init_data)


@dataclass
class ChildFoo(BaseFoo):
    x: int
    y: int

运行 Mypy 使我的

main.py:12: error: Too many arguments for "BaseFoo"
Found 1 error in 1 file (checked 1 source file)

from_dict 将成为子数据类的替代构造函数。它根据 cls.__annotations__ 属性读取输入字典,因此它不会在子类中引发。至于BaseFoo本身,检查初始化是没有意义的,因为它是一个抽象类。

如何在不使用 # type:ignore 的情况下使 BaseFoo.from_dict 传递 Mypy ?

I have an abstract base class BsaeFoo that my dataclasses such as ChildFoo is inheriting from.

from abc import ABCMeta
from typing import Dict, Any, TypeVar, Type
from dataclasses import dataclass

Foo = TypeVar("Foo", bound="BaseFoo")


class BaseFoo(metaclass=ABCMeta):
    @classmethod
    def from_dict(cls: Type[Foo], data: Dict[str, Any]) -> Foo:
        init_data = {key: data.get(key, None) for key in cls.__annotations__}
        return cls(**init_data)


@dataclass
class ChildFoo(BaseFoo):
    x: int
    y: int

Running Mypy gives me

main.py:12: error: Too many arguments for "BaseFoo"
Found 1 error in 1 file (checked 1 source file)

from_dict would be an alternative constructor of the child dataclasses. It reads the input dict based on the cls.__annotations__ attribute, so it won't raise in the child classes. As for BaseFoo itself, it does not make sense to check initialization since it is an abstract class.

How do I make BaseFoo.from_dict pass Mypy without using # type: ignore ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

葮薆情2025-01-24 23:51:49

BaseFoo 中添加 __init__ 的显式定义

class BaseFoo(ABC):
    def __init__(self, **kwargs: Any) -> None:
        raise NotImplementedError

    @classmethod
    def from_dict(cls: type[Foo], data: Dict[str, Any]) -> Foo:
        init_data = {key: data.get(key, None) for key in cls.__annotations__}
        return cls(**init_data)

Add explicit definition of __init__ in BaseFoo

class BaseFoo(ABC):
    def __init__(self, **kwargs: Any) -> None:
        raise NotImplementedError

    @classmethod
    def from_dict(cls: type[Foo], data: Dict[str, Any]) -> Foo:
        init_data = {key: data.get(key, None) for key in cls.__annotations__}
        return cls(**init_data)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文