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

Guido van Rossum guido at python.org
Wed May 18 18:53:25 EDT 2016

On Wed, May 18, 2016 at 3:41 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Guido van Rossum wrote:
>> your original remark claimed
>> something wasn't syntactic sugar because of the difference between the
>> box and its contents, and that's what I disagree with.
> Maybe I misunderstood -- you seemed to be saying that
> algebraic types were just syntactic sugar for something.
> Perhaps I should have asked what you thought they were
> syntactic sugar *for*?

That's a good question, for which I don't have a great answer. I've
just discussed some of this with the author of that blog article (Chad
Austin) and we came to the conclusion that there isn't a great future
for ADTs or Sum types in Python because almost everything you can do
with them already has a way to do it in Python that's good enough.

Sometimes what you need is Haskell's Maybe (i.e. 'Nothing' or 'Just
x'), and in most cases just checking for None is good enough. The
strict optional checking that's coming to mypy soon will help here
because it'll catch you when you're not checking for None before doing
something else with the value.

Sometimes you really do want to distinguish between the box and what's
in it, and then you can use a bunch of simple classes, or maybe a
bunch of namedtuples, to represent the different kinds of boxes. If
you declare the unopened box type as a Union you can get mypy to check
that you've covered all your bases. (If you don't want/need a check
that you're handling all cases you can use a shared superclass instead
of a union.)

There are probably a few other cases.

The one thing that Python doesn't have (and mypy doesn't add) would be
a match statement. The design of a Pythonic match statement would be
an interesting exercise; perhaps we should see how far we can get with
that for Python 3.7.

> I was also responding to a comment that values in
> Python are already tagged with their type, so tagged
> unions are unnecessary. But the type tag of a Python
> object is not equivalent to the tag of an algebraic
> type, because the latter conveys information over and
> above the type of its payload.

Right. And if you need that feature you can wrap it in a class or namedtuple.

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list