I have what is probably a very obscure problem. My python script is intended to be ran from the command line with some command line arguments. Each argument needs to be parsed into a type more useful than a string. I am doing the following:
typed_arguments = []
for argument, (parameter, parameter_type) in zip(arguments, self.parameters.items()):
try:
argument = parameter_type(argument)
typed_arguments.append(argument)
except ValueError:
print(self.usage_prompt)
raise TypeError(f"Invalid {parameter}! Must conform to {parmeter_type}.")
where arguments
is sys.argv[1:]
and self.parameters
is an OrderedDict[str, type]
mapping the names of the parameters to the type they should conform to.
One of the arguments needs to be of an enum type. I have the following:
from enum import Enum
class MessageType(Enum):
READ = 1
CREATE = 2
RESPONSE = 3
...
where the entry in the parameter dictionary is {"message_type" : MessageType}
The problem, is that the code MessageType("READ")
throws an exception instead of returning <MessageType.READ: 1>
. Converting string to enum is instead done like so MessageType["READ"]
, but this is not helpful for my above code.
Is there some way, maybe through overriding __new__
, making a MetaClass, or somthing entirely different, that I can make MessageType("READ")
give me MessageType.READ
and not throw an error?
Also, whilst trying to solve this problem, I discovered the argparse module. However this doesn't really solve my problem. Performing
parser.add_argument("message_type", type=MessageType)
still gives me error: argument message_type: invalid MessageType value: 'READ'
, as I presume its trying to do the exact same thing