What does this strange string in the format "{[[[]}" do?

I come across the code below in some code from a former employee.

the code is not called anywhere, but my question is, can it actually do something useful, as it is?

def xshow(x):
    print("{[[[[]}".format(x))
+4
source share
2 answers

This is a format string with an empty argument name and an element index (part between [and ]for the key [[[(these indices should not be integer). Value for this key.

Vocation:

xshow({'[[[': 1})

will print 1

+4
source

You can use an interactive interpreter to explore something like this experimentally.

>>> xshow(None)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    xshow(None)
  File "<pyshell#11>", line 1, in xshow
    def xshow(x): print("{[[[[]}".format(x))
TypeError: 'NoneType' object is not subscriptable

# So let us try something subscriptable.
>>> xshow([])
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    xshow([])
  File "<pyshell#11>", line 1, in xshow
    def xshow(x): print("{[[[[]}".format(x))
TypeError: list indices must be integers or slices, not str

# That did not work, try something else.
>>> xshow({})
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    xshow({})
  File "<pyshell#11>", line 1, in xshow
    def xshow(x): print("{[[[[]}".format(x))
KeyError: '[[['

# Aha! Try a dict with key '[[['.
>>> xshow({'[[[':1})
1

Now, perhaps read the document.

0
source

Source: https://habr.com/ru/post/1651710/


All Articles