Hi Nick,
On 23/03/16 03:17, Nick Eubank wrote:
In other words:
In[1]:
d = {True: 'a', False: 'b'}
d[0] = 'z'
d[False]
Out[1]:
'z'
[snip]
Relatedly, if this is a desired behavior, any advice one how best to work
with dictionaries when one wants "True" and 1 to be different?
See the accepted answer here:
http://stackoverflow.com/questions/3387691/python-how-to-perfectly-override-a-dict
If you use the class that the answer suggests and then define a subclass:
"""
class MyTransformedDict(TransformedDict):
__reverse_transform__ = {
"__True__": True,
"__False__": False,
}
def __keytransform__(self, key):
if key is True: return "__True__"
if key is False: return "__False__"
return key
def __iter__(self):
return (self.__reverse_transform__.get(k, k)
for k in super(MyTransformedDict, self).__iter__())
def __contains__(self, key):
return self.__keytransform__(key) in self.store
"""
Then as long as you wrap such dictionaries in a "MyTransformedDict()"
(choose a better name!), it will do what:
"""
d = MyTransformedDict({True: 'a', False: 'b'})
d[0] = 'z'
d[False]
"""
Note that in your case, I've added the reverse transformation from the
magic tokens so that iter(), .iterkeys() and .iteritems()) return the
original True and False keys.
I've also added __contains__, but that should be in the
"TransformedDict()" superclass (I didn't want to reproduce the whole of
that here).
There are things missing (such as a dict-like repr()) or not done
optimally there, but it might be a good start. This works on Python 2 and 3.
E.
--
https://mail.python.org/mailman/listinfo/python-list