MongoEngine fields, typing and PyCharm

Viewed 612

PyCharm gives a type warning when working with a MongoEngine field's value. For example, when working with StringField as with str:

class ExampleDocument(Document):
    s = StringField()

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

I get a warning Unresolved attribute reference 'endswith' for class StringField unless I use typing.cast (i.e. typing.cast(str, doc.s).endswith('test'). The code executes as intended, but is there any way to get rid of these warnings and also to get the necessary autocompletes for MongoEngine field types?

1 Answers

It is probably not the best of all thinkable solutions, but you can add your own type hints directly to the field declarations. Either using 2.7 syntax with comments (also works in 3.x):

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

Or with 3.x:

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

Using type defintions in doc strings should also work:

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

Either one of those gives PyCharm (or Intelij with python plugins) the necessary clues about the type to use for these field.

Note that now you will get warnings, when you access something from original mongoengine field types, because you effectively replaced the type used for type checking. If you want PyCharm to recognise both the mongoengine and the Python type, you can use a Union type:

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

You find more details on using type hins in PyCharm in the PyCharm docs here.

Related