Fixing error messages for check_ops.py and control_flow_state.py

PiperOrigin-RevId: 396064202
Change-Id: Iac225d4427836134fbebea86a1df45e28a41aa44
diff --git a/tensorflow/python/kernel_tests/check_ops_test.py b/tensorflow/python/kernel_tests/check_ops_test.py
index 435da22..17ea8c2 100644
--- a/tensorflow/python/kernel_tests/check_ops_test.py
+++ b/tensorflow/python/kernel_tests/check_ops_test.py
@@ -135,7 +135,7 @@
   @test_util.run_in_graph_and_eager_modes
   def test_non_iterable_object_raises(self):
     non_iterable = 1234
-    with self.assertRaisesRegex(TypeError, "to be iterable"):
+    with self.assertRaisesRegex(TypeError, "to be an iterable"):
       check_ops.assert_proper_iterable(non_iterable)
 
   @test_util.run_in_graph_and_eager_modes
@@ -1177,13 +1177,13 @@
       desired_rank = 2
       with ops.control_dependencies(
           [check_ops.assert_rank(tensor, desired_rank)]):
-        with self.assertRaisesOpError("my_tensor.*rank"):
+        with self.assertRaisesOpError("my_tensor.* must have rank"):
           array_ops.identity(tensor).eval(feed_dict={tensor: [1, 2]})
 
   @test_util.run_in_graph_and_eager_modes
   def test_raises_if_rank_is_not_scalar_static(self):
     tensor = constant_op.constant([1, 2], name="my_tensor")
-    with self.assertRaisesRegex(ValueError, "Rank must be a scalar"):
+    with self.assertRaisesRegex(ValueError, "Argument `rank` must be a scalar"):
       check_ops.assert_rank(tensor, np.array([], dtype=np.int32))
 
   @test_util.run_deprecated_v1
@@ -1192,7 +1192,7 @@
       tensor = constant_op.constant(
           [1, 2], dtype=dtypes.float32, name="my_tensor")
       rank_tensor = array_ops.placeholder(dtypes.int32, name="rank_tensor")
-      with self.assertRaisesOpError("Rank must be a scalar"):
+      with self.assertRaisesOpError("Rank must be a scalar."):
         with ops.control_dependencies(
             [check_ops.assert_rank(tensor, rank_tensor)]):
           array_ops.identity(tensor).eval(feed_dict={rank_tensor: [1, 2]})
@@ -1221,7 +1221,7 @@
   @test_util.run_in_graph_and_eager_modes
   def test_rank_zero_tensor_raises_if_rank_mismatch_static_rank(self):
     tensor_rank0 = constant_op.constant(42, name="my_tensor")
-    with self.assertRaisesRegex(ValueError, "fail.*must have rank.*in.*1.*2"):
+    with self.assertRaisesRegex(ValueError, "fail.*must have rank.*1.*2"):
       with ops.control_dependencies([
           check_ops.assert_rank_in(tensor_rank0, (1, 2), message="fail")]):
         self.evaluate(array_ops.identity(tensor_rank0))
@@ -1296,7 +1296,8 @@
     desired_ranks = (
         np.array(1, dtype=np.int32),
         np.array((2, 1), dtype=np.int32))
-    with self.assertRaisesRegex(ValueError, "Rank must be a scalar"):
+    with self.assertRaisesRegex(
+        ValueError, "Argument `ranks` must contain scalar tensors."):
       check_ops.assert_rank_in(tensor, desired_ranks)
 
   @test_util.run_deprecated_v1
@@ -1550,15 +1551,15 @@
         constant_op.constant([[111], [232]], dtypes.int64),
         constant_op.constant([23.4, -43.2], dtypes.float16),
         constant_op.constant([500], dtypes.int64))
-    with self.assertRaisesRegexp(TypeError, "must be of type.*float32"):
+    with self.assertRaisesRegex(TypeError, "must be of type.*float32"):
       check_ops.assert_type(sparse_float16, dtypes.float32)
 
   def test_raise_when_tf_type_is_not_dtype(self):
     # Test case for GitHub issue:
     # https://github.com/tensorflow/tensorflow/issues/45975
     value = constant_op.constant(0.0)
