0

I am testing mypy in one of my projects to see if I will like or not. I know only the basics so far. Here is a little problem I am unable to solve.

I need a function with positional-only parameters. In Python 3.8+:

def func(self, arg: int, /, **data):

(This allows to use self=something and arg=something in the data, if you're curious why.)

To make it work also in Python 3.7 I had to write:

def func(*args, **data):
    self, arg = args

And it works fine, but seems to confuse the mypy, it complains about parameter types in calls of this func.

How can I annotatate, that arg[1] is an int?


Update:

I had some partial success with typing.overload.

A single @overload generates this error: "Single overload definition, multiple required" and when I write it twice: "Overloaded function signature 2 will never be matched" but the calls to that method are now checked OK.

VPfB
  • 14,927
  • 6
  • 41
  • 75
  • You don't! This is hard to explain, but how would you guarantee order to the elements in `*args`? The only way would be passing in a tuple (because using a list you can't type hint order of the elements - just the types inside the collection without order.) So the way to type hint this is ensuring that when you unpack you get the order right and declare the type on the variables you're unpacking to, and mypy will force you to use [type narrowing](https://mypy.readthedocs.io/en/latest/type_narrowing.html) – bad_coder Feb 22 '22 at 04:16
  • The same goes for **kwargs, see [this answer and the linked post](https://stackoverflow.com/a/63550734). With Python 3.11 there's a way of doing this but I haven't tried it yet. – bad_coder Feb 22 '22 at 04:19
  • @bad_coder thanks for you comments. I see a value in type annotations for documentation purposes, but I hesitate to write extra lines of code just to help the `mypy` to understand the code. But things may change, I haven't made my mind about the usefulness of `mypy` in my workflow yet.... – VPfB Feb 22 '22 at 08:00

0 Answers0