Why am I getting a KeyError when attempting to use an Enum as a Dictionary Key in Python?

Question:

For context, I have the following file structure:

Helpers.Py
Constants.Py
/Tests
 - Test_Helpers.Py

I defined an Enum in Constants like so:

class HelperEnum(Enum):
    ValueOne = auto()
    ValueTwo = auto()

Then used it as a Dictionary Key in Helpers.Py like so:

from Constants import HelperEnum

class ClassOne:
   def __init__(self):
      self.dictionary = { HelperEnum.ValueOne: "TEMP" }

But when I try to access it from Tests/Test_Helpers.py, it doesn’t work.

from .. import Helpers
from .. import Constants

Helpers.ClassOne().dictionary[Constants.HelperEnum.ValueOne] 

Retuns KeyError. I can see in the debugger that the enum.Name and .Value are the same, so why is there a KeyError?

Asked By: Henry C

||

Answers:

In Constants.py, ensure you import Enum and auto:

from enum import Enum, auto

class HelperEnum(Enum):
    ValueOne = auto()
    ValueTwo = auto()

In Helpers.py, import HelperEnum:

from .Constants import HelperEnum

class ClassOne:
    def __init__(self):
        self.dictionary = {HelperEnum.ValueOne: "TEMP"}

In Test_Helpers.py, import the necessary modules:

from ..Helpers import ClassOne
from ..Constants import HelperEnum

print(ClassOne().dictionary[HelperEnum.ValueOne])

If you still encounter an issue, please double-check your import statements and file paths to ensure everything is set up correctly. You may also want to consider using absolute imports instead of relative imports to help avoid issues with the import paths.

Answered By: Obaskly
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.