-    with self.assertRaisesRegexp(TypeError,
-                                 "Cannot convert.*to a TensorFlow DType"):
+    with self.assertRaisesRegex(TypeError,
+                                "Cannot convert.*to a TensorFlow DType"):
       check_ops.assert_type(value, (dtypes.float32,))
 
 
@@ -1572,8 +1573,8 @@
         (x, ("N", "Q")),
         (y, ("N", "D")),
     ]
-    regex = (r"Specified by tensor .* dimension 0.  "
-             r"Tensor .* dimension 0 must have size 3.  "
+    regex = (r"Specified by tensor .* dimension 0. "
+             r"Tensor .* dimension 0 must have size 3. "
              r"Received size 2")
     self.raises_static_error(shapes=shapes, regex=regex)
 
@@ -1598,8 +1599,8 @@
         (x, (3, "Q")),
         (y, (3, "D")),
     ]
-    regex = (r"Specified explicitly.  "
-             r"Tensor .* dimension 0 must have size 3.  "
+    regex = (r"Specified explicitly. "
+             r"Tensor .* dimension 0 must have size 3. "
              r"Received size 2")
     self.raises_static_error(shapes=shapes, regex=regex)
 
@@ -1622,8 +1623,8 @@
     shapes = [
         (x, ()),
     ]
-    regex = (r"Specified explicitly.  "
-             r"Tensor .* dimension 0 must have size 1.  "
+    regex = (r"Specified explicitly. "
+             r"Tensor .* dimension 0 must have size 1. "
              r"Received size 2")
     self.raises_static_error(shapes=shapes, regex=regex)
 
@@ -1633,8 +1634,8 @@
     shapes = [
         (x, (2,)),
     ]
-    regex = (r"Specified explicitly.  "
-             r"Tensor .* dimension 0 must have size 2.  "
+    regex = (r"Specified explicitly. "
+             r"Tensor .* dimension 0 must have size 2. "
              r"Received size 1")
     self.raises_static_error(shapes=shapes, regex=regex)
 
@@ -1643,8 +1644,8 @@
     scalar = array_ops.constant(5, name="rank_zero")
     x = array_ops.ones([2, 2], name="x")
     shapes = [(scalar, ("a",)), (x, ("a", 2))]
-    regex = (r"Specified by tensor .* dimension 0.  "
-             r"Tensor .* dimension 0 must have size 1.  "
+    regex = (r"Specified by tensor .* dimension 0. "
+             r"Tensor .* dimension 0 must have size 1. "
              r"Received size 2")
     self.raises_static_error(shapes=shapes, regex=regex)
 
@@ -1652,9 +1653,9 @@
   def test_raise_not_iterable(self):
     x = array_ops.constant([1, 2], name="x")
     shapes = [(x, 2)]
-    regex = (r"Tensor .*.  "
-             r"Specified shape must be an iterable.  "
-             r"An iterable has the attribute `__iter__` or `__getitem__`.  "
+    regex = (r"Tensor .*. "
+             r"Specified shape must be an iterable. "
+             r"An iterable has the attribute `__iter__` or `__getitem__`. "
              r"Received specified shape: 2")
     self.raises_static_error(shapes=shapes, regex=regex)
 
@@ -1696,7 +1697,7 @@
 
     def raises_static_rank_error(shapes, x, correct_rank, actual_rank):
       for shape in shapes:
-        regex = (r"Tensor .* must have rank %d.  Received rank %d" %
+        regex = (r"Tensor .* must have rank %d. Received rank %d" %
                  (correct_rank, actual_rank))
         self.raises_static_error(shapes=[(x, shape)], regex=regex)
 
@@ -1787,8 +1788,8 @@
     for shapes in styles:
       self.raises_static_error(
           shapes=shapes,
-          regex=(r"Specified by tensor .* dimension 0.  "
-                 "Tensor .* dimension 0 must have size 2.  "
+          regex=(r"Specified by tensor .* dimension 0. "
+                 "Tensor .* dimension 0 must have size 2. "
                  "Received size 1"))
 
   @test_util.run_in_graph_and_eager_modes
@@ -1814,8 +1815,8 @@
     for shapes in styles:
       self.raises_static_error(
           shapes=shapes,
-          regex=(r"Specified explicitly.  "
-                 "Tensor .* dimension 0 must have size 2.  "
+          regex=(r"Specified explicitly. "
+                 "Tensor .* dimension 0 must have size 2. "
                  "Received size 1"))
 
   @test_util.run_in_graph_and_eager_modes
@@ -1850,8 +1851,8 @@
         (x, "3Q"),
         (y, "*3D"),
     ]
-    regex = (r"Specified explicitly.  "
-             r"Tensor .* dimension -2 must have size 3.  "
+    regex = (r"Specified explicitly. "
+             r"Tensor .* dimension -2 must have size 3. "
              r"Received size 2")
     self.raises_static_error(shapes=s1, regex=regex)
     self.raises_static_error(shapes=s2, regex=regex)
@@ -1881,7 +1882,7 @@
     s2 = [
         (x, "N*Q"),
     ]
-    regex = (r"Tensor .* specified shape index .*.  "
+    regex = (r"Tensor .* specified shape index .*. "
              r"Symbol `...` or `\*` for a variable number of "
              r"unspecified dimensions is only allowed as the first entry")
     self.raises_static_error(shapes=s1, regex=regex)
@@ -1949,7 +1950,7 @@
         constant_op.constant([[111], [232]], dtypes.int64),
         constant_op.constant([23.4, -43.2], dtypes.float32),
         constant_op.constant([500], dtypes.int64))
-    with self.assertRaisesRegexp(ValueError, r"dimension 0 must have size 499"):
+    with self.assertRaisesRegex(ValueError, r"dimension 0 must have size 499"):
       assertion = check_ops.assert_shapes([(sparse_float, [499])])
       with ops.control_dependencies([assertion]):
         out = array_ops.identity(sparse_float)
@@ -1983,7 +1984,7 @@
         constant_op.constant([[5, 6], [7, 8]], dtypes.int64),
         constant_op.constant([23, -43], dtypes.int32),
         constant_op.constant([30, 40], dtypes.int64))
-    with self.assertRaisesRegexp(ValueError, r"dimension 1 must have size 41"):
+    with self.assertRaisesRegex(ValueError, r"dimension 1 must have size 41"):
       assertion = check_ops.assert_shapes([(sparse_int, [None, 41])])
       with ops.control_dependencies([assertion]):
         out = array_ops.identity(sparse_int)
@@ -2008,7 +2009,7 @@
         constant_op.constant([[5, 6], [7, 8]], dtypes.int64),
         constant_op.constant([23, -43], dtypes.int32),
         constant_op.constant([30, 40], dtypes.int64))
-    with self.assertRaisesRegexp(ValueError, r"dimension 1 must have size 30"):
+    with self.assertRaisesRegex(ValueError, r"dimension 1 must have size 30"):
       assertion = check_ops.assert_shapes([(sparse_int, ["D", "D"])])
       with ops.control_dependencies([assertion]):
         out = array_ops.identity(sparse_int)
@@ -2040,7 +2041,7 @@
         constant_op.constant([[5, 6], [7, 8]], dtypes.int64),
         constant_op.constant([23, -43], dtypes.int32),
         constant_op.constant([30, 40], dtypes.int64))
-    with self.assertRaisesRegexp(ValueError, r"dimension 1 must have size 30"):
+    with self.assertRaisesRegex(ValueError, r"dimension 1 must have size 30"):
       assertion = check_ops.assert_shapes([(sparse_scalar, []),
                                            (sparse_2d, ["N", "N"])])
       with ops.control_dependencies([assertion]):
@@ -2067,7 +2068,7 @@
         constant_op.constant([[5, 6], [7, 8]], dtypes.int64),
         constant_op.constant([23, -43], dtypes.int32),
         constant_op.constant([30, 40], dtypes.int64))
-    with self.assertRaisesRegexp(ValueError, r"dimension 1 must have size 30"):
+    with self.assertRaisesRegex(ValueError, r"dimension 1 must have size 30"):
       assertion = check_ops.assert_shapes([(dense_scalar, []),
                                            (sparse_2d, ["N", "N"])])
       with ops.control_dependencies([assertion]):
diff --git a/tensorflow/python/ops/check_ops.py b/tensorflow/python/ops/check_ops.py
index aa36eb7..10a72b8 100644
--- a/tensorflow/python/ops/check_ops.py
+++ b/tensorflow/python/ops/check_ops.py
@@ -453,12 +453,12 @@
   )
   if isinstance(values, unintentional_iterables):
     raise TypeError(
-        'Expected argument "values" to be a "proper" iterable.  Found: %s' %
-        type(values))
+        'Expected argument `values` to be a "proper" iterable. Found: '
+        f'{type(values)}')
 
   if not hasattr(values, '__iter__'):
     raise TypeError(
-        'Expected argument "values" to be iterable.  Found: %s' % type(values))
+        f'Expected argument `values` to be an iterable. Found: {type(values)}')
 
 
 @tf_export('debugging.assert_negative', v1=[])
@@ -1123,7 +1123,8 @@
   rank_static = tensor_util.constant_value(rank)
   if rank_static is not None:
     if rank_static.ndim != 0:
-      raise ValueError('Rank must be a scalar.')
+      raise ValueError('Argument `rank` must be a scalar tensor. Received '
+                       f'tensor {rank} of rank: {rank_static}')
 
     x_rank_static = x.get_shape().ndims
     if x_rank_static is not None:
@@ -1137,7 +1138,7 @@
   # Add the condition that `rank` must have rank zero.  Prevents the bug where
   # someone does assert_rank(x, [n]), rather than assert_rank(x, n).
   if rank_static is None:
-    this_data = ['Rank must be a scalar. Received rank: ', rank]
+    this_data = [f'Rank must be a scalar. Received rank: {rank}']
     rank_check = assert_rank(rank, 0, data=this_data)
     condition = control_flow_ops.with_dependencies([rank_check], condition)
 
@@ -1234,8 +1235,8 @@
     except ValueError as e:
       if e.args[0] == 'Static rank condition failed':
         raise ValueError(
-            '%sTensor %s must have rank %d.  Received rank %d, shape %s' %
-            (message, name, e.args[2], e.args[1], x.get_shape()))
+            f'{message}Tensor x = {name} must have rank {e.args[2]}. Received '
+            f'rank {e.args[1]}, shape {x.get_shape()}')
       else:
         raise
 
