Python NoneType cannot be called when indexing in dict

I came across this strange error that I cannot explain.

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import UserDict >>> a = UserDict.UserDict() >>> b = {} >>> b[a] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'NoneType' object is not callable 

I understand that this must be a mistake. I do not understand why it says 'NoneType' object is not callable . As far as I can tell, I am not calling anything on the line that is causing the error.

I expected the error to be something like this:

 >>> b[b] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' 

Can someone explain this to me before I go crazy?

+4
source share
2 answers

Looking at the UserDict implementation suggested by @Wooble, I see the following:

 __hash__ = None # Avoid Py3k warning 

Therefore, it is true that the problem is related to the implementation of UserDict .

If you really need to use your own type of dictionary, I suggest subclassing directly from dict and implementing your own __hash__ method or, conversely, converting the dictionary into a hashable object using, for example, frozenset :

 >>> a = UserDict.UserDict() >>> b[frozenset(a.items())] 
+4
source

UserDict.UserDict().__hash__ None . Combine with the Wooble comment and you'll see why this is happening.

0
source

Source: https://habr.com/ru/post/1393949/


All Articles