[Python-Dev] Getting values stored inside sets
python at rcn.com
Sat Apr 4 04:37:38 CEST 2009
> It doesn't quite work the way RDM desribed it - he missed a step.
Thanks for the clarification. We ought to write-out the process somewhere in a FAQ.
It may also be instructive to step through the recipe that answers the OP's
original request, http://code.activestate.com/recipes/499299/
The call "get_equivalent(set([1, 2, 3]), 2.0)" wraps the 2.0 in a new
object t and calls "t in set([1,2,3])". The set.__contains__ method
hashes t using t.__hash__(self) and checks for an exact match
using t.__eq__(other). Both calls delegate to float objects but the
latter also records the "other" that resulted in a successful equality
test (i.e. 2 is the member of the set that matched the 2.0). The
get_equivalent call then returns the matching value, 2.0.
As far as I can tell, the technique is completely generic and lets
you reach inside any function or container to retrieve the "other"
value that is equivalent to "self".
More information about the Python-Dev