Can I extend syntax in python for dict comprehensions for other dicts, like the OrderedDict in collections
module or my own types which inherit from dict
?
Just rebinding the dict
name obviously doesn't work, the {key: value}
comprehension syntax still gives you a plain old dict for comprehensions and literals.
>>> from collections import OrderedDict
>>> olddict, dict = dict, OrderedDict
>>> {i: i*i for i in range(3)}.__class__
<type 'dict'>
So, if it's possible how would I go about doing that? It's OK if it only works in CPython. For syntax I guess I would try it with a O{k: v}
prefix like we have on the r'various' u'string' b'objects'
.
note: Of course we can use a generator expression instead, but I'm more interested seeing how hackable python is in terms of the grammar.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…