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

Dennis Brakhane brakhane at googlemail.com
Fri Aug 15 00:11:16 CEST 2014


Am 14.08.2014 22:16, schrieb Sunjay Varma:
> One of the many benefits of Python is that you can use objects with
> equivalent interfaces in functions that may not have expected that
> type while they were being written. 
Exactly. As others have already noted, Guido's example is actually
restricting code from calling it with a file object for no particular
reason.

Another thing is that it restricts the entries of the iterables to be
str, while it actually only requires them to provide a split method.

For example, and I'm aware that this is a contrieved case, let's assume
word_count would actually be somehow extremely optimized code that
I don't want to rewrite.

I now want to count all prime factors in a list of integers.

Without annotations I *could* do something like this ("Language for
consenting adults"):

  class IntWrapper(int):
      def split(self):
          return primefactors(self)

  word_count(IntWrapper(i) for i in my_integer_list)

I don't want to argue whether that's good code or not (it probably
isn't), it would be possible to write such code and it will work correctly.

For mypy to accept such code, the type declaration of word_count would
have to be something like

  def word_count(input: Iterable[has("split() -> T")]) -> Dict[T, int]

Which would require a very complex type system.

If I understand MyPy correctly, the above would be possible, but it
would have to look something like

  cast(Dict[int, int], word_count(cast(List[str], (IntWrapper(i) for i
in my_integer_list)))

One could argue that this ugly piece of code is the rightful punishment
for abusing duck typing, but I'm not convinced
you should be forced to make the code unreadable (and therefore refactor
your code and reimplement word_count yourself).


> We have to be careful with this. If we do accept it (or any of the
> many alternatives suggested so far), then we should choose a few use
> cases and focus on solving them as best as possible. 
Yes, my fear is that we will either end up with a broken type system
like Java (which provides more problems than it solves) or end up with a
hugely complex type system and type hierachy like Scala
(see http://www.scala-lang.org/api/2.11.2/#scala.collection.MapLike for
a quick example what you end up with)





More information about the Python-ideas mailing list