my goal is to have a user input a string that is checked to be valid - by defining a dict of allowed strings - and mapped to another string to be stored in a list. Another function is supposed to map these stored strings to Enums and work with those. Here's the code I have:
from __future__ import annotations
from enum import Enum
from typing import List, Type
ONG_SPS_STATES = {
"pre": "PreReleased",
"rel": "Released",
"ret": "Retired",
"tgt": "Target"
}
sps_states: List[str] = []
def str_to_state(input: str) -> None:
if (input in ONG_SPS_STATES.keys()):
sps_states.append(ONG_SPS_STATES[input])
else:
print('Invalid input')
SpsState = Enum('SpsState', list(ONG_SPS_STATES.values()))
def get_sps_state(index: int) -> Type[Enum]:
if (len(sps_states) > index):
return SpsState[sps_states[index]]
raise Exception('Invalid index')
if (__name__ == '__main__'):
cont = True
while cont:
inp = input('State: ')
if (inp.lower() != 'e'):
str_to_state(inp)
else:
cont = False
cont = True
while cont:
inp = input('Index: ')
if (inp.lower() != 'e'):
print(get_sps_state(int(inp)))
else:
cont = False
The problem is that mypy complains about line 21 (SpsState = Enum('SpsState', list(ONG_SPS_STATES.values()))
) with error: Enum() expects a string, tuple, list or dict literal as the second argument [misc]
and line 25 (return SpsState[sps_states[index]]
) with error: Incompatible return value type (got "SpsState", expected "Type[Enum]") [return-value]
How can the existing code with the described "ease of use" be rewritten to be pythonic (Python 3.9 if that is important) and compatible with mypy at the same time?