@@ -1335,8 +1336,8 @@
     except ValueError as e:
       if e.args[0] == 'Static rank condition failed':
         raise ValueError(
-            '%sTensor %s must have rank at least %d.  Received rank %d, '
-            'shape %s' % (message, name, e.args[2], e.args[1], x.get_shape()))
+            f'{message}Tensor x = {name} must have rank at least {e.args[2]}. '
+            f'Received rank {e.args[1]}, shape {x.get_shape()}')
       else:
         raise
 
@@ -1387,7 +1388,8 @@
   if not any(r is None for r in ranks_static):
     for rank_static in ranks_static:
       if rank_static.ndim != 0:
-        raise ValueError('Rank must be a scalar.')
+        raise ValueError('Argument `ranks` must contain scalar tensors. '
+                         f'Received tensor of rank: {rank_static}')
 
     x_rank_static = x.get_shape().ndims
     if x_rank_static is not None:
@@ -1402,7 +1404,7 @@
   # someone does assert_rank(x, [n]), rather than assert_rank(x, n).
   for rank, rank_static in zip(ranks, ranks_static):
     if rank_static is None:
-      this_data = ['Rank must be a scalar. Received rank: ', rank]
+      this_data = [f'Rank must be a scalar. Received rank: {rank}']
       rank_check = assert_rank(rank, 0, data=this_data)
       condition = control_flow_ops.with_dependencies([rank_check], condition)
 
