[Python-Dev] PEP 455: TransformDict (original) (raw)

Ethan Furman ethan at stoneleaf.us
Mon Oct 7 23:55:44 CEST 2013


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



More information about the Python-Dev mailing list