Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str object in Python 2.7 doesn't have __iter__, yet it act like iterable. Why?

I was checking out str objects in Python, and I realized that str object in Python 2.7 doesn't have either __iter__() method nor next() method, while in Python 3.0 str objects have __iter__() method, and thus they are iterable. However, I can still use str objects as if they are iterable's in Python 2.7. For example, I can use them in for loops. How does this work?

like image 585
yasar Avatar asked May 09 '12 01:05

yasar


1 Answers

Simple answer: because iter(s) returns an iterable object.

Longer answer: iter() looks for an __iter__() method, but if it doesn't find one it tries to construct and iterator itself. Any object that supports __getitem__() with integer indices starting at 0 can be used to create a simple iterator. __getitem__() is the function behind list/string indexing operations, eg s[0].

>>> "abc".__iter__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__iter__'
>>> iter("abc")
<iterator object at 0x1004ad790>
>>> iter("abc").next()
'a'

See here for details.

like image 172
Eric W. Avatar answered Oct 30 '22 22:10

Eric W.