0

In Python 3, most of the time, the result of repr(repr(obj)) will be repr(obj) wrapped in single quotes. But when obj is a non-empty mapping proxy repr(repr(obj)) is wrapped in double quotes. Why?

This is a Windows 10 server running Python 3.7 on Wing IDE 101.

mappingproxy = type(object.__dict__)
#Single quotes for undefined mapping proxies
print(repr("mappingproxy({})"))

'mappingproxy({})'
#Double quotes for defined mapping proxies
print(repr(repr(object.__dict__)))
<<< "mappingproxy({...})"
#For custom empty mapping proxies...
print(repr(repr(mappingproxy({}))))
<<< 'mappingproxy({})'
#...single, at least for ones evaluating to False
#For mapping proxies evaluating to True...
print(repr(repr(mappingproxy({'a':1, 'b':2}))))
<<< "mappingproxy({'a': 1, 'b': 2})"
#...double
#For non-existant non-empty ones...
print(repr("mappingproxy({'a':1})"))
<<< "mappingproxy({'a':1})"
#...double
#Why is that?

The resultants from the print statements start with "<<<". By the way, I think I can derive an empty mapping proxy representation's representation is wrapped in single quotes.

Massifox
  • 4,369
  • 11
  • 31
Elijah
  • 206
  • 1
  • 8

1 Answers1

3

Python's string repr defaults to single quotes, but will switch to double quotes if it contains any single quotes so it doesn't have to escape them with a backslash. (Otherwise the first internal single quote would end the string.)

But if it contains both double and single quotes, it will use the default single quotes and escape them with a backslash internally.

Note that your mappingproxy repr examples contain single-quoted strings, except for the empty one. That's internal single quotes.

gilch
  • 10,813
  • 1
  • 23
  • 28