python-3.x - MongoEngine 字段、类型和 PyCharm

标签 python-3.x pycharm mongoengine

PyCharm 在处理 MongoEngine 字段的值时给出类型警告。例如,与 str 一样使用 StringField 时:

class ExampleDocument(Document):
    s = StringField()

doc = ExampleDocument(s='mongoengine-test')
print(doc.s.endswith('test'))

除非我使用 typing.cast(即 typing.cast(str, doc.s ).endswith('test')。代码按预期执行,但有什么方法可以消除这些警告并获得 MongoEngine 字段类型所需的自动完成功能?

最佳答案

这可能不是所有可想到的解决方案中最好的,但您可以将自己的类型提示直接添加到字段声明中。使用带注释的 2.7 语法(也适用于 3.x):

class ExampleDocument(Document):
    s = StringField()  # type: str

或使用 3.x:

class ExampleDocument(Document):
    s: str = StringField()

在文档字符串中使用类型定义也应该有效:

class ExampleDocument(Document):
    s = StringField()
    """:type: str"""

其中任何一个都为 PyCharm(或带有 python 插件的 Intelij)提供了有关用于这些字段的类型的必要线索。

请注意,现在当您从原始 mongoengine 字段类型访问某些内容时,您将收到警告,因为您有效地替换了用于类型检查的类型。如果您希望 PyCharm 同时识别 mongoengine 和 Python 类型,您可以使用 Union 类型:

from typing import Union
class ExampleDocument(Document):
    s = StringField()  # type: Union[str, StringField]

您可以在 PyCharm 文档中找到有关在 PyCharm 中使用类型 hins 的更多详细信息 here .

关于python-3.x - MongoEngine 字段、类型和 PyCharm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46512309/

相关文章:

django - Mongoengine FileField 保存到磁盘?

python - 如何在 mongoengine 类模型中将属性名称表示为日期时间

python - 以编程方式获取函数参数(没有 **kwargs)?

python - 删除列表中的重复项,但不应根据计数删除第一个首选项

pycharm - 在pycharm中,如何跳转到下一个严重错误? (F2查找样式警告)

node.js - NodeJS/MongoDB 中集合的不同数据库

python - 在电子邮件中嵌入图片

python - 如何使用 PyQt5 播放视频的特定部分

heroku - 如何使用 Heroku 设置 Pydevd 远程调试

Jupyter 和 PyCharm 中的 Python 统计模型和简单指数平滑