[Python-ideas] Proposal: Use mypy syntax for function annotations
Andrew Barnert
abarnert at yahoo.com
Thu Aug 14 08:45:02 CEST 2014
On Aug 13, 2014, at 21:06, Jukka Lehtosalo <jlehtosalo at gmail.com> wrote:
> You could use AnyStr to make the example work with bytes as well:
>
> def word_count(input: Iterable[AnyStr]) -> Dict[AnyStr, int]:
> result = {} #type: Dict[AnyStr, int]
> for line in input:
> for word in line.split():
> result[word] = result.get(word, 0) + 1
> return result
Defining a function as taking an Iterable[AnyStr] and returning a Dict[AnyStr, int], without any way to declare that the two AnyStr are the same type, is exactly what I meant by losing critical information. I pass in something that I know is a text file, and I get out something that are either strings or bytes and I don't know which; what am I going to do with that? If you can't propagate types, static typing doesn't help.
My point is that the depth you seem to be reaching for is not actually a sweet spot for power vs. simplicity. You could make it simpler by just dropping generics in favor of a handful of special-purpose modifiers (optional, iterable-of), or you could make it more useful by having real parametric types, or at least the equivalent of C++ template templates or Swift arbitrary constraints. What makes Java-style simple generics with subclass constraints the right level of complexity?
More information about the Python-ideas
mailing list