[Python-ideas] [Python-Dev] One obvious way to do interning [Was: Retrieve anarbitrary element from a set without removing it]

Alexander Belopolsky alexander.belopolsky at gmail.com
Mon Oct 26 19:10:24 CET 2009

On Mon, Oct 26, 2009 at 1:40 PM, Raymond Hettinger <python at rcn.com> wrote:
> FWIW, here is a recipe that can retrieve canonical objects
> from any container, letting look-up a preferred representative
> of an equivalence class: http://code.activestate.com/recipes/499299/

This is very clever, but I am not sure whether existence of this
recipe is an argument for or against adding functionality to sets.  On
one hand, it does provide a solution for O(1) retrieval of an
equivalent item, but it is far from obvious.  Overloading == with a
mutating method is borderline black magic!  Furthermore, it is not
clear how to generalize this recipe to efficiently insert the value
that is not found in the set.  Finally, overloading both __eq__ and
__getattr__  with python methods is likely to negate any performance
gains of an O(1) over O(n) algorithm for typical sets of built-in

The use case in this recipe is not addressed by the "return value from
set.add(..)" proposal.  One would need a different "get-like" method
for that.

More information about the Python-ideas mailing list