Hello, all.
Is it possible to get an object out of a set() given another object that has the same hash code and equality (__hash__() and __eq__() return the same)?
You can't do this with Java Sets either and I've needed it on multiple occasions. Doesn't it seem like it would be useful? Consider:
class Person: def __init__(self, id, name): self.id = id self.name = name
def __hash__(self): return self.id
def __eq__(self, other): return self.id == other.id
people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) ... p = people.get_equivalent(2) #method doesn't exist as far as I know print p.name #prints Sue
I'm not sure if the above code compiles but I hope you get the idea. Is it possible? Much Thanks. - Cruxic
Cruxic's gravatar image asked Mar 7 2008 at 19:13 in Python by Cruxic

7 Answers

Yes, but it requires an indirect approach. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299
Raymond Hettinger's gravatar image answered Mar 7 2008 at 19:20 by Raymond Hettinger
def get_equivalent(test, container):
for p in container:
if p == test:
return p
Alan Isaac
#example (note change in __eq__ to match your case; fix if nec)
class Person:
def __init__(self, id, name):
self.id = id
self.name = name
def __hash__(self):
return self.id
def __eq__(self, other):
return self.id == other
people = set( [Person(1, 'Joe'), Person(2, 'Sue')] )
Alan Isaac's gravatar image answered Mar 8 2008 at 15:32 by Alan Isaac
That's a clever work around. Thanks, Raymond. Clearly you had a need for this. Do you feel it's a common need that should be submitted as a Python feature request? To me it seems like such a simple thing that would increase the general utility of the set class. I suppose I could start another thread like "feature request: New method for set - get_equivalent".
Cruxic's gravatar image answered Mar 8 2008 at 16:25 by Cruxic
That works fine for small data sets but my goal is to avoid a linear search, instead leveraging the O(1) lookup time for a hash based set.
Cruxic's gravatar image answered Mar 8 2008 at 16:28 by Cruxic
Glad you liked the recipe. :-) FWIW, it is not specific to sets. The recipe works with any container including dictionaries and lists. The approach is easily extended to any situation with equality testing. For example, it can be used with list.remove(x) to find the identity of the removed object.
Long ago, I rejected adding get_equivalent() to the set API. The existing API has a near zero learning curve and it would be nice to keep it that way.
For most use cases, the obvious, explicit approach is better. Just make a dictionary where the value is the canonical representative of the equivalence class:
>>> d = {1:1, 2:2, 3:3} >>> d[2.0] 2
The intern() builtin uses this approach:
interned = {} def intern(s): if s in interned: return interned[s] interned[s] = s return s
Raymond Hettinger's gravatar image answered Mar 8 2008 at 19:15 by Raymond Hettinger
If you've seen it before, and have the old one, return the old one. Do I have this straight?
castironpigmail.com's gravatar image answered Mar 8 2008 at 20:27 by castironpigmail.com
Raymond Hettinger's gravatar image answered Mar 9 2008 at 17:36 by Raymond Hettinger

