Skip to content

Idiomatic tuple element replacement #16948

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
finite-state-machine opened this issue Feb 25, 2024 · 0 comments
Open

Idiomatic tuple element replacement #16948

finite-state-machine opened this issue Feb 25, 2024 · 0 comments
Labels

Comments

@finite-state-machine
Copy link

finite-state-machine commented Feb 25, 2024

Feature

To replace one element within a tuple (returning a modified copy), we're currently forced to write something like this:

[mypy-play.net]

from __future__ import annotations
from typing import (
        Any,
        Dict,
        Final,
        Tuple,
        )
from typing_extensions import (
        assert_type,
        )

ComplexTuple = Tuple[str, int, str, Dict[Any, Any], Dict[str, Any]]
        # (field0, lineno, field2, field3, field4)

def add_to_lineno(ctup: ComplexTuple, lineno_delta: int) -> ComplexTuple:

    # we want to represent the index to be replaced in one place, to
    # keep things DRY:
    index: Final = 1  # s.t. ctup[index] == lineno

    left = ctup[:index]  # element(s) left of the value being replaced

    lineno = ctup[index]
    lineno += lineno_delta
    lineno_frag = (lineno,)

    right = ctup[index:][1:]  # elements right of the value being
                              # replaced
            # NOTE: ↑ weird, inefficient phrasing of 'ctup[index+1:]'

    ret = left + lineno_frag + right
    return ret

Note the very odd phrasing of right = ... at line 27; this serves to work around incomplete #11990 (which appears to be stale).

It took me quite a while to identify this work-around; I'm sure others would struggle with the same issue.

Pitch

In my opinion, there would be value in doing one of the following:

  • document namedtuple._replace() as the preferred work-around for this case, in a way that aids discovery
  • (ideally) implement a subset of proposal Literal type math #11990, specifically focused on basic arithmetic support for Literals with exactly one, integer value
  • implement a function to idiomatically replace elements of a tuple (that isn't a namedtuple)

Notes

I apologize if a "feature" isn't the right venue for discussing this.

This builds on #3078.

@finite-state-machine finite-state-machine changed the title Idiomatic tuple value replacement Idiomatic tuple element replacement Feb 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant