TypeError: object cannot be interpreted as an index

Discussion in 'Python' started by tleeuwenburg, Apr 8, 2009.

  1. tleeuwenburg

    tleeuwenburg Guest

    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

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

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

    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
    import pydoc
    File "/usr/local/python-2.5.1/lib/python2.5/pydoc.py", line 56, in
    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?
    tleeuwenburg, Apr 8, 2009
    1. Advertisements

  2. tleeuwenburg

    Peter Otten Guest

    "interpreted" or "used"?

    If the former, 'foo' may be a list rather than a dict, and someClass a
    classic class:
    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>


    PS: Please cut and paste in the future.
    Peter Otten, Apr 8, 2009
    1. Advertisements

  3. It must have __hash__ and __cmp__ or __eq__ methods. Newstyle classes
    inherit these from object.
    Piet van Oostrum, Apr 8, 2009
  4. Awesome, thanks.

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

    TennesseeLeeuwenburg, Apr 8, 2009
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.