I have encountered some unexpected behavior with dicts in python.
It might be because of annotations, but i'm not sure.
Please see the snippet below:
>>> d = {} # lets create a dictionary and add something to it.
>>> d['a'] = 'a'
>>> d
{'a': 'a'}
>>> d['a']
'a'
>>> # ok all well and good, we know how dicts work, right ?
...
>>> d['z']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
>>>
>>> # yea no key 'z' was inserted. Lets add a colon (:) in the mix
...
>>> d['z']: d
>>>
>>> # nothing happend! weird...
...
>>> d['z']: d['z']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
>>> # again 'z' was not added to the dict, but what did the colon ???
...
>>> d['z']: d['z']: None
File "<stdin>", line 1
d['z']: d['z']: None
^
SyntaxError: invalid syntax
>>>
>>> # NOW the colon gives an SyntaxError !?!
>>> # Lets try to directly use a colon after the dict
...
>>> {'a': 'a'}: ()
File "<stdin>", line 1
SyntaxError: illegal target for annotation
>>>
>>> # so annotation huh ?
>>> # is it possible to annotate on the fly ?
...
>>> def func(x): return x
...
>>> d = {'f': func} # overwrite previous dict
>>> d['f']: callable
>>> d['f'].__annotations__
{}
>>> # doesn't look like it was taken over
... # lets check if d['f'] returns the callable function: func
...
>>>
>>> def func(x: str) -> callable: return x
...
>>> d = {'f': func}
>>> d['f'].__annotations__ # lets check for annotations !!
{'x': <class 'str'>, 'return': <built-in function callable>}
>>>
>>> # I'm confused, what does the colon do?
...
>>>
I'm curious why the dict syntax doesn't always react on the given colon (:).
Also the annotations doesn't seem to be the case (or my conclusion is wrong)
So dear readers, what is the purpose of the colon used in the context described above?