fix: Corrected enum metaclass to fix pickle.dumps() (#1495)

* Corrected enum metaclass to fix pickle.dumps()

* considered case with colliding class names (try to distinguish by file name)

* reverted simple solution back (without attempt to support duplicate Enum class names)

---------

Co-authored-by: sgrekov <sgrekov@lohika.com>
Co-authored-by: Erik Wrede <erikwrede@users.noreply.github.com>
This commit is contained in:
senseysensor 2023-06-05 00:10:05 +03:00 committed by GitHub
parent 2da8e9db5c
commit c636d984c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 1 deletions

View File

@ -0,0 +1,27 @@
import pickle
from ...types.enum import Enum
class PickleEnum(Enum):
# is defined outside of test because pickle unable to dump class inside ot pytest function
A = "a"
B = 1
def test_enums_pickling():
a = PickleEnum.A
pickled = pickle.dumps(a)
restored = pickle.loads(pickled)
assert type(a) is type(restored)
assert a == restored
assert a.value == restored.value
assert a.name == restored.name
b = PickleEnum.B
pickled = pickle.dumps(b)
restored = pickle.loads(pickled)
assert type(a) is type(restored)
assert b == restored
assert b.value == restored.value
assert b.name == restored.name

View File

@ -31,9 +31,11 @@ class EnumMeta(SubclassWithMeta_Meta):
# with the enum values. # with the enum values.
enum_members.pop("Meta", None) enum_members.pop("Meta", None)
enum = PyEnum(cls.__name__, enum_members) enum = PyEnum(cls.__name__, enum_members)
return SubclassWithMeta_Meta.__new__( obj = SubclassWithMeta_Meta.__new__(
cls, name_, bases, dict(classdict, __enum__=enum), **options cls, name_, bases, dict(classdict, __enum__=enum), **options
) )
globals()[name_] = obj.__enum__
return obj
def get(cls, value): def get(cls, value):
return cls._meta.enum(value) return cls._meta.enum(value)