Python 3.10和3.11中的枚举成员为什么在序列化到YAML时不同?

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

Why are enum members in Python 3.10 and 3.11 serialized to YAML differently?

问题

以下是翻译好的内容:

使用此代码片段:

  1. import sys
  2. import yaml
  3. try:
  4. from enum import ReprEnum
  5. except ImportError:
  6. from enum import Enum as ReprEnum
  7. class MyEnum(int, ReprEnum):
  8. foo = 123
  9. print('Python version:', ''.join(map(str, sys.version_info[:3])))
  10. print(yaml.dump({'test': MyEnum.foo}))

我在Python 3.10和3.11上获得了非常不同的输出:

3.10 输出:

  1. Python 版本:3.10.12
  2. test: !!python/object/apply:__main__.MyEnum
  3. - 123

3.11 输出:

  1. Python 版本:3.11.4
  2. test: !!python/object/apply:builtins.getattr
  3. - !!python/name:__main__.MyEnum ''
  4. - foo

我猜想这与Python 3.11的enum模块中的许多更改有关,但我想了解为什么发生了这种变化...

英文:

Using this snippet:

  1. import sys
  2. import yaml
  3. try:
  4. from enum import ReprEnum
  5. except ImportError:
  6. from enum import Enum as ReprEnum
  7. class MyEnum(int, ReprEnum):
  8. foo = 123
  9. print('Python version:', ''.join(map(str, sys.version_info[:3])))
  10. print(yaml.dump({'test': MyEnum.foo}))

I get very different output on Python 3.10 and 3.11:

3.10 output:

  1. Python version: 3.10.12
  2. test: !!python/object/apply:__main__.MyEnum
  3. - 123

3.11 output:

  1. Python version: 3.11.4
  2. test: !!python/object/apply:builtins.getattr
  3. - !!python/name:__main__.MyEnum ''
  4. - foo

My guess would be that it's related to the many changes in Python 3.11's enum module, but I'd like to understand why this changed...

答案1

得分: 1

从按值序列化更改为按名称序列化发生在这个Python PR中。

然而,后来已经在这个PR中重新更改为按值序列化,我认为这将在3.11.5版本中生效。

在3.11.5版本(假设它会在那里)发布之前或者当您想要支持早期的3.11版本时,可以将以下内容添加到您的Enum子类中以解决问题:

  1. def __reduce_ex__(self, proto):
  2. return self.__class__, (self._value_,)
英文:

Changing from by-value to by-name serialization happened in this Python PR.

However, it has later been reverted to by-value serialization in this PR which I assume will end up in 3.11.5.

A workaround until 3.11.5 (assuming it will be in there) is out, or when you want to support earlier 3.11 version as well is adding this to your Enum subclass:

  1. def __reduce_ex__(self, proto):
  2. return self.__class__, (self._value_,)

huangapple
  • 本文由 发表于 2023年6月29日 18:12:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580083.html
匿名

发表评论

匿名网友

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

确定