英文:
Why are enum members in Python 3.10 and 3.11 serialized to YAML differently?
问题
以下是翻译好的内容:
使用此代码片段:
import sys
import yaml
try:
from enum import ReprEnum
except ImportError:
from enum import Enum as ReprEnum
class MyEnum(int, ReprEnum):
foo = 123
print('Python version:', ''.join(map(str, sys.version_info[:3])))
print(yaml.dump({'test': MyEnum.foo}))
我在Python 3.10和3.11上获得了非常不同的输出:
3.10 输出:
Python 版本:3.10.12
test: !!python/object/apply:__main__.MyEnum
- 123
3.11 输出:
Python 版本:3.11.4
test: !!python/object/apply:builtins.getattr
- !!python/name:__main__.MyEnum ''
- foo
我猜想这与Python 3.11的enum模块中的许多更改有关,但我想了解为什么发生了这种变化...
英文:
Using this snippet:
import sys
import yaml
try:
from enum import ReprEnum
except ImportError:
from enum import Enum as ReprEnum
class MyEnum(int, ReprEnum):
foo = 123
print('Python version:', ''.join(map(str, sys.version_info[:3])))
print(yaml.dump({'test': MyEnum.foo}))
I get very different output on Python 3.10 and 3.11:
3.10 output:
Python version: 3.10.12
test: !!python/object/apply:__main__.MyEnum
- 123
3.11 output:
Python version: 3.11.4
test: !!python/object/apply:builtins.getattr
- !!python/name:__main__.MyEnum ''
- 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子类中以解决问题:
def __reduce_ex__(self, proto):
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:
def __reduce_ex__(self, proto):
return self.__class__, (self._value_,)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论