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

Steven D'Aprano steve at pearwood.info
Tue Oct 8 02:23:36 CEST 2013


On Mon, Oct 07, 2013 at 02:55:44PM -0700, Ethan Furman wrote:

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.

I fear you are right, particularly for subclasses. dict itself would only have the cost of testing whether the instance is an actual dict, which I presume is cheap. Still, given enough "cheap" tests, the overall performance hit could be significant.

[...]

So something more like:

transform = getattr(self, 'transform', None) if transform is not None: key = transform(key) ...

One minor point, being a dunder method, it should be grabbed from the class itself, not the instance:

getattr(type(self), ...)

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:

Yes.

-- Steven



More information about the Python-Dev mailing list