[code-quality] __len__ but no __getitem__
Sylvain Thénault
sylvain.thenault at logilab.fr
Mon Sep 23 16:26:49 CEST 2013
Hi Skip,
On 23 septembre 09:07, Skip Montanaro wrote:
> Having demonstrated my confusion about early breaks from loops, I will
> proceed to demonstrate my confusion about containers.
:)
> I have a queue-like class in which I implement __len__ but not
> __getitem__. Pylint complains:
>
> timeddata.py:79: [R0924(incomplete-protocol), TimedDataQueue] Badly
> implemented Container, implements __len__ but not __getitem__
>
> I can see where that would be a valid complaint for an array-like
> container, but not all containers should support indexing even if they
> have a measurable length. Python sets are one example:
>
> >>> s = set(range(10))
> >>> len(s)
> 10
> >>> s[0]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: 'set' object does not support indexing
>
> Queue-like containers seem similar. While I would allow access to the
> element at one end or the other (depending if I want queue-like or
> stack-like behavior), I think it would violate the definition of those
> types to allow indexing.
>
> Should pylint really be this strict? Or am I expected to implement
> everything necessary for an array-like containiner and just raise
> exceptions in those methods the user really shouldn't access?
No I'ld say you're right. While it sounded a good idea when proposed, you're not
the first one being confused by this message, so I tend to think this check
should be either removed or kept for well defined and all-or-nothing protocols
(the only one coming to my mind being the context manager __enter__ / __exit__,
but there may be others). I would be glad to have others'opinion though.
--
Sylvain Thénault, LOGILAB, Paris (01.45.32.03.12) - Toulouse (05.62.17.16.42)
Formations Python, Debian, Méth. Agiles: http://www.logilab.fr/formations
Développement logiciel sur mesure: http://www.logilab.fr/services
CubicWeb, the semantic web framework: http://www.cubicweb.org
More information about the code-quality
mailing list