Python 创建有限类型

问题描述 投票:0回答:1

我有一个 python 函数,我想接受 5 个可能值之一。这些值是:“Q”、1、2、3 和 4。是的,这是一个字符串和 4 个整数。有没有办法创建一个对象,我可以在类型提示中使用该对象来仅指定这 5 个值中的一个?下面的内容显然不起作用,但它具有我在定义一个对象时所寻找的要点,该对象类型的变量只能是上面列出的 5 个值之一。这可能吗?

PlayoffRound = ["Q", 1, 2, 3, 4]  # or some other way to define an object with only these possibilities
def func(playoff_round: PlayoffRound) -> None:
    # do something
    pass
python type-hinting
1个回答
0
投票

您正在描述

typing.Literal
的作用:

from typing import Literal

PlayoffRound = Literal["Q", 1, 2, 3, 4]

def func(playoff_round: PlayoffRound) -> None:
    pass
© www.soinside.com 2019 - 2024. All rights reserved.