On 10/07/2013 02:24 PM, Steven D'Aprano wrote:
On Fri, Oct 04, 2013 at 11:06:15PM +0200, Victor Stinner wrote:
if type(self) is not dict: # This only applies to subclasses, not dict itself. try: transform = type(self).__transform__ except AttributeError: pass else: key = transform(key) # now use the key as usual
Am I barking up the wrong tree? Would this slow down dict access too much?
Considering that __transform__ would usually not exist, and triggered exceptions are costly, I think it would. From the docs[1]: (10) If a subclass of dict defines a method __missing__, if the key k is not present, the a[k] operation calls that method with the key k as argument. The a[k] operation then returns or raises whatever is returned or raised by the __missing__(k) call if the key is not present. No other operations or methods invoke __missing__(). If __missing__ is not defined, KeyError is raised. __missing__ must be a method; it cannot be an instance variable. For an example, see collections.defaultdict. New in version 2.5. So something more like: transform = getattr(self, '__transform__', None) if transform is not None: key = transform(key) ... A key difference (pun unavoidable ;) between __missing__ and __transform__ is that __missing__ is only called when a key is not found, while __transform__ needs to be called /every/ time a key is looked up: d[k] d.get(k) d.has_key(k) d.fromkeys(...) d.setdefault(...) k in d -- ~Ethan~