views:

253

answers:

2

I want to define a class that supports __getitem__, but does not allow iteration. for example:

class b:
   def __getitem__(self, k):
      return k

cb = b()

for x in cb:
   print x

What could I add to the class b to force the "for x in cb:" to fail?

+2  A: 

From the answers to this question, we can see that __iter__ will be called before __getitem__ if it exists, so simple define b as:

class b:
   def __getitem__(self, k):
      return k

   def __iter__(self):
      raise Exception("This class is not iterable")

Then:

cb = b()
for x in cb: # this will throw an exception when __iter__ is called.
  print x
grieve
If there is a more pythonic answer than this I would gladly accept it.
grieve
have you class name properly capitalised, that'd be more pythonic
SilentGhost
+11  A: 

I think a slightly better solution would be to raise a TypeError rather than a plain exception (this is what normally happens with a non-iterable class:

class A(object):
    # show what happens with a non-iterable class with no __getitem__
    pass

class B(object):
    def __getitem__(self, k):
        return k
    def __iter__(self):
        raise TypeError('%r object is not iterable'
                        % self.__class__.__name__)

Testing:

>>> iter(A())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'A' object is not iterable
>>> iter(B())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "iter.py", line 9, in __iter__
    % self.__class__.__name__)
TypeError: 'B' object is not iterable
Rick Copeland
+1 for the proper use of new-style classes (as well as the overall goodness of the approach).
Alex Martelli