跳至内容

Mypy

我们提供了一个 mypy 插件来扩展类型检查功能并提高易用性。

设置

创建或修改 mypy 配置文件(默认:mypy.ini),使其看起来像下面这样

[mypy]
plugins = prisma.mypy

配置

选项通过 mypy 配置文件 中的 [prisma-mypy] 键传递给 mypy 插件。

[prisma-mypy]
option = True

警告解析错误

如果 Prisma 无法解析值,它将引发解析错误,例如,以下内容将引发错误,因为 include 参数的值目前无法解析。

注意

这并不意味着代码存在类型错误,此错误只是警告插件无法应用某些功能。

from prisma.types import UserInclude

include = dict()  # type: UserInclude
include['posts'] = True
user = await db.user.find_unique(
    where={
      'id': 'user_id',
    },
    include=include,
)

此错误可以通过两种方式禁用

  • 内联
user = await db.user.find_unique(
    where={
        'id': 'user_id',
    },
    include=include  # type: ignore[prisma-parsing]
)
  • 全局

此行为可以通过布尔型 warn_parsing_errors 配置选项控制。

将以下内容添加到 mypy 配置文件 中将禁用整个项目中的错误。

[prisma-mypy]
warn_parsing_errors = False

特性

从关系字段中删除可选

如果关系字段使用 include 显式传递,则返回模型上的字段将不再被类型化为 Optional(如果适用)。

例如,如果没有插件,以下代码段将引发错误,即 user.posts 可能为 None,但是由于我们显式地包含了用户的帖子,因此在这种情况下的 posts 属性永远不会为 None

注意

如果没有找到帖子,则 user.posts 将是一个空列表

user = await db.user.find_unique(
    where={
        'id': 'user_id',
    },
    include={
        'posts': True
    }
)
print(f'User {user.name} has {len(user.posts)} posts')

需要注意的是,如果关系在模式中是可选的,即使显式包含,关系字段仍将被类型化为 Optional,例如,以下内容将引发错误,即 profile 可能为 None

user = await db.user.find_unique(
    where={
        'id': 'user_id',
    },
    include={
        'profile': True,
    }
)
print(f'User {user.name}, bio: {user.profile.bio}')

需要注意的是,目前不支持动态 include 值,例如,以下内容将引发错误。请参阅 此处,了解如何禁用错误。

from prisma.types import UserInclude

include = dict()  # type: UserInclude
include['posts'] = True
user = await db.user.find_unique(
    where={
        'id': 'user_id',
    },
    include=include,
)