I’m implementing a little UserOptionHandler class in python. It goes something like this:
class OptionValue():
__init__(self, default_value, value_type=None):
self.value=default_value
if value_type == None:
self.value_type = type( default_value )
else:
self.value_type = value_type
class OptionHandler():
__init__(self, option_list):
self.options = {}
for opt_spec in option_list:
key, value, value_type = opt_spec
self.options[key] = Option( value, value_type )
def set(self, key, value):
opt = self.options[key]
opt.value = value
When I get user input to set the value for an option, I want to make sure that they’ve entered sane. Otherwise, the application run until it gets to a state where it uses the option, which may or may not crash it.
How do you do something like the following?
opt = handler.get( key )
user_input = input("Enter value for {0}:".format(key) )
if( magic_castable_test( user_input, opt.value_type ) ):
print "Your value will work!"
else:
print "You value will break things!"
i’m not sure i follow what you’re asking, but i think that you just need to use
typeitself because:user input is a string
many types, like
intandfloatare functions/constructors that return an instance from a string. for exampleint("3")returns the integer 3.so in your code, you would replace
with:
where i am assuming it’s an error if either (1) an exception is thrown or (2) the type returning null.
and you can take this further and simply require that any types work this way. so, for example, you might have some information that is best represented as a custom class. then you should write the class so that it has an
__init__that takes a single string:and you can then pass
MyClassas an option type to your code above.ps here’s perhaps a clearer example of what i mean: