python / python/mypy

Variadic tuple unpacking requires a star target -- why?

Open
#17,282 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When attempting to unpack a tuple that uses Unpack, if you don't use a star target to capture the variadic tuple as a list, you get the error Variadic tuple unpacking requires a star target.

This is overly strict and prescriptivist and is not even applied consistently between similar type concepts within mypy.

  1. You definitely can do this if the lengths check out.
  2. pyright doesn't raise an error like this. You are simply on your own for length checking the unpacking of indeterminate length tuples, just like you are for list, another indeterminate length unpackable sequence.
  3. In fact, this is also how mypy treats unpacking list. It doesn't raise an error if you don't use a star target.
  4. I have a real use case where I want to do exactly this. I lay out my use case in this bug report to pyright: https://github.com/microsoft/pyright/issues/7987

To Reproduce

from typing import Tuple

from typing_extensions import Unpack


def foo() -> Tuple[int, Unpack[Tuple[str, ...]]]:
    return 1, "bar", "baz"

a, b, c = foo()  # error: Variadic tuple unpacking requires a star target  [misc]

d, e, f = [1, "bar", "baz"]  # OK

Gist URL: https://gist.github.com/mypy-play/4014976ca069e54b5c1fe86a45353f58
Playground URL: https://mypy-play.net/?mypy=master&python=3.12&gist=4014976ca069e54b5c1fe86a45353f58

Expected Behavior

No errors in the above example. a's type should be revealed to be int, and b and c's types should be revealed to be str.

Actual Behavior

An error, and a, b, and c are all revealed to be Any.

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 with the minimal reproduction in the report or its mypy-play URL, and compare the diagnostic and revealed types for tuple and list unpacking. Done means the tuple assignment produces no error, reveals a as int and b and c as str, and does not regress the list case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.