TypeError: object cannot be interpreted as an index

T

tleeuwenburg

It started with this error message... "TypeError: object cannot be
used as an index"

foo = {}
someObject = someClass()
foo[someObject] = "hello"

Obviously, there are some known reasons why objects may not be
indexes, such as if they are not hashable (as in the case of lists).
However, I'm not getting that error message. I tested this out with
some minimal Python code, and the error did not occur. It only occurs
in my big codebase, not in a neat minimal example using a very small
class.

The type of this object is listed as 'instance'. My interpreter is
2.5.1

So I tried looking for more information inside types, and found
types.InstanceType.

Running help(types.InstanceType) gave me:hello
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python-2.5.1/lib/python2.5/site.py", line 345, in
__call__
import pydoc
File "/usr/local/python-2.5.1/lib/python2.5/pydoc.py", line 56, in
<module>
from repr import Repr
ImportError: cannot import name Repr

There is a good chance that this object is build from C code,
instantiated through Swig. I'll have to do a bit more work to trace
back where the problem object is being created...

What, exactly, needs to be in place for an object to be a valid
dictionary key?
 
P

Peter Otten

It started with this error message... "TypeError: object cannot be
used as an index"

foo = {}
someObject = someClass()
foo[someObject] = "hello"

"interpreted" or "used"?

If the former, 'foo' may be a list rather than a dict, and someClass a
classic class:
class A: pass ....
{A(): 42}
{ said:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object cannot be interpreted as an index

To find out the actual the actual type of a classic class look into the
__class__ attribute:
<class __main__.A at 0x2ac2a6d1e830>

Peter

PS: Please cut and paste in the future.
 
T

TennesseeLeeuwenburg

It must have __hash__ and __cmp__ or __eq__ methods. Newstyle classes
inherit these from object.

Awesome, thanks.

I wonder if this is an 'old-style' class, something I've never used
myself... I'll have to do some research.

-T
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top