7

I'm wondering what's the best approach to deal with unknown types of functions/methods associated with other modules. Note that I'm using strict mode

For example, I have the following:

rooms: List[str] = list(mongo_client.devices.distinct("room"))

mongo_client is just an instance of a MongoClient imported from pymongo. VSCode screams that it doesn't know the type of the distinct method:

Type of "distinct" is partially unknown
  Type of "distinct" is "(key: Unknown, filter: Unknown = None, session: Unknown = None, **kwargs: Unknown) -> Unknown"PylancereportUnknownMemberType
Argument type is unknown
  Argument corresponds to parameter "iterable" in function "__init__"PylancereportUnknownArgumentType

What I can do:

  • Add reportUnknownMemberType to pyrightconfig.json; however, while this removes the previous warning, it's also going to disable warnings that I probably really want
  • Add # type: ignore on the line with that distinct call; I usually hate having flying ignore-comments like this and I don't think it "fixes" anything
  • Create a stub file myself

What would you do? Should I not use strict mode? Most of the project was written with the strict mode activated to make sure I'm not missing anything. Is these some cast trick I can do?

Thanks!

Adrian Pop
  • 1,879
  • 5
  • 28
  • 40
  • I also found [this](https://github.com/sbdchd/mongo-types) and the warnings disappear if I install that. Not sure if it's a module that I should keep installed or pymongo will have types in the future. – Adrian Pop Apr 27 '21 at 15:41
  • 5
    I'm surprised that this question doesn't have more traction. I have a whole slew of third-party libraries in my project with no typing information, and with strict type checking, it's creating quite the headache. So far, I'm actually resorting to writing stubs manually for the bits of the third-party libraries that I'm using. – Alex Peters Jun 13 '21 at 02:17
  • Someone has already published stubs for pymongo: https://pypi.org/project/pymongo-stubs/ – teaishealthy Nov 01 '22 at 13:30

1 Answers1

0

This isn't an ideal solution since it ruins the import's IntelliSense, but it avoids disabling type checks you might want elsewhere and makes it so you don't have to write your own stubs.

from typing import Any, cast

from somewhere import Something  # type: ignore

Something = cast(Any, Something)

Now you can use Something freely.

Grant Gryczan
  • 1,314
  • 16
  • 24