Related Discussions

  • Embedded Python : Can't Get Or Set A Variable in Python

  • Hello, I'm trying to write a program to send python statements to a python server via tcp and then get back results via a tcp connection. It nearly works ... but I'm totally lost with the embedded dictionary (I'm quite new to python). The first part of the server start the python interpreter via Py_Initialize() and then waits for python statements. To send command, I get some strings and evaluate...

  • [implement Python Code In C] Can't Set Attributes Of in Python

  • built-in/extension type Hello! I tried to rewrite my python module in C. My module is successfully imported but i can't assing anything to class attributes (tp_setattr in PyTypeObject for class FlowReportRow filled up by pointer to FlowReportRowObjectSetAttr function and printf in ones show the function does not called) Where I was mistaken? (you may see the module sources at http://astral.ua...

  • How To Get Or Set The Text Of A Textfield? in Python

  • Hi Everyone, So I've built a UI with Glade and have loaded it using the standard Python code. In my UI, I have a textfield called txtUsername. How do I get and set the text in this field from my Python code? Thanks! Anthony Anthony Papillion Advanced Data Concepts Get real about your software/web development and IT Services Phone: (918) 919-4624 Does your business need to reduce its phone bill...

  • How To Get A Set Of Keys With Largest Values? in Python

  • Hi all, I have a dictionary with n elements, and I want to get the m(m...

  • Creating A Windows Installer For Python + A Set Of Dependencies in Python

  • Hi all, I need to create an installer for Windows which should be able to install a specific version of the Python interpreter (2.7) plus a set a dependencies such as ipython, numpy, pandas, etc. Basically this is the same thing Active State did for their Active Python distribution: a single bundle including interpreter + deps. Not being a Windows user I'm not sure where to start with this except ...

  • Get/set in Python

  • hi, coming from java, i use to do a lot of get set method and make all the variable as private. class Toto: def getA(self): return self._a def setA(self,v): self._a=v ... Shall i do like that in python ? bye William Dod? - Informaticien Ind?pendant http://www.flibuste.net...

  • Get/set in Python

  • In-Reply-Message-ID: [William Dode] As Gerhard pointed out, pre-2.2 you had to resort to __getattr__ and __setattr__ for this kind of bondage. Cheers, // mark...

  • Get/set in Python

  • ...

  • Get/set in Python

  • In-Reply-Message-ID: yes you do. But realize this is not C++ or Java. There are no private members. Class Sneaky: def __init__(self): self.a = 0 self.b = 0 def getA(self): return self.a def setA(self, val): self.a = val # normally would have checks foo = Sneaky() foo.a = 'Sean was here!' is 100% valid. Will you ever do it, likely not. But the key is, in python data...

  • Get/set in Python

  • In-Reply-Message-ID: [William Dode] Field descriptors are new with Python 2.2 and require the new-style classes. To create a new-style class, simple subclass from object (as shown below). Then, you can create properties... class Person(object): def __init__(self): self._first_name = '' def get_first_name(self): return self._first_name def set_first_name(self, value): self....

  • Validate XML Against A Set Of XSD Files, With Python in Python

  • Do you know an open source lib that can do $subject? Thanks, Laszlo...

  • To Write Set Of Values To A File From Python in Python

  • hi everybody i want to write a set of values to a file from python. For ex:: the fields name will "comp name", "ip addr", "mac addr" etc. And below all these fields i ll have the values for these fields. it should look some what like this. comp name ipaddr macaddr jdasfhjashd 234.347.23.12 334.12.354.43.232 dfdsfusdaufisa ...

  • Support For New Items In Set Type in Python

  • I have a bit of a specialized request. I'm reading a table of strings (specifically fixed length 36 char uuids generated via uuid.uuid4() in the standard library) from a file and creating a set out of it. Then my program is free to make whatever modifications to this set. When I go back to save this set, I'd like to be able to only save the new items. Currently I am creating a copy of the set as...

  • Can't Set Attribute?! in Python

  • Hi there, i'm new to Python, and i don't understand why following exception occurs in this code: class NETRPCGateway(RPCGateway): """NETRPC Implementation. """ def __init__(self, host, port): self.host = host self.port = port super(NETRPCGateway, self).__init__(self.host, self.port, 'socket') def listdb(self): sock = tiny_socket.mysocket() ...

  • Python, Equivalent Of Set Command in Python

  • In unix shell script I can do the following to get the status and values returned by a unix command OUTPUT=`some unix command` STATUS=$? if [ $STATUS -ne 0 ] then exit 1 else set $OUTPUT VAL1=$1 VAL2=$2 VAL3=$3 fi How can I achieve the same in python? I know how to run it via the os.system command and return the status, but how do I return the values too?...

  • Can't Set Attributes Of Built-in/extension Type in Python

  • I'm working on a simple extension. Following the classic 'noddy' example. In [15]: cmplx_int32 Out[15]: Now I want to add an attribute to this type. More precisely, I want a class attribute. cmplx_int32.test = 0 TypeError Traceback (most recent call last) /home/nbecker/numpy/ in () TypeError: can't set attributes of built-in/extension type 'numpy.cmplx_int32...

  • Why Can't I Set Sys.ps1 To A Unicode String? in Python

  • More precisely, why does sys.ps1 not appear if I set it to a unicode string? This problem is hard for me to describe here because my newsreader is not properly unicode enabled, but here's the gist of it: Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. First, let's make sure our...

  • Use Python To Split A Video File Into A Set Of Parts in Python

  • I use the following python code to split a FLV video file into a set of parts ,when finished ,only the first part video can be played ,the other parts are corrupted.I wonder why and Is there some correct ways to split video files import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy print(chunksize , type(chunksize...

  • Set Parity Of A String in Python

  • Is there a module that sets the parity of a string? I have an application that needs to communicate with a host using even parity So what I need is before sending the message, convert it from space to even parity. And when I get the response I need to convert that from even to space parity. The perl module String::Parity is what I have used to do this under perl. Chris...

  • Python COM Servers And Excel/VBA: Set/Get Multidimensional Attributes... in Python

  • Does anyone know how to set/get attributes in Python COM objects that are multidimensional arrays (list of lists)? Here is a short extract of code that I have been playing around with. Yours, Carl Python COM Server: COMEXPOSE = 1 class RandomStockPrice: if COMEXPOSE == 1: _public_methods_ = [ '__init__', 'StockPrice' ] _public_attrs_ = [ 'l_S0', 'l_Sigma'] ...