TypeError: unhashable type: 'list'

Chris Angelico rosuav at gmail.com
Mon Dec 22 18:23:10 EST 2014


On Tue, Dec 23, 2014 at 10:10 AM,  <ronald.kevin.burton at gmail.com> wrote:
> My problem is that I am not sure what the problem is. I can check the type of 'self' which is an object and the string 'Furnace Whistle' is obviously not a list. The static function 'MeasureMaker.Code2Measure' is a simple factory:
>
> class MeasureMaker:
>
>     def Code2Measure(measure_code, core):
>         try:
>             return {
> ...
>                 'Furnace Whistle': FurnaceWhistle(core)
>             }[measure_code]
>         except KeyError as error:
>             return None
>     Code2Measure = staticmethod(Code2Measure)
>
> What is the 'list' that is in the exception? Or how do I find out?

Does your MeasureMaker class define a __hash__ method? If so, what's
its definition? Possibly that's using some attributes and one of those
is a list.

Incidentally, is this actually how your code is laid out? What Python
versions do you need to support? Unless this code has to run on 2.3 or
earlier, you can replace the staticmethod call with a decorator:

@staticmethod
def Code2Measure(measure_code, core):
    ... code as above, but without the reassignment at the end ...

And if you were running this on 2.3, the "except KeyError as error"
syntax would be invalid anyway, so this should be a safe change :)

(You don't even need that try/except block, actually. If you use the
dict's .get() method, it'll return None instead of raising KeyError,
which is exactly what you need here.)

ChrisA



More information about the Python-list mailing list