How to deal with unknown types of functions/methods from imported modules
Asked Answered
S

1

11

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!

Shannan answered 27/4, 2021 at 13:34 Comment(3)
I also found this 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.Shannan
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.Odle
Someone has already published stubs for pymongo: pypi.org/project/pymongo-stubsHovercraft
E
1

This isn't an ideal solution since it ruins the import's typing, 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.

Egide answered 6/5, 2022 at 8:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.