[Python-ideas] "Sum" Type hinting [was: Type hinting for path-related functions]

Koos Zevenhoven k7hoven at gmail.com
Mon May 16 11:05:24 EDT 2016


On Mon, May 16, 2016 at 2:37 AM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
>
> I'm not deeply into category theory, but the proposal
> seems to be that Sum would be a special kind of type
> that's assumed to be the same type wherever it appears
> in the signature of a function.

Indeed, that's TypeVar.

> That might work for the special case of a function of
> one parameter that returns the same type as its
> argument, but that's about all.

I was actually trying to interpret the (vague) proposal as going even
a step further, closer to what may have helped slightly in the fspath
type hinting problem. Perhaps something like this:

M = TagMatcher(3)  # 3 is the number of "summed" types
# (and yes, I just made up the term TagMatcher)

def onehalf(value: M.sum[int, float, complex]) -> M.sum[float, float, complex]:
    return 0.5 * value

That would then match the "tag" between the argument and return types
(within the sum types which are tagged unions):

int -> float
float -> float
complex -> complex

As you can see, "onehalf(...)" will turn int, float and complex into
float, float and complex, respectively. I suppose one or more
"functors" could be seen in there to make this happen in theory XD.
This is not solved by a TypeVar.

> As has been pointed out, type parameters allow the
> same thing to be expressed, and a lot more besides,
> so a Sum type is not needed. We already have everything
> we neeed.

So, despite what I write above, you still seem to agree with me,
assuming you did not literally mean *everything* ;-).

The reason why we agree is that we can already do:

@overload
def onehalf(value: int) -> float:
    ...
@overload
def onehalf(value: float) -> float:
    ...
@overload
def onehalf(value: complex) -> complex:
    ...

So, the sum type, even with my "TagMatcher" described above, does not
provide anything new. After all, the whole point of sum types is to
give *statically typed* languages something that resembles dynamic
typing.


-- Koos


>
> --
> Greg
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list