Search code examples
pythonmagic-methodspython-datamodelfirst-class

How to make Python 2's __getitem__ work on a class?


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?


Solution

  • 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