How well-documented is repr() for builtin types?

Hi all,
Recently I wish to implement something that is similar to repr(a_string) but always uses single quotes.
In this StackOverflow post a few people suggested using the following:

def repr_single(s: str) -> str:
    return "'" + repr('"' + s)[2:]

This does work (at least on CPython) but relies on the fact that repr() of a string always uses single quotes if a double quote appears in the string.

My question is that: is this a behavior that we could rely on? Or is this just an implementation detail?

It seems that the documentation does not provide information on how repr() works for specific types. Maybe it should clarify a bit on that?

The only documented behavior of repr() is that it should “attempt” to return a string that can be evaluated back to an equivalence of the original object, or a descriptive string enclosed in angle brackets, so there is no guarantee for the output of repr() for any object as long as it continues to satisfy that description.

That said, given that there is so much code that relies on the existing output of repr(), mainly in the expected output of many unit tests, it is extremely unlikely that the logics of __repr__ of an object type as fundamental as a string is ever going to change. In other words, theoretically no, but practically yes, you can rely on the existing quoting behavior, even though it is apparently an implementation detail.

1 Like