Python __iter__ and for loops

As I understand it, I can use the loop construct forfor an object using a method __iter__that returns an iterator. I have an object for which I am implementing the following method __getattribute__:

def __getattribute__(self,name):
    if name in ["read","readlines","readline","seek","__iter__","closed","fileno","flush","mode","tell","truncate","write","writelines","xreadlines"]:
        return getattr(self.file,name)
    return object.__getattribute__(self,name)

I have an object of this class a, for which the following happens:

>>> hasattr(a,"__iter__")
True
>>> for l in a: print l
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'TmpFile' object is not iterable
>>> for l in a.file: print l
...
>>>

So python sees that it ahas a method __iter__, but does not think it is iterable. What have I done wrong? This is with python 2.6.4.

+3
source share
2 answers

There are subtle implementation details in your path: __iter__not really an instance method, but a class method. That is, it obj.__class__.__iter__(obj)is called, not obj.__iter__().

, Python . , , .

__getattribute__ class, . __metamethods__; .

+12

. . __getattribute__, :

, .

, __iter__, :

def __iter__(self):
    return self.file.__iter__()
+4

All Articles