[Python-ideas] Type Hinting Kick-off

Eugene Toder eltoder at gmail.com
Fri Dec 26 18:59:28 CET 2014

On Fri, Dec 26, 2014 at 10:26 AM, Andrew Barnert <abarnert at yahoo.com> wrote:
> The builtin set (and therefore the undocumented MyPy/typing TypeAlias Set)
> had a union method, but its signature is not that restrictive. It takes 1
> or more arbitrary iterables of any element type, and of course it returns
> a set whose element type is the union of the element types of self and
> those. And the same is true in general for all of the builtin abstract and
> concrete types.
You are right. The union type solves the problem, and is a more precise type
than with a lower bound. So we don't need lower bounds on type variables for
collection methods, and maybe at all.

> The _opposite_ problem--that it's hard to define the _actual_ type of
> set.union or similarly highly parameterized types--may be more serious,

Why is it hard? Isn't the actual type just:

def union(self, *others: Iterable[Y]) -> Set[Union[X, Y]]

where typing of vararg is similar to Java -- all elements must conform to the
single type annotation.

Also note that I posted set.union method as an example that needs a forward
reference to a generic class. I was arguing that if we use strings for forward
references, we'll eventually have complicated expressions in those strings,
not just class names:

class Set(Generic[X]):
    # Note that the name "Set" is not yet available, so we have to use
    # a forward reference. This puts the whole return type inside a string.
    def union(self, *others: Iterable[Y]) -> "Set[Union[X, Y]]": ...

Your type for set.union seems to prove the point even better than what I used.


More information about the Python-ideas mailing list