[Python-Dev] Real-world use of Counter
R. David Murray
rdmurray at bitdance.com
Wed Nov 5 20:47:56 CET 2014
On Wed, 05 Nov 2014 11:13:37 -0800, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 11/05/2014 10:56 AM, Raymond Hettinger wrote:
> > The in-place operations on counters are duck-typed. They are intended (by design) to work with ANY type that has an
> > items() method. The exception raised if doesn't have on is an AttributeError saying that the operand needs to have an
> > items() method.
>
> It would still be duck-typed with a `hasattr` call on the second operand checking for the necessary method, a TypeError
> could just as easily state the problem is a missing `items()` method, and then those three [*] in-place methods would
> raise the same error as the 20(?) other Counter methods under similar conditions.
The technique of duck typing as used in Python is you just let errors
bubble up when the input doesn't work. Adding special case checks
should in general only be done if the resulting error message is
otherwise really confusing, which is not the case here.
As I said on the issue, there is no reason I can see to add extra code
just to turn an AttributeError into a TypeError. The AttributeError
works just fine in letting you know your input type didn't work.
--David
More information about the Python-Dev
mailing list