Skip to content

Commit dd308b0

Browse files
committed
use redefined __repr__ method for integer subclass if it exists
1 parent b667e01 commit dd308b0

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

Lib/pprint.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -529,7 +529,7 @@ def _safe_repr(self, object, context, maxlevels, level):
529529

530530
r = getattr(typ, "__repr__", None)
531531

532-
if issubclass(typ, int):
532+
if issubclass(typ, int) and r is int.__repr__:
533533
if self._underscore_numbers:
534534
return builtins.format(object, "_d"), True, False
535535
else:

Lib/test/test_pprint.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,14 @@ def test_integer(self):
327327
self.assertEqual(pprint.pformat(1234567), '1_234_567')
328328
self.assertEqual(pprint.pformat(1234567, underscore_numbers=False), '1234567')
329329

330+
class Temperature(int):
331+
def __new__(cls, celsius_degrees):
332+
return super().__new__(Temperature, celsius_degrees)
333+
def __repr__(self):
334+
kelvin_degrees = self + 273.15
335+
return f"{kelvin_degrees}°K"
336+
self.assertEqual(pprint.pformat(Temperature(1000)), '1273.15°K')
337+
330338
def test_sorted_dict(self):
331339
# Starting in Python 2.5, pprint sorts dict displays by key regardless
332340
# of how small the dictionary may be.

0 commit comments

Comments
 (0)