2

How do I make item access ie. __getitem__ available on a class object in Python 2.x?

I've tried:

class B:
    @classmethod
    def __getitem__(cls, key):
        raise IndexError

test:

B[0]
# TypeError: 'classobj' object has no attribute '__getitem__'
print B.__dict__
# { ... '__getitem__': <classmethod object at 0x024F5E70>}

How do I make __getitem__ work on the class itself?

4
  • 1
    You'll have to put special methods on the metaclass instead. Commented Apr 29, 2014 at 16:13
  • @MartijnPieters I've failed to find that question, thanks Martin. Although my B is an old-style class, but the important thing here is the special methods I see. Commented Apr 29, 2014 at 16:15
  • old-style classes don't support @classmethod decorators (or any other descriptors) either. Commented Apr 29, 2014 at 16:25
  • @MartijnPieters I made a mistake with that then. But I wonder, what happens with my decorator here? Whether my class is still old-style and whether the decorator gets ignored. Commented Apr 29, 2014 at 16:27

1 Answer 1

1

As pointed out by Martijn Pieters, one would want to define a metaclass for the special methods lookup here.

If you can use new-style class (or don't know what's that):

class Meta_B(type):
    def __getitem__(self, key):
        raise IndexError
#

class B(object):
    __metaclass__ = Meta_B
#

test

B[0]
# IndexError, as expected
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.