[Python-ideas] Type Hinting Kick-off

Eugene Toder eltoder at gmail.com
Fri Dec 26 21:30:30 CET 2014

On Fri, Dec 26, 2014 at 2:15 PM, Andrew Barnert <abarnert at yahoo.com> wrote:
> I'm not sure you can just skip over that last point without addressing it.
> In this case, given iterables of element types Y1, Y2, ..., Yn, you can say
> that they're all type Iterable[Union[Y1, Y2, ..., Yn]]. I _think_ an
> inference engine can find that Union type pretty easily, and I _think_ that
> at least for collection methods there won't be any harder problems--but I
> wouldn't just assume either of those without looking carefully.
With what I suggest the vararg is typed the same as a literal list: I assume
the type of the expression [Y1, Y2, ...] is List[Union[Y1, Y2, ...]].
Alternatively, the function call is typed as if the argument was replicated
the number of times equal to the number of actual arguments. Both ways should
give the same result, and are already supported in the type checker. This
seems intuitive, matches your analysis above, and implemented in at least C#,
Java and Scala, so there's a good evidence that this is quite usable.

> And it certainly isn't true when we go past collection methods--clearly map
> and zip can't be handled this way.
You're right, these cannot be typed without specifying some rewrite rules on
the arguments types. You can go further, and say that str.format() type needs
to parse the format string to determine the number and the types of what goes
into varargs.
I think the simple "all of the same type" rule is good enough to type the
majority of uses of varargs, except for argument forwarding into a call. At
least it's better than nothing.

> The point is, at least this example only really needs the type of self, not
> an arbitrary forward declaration or an expression that has to be crammed
> into a string. Are there any good examples where that isn't true?
Depends on what you consider good :-) What is in your opinion a good use of
a forward reference not to the current class?
Say you have a helper class to implement your collection (e.g. List[X] and
ListNode[X]), and for some reason you need to reference the their types from
each other. I think this is not too hard to imagine, but there are may be
ways to avoid it.

> Also, should Set.union be contravariant in the generic type Set, or is it
> always going to return a Set[Something]? The two options there could both
> easily be handled by type expressions, or maybe with explicit forward
> declarations, but with implicit forward declaration via string?
I assume you mean covariant? As in, subclasses of Set will return their own
types from union. This can be solved without type expressions by having a
special SelfType. A few languages use that -- it's useful for copy()-like


More information about the Python-ideas mailing list