3

I like making use of the typing capabilities in Python along with a static type check e.g. pyright. Unfortunately, not all libraries are completely typed. For example some functions may be generated at runtime (therefore missing) or the function return type is not specified because it depends on the input parameters.

These type of functions obviously result in warnings. How do you resolve these types of warnings from your type checker?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
TomTom
  • 2,820
  • 4
  • 28
  • 46
  • it depends on your checker. Basically you need to tell the checker that not having type annotations is not an error. – balderman Aug 10 '21 at 12:53
  • There is no portable way to do this for all type checkers. Please focus on one. You have mentioned pyright as an example, is it the only one you care about? – MisterMiyagi Aug 10 '21 at 12:56
  • Note that both generating functions ("higher order functions") and type dependencies between parameter/return types ("type variables") are supported by Python's ``typing``. In many cases, they are not a reason to skip typing – on the contrary, typing can offer significant advantage for these cases due to automatic checking. – MisterMiyagi Aug 10 '21 at 12:59
  • @MisterMiyagi I care about pyright and mypy. – TomTom Aug 10 '21 at 13:05
  • Does this answer your question? [Is it possible to reduce/eliminate MyPy errors for system level code with a command line option?](https://stackoverflow.com/questions/64432831/is-it-possible-to-reduce-eliminate-mypy-errors-for-system-level-code-with-a-comm) – MisterMiyagi Aug 10 '21 at 13:10
  • Does this answer your question? [Why does mypy think library imports are missing?](https://stackoverflow.com/questions/57785471/why-does-mypy-think-library-imports-are-missing) – MisterMiyagi Aug 10 '21 at 13:13
  • Does this answer your question? [error: Skipping analyzing 'flask_mysqldb': found module but no type hints or library stubs](https://stackoverflow.com/questions/60716482/error-skipping-analyzing-flask-mysqldb-found-module-but-no-type-hints-or-lib) – MisterMiyagi Aug 10 '21 at 13:13

1 Answers1

0

Something that can be helpful here is that Unknown can be converted to Any, which can then be downcasted without causing warnings. For example, I have a class member of type dateutil.rrule.rrule, which has no type hints. So the following makes Pylance complain that advance() and self.time have an unknown type:

@dataclass
class Event:
    recurrence: dateutil.rrule.rrule
    time: datetime.datetime

    def advance(self):
        step = self.recurrence.after(self.time)
        self.time = step
        return self.time

But casting the result of after() to Any and ignoring the errors on that line fixes it:

    def advance(self) -> datetime.datetime:
        step: Any = self.recurrence.after(self.time)  # type: ignore
        self.time = step
        return self.time
Dan
  • 12,409
  • 3
  • 50
  • 87