diff --git a/tensorflow/python/eager/tensor_test.py b/tensorflow/python/eager/tensor_test.py index f61d8478177..d0500a413df 100644 --- a/tensorflow/python/eager/tensor_test.py +++ b/tensorflow/python/eager/tensor_test.py @@ -128,6 +128,23 @@ class TFETensorTest(test_util.TensorFlowTestCase): tensor = constant_op.constant(numpy_tensor) self.assertAllEqual(numpy_tensor.ndim, tensor.ndim) + def testLenAgreesWithNumpy(self): + numpy_tensor = np.asarray(1.0) + tensor = constant_op.constant(numpy_tensor) + with self.assertRaises(TypeError): + len(numpy_tensor) + with self.assertRaisesRegexp( + TypeError, r"Scalar tensor has no `len[(][)]`"): + len(tensor) + + numpy_tensor = np.asarray([1.0, 2.0, 3.0]) + tensor = constant_op.constant(numpy_tensor) + self.assertAllEqual(len(numpy_tensor), len(tensor)) + + numpy_tensor = np.asarray([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]) + tensor = constant_op.constant(numpy_tensor) + self.assertAllEqual(len(numpy_tensor), len(tensor)) + def testCopy(self): t = constant_op.constant(1.0) tt = copy.copy(t) diff --git a/tensorflow/python/framework/ops.py b/tensorflow/python/framework/ops.py index aaa12bf71ff..84f7dc5c7ca 100644 --- a/tensorflow/python/framework/ops.py +++ b/tensorflow/python/framework/ops.py @@ -890,6 +890,12 @@ class _EagerTensorBase(Tensor): """Returns the number of Tensor dimensions.""" return self.shape.ndims + def __len__(self): + """Returns the length of the first dimension in the Tensor.""" + if not self.shape.ndims: + raise TypeError("Scalar tensor has no `len()`") + return self._shape_tuple()[0] + def _cpu_nograd(self): """A copy of this Tensor with contents backed by host memory.