简体   繁体   English

将字符串联合用作可能的字典键

[英]Make a Union of strings to be used as possible dictionary keys

I have some Python 3.7 code and I am trying to add types to it.我有一些 Python 3.7 代码,我正在尝试向其中添加类型。 One of the types I want to add is actually an Union of several possible strings:我要添加的类型之一实际上是几个可能字符串的Union

from typing import Union, Optional, Dict

PossibleKey = Union["fruits", "cars", "vegetables"]
PossibleType = Dict[PossibleKey, str]

def some_function(target: Optional[PossibleType] = None):
  if target:
    all_fruits = target["fruits"]
    print(f"I have {all_fruits}")

The problem here is that Pyright complains about PossibleKey .这里的问题是 Pyright 抱怨PossibleKey密钥。 It says:它说:

"fruits is not defined" “水果没有定义”

I would like to get Pyright/Pylance to work.我想让 Pyright/Pylance 工作。

I have checked the from enum import Enum module from another SO answer, but if I try that I end up with more issues since I am actually dealing with a Dict[str, Any] and not an Enum .我已经从另一个 SO 答案检查了from enum import Enum模块,但是如果我尝试这样做,我最终会遇到更多问题,因为我实际上是在处理Dict[str, Any]而不是Enum

What is the proper Pythonic way of representing my type?表示我的类型的正确 Pythonic 方式是什么?

"fruits" is not a type (hint), but Literal["fruits"] is. "fruits"不是类型(提示),但Literal["fruits"]是。

from typing import Union, Literal

PossibleKey = Union[Literal["fruits"], Literal["cars"], Literal["vegetables"]]

or the much shorter version,或者更短的版本,

PossibleKey = Literal["fruits", "cars", "vegetables"]

Or, as you mentioned, define an Enum populated by the three values.或者,正如您所提到的,定义一个由三个值填充的Enum

from enum import Enum


class Key(Enum):
    Fruits = "fruits"
    Cars = "cars"
    Vegetables = "vegetables"


def some_function(target: Optional[PossibleType] = None):
    if target:
        all_fruits = target[Key.Fruits]
        print(f"I have {all_fruits}")

(However, just because target is not None doesn't necessarily mean it actually has "fruits" as a key, only that doesn't have a key other than Key.Fruits , Key.Cars , or Key.Vegetables .) (然而,仅仅因为target不是None并不一定意味着它实际上"fruits"作为键,只是没有Key.FruitsKey.CarsKey.Vegetables以外的键。)

Pyright error disappears if you define PossibleKey as Enum as below.如果您将PossibleKey定义为Enum ,则Pyright错误消失,如下所示。 This requires only one line change to the original code.这仅需要对原始代码进行一行更改。 If there is some issue with using Enum, please elaborate on that.如果使用 Enum 存在一些问题,请详细说明。

from typing import Union, Optional, Dict
from enum import Enum

PossibleKey = Enum("PossibleKey", ["fruits", "cars", "vegetables"])
PossibleType = Dict[PossibleKey, str]

def some_function(target: Optional[PossibleType] = None):
  if target:
    all_fruits = target["fruits"]
    print(f"I have {all_fruits}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM