
On Thu, May 19, 2016 at 12:00 AM, Greg Ewing <greg.ewing@canterbury.ac.nz> wrote:
Guido van Rossum wrote:
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.
Well, sort of. It will check that you don't pass anything outside of the set of allowed types, but it can't tell whether you've handled all the possible cases in the code. That's something Haskell can do because (1) it has special constructs for case analysis, and (2) its algebraic types can't be extended or subclassed.
I'm still not sure I understand why this check that you've handled all cases is so important (I've met a few people who obsessed about it in other languages, but I don't really feel the need in my gut yet). I also don't think that subclasses cause problems (if there's a match for a particular class, it will match the subclass too). Anyway, I believe mypy could easily check that you're always returning a value in situations like this (even though it doesn't do that now): def foo(arg: Union[X, Y, Z]) -> int: if isinstance(arg, X): return arg.counter if isinstance(arg, Y): return 0 It should be possible to figure out that Z is missing here.
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;
Yes, if there were dedicated syntax for it, mypy could check that you covered all the branches of a Union.
I've thought about this off and on a bit. Maybe I'll write about some ideas in another post.
Would love to hear your thoughts!. -- --Guido van Rossum (python.org/~guido)