From ee333ea0b078975fffc5ff77eb61d22c5e9b7404 Mon Sep 17 00:00:00 2001 From: Wenqi Li Date: Tue, 16 May 2023 16:03:58 +0100 Subject: [PATCH 1/2] fixes #6522 Signed-off-by: Wenqi Li --- monai/data/meta_tensor.py | 6 ++++++ tests/test_meta_tensor.py | 1 + 2 files changed, 7 insertions(+) diff --git a/monai/data/meta_tensor.py b/monai/data/meta_tensor.py index e3aacb95ee..33f7b8a53c 100644 --- a/monai/data/meta_tensor.py +++ b/monai/data/meta_tensor.py @@ -590,6 +590,12 @@ def __str__(self): """ return f"meta{str(self.as_tensor())}" + def __format__(self, format_spec): + """ + returns the output of pytorch tensor's ``__format__`` method. + """ + return self.as_tensor().__format__(format_spec) + def print_verbose(self) -> None: """Verbose print with meta data.""" print(self) diff --git a/tests/test_meta_tensor.py b/tests/test_meta_tensor.py index e547675a0e..3e65265453 100644 --- a/tests/test_meta_tensor.py +++ b/tests/test_meta_tensor.py @@ -433,6 +433,7 @@ def test_str(self): t = MetaTensor([1.0], affine=torch.tensor(1), meta={"fname": "filename"}) self.assertEqual(str(t), "metatensor([1.])") self.assertEqual(t.__repr__(), "metatensor([1.])") + self.assertEqual("{:.2f}".format(t[0]), "1.00") def test_shape(self): s = MetaTensor([1]) From b2ea87ea6efc8da219bf7a6fb77730aee5d9937f Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 16 May 2023 15:04:59 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- tests/test_meta_tensor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_meta_tensor.py b/tests/test_meta_tensor.py index 3e65265453..739955ea67 100644 --- a/tests/test_meta_tensor.py +++ b/tests/test_meta_tensor.py @@ -433,7 +433,7 @@ def test_str(self): t = MetaTensor([1.0], affine=torch.tensor(1), meta={"fname": "filename"}) self.assertEqual(str(t), "metatensor([1.])") self.assertEqual(t.__repr__(), "metatensor([1.])") - self.assertEqual("{:.2f}".format(t[0]), "1.00") + self.assertEqual(f"{t[0]:.2f}", "1.00") def test_shape(self): s = MetaTensor([1])