On 2019-12-11 7:40 a.m., Jonathan Fine wrote:
Consider these two examples:

>>> {0} == {0.0} == {False}
True
>>> hash(0) == hash(0.0) == hash(False)
True
>>> 0.0 in {False}
True

>>> class mystr(str): pass
>>> 'hi' in {mystr('hi')}
True

The original poster want a way to obtain the actual object that is in the set, rather than just a truth value. This can be done in O(n) time, by iterating through the set. However, better is possible.

Here's are examples, followed by implementaion.

>>> from hashhack import HashHack
>>> HashHack(2) in {2}
(<class 'int'>, 2)
False
>>> HashHack(2) in {2.0}
(<class 'float'>, 2.0)
False

Here's the implementation.
<BEGIN>
class HashHack:

    def __init__(self, obj):
        self.hash_obj = hash(obj)

    def __hash__(self):
        return self.hash_obj

    def __eq__(self, other):
        print((type(other), other))
        return False
<END>

So you could do

class Finder:
  def __init__(self, obj):
    self.obj = obj
  def __hash__(self):
    return self.obj.__hash__()
  def __eq__(self, other):
    res = self.obj == other
    if res:
      self.found_obj = other
    return res

finder = Finder(x)
if finder in foo:
  return finder.found_obj

?



Looking at this URL helped me
https://stackoverflow.com/questions/3588776/how-is-eq-handled-in-python-and-in-what-order

--
Jonathan

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/HU2HJ4LDMAYKZUHMLLAQARDWSLJKWCGO/
Code of Conduct: http://python.org/psf/codeofconduct/

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/HQAVPRCL6KWKMVFYHXMK5TRJQPIEAP2S/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to