List objects are un-hashable

Ant antroy at gmail.com
Fri Apr 27 04:15:58 EDT 2007


> for line in inp:
>     lines +=1
>     # a list of words
>     tempwords = line.split(None)
>     if keyword.iskeyword(tempwords):
>         print tempwords

You are trying here to ask if a list of words (tempwords) is a
keyword. The error is due to the implementation of the iskeyword
function which converts the keyword list into a frozenset (in which
elements must be hashable) for, I presume, performance reasons:

>>> f_set = frozenset((1,2,3,4))
>>> ["test"] in f_set
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable

What you want is something like:

 for line in inp:
     lines +=1
     # a list of words
     tempwords = line.split()
     for k in tempwords:
         if keyword.iskeyword(k):
            print tempwords

Which iterates over each word in your tempwords list in turn. Note
though the following:

>>> if(True):print"Hey!"
...
Hey!
>>> s = 'if(True):print"Hey!"'
>>> s.split()
['if(True):print"Hey!"']

Which may be a problem for you if you are trying to parse badly spaced
python source files!




More information about the Python-list mailing list