Why is there no instancemethod builtin?
Raymond Hettinger
python at rcn.com
Mon Jun 20 04:26:23 EDT 2005
[George Sakkis]
> The fact that strings don't have __iter__ is an implementation
> detail. I can't think of any reason other than historic and perhaps
> backwards compatibility for this;
> iterables should IMHO by definition be exactly
> the objects with __iter__).
There would be no benefit other than satisfying that particular world
view. It is a feature that all sequences are automatically iterable
without having to write a custom __iter__ method. That makes life a
bit easier for writers of sequence-like classes.
[Michele Simionato]
> I think strings do not have __iter__ on purpose, exactly to
> distinguish them from other iterables, since sometimes it is nice
> to consider them atomic, but I am not sure of this. You should
> ask the developers.
That is not correct. Since any sequence is automatically iterable
(because of the presence of __getitem__), the inclusion of a separate
__iter__ method is purely optional. The option to include a custom
__iter__ method has been exercised only when it has offered some
performance benefit. IOW, the inclusion of __iter__ for a sequence is
an arbitrary implementation detail -- there is no other significance.
> Anyway, the right definition of iterable is
> (as I was told) "an object X such that iter(X) does not throw an
> exception". Objects following the __getitem__ protocol
>- such as strings -are iterables even if they do not have
>an __iter__ method.
An object is iterable if and only if it provides either __iter__ or
__getitem__.
Raymond
More information about the Python-list
mailing list