[Python-ideas] Proposal: Use mypy syntax for function annotations

Ryan rymg19 at gmail.com
Thu Aug 14 20:05:58 CEST 2014



Andrew Barnert <abarnert at yahoo.com> wrote:
>On Aug 14, 2014, at 7:37, Ryan Gonzalez <rymg19 at gmail.com> wrote:
>
>>> On 8/13/2014 3:44 PM, Guido van Rossum wrote:
>
>>> Now consider an extended version (after Lucas).
>>> 
>>> def fib(n, a, b):
>>>     i = 0
>>>     while i <= n:
>>>         print(i,a)
>>>         i += 1
>>>         a, b = b, a+b
>>> 
>>> The only requirement of a, b is that they be addable. Any numbers
>should be allowed, as in fib(10, 1, 1+1j), but so should fib(5, '0',
>'1'). Addable would be approximated from below by Union(Number, str).
>> 
>> Unless MyPy added some sort of type classes...
>
>By "type classes", do you mean this in the Haskell sense, or do you
>mean classes used just for typing--whether more granular ABCs (like an
>Addable which both Number and AnyStr and probably inherit) or typing.py
>type specifiers (like an Addable defined as Union(Number, AnyStr)?

The Haskell way. Having ABCs and type classes can get confusing, but, when I can, I use type classes for the more unrelated concepts(such as Addable) and ABCs for the more parent-child concepts(such as Node in an AST or Generator in a set of generators).

The fine line might actually make it a bad choice to add to Python/mypy, though.

>
>It's also worth noting that the idea that this function should take a
>Number or a str seems way off. It's questionable whether it should
>accept str, but if it does, shouldn't it also accept bytes, bytearray,
>and other string-like types? What about sequences? And meanwhile,
>whether or not it accepts str, it should probably accept np.ndarray and
>other types of element-wise adding types. If you create an Addable
>type, it has to define, globally, which of those counts as addable, but
>different functions will have different definitions that make sense.
>
>In fact, look at the other discussion going on. People want to ensure
>that sum only works on numbers or number-like types (and does that
>include NumPy arrays or not?), while others want to change it to work
>on all sequences, or only mutable sequences with += plus str because it
>effectively has magical += handling under the covers, etc. If we can't
>even decide what Addable means for one specific function that everyone
>has experience with...
>
>On the other hand, if sum could have been annotated to tell us the
>author's intention (or, rather, the consensus of the dev list), then
>all of these recurring arguments about summing str would go away. Until
>someone defined a number-like class (maybe even one that meets the ABC,
>but by calling register on it) and sum won't work for him.

-- 
Sent from my Android phone with K-9 Mail. Please excuse my brevity.


More information about the Python-ideas mailing list