Hello!
During the typing meetup from a week or two ago, I mentioned that we (the
mypy team) were planning on implementing Literal types and would have a
draft of the proposed semantics ready soon. Well, here it is:
https://github.com/Michael0x2a/peps/blob/literal-types/pep-9999.rst
It basically combines and elaborates on the discussion from
https://github.com/python/typing/issues/478 and
https://github.com/python/mypy/issues/3062, so hopefully there shouldn't be
too many surprises.
This is probably a little premature in that we've only just barely started
the PoC work in mypy: we'll almost certainly need to tweak some things as
we work through the implementation.
But we're reasonably happy with the proposed semantics and thought it would
be nice to just publish it now so that people can start giving feedback.
(Also, I guess we wanted an excuse to try using this shiny new mailing
list, lol)
-- Michael
For the current code I am writing, this proposal will fulfill my
number one wish, which is exhaustiveness matching for enumerations.
Where previously I used e.g.
class Status(enum.Enum):
Started = 'STARTED'
Finished = 'FINISHED'
def example(status: Status) -> int:
if status is Status.Started:
return 1
elif status is Status.Finished:
return 2
else:
assert False, 'Impossible'
I could now use
Status2 = Literal['STARTED', 'FINISHED']
def example(status: Status2) -> int:
if status == 'STARTED':
return 1
elif status 'FINISHED':
return 2
else:
assert_never(status)
where `assert_never` is as discussed in
https://github.com/python/mypy/issues/5818.
Of course, I would prefer to keep using Enums. That would require the
type checker to consider `Status` similarly to
`Literal[Status.Started, Status.Finished]`. This is what TypeScript
does with its "const enums". The PEP does not discuss this particular
point.
Ran