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/