python / python/typeshed

Typing for callable inputs in itertools.starmap

Open
#14,892 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.1k
Forks
2.1k
Avg merge
1d 19h
Merged PRs (30d)
82

Description

The type annotations for itertools.starmap allow any iterables for any function arguments:
https://github.com/python/typeshed/blob/11c7821a79a8ab7e1982f3ab506db16f1c4a22a9/stdlib/itertools.pyi#L112-L116

This means I can do something like:

def myfunc(x: int, y: int):
    return x + y

itertools.starmap(myfunc, [["foo, "bar"]])

and type checkers won't complain.

map gets around this to some extent with overloads for callables with up to 5 arguments (but if you need 6 or more, you're out of luck!)
https://github.com/python/typeshed/blob/11c7821a79a8ab7e1982f3ab506db16f1c4a22a9/stdlib/builtins.pyi#L1629-L1670

I couldn't figure out a way to ge that to work with starmap, though, because as far as I can tell the python type system doesn't have any way of specifying an iterable that returns a particular sequence of types. The best you can do is something like def __new__(cls, function: Callable[[_T1, _T2], T], iterable: Iterable[Iterable[_T1 | _T2]], /), which is still better in my opinion (it prevents invalid argument types), but it doesn't stop you from swapping function arguments.

Is there a way to do this? Or does it just need a new language feature? It would be great if we could do something like

P = ParamSpec("P")
def __new__(cls, function: Callable[P, T], iterable: Iterable[P.args], /)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the itertools.starmap annotation in stdlib/itertools.pyi around lines 112-116, then compare it with the callable overloads for map in stdlib/builtins.pyi around lines 1629-1670. Determine whether the requested callable-input relationship is expressible with current Python typing, and define what a correct annotation should guarantee.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.