【问题标题】:MongoEngine fields, typing and PyCharmMongoEngine 字段、打字和 PyCharm
【发布时间】:2017-11-17 21:50:26
【问题描述】:

PyCharm 在使用 MongoEngine 字段的值时会发出类型警告。例如,当使用StringField 和str 工作时:

class ExampleDocument(Document):
    s = StringField()

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

我收到警告类 StringField 的未解析属性引用 'endswith' 除非我使用 typing.cast(即 typing.cast(str, doc.s).endswith('test')。代码按预期执行,但有什么办法可以摆脱这些警告以及获取 MongoEngine 字段类型的必要自动完成功能?

【问题讨论】:

    标签: python-3.x pycharm mongoengine


    【解决方案1】:

    这可能不是所有可以想到的解决方案中最好的,但您可以将自己的类型提示直接添加到字段声明中。将 2.7 语法与 cmets 一起使用(也适用于 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 字段类型访问某些内容时,您将收到警告,因为您有效地替换了用于类型检查的类型。如果你想让 PyC​​harm 同时识别 mongoengine 和 Python 类型,你可以使用 Union 类型:

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

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

    【讨论】:

    • 谢谢,这或多或少是我正在使用的。有没有办法声明一种类型扩展另一种类型(例如 StringField 实现了 str 的所有方法)?
    • 您可以在评论或 Python 3.x 类型提示中使用Union[str, StringField]。 Union 必须从 typing 模块导入。
    猜你喜欢
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2012-05-30
    • 2021-10-07
    • 2014-02-03
    • 2016-10-31
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多