def _check_postconditions(postconditions: Sequence[Union[Ensure, EnsureTrue]],
                          args_dict: Dict[Text, Any],
                          named_dims: Dict[Text, Union[int, tf.Tensor]],
                          context: _Context,
                          result: Any) -> Any:
  """Check postconditions, mutating `result` to include dynamic checks."""
  for postcondition in postconditions:
    if isinstance(postcondition, Ensure):
      if postcondition.tensor.startswith(RESULT + "."):
        # We need to do the work of writing to structured objects with
        # properties.
        raise ValueError(
            "Postconditions with RESULT.attributes are not yet supported.")
      if postcondition.tensor != RESULT:
        raise ValueError(
            "`Ensure` must use `RESULT` (or some property of result). "
            "Use `Require` instead.")
    # *Only* when checking postconditions, add `RESULT` to `args_dict`.
    args_dict[RESULT] = result
    postcondition_ops = postcondition.check(
        context,
        args_dict,
        named_dims,
        dynamic_asserts=_dynamic_asserts_enabled)

    tuple_index = None
    if isinstance(postcondition, Ensure):
      tuple_index = postcondition.tuple_index

    # If there's a tuple index for this postcondition, we must attach this
    # postcondition to exactly that tensor.
    target_tensor = result
    if tuple_index is not None:
      target_tensor = _get_tensor_arg(
          args_dict,
          postcondition.tensor,
          tuple_index=postcondition.tuple_index,
          context=context)
    # For TF1 / non-eager mode, we have to generate a dummy op to attach
    # the op to.
    if _dynamic_asserts_enabled:
      with tf.control_dependencies(postcondition_ops):
        target_tensor = tf.identity(target_tensor)

      # Now that we've potentially modified a result or tuple result, we
      # need to overwrite the original result.
      if tuple_index is None:
        result = target_tensor
      else:
        result = _tuple_assign(result, postcondition.tuple_index, target_tensor)
  return result
Check postconditions, mutating `result` to include dynamic checks.
language/canine/tensor_contracts.py