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 _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com