Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to "perfectly" override a dict?
    primarykey
    data
    text
    <p>How can I make as "perfect" a subclass of <em>dict</em> as possible? The end goal is to have a simple <em>dict</em> in which the keys are lowercase.</p> <p>It would seem that there should be some tiny set of primitives I can override to make this work, but according to all my research and attempts it seem like this isn't the case:</p> <ul> <li><p>If I <a href="https://stackoverflow.com/a/2390889">override <code>__getitem__</code>/<code>__setitem__</code></a>, then <code>get</code>/<code>set</code> don't work. How can I make them work? Surely I don't need to implement them individually?</p></li> <li><p>Am I preventing pickling from working, and do I need to implement <code>__setstate__</code> etc?</p></li> <li><p>Do I <a href="https://stackoverflow.com/a/2390997">need <code>repr</code>, <code>update</code> and <code>__init__</code></a>?</p></li> <li><p>Should I just <a href="https://stackoverflow.com/a/1622872">use mutablemapping</a> (it seems one shouldn't use <code>UserDict</code> or <code>DictMixin</code>)? If so, how? The docs aren't exactly enlightening.</p></li> </ul> <p>Here is my first go at it, <code>get()</code> doesn't work and no doubt there are many other minor problems:</p> <pre><code>class arbitrary_dict(dict): """A dictionary that applies an arbitrary key-altering function before accessing the keys.""" def __keytransform__(self, key): return key # Overridden methods. List from # https://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict def __init__(self, *args, **kwargs): self.update(*args, **kwargs) # Note: I'm using dict directly, since super(dict, self) doesn't work. # I'm not sure why, perhaps dict is not a new-style class. def __getitem__(self, key): return dict.__getitem__(self, self.__keytransform__(key)) def __setitem__(self, key, value): return dict.__setitem__(self, self.__keytransform__(key), value) def __delitem__(self, key): return dict.__delitem__(self, self.__keytransform__(key)) def __contains__(self, key): return dict.__contains__(self, self.__keytransform__(key)) class lcdict(arbitrary_dict): def __keytransform__(self, key): return str(key).lower() </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload