Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[eager Tensor] Update type hint for Tensor.__format__ and add unittest #68694

Merged
merged 1 commit into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion python/paddle/base/dygraph/tensor_patch_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -913,7 +913,7 @@ def __str__(self: Tensor) -> str:

return tensor_to_string(self)

def __format__(self, format_spec):
def __format__(self, format_spec: str) -> str:
if self.ndim == 0:
return self.item().__format__(format_spec)

Expand Down
12 changes: 12 additions & 0 deletions test/legacy_test/test_eager_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1301,6 +1301,12 @@ def test_tensor__format__(self):
numpy_scalar.__format__(format_spec),
)

format_spec = "{:.{}f}"
self.assertEqual(
format_spec.format(paddle_scalar, width),
format_spec.format(numpy_scalar, width),
)

# test for integer scalar
for width in range(0, 5):
paddle_scalar = paddle.uniform([], min=-100, max=100).to("int64")
Expand All @@ -1321,6 +1327,12 @@ def test_tensor__format__(self):
numpy_scalar.__format__(format_spec),
)

format_spec = "{:{}d}"
self.assertEqual(
format_spec.format(paddle_scalar, width),
format_spec.format(numpy_scalar, width),
)

# test for tensor that ndim > 0, expected to raise TypeError
paddle_scalar = paddle.uniform([1], min=-100, max=100)
self.assertRaises(TypeError, paddle_scalar.__format__, ".3f")
Expand Down