[ 
https://issues.apache.org/jira/browse/THRIFT-162?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=12640778#action_12640778
 ] 

Esteve Fernandez commented on THRIFT-162:
-----------------------------------------

bq. From the Python docs: """If a class defines mutable objects and implements 
a _cmp() or __eq() method, it should not implement __hash_(), since the 
dictionary implementation requires that a key's hash value is immutable (if the 
object's hash value changes, it will be in the wrong hash bucket)."""

Yes, I know, that's why I said that only immutable objects can have both 
__eq__() and __hash__()

bq. Thrift structures are inherently mutable, so they should not define 
_hash_(). Please use a map with simple types as keys if you are using Python.

No, using a map won't solve this problem. As I already said, dictionaries 
(maps) are mutable and thus, can't be used as set elements. I'll either use a 
tuple (i64, i64) or a tree-based set, such as ZODB's TreeSet 
(http://www.zope.org/Wikis/ZODB/guide/node6.html#SECTION000630000000000000000), 
it won't be O(1), though.

Anyway, would it be useful to add an immutable keyword to Thrift structures in 
the IDL? This would make structures immutable (overriding __setattr__ in 
Python, removing setters in Java, declaring attributes with attr_reader, but 
not attr_writer in Ruby, etc.) I'm sure there are more implications, for 
example, one would have to make struct members immutable as well, but would 
like to know your opinions.

> Thrift structures are unhashable, preventing them from being used as set 
> elements
> ---------------------------------------------------------------------------------
>
>                 Key: THRIFT-162
>                 URL: https://issues.apache.org/jira/browse/THRIFT-162
>             Project: Thrift
>          Issue Type: Bug
>          Components: Compiler (Python), Library (Python)
>            Reporter: Esteve Fernandez
>            Priority: Minor
>         Attachments: thrift_py_hash.patch
>
>
> Let Foo be a Thrift structure:
> struct Foo {
>  1: i32 bar
> }
> If you want to use it properly as a set element or a as a dictionary key, the 
> autoegenerated Python code will complain about not being hashable:
> >>> f1 = Foo()
> >>> f1.bar = 1
> >>> f2 = Foo()
> >>> f2.bar = 1
> >>> f1 == f2
> True
> >>> set([f1]) & set([f2])
> set([])
> >>> d = {}
> >>> d[f1] = 2
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> TypeError: unhashable instance
> Since Thrift structures already implement __eq__ and __ne__, they should 
> implement __hash__ as well. The attached patch tries to mimic the behaviour 
> of the Java compiler, including a HashCodeBuilder class written in Python.

-- 
This message is automatically generated by JIRA.
-
You can reply to this email to add a comment to the issue online.

Reply via email to