def _tuple_assign(target: Tuple[Any], index: int, item: Any) -> Tuple[Any]:
  """Assign a result into an (immutable) tuple via copy-on-write."""

  # TODO(jhclark): Support `tuple_item` with string names for named tuples.
  result = list(target)
  result[index] = item
  if _is_named_tuple(target):
    # For NamedTuples, we need to still return another NamedTuple.
    result = type(target)._make(result)  # pytype: disable=attribute-error
  elif isinstance(target, list):
    pass
  else:
    result = tuple(result)
  # Make sure we didn't mutilate the type somehow.
  assert isinstance(result, type(target))
  return result
Assign a result into an (immutable) tuple via copy-on-write.
language/canine/tensor_contracts.py