@@ -1499,8 +1501,8 @@
     except ValueError as e:
       if e.args[0] == 'Static rank condition failed':
         raise ValueError(
-            '%sTensor %s must have rank in %s.  Received rank %d, '
-            'shape %s' % (message, name, e.args[2], e.args[1], x.get_shape()))
+            f'{message}Tensor x = {name} must have rank {e.args[2]}. Received '
+            f'rank {e.args[1]}, shape {x.get_shape()}')
       else:
         raise
 
@@ -1560,8 +1562,8 @@
       else:
         name = x.name
       err_msg = (
-          '%sExpected "x" to be integer type.  Found: %s of dtype %s'
-          % (_message_prefix(message), name, x.dtype))
+          f'{_message_prefix(message)}Expected argument `x` to be integer type.'
+          f' Found: {name} of dtype {x.dtype}')
       raise TypeError(err_msg)
 
     return control_flow_ops.no_op('statically_determined_was_integer')
@@ -1627,13 +1629,13 @@
       tensor = ops.convert_to_tensor(tensor, name='tensor')
     if tensor.dtype != tf_type:
       if context.executing_eagerly():
-        raise TypeError('%s tensor must be of type %s' % (message, tf_type))
+        raise TypeError(f'{message} Expected type of argument `tensor` must be '
+                        f'of type {tf_type}, obtained {tensor.dtype}')
       else:
