5

Are repr and str identical on Pythons built-in numeric types (int, bool, float, and complex), or are there (esoteric?) situations where the two may yield different results?

Related questions on SO (such as this one) focus on how __repr__ and __str__ may be implemented differently, and return different values for strings, but I can't find anything on the actual implementation on numbers.

Community
  • 1
  • 1
gerrit
  • 24,025
  • 17
  • 97
  • 170
  • The question was closed as being a duplicate, but the linked post does not answer my question, which is specifically about the `__repr__` and `__str__` methods on `int`, `bool`, `float`, and `complex`. – gerrit Nov 20 '12 at 12:58

1 Answers1

3

Your primary source of information on this is http://hg.python.org/cpython/file/tip/Objects For example, in boolobject.c:

PyTypeObject PyBool_Type = {
    ...stuff...

    bool_repr,                                  /* tp_repr */

    ...stuff...

    bool_repr,                                  /* tp_str */

so yes, they're guaranteed to be the same.

For floats, float_repr is different from float_str and depends on sys.float_repr_style.

georg
  • 211,518
  • 52
  • 313
  • 390