Search code examples
pythonellipsis

What does `{...}` mean in the print output of a python variable?


Someone posted this interesting formulation, and I tried it out in a Python 3 console:

>>> (a, b) = a[b] = {}, 5
>>> a
{5: ({...}, 5)}

While there is a lot to unpack here, what I don't understand (and the semantics of interesting character formulations seems particularly hard to search for) is what the {...} means in this context? Changing the above a bit:

>>> (a, b) = a[b] = {'x':1}, 5
>>> a
{5: ({...}, 5), 'x': 1}

It is this second output that really baffles me: I would have expected the {...} to have been altered, but my nearest guess is that the , 5 implies a tuple where the first element is somehow undefined? And that is what the {...} means? If so, this is a new category of type for me in Python, and I'd like to have a name for it so I can learn more.


Solution

  • It's an indication that the dict recurses, i.e. contains itself. A much simpler example:

    >>> a = []
    >>> a.append(a)
    >>> a
    [[...]]
    

    This is a list whose only element is itself. Obviously the repr can't be printed literally, or it would be infinitely long; instead, the builtin types notice when this has happened and use ... to indicate self-containment.

    So it's not a special type of value, just the normal English use of "..." to mean "something was omitted here", plus braces to indicate the omitted part is a dict. You may also see it with brackets for a list, as shown above, or occasionally with parentheses for a tuple:

    >>> b = [],
    >>> b[0].append(b)
    >>> b
    ([(...)],)
    

    Python 3 provides some tools so you can do this with your own objects, in the form of reprlib.