-2

While debugging a python program I had to print the value of a huge dictionary on a log file. I copy-pasted the value and when I assigned it in the python 2 interpreter I got SyntaxError: invalid syntax. What? How was that possible? After a closer look I realised the dictionary in the file was something like this:

{'one': 1, 'two': 2, 'three': {...}}

The key three value was {...}, which caused the invalid syntax error.

Pasting this dictionary on a python 2 interpreter raises a Syntax Error exception. Pasting it on a python 3 interpreter the assigned value results to be {'one': 1, 'two': 2, 'three': {Ellipsis}}.

So, what does {...} mean in python 2 and why the syntax is invalid in python 2 even if the value is printed in the log file from a python 2 script?

lainatnavi
  • 1,453
  • 1
  • 14
  • 22
  • 3
    Perhaps the logger abbreviated the output…!? It then becomes an invalid literal. `...` in Python 3 happens to be a valid literal, but obviously probably not the original value. – deceze Nov 22 '19 at 11:23
  • 1
    It looks like you put the dictionary inside itself as one of its own values. – khelwood Nov 22 '19 at 11:25
  • 1
    as @deceze points out it is a standard way of leting you know that dictionaries can be nested, e.g. the value associated with a key can be another dictionary and so on (notation pbbly comes from infinite series as in 1+2+3 .....) – E.Serra Nov 22 '19 at 11:26
  • @khelwood yep, `d['three']` gives `d`. The dictionary was referencing itself. Thank you, the comments pointed in the right direction. – lainatnavi Nov 22 '19 at 11:30

1 Answers1

2

If you write a dictionary like this:

d = dict(one=1, two=2)
d['three'] = d
print(d)

you get the output

{'one': 1, 'two': 2, 'three': {...}}

(though order may vary on older versions of Python).

... in container repr are used to indicate that a container contains itself, so that the repr doesn't become infinitely recursive.

khelwood
  • 55,782
  • 14
  • 81
  • 108