枚举不能在Python 3.6中腌制,但可以在3.7中腌制

今天,我遇到了一个问题,其中在Python 3.6中无法腌制枚举,但在Python 3.7中没有发生错误。以下代码演示了该问题:

import enum
import pickle


class GoodEnum(enum.Enum):
    CAT = 'C'
    DOG = 'D'

    def __str__(self):
        return str(self.value)


# Can be pickled just fine
print(pickle.dumps(GoodEnum.CAT))


class StringValue:
    def __str__(self):
        return str(self.value)


class ErrorEnum(StringValue,enum.Enum):
    CAT = 'C'
    DOG = 'D'


# Causes TypeError: <ErrorEnum.CAT: 'C'> cannot be pickled in Python 3.6
print(pickle.dumps(ErrorEnum.CAT))

在Python 3.6 中:

$ python --version
Python 3.6.9
$ python pickleerror.py
b'\x80\x03c__main__\nGoodEnum\nq\x00X\x01\x00\x00\x00Cq\x01\x85q\x02Rq\x03.'
Traceback (most recent call last):
  File "pickleerror.py",line 28,in <module>
    print(pickle.dumps(ErrorEnum.CAT))
  File "/usr/local/lib/python3.6/enum.py",line 46,in _break_on_call_reduce
    raise TypeError('%r cannot be pickled' % self)
TypeError: <ErrorEnum.CAT: 'C'> cannot be pickled

使用Python 3.7 时:

$ python --version
Python 3.7.5
$ python pickleerror.py
b'\x80\x03c__main__\nGoodEnum\nq\x00X\x01\x00\x00\x00Cq\x01\x85q\x02Rq\x03.'
b'\x80\x03c__main__\nErrorEnum\nq\x00X\x01\x00\x00\x00Cq\x01\x85q\x02Rq\x03.'

我在Python发行说明中找不到关于此特定问题的任何内容。所以基本上这里有两个问题:

  • 为什么这段代码在Python 3.6中会导致此错误?
  • 为什么在Python 3.7中不会引起相同的错误?
cuisong123 回答:枚举不能在Python 3.6中腌制,但可以在3.7中腌制

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3163807.html

大家都在问