[Python-3000] Builtin iterator type
Nick Coghlan
ncoghlan at gmail.com
Wed Nov 15 11:34:44 CET 2006
George Sakkis wrote:
> Fredrik Lundh <fredrik at pythonware.com> wrote:
>
>> George Sakkis wrote:
>>
>>> 1) why having a "generic operation" len() that ends up looking for an
>>> ugly special *method* called __len__() makes sense, while calling
>>> directly a method len() doesn't
>> for the very reason Mike explained: keeping implementation interfaces
>> separate from public interfaces has allowed Python to avoid a certain
>> category of design fragmentation that other languages suffer from.
>
> Fredrik, I am not arguing for the argument's sake, I just don't get
> it: Python requires my class to define __len__, otherwise len() fails.
> Why not require len() as a method instead and forget about __len__ ?
> Does len() (the function) do anything smarter behind the scenes than
> just passing the ball to __len__ ? That could justify its role but
> AFAIK it doesn't.
The benefit of the magic method approach is that it leaves control of the
public namespace of the class instance in the hands of the class developer.
For a given class, it may make sense for the class API to expose its length
under a different name like "size()" or "count()" (e.g. exposing an existing
Java or C++ class to Python).
However, regardless of what the class API itself looks like, it can be mapped
behind the scenes into the standard Python idiom by doing "__len__ = size" (or
whatever). If the Python idioms for these protocols were based on public API
methods instead of the magic methods then it would greatly interfere with the
developer's control over their own class interface.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://www.boredomandlaziness.org
More information about the Python-3000
mailing list