MongoEngine fields, typing and PyCharm



pycharm在使用MongoEngine字段的值时会发出类型的警告。例如,与StringField一起使用str

class ExampleDocument(Document):
    s = StringField()
doc = ExampleDocument(s='mongoengine-test')
print(doc.s.endswith('test'))

我得到警告未解决的属性参考'endswith'for类Stringfield ,除非我使用typing.cast(即typing.cast(str, doc.s).endswith('test')。代码按预期执行,但是是否有任何方法可以摆脱这些警告,也可以要获取蒙古工程类型的必要自动完成?

它可能不是所有可思考的解决方案中最好的,但是您可以将自己的类型提示直接添加到字段声明中。要么在注释中使用2.7语法(也可以在3.x中起作用):

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

或3.x:

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

使用DOC字符串中的类型定义也应起作用:

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

其中一种使Pycharm(或带有Python插件的Intelij)提供了有关用于这些字段的类型的必要线索。

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

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

您在此处找到有关在Pycharm文档中使用Pycharm中使用键入的更多详细信息。

最新更新