+        tensor_name = tensor.name if hasattr(tensor, 'name') else ''
         raise TypeError(
-            '%s%s must be of type %s' %
-            (_message_prefix(message),
-             tensor.name if hasattr(tensor, 'name') else '',
-             tf_type))
+            f'{_message_prefix(message)} Expected type of argument `tensor`, '
+            f'{tensor_name} must be of type {tf_type}, obtained {tensor.dtype}')
 
     return control_flow_ops.no_op('statically_determined_correct_type')
 
@@ -1880,11 +1882,9 @@
       )
       if not is_iterable:
         raise ValueError(
-            '%s'
-            'Tensor %s.  Specified shape must be an iterable.  '
-            'An iterable has the attribute `__iter__` or `__getitem__`.  '
-            'Received specified shape: %s' %
-            (message_prefix, tensor_name(tensor), symbolic_shape))
+            f'{message_prefix} Tensor {tensor_name(tensor)}. Specified shape '
+            'must be an iterable. An iterable has the attribute `__iter__` or '
+            f'`__getitem__`. Received specified shape: {symbolic_shape}')
 
       # We convert this into a tuple to handle strings, lists and numpy arrays
       symbolic_shape_tuple = tuple(symbolic_shape)
@@ -1896,11 +1896,10 @@
 
         if i != 0:
           raise ValueError(
-              '%s'
-              'Tensor %s specified shape index %d.  '
-              'Symbol `...` or `*` for a variable number of '
-              'unspecified dimensions is only allowed as the first entry' %
-              (message_prefix, tensor_name(tensor), i))
+              f'{message_prefix} Tensor {tensor_name(tensor)} specified shape '
+              f'index {i}. Symbol `...` or `*` for a variable number of '
+              'unspecified dimensions is only allowed as the first entry of '
+              f'argument `shapes` (={shapes})')
 
         tensors_specified_innermost = True
 
@@ -1984,11 +1983,10 @@
           if _has_known_value(actual_size) and _has_known_value(specified_size):
             if int(actual_size) != int(specified_size):
               raise ValueError(
-                  '%s%s.  Tensor %s dimension %s must have size %d.  '
-                  'Received size %d, shape %s' %
-                  (message_prefix, size_check_message, tensor_name(sizes.x),
-                   tensor_dim, specified_size, actual_size,
-                   sizes.x.get_shape()))
+                  f'{message_prefix}{size_check_message}. Tensor '
+                  f'{tensor_name(sizes.x)} dimension {tensor_dim} must have '
+                  f'size {specified_size}. Received size {actual_size}, '
+                  f'shape {sizes.x.get_shape()}')
             # No dynamic assertion needed
             continue
 
@@ -2024,7 +2022,8 @@
   """Gets the difference x[1:] - x[:-1]."""
   x = array_ops.reshape(x, [-1])
   if not is_numeric_tensor(x):
-    raise TypeError('Expected x to be numeric, instead found: %s' % x)
+    raise TypeError(f'Expected argument `x` to be numeric, instead found: {x} '
+                    f'with dtype {x.dtype}')
 
   # If x has less than 2 elements, there is nothing to compare.  So return [].
   is_shorter_than_two = math_ops.less(array_ops.size(x), 2)
@@ -2186,10 +2185,11 @@
           expected_type = item_type
           original_item_str = item.name if hasattr(item, 'name') else str(item)
         elif expected_type != item_type:
-          raise ValueError('%s, type=%s, must be of the same type (%s)%s.' % (
-              item.name if hasattr(item, 'name') else str(item),
-              item_type, expected_type,
-              (' as %s' % original_item_str) if original_item_str else ''))
+          item_name = item.name if hasattr(item, 'name') else str(item)
+          item_str = (' as %s' % original_item_str if original_item_str else '')
+          raise ValueError(
+              f'{item_name}, type={item_type}, must be of the same type '
+              f'({expected_type}){item_str}.')
     return expected_type  # Should be unreachable
   else:
     return expected_type
