I'm using the new Python 3.5 module typing and it has been joyous.
I was wondering how one might specify a type based on an exact string literal. For example, a function is guaranteed to return one of the four strings - "North", "West", "East", "South - how can we express that as a specific type variable, instead of just str
.
I looked through the documentation, finding the Union
type and the TypeVar
function, but was unable to find an answer.
An example function expressing this problem:
def compute_quadrant(x: int, y: int) -> str:
if x > 0 and y > 0:
return 'I'
elif x < 0 and y > 0:
return 'II'
elif x < 0 and y < 0:
return 'III'
elif x > 0 and y < 0:
return 'IV'
Instead of just returning str
, I'd like to to return a more specific type that is one of four values - "I"
, "II"
, "III"
, or "IV"
.
In Typescript, one can do: type Quadrant = "I" | "II" | "III" | "IV"
- is there any nice Python sugar for this use case with the typing
module?
enum
fits perfectly.