Signed values in Literal[] type

I noticed today that I’m not able to declare: sign: Literal[-1, +1], because +1 counts as an “arbitrary expression”. I was a bit surprised about this, especially given that in Python +1 is as much an expression as -1. I observed the same behaviour in mypy and pyright.

Is there any reason why this happens? I think it would make sense to change this behaviour. I know that I could use Literal[-1, 1], but in some contexts using an explicit sign is more consistent with the domain.

This is explicitly specified in PEP 586 – Literal Types | the only legal operator inside Literal[] is unary minus on ints. But as you say, it seems fine to allow unary + too; it’s trivial to implement and can improve clarity in some cases.

1 Like

Is an issue in python/typing the right way to follow this up?

As of very soon, the right way would be the one outlined in Expand the README by JelleZijlstra · Pull Request #4 · python/typing-council · GitHub open a discussion here (you did that already), then open a PR against the spec on python/typing (which hasn’t yet been merged), then ask the Typing Council for a decision.