gpt4 book ai didi

python - 如何让 Mypy 识别不可为 null 的 ORM 属性?

转载 作者:行者123 更新时间:2023-12-05 05:44:01 26 4
gpt4 key购买 nike

Mypy 将 ORM 不可空实例属性推断为可选。

文件名:test.py

from sqlalchemy.orm import decl_api, registry
from sqlalchemy import BigInteger, Column, String

mapper_registry = registry()


class Base(metaclass=decl_api.DeclarativeMeta):
__abstract__ = True

registry = mapper_registry
metadata = mapper_registry.metadata

__init__ = mapper_registry.constructor


class Person(Base):
__tablename__ = "persons"

id = Column(BigInteger, primary_key=True, autoincrement=True)
name = Column(String(40), nullable=False)


def main(person: Person):
person_id = person.id
person_name = person.name

reveal_locals()

运行 mypy test.py 产生:

test.py:27: note: Revealed local types are:
test.py:27: note: person: test.Person
test.py:27: note: person_id: Union[builtins.int, None]
test.py:27: note: person_name: Union[builtins.str, None]

据我所知,person_idperson_name 应该分别是 intstr,因为它们被设置为不可为空。

我在这里错过了什么?


相关图书馆:

SQLAlchemy         1.4.25
sqlalchemy2-stubs 0.0.2a15
mypy 0.910
mypy-extensions 0.4.3

最佳答案

我在使用 mypy 评估 nullable=False 列时遇到了同样的问题。我的一位队友在 SqlAlchemy 文档中找到了答案:

https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html#introspection-of-columns-based-on-typeengine

The types are by default always considered to be Optional, even forthe primary key and non-nullable column. The reason is because whilethe database columns “id” and “name” can’t be NULL, the Pythonattributes id and name most certainly can be None without an explicitconstructor:

他们在那篇文章中还列出了缓解措施,将列显式声明为映射类型。

关于python - 如何让 Mypy 识别不可为 null 的 ORM 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71674202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com