【问题标题】:mypy complains about classmethodmypy 抱怨类方法
【发布时间】:2023-02-10 02:54:49
【问题描述】:

我有一个简单的数据类(来自 pydantic)

from pydantic.dataclasses import dataclass

from abc import ABCMeta
from abc import abstractmethod

from pydantic.dataclasses import dataclass


@dataclass
class BaseEntity(metaclass=ABCMeta):
    @classmethod
    @abstractmethod
    def from_dict(cls, other: dict):
        ...

    @abstractmethod
    def dict(self):
        ...


@dataclass
class UserEntity(BaseEntity):
    id: Optional[str]
    name: str
    email: str
    avatar: str

    @classmethod
    def from_dict(cls, other: dict):
        return cls(
            id=other.get("id"),
            name=other.get("name"),
            email=other.get("email"),
            avatar=other.get("avatar"),
        )

当我运行 mypy 时,我得到了这组错误:

app/entities/user.py:25: 错误:“UserEntity”的意外关键字参数“id”[call-arg]

app/entities/user.py:25: 错误:“UserEntity”的意外关键字参数“name”[call-arg]

app/entities/user.py:25: 错误:“UserEntity”的意外关键字参数“email”[call-arg]

app/entities/user.py:25: 错误:“UserEntity”的意外关键字参数“avatar”[call-arg]

我做错了什么?代码很好;它运行。或者它是一个 mypy 错误?

$ mypy --version
mypy 1.0.0 (compiled: yes)

编辑:MRE https://github.com/skhaz/fastapi-restful

【问题讨论】:

  • 请提供不依赖于未指定模块app.entitiesminimal reproducible example
  • 我在最底部添加了一个 MRE
  • MRE 需要在问题本身
  • 整个 github repo 不是 MRE——强调 M。
  • 此外,一旦您在此处获得解决方案,您可能会修复 repo 中的错误,因此它对未来的问题读者没有用。

标签: python mypy


【解决方案1】:

您缺少应该调用的构造函数 from_dict

def __init__(self, id, name, email, avatar):                                                                                      
        self.id = id                                                                                                                  
        self.name = name                                                                                                              
        self.email = email                                                                                                            
        self.avatar = avatar

【讨论】:

  • 但它是一个数据类;没有必要。
【解决方案2】:

与标准库dataclasses模块相同的代码就可以了。

问题是单独给定类定义,没有迹象表明 UserEntity.__init__ 会接受任何参数、位置或关键字,因为要检查的 mypy 唯一静态定义的 __init__object.__init__

但是,mypy 被编码为从标准库中了解 dataclasses,因此它可以识别那里将要是一个__init__方法,它有idname等作为参数。

但是,这种特殊处理不适用于pydantic.dataclasses

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 2021-09-29
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2020-06-25
    相关资源
    最近更新 更多