@@ -2226,7 +2226,8 @@
   if not dtype:
     dtype = dtypes.float32
   elif not dtype.is_floating:
-    raise ValueError('Expected floating point type, got %s.' % dtype)
+    raise ValueError('Expected floating point type for argument `tensors`, '
+                     f'got {dtype}')
   return dtype
 
 
@@ -2281,11 +2282,11 @@
     message = _message_prefix(message)
     if shape.ndims != 0:
       if context.executing_eagerly():
-        raise ValueError('%sExpected scalar shape, saw shape: %s.'
-                         % (message, shape,))
+        raise ValueError(f'{message}Expected scalar shape for argument `tensor`'
+                         f', saw shape: {shape}.')
       else:
-        raise ValueError('%sExpected scalar shape for %s, saw shape: %s.'
-                         % (message, tensor.name, shape))
+        raise ValueError(f'{message}Expected scalar shape for argument `tensor`'
+                         f' {tensor.name}, saw shape: {shape}.')
     return tensor
 
 
diff --git a/tensorflow/python/ops/control_flow_state.py b/tensorflow/python/ops/control_flow_state.py
index 5f0838a..fea80be 100644
--- a/tensorflow/python/ops/control_flow_state.py
+++ b/tensorflow/python/ops/control_flow_state.py
@@ -69,9 +69,9 @@
     max_iter = while_ctxt.maximum_iterations
     if max_iter is None:
       raise ValueError(
-          "Cannot create a gradient accumulator for tensor '%s' inside "
-          "XLA while_loop because maximum_iterations was not passed to "
-          "the tf.while_loop call ('%s')." % (value_name, while_ctxt.name))
+          f"Cannot create a gradient accumulator for tensor '{value_name}' "
+          "inside XLA while_loop because maximum_iterations was not passed to "
+          f"the tf.while_loop call ('{while_ctxt.name}').")
 
     # pylint: disable=protected-access
     max_iter_ctxt = max_iter.op._get_control_flow_context()
@@ -88,13 +88,13 @@
       const_max_iter = tensor_util.constant_value(max_iter)
       if const_max_iter is None:
         raise ValueError(
-            "Cannot create a gradient accumulator for tensor '%s' inside XLA "
-            "while_loop. maximum_iterations tensor '%s' for while_loop context "
-            "'%s' must be statically known (e.g. a constant value or known "
+            f"Cannot create a gradient accumulator for tensor '{value_name}' "
+            "inside XLA while_loop. maximum_iterations tensor "
+            f"'{max_iter.name}' for while_loop context '{while_ctxt.name}' "
+            "must be statically known (e.g. a constant value or known "
             "shape dimension), or be defined at or outside the while loop "
-            "context '%s' (currently defined in '%s')." %
-            (value_name, max_iter.name, while_ctxt.name, curr_ctxt_name,
-             max_iter_ctxt.name))
+            f"context '{curr_ctxt_name}' (currently defined in "
+            f"'{max_iter_ctxt.name}').")
       max_size *= const_max_iter
 
     # Find the next outer WhileContext (or stop if we reach the
@@ -156,8 +156,10 @@
       outer_forward_ctxt = outer_grad_state.forward_context
     else:
       if not hasattr(forward_ctxt, "outer_context"):
-        raise ValueError("Failed to call gradients on a while loop without"
-                         "properly serializing graph via MetaGraphDef")
+        raise ValueError("Expected `outer_context` attribute on argument "
+                         "`forward_ctxt`. Failed to call gradients on a while "
+                         "loop without properly serializing graph via "
+                         "MetaGraphDef.")
       outer_forward_ctxt = forward_ctxt.outer_context
 
     # Add the forward loop counter.
@@ -364,7 +366,9 @@
         else:
           # value is in a cond context within the forward context.
           if not isinstance(value_ctxt, control_flow_ops.CondContext):
-            raise TypeError("value_ctxt is not a CondContext: %s" % value_ctxt)
+            raise TypeError(
+                "OutputContext for `value.op` is not a CondContext: "
+                f"{type(value_ctxt)}")
           if dead_branch:
             # The special case for creating a zero tensor for a dead
             # branch of a switch. See _ControlFlowState.ZerosLikeV1WhileLoop().