Python Glossary Русский

Python 3.11+enumfunction

enum.pickle_by_enum_name

pickle

A pickle reducer that serializes an enum member by (class, member name) instead of by value.

Syntax

member.__reduce_ex__ = enum.pickle_by_enum_name

By default an enum member is pickled by value, so the stream effectively holds a Colour(1) call. If the values later shift, typically because they came from auto(), an old pickle will not fail loudly but quietly resolve to a different member; storing the name instead removes that trap. Assign the reducer inside the enum class body as __reduce_ex__ = enum.pickle_by_enum_name.

Examples

import enum
print(callable(enum.pickle_by_enum_name))   # → True
Color = enum.Enum('Color', 'RED GREEN')
print(Color.RED.__reduce_ex__(2)[1])   # → (1,)
func, args = enum.pickle_by_enum_name(Color.RED, 2)
print(func is getattr)   # → True
print(args[1])   # → RED
print(func(*args) is Color.RED)   # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy