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

不羁岁月 提交于 2020-01-01 04:52:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/32408387/what-does-mean-in-the-print-output-of-a-python-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!