Skip to content

Pickling of enum with functional API throws error #106959

Closed as not planned
Closed as not planned
@fnobis

Description

@fnobis

Bug report

I want to create a enum from a list of variables and then pickle it. I use the functional constructor. When I try to pickle it, an error is thrown:

_pickle.PicklingError: Can't pickle <enum 'classes_enum_name'>: attribute lookup classes_enum_name on __main__ failed

If I create the class explicitly the pickling works.

See the following example to reproduce the error:

import pickle
import enum


class ClassEnum(enum.Enum):
    dog = 1
    cat = 2
    cow = 3


if __name__ == "__main__":
    # **************************************************************************
    # Enum variant 1 - works
    # **************************************************************************

    class_enum = ClassEnum
    print(class_enum["cow"])
    with open("test.pkl", "wb") as f:
        pickle.dump(class_enum, f)  # works

    # **************************************************************************
    # Enum variant 2 - error
    # **************************************************************************
    classes = ["dog", "cat", "cow"]
    list_enum = enum.Enum("classes_enum_name", classes, start=0)
    print(list_enum["cow"])
    with open("test.pkl", "wb") as f:
        pickle.dump(list_enum, f)  # throws error

Metadata

Metadata

Assignees

Labels

docsDocumentation in the Doc dir

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions