I have a GUI where I ask the user to enter some values. When the user submits the data I do some validation:
- first I check if the user has entered a value for each input
- then I check if each of the inputted values are integers
Trying not to repeat myself to much I came up with this, but the second part of the validation looks more like a hack. Is there a more pythonic way of rewriting this, short of spelling everything out like in the first part of the validation?
errors = []
# 1) check if values exist
if not self.startInput.GetValue():
errors.append("Please provide a start")
if not self.stopInput.GetValue():
errors.append("Please provide a stop")
if not self.valueInput.GetValue():
errors.append("Please provide a value")
# 2) check if values are integers
try:
self.start = int(self.startInput.GetValue())
self.stop = int(self.stopInput.GetValue())
self.value = int(self.valueInput.GetValue())
except ValueError as err:
tb = traceback.format_exc()
func = re.search('self\.(.*) =', tb).groups()[0]
errors.append("Value for {0} needs to be an integer.".format(func))
if errors:
raise RuntimeError('\n'.join(errors))