typing module - String Literal Type [duplicate]

≯℡__Kan透↙ 提交于 2019-12-03 11:29:03

Disregarding the typing module you asked about, one solution to your problem could be the use of an Enum as supposed in multiple comments. The code for this would look like this:

from enum import Enum

class Quadrant(Enum):
    I = 1
    II = 2
    III = 3
    IV = 4

def compute_quadrant(x: int, y: int) -> Quadrant:
    if x > 0 and y > 0:
        return Quadrant.I
    elif x < 0 and y > 0:
        return Quadrant.II
    elif x < 0 and y < 0:
        return Quadrant.III
    elif x > 0 and y < 0:
        return Quadrant.IV
    # return None  # this is what happens without an else clause!

if __name__ == "__main__":
    quad = compute_quadrant(1, -1)
    print(quad, type(quad))              # -> Quadrant.IV <enum 'Quadrant'>
    print(quad.name, type(quad.name))    # -> IV <class 'str'>
    print(quad.value, type(quad.value))  # -> 4 <class 'int'>

As you can see you can use the Enums name and value. The name is one of the strings you asked for.

One issue I see here is the missing else clause in the function and mypy's current behaviour of accepting None as a valid return value for Quadrant. This should be handled manually.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!