Pythonic方式将枚举映射到API值

huangapple go评论56阅读模式
英文:

Pythonic way to map enum to api values

问题

I have a proto generated code which has 3 values (values I am interested in):

proto_type.VALUE1
proto_type.VALUE2
proto_type.VALUE3

I have created an enum in my python project.

class MyEnum(Enum):
    VALUE1 = 0
    VALUE2 = 1
    VALUE3 = 2

The sole reason I have done this is so that I can restrict the callee to use specific values. Now I want to map MyEnum to proto_type values.

I was thinking of creating a dictionary, i.e.,

Mapping = {
  MyEnum.Value1: imported_proto_type.VALUE1,
  MyEnum.Value2: imported_proto_type.VALUE2,
  MyEnum.Value3: imported_proto_type.VALUE3,
}

What I wanted to ask is this the best pythonic way to do so? Is there any better approach?

英文:

I have a proto generated code which has 3 values (values i am interested in)

proto_type.VALUE1
proto_type.VALUE2
proto_type.VALUE3

I have created an enum in my python project.

class MyEnum(Enum):
    VALUE1 = 0
    VALUE2 = 1
    VALUE3 = 2

The sole reason i have done this so that i can restrict callee to use specific values. Now I want to map MyEnum to proto_type values.

I was thinking to create a dictionary i.e.,

Mapping = {
  MyEnum.Value1: imported_proto_type.VALUE1,
  MyEnum.Value2: imported_proto_type.VALUE2,
  MyEnum.Value3: imported_proto_type.VALUE3,
} 

What i wanted to ask is this best pythonic way to do so? Is there any better approach?

答案1

得分: 2

为什么不直接在你的枚举中使用生成的 proto 值?

class MyEnum(Enum):
  VALUE1 = imported_proto_type.VALUE1
  VALUE2 = imported_proto_type.VALUE2
  VALUE3 = imported_proto_type.VALUE3

然后,如果你有:

x = MyEnum.VALUE1

你可以通过以下方式直接获取 proto 值:

x.value
英文:

Why not just use the proto generated values in your Enum?

class MyEnum(Enum):
  VALUE1 = imported_proto_type.VALUE1
  VALUE2 = imported_proto_type.VALUE2
  VALUE3 = imported_proto_type.VALUE3

Then if you have:

x = MyEnum.VALUE1

You can get at the proto value directly by writing:

x.value

答案2

得分: 1

使用字典进行映射是一种非常常见且容易理解的做法。现在有一种不需要映射的处理方式。如果proto_type中的值是整数,那么可以采用以下方式。

from enum import IntEnum

class MyEnum(IntEnum):
    VALUE1 = proto_type.VALUE1
    VALUE2 = proto_type.VALUE2
    VALUE3 = proto_type.VALUE3

现在可以这样使用。
MyEnum.VALUE1.value

英文:

Using dictionary for mapping is very common and easy to understand practice. Now there is another way to handle this without mapping. If the values in proto_type are integers that following way would be better.

from enum import IntEnum

class MyEnum(IntEnum):
    VALUE1 = proto_type.VALUE1
    VALUE2 = proto_type.VALUE2
    VALUE3 = proto_type.VALUE3

Now you can use this as follow.
MyEnum.VALUE1.value

huangapple
  • 本文由 发表于 2023年4月20日 03:58:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058371.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定