Typing for callable inputs in itertools.starmap
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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