Hacker News new | ask | show | jobs
by prawks 3539 days ago
From the mypy docs linked in the article (http://mypy.readthedocs.io/en/latest/duck_type_compatibility...), it seems it supports a small number of built-in duck types currently, and has support for some protocols (http://mypy.readthedocs.io/en/latest/cheat_sheet.html#standa...)

> mypy considers an int object to be valid whenever a float object is expected.

> Use Iterable for generic iterables (anything usable in `for`)

Thus you should be able to get a more broadly correct (though still not 100% if you have your own types implementing __add__ and __radd__) like this:

  from typing import Iterator

  def sum_and_stringify(nums: Iterator[float]) -> str:
      return str(sum(nums))
It also looks like implementing an abstract base class SupportsSum (to check for __add__ and __radd__) may not take a whole lot of work, see `SupportsInt`: https://github.com/python/mypy/blob/d7f6ea617317103534d86686...

http://mypy.readthedocs.io/en/latest/class_basics.html?highl...

1 comments

I had heard of the support for the hierarchy of some builtins like floats being more general than ints, but this isn't a very satisfactory approach because it's not extensible to user-defined numeric types. Perhaps what I'm suggesting is possible with either the existing classes in abc, or by defining more like them (and ensuring users can define their own). Would be nice to see more focus on this in the examples if that's the case.