From 609379d4269ee4d03ba39dc509e2fdc4476a0264 Mon Sep 17 00:00:00 2001 From: Juho Vepsalainen Date: Wed, 16 Nov 2011 16:26:54 +0200 Subject: [PATCH] Add "other" alternative to choice automatically --- demos/persistency/questions.yaml | 1 - demos/question_types/questions.yaml | 1 - pyqa/pyqa.py | 2 +- pyqa/questions.py | 13 +++++++++++-- pyqa/questions.spec | 9 +++++++++ 5 files changed, 21 insertions(+), 5 deletions(-) diff --git a/demos/persistency/questions.yaml b/demos/persistency/questions.yaml index 96033f3..246e209 100644 --- a/demos/persistency/questions.yaml +++ b/demos/persistency/questions.yaml @@ -12,7 +12,6 @@ choices: - BSD - GPL - MIT - - Other --- id: use_fizzler q: Do you want to use fizzler? diff --git a/demos/question_types/questions.yaml b/demos/question_types/questions.yaml index 96033f3..246e209 100644 --- a/demos/question_types/questions.yaml +++ b/demos/question_types/questions.yaml @@ -12,7 +12,6 @@ choices: - BSD - GPL - MIT - - Other --- id: use_fizzler q: Do you want to use fizzler? diff --git a/pyqa/pyqa.py b/pyqa/pyqa.py index bcdfbc3..506e8c2 100644 --- a/pyqa/pyqa.py +++ b/pyqa/pyqa.py @@ -1,6 +1,6 @@ from __future__ import print_function from functools import partial -from questions import boolean, choice, match +from questions import boolean, choice def ask(questions, answers={}): diff --git a/pyqa/questions.py b/pyqa/questions.py index 2202f82..548e93b 100644 --- a/pyqa/questions.py +++ b/pyqa/questions.py @@ -1,5 +1,6 @@ from __future__ import print_function from string import lower +from copy import copy def boolean(answers): @@ -19,11 +20,19 @@ def in_range(o, i, j): except (TypeError, ValueError): return False lower_choices = map(lower, choices) + shown_choices = copy(choices) + shown_choices.append('Other') answer = '' while (not in_range(answer, 0, len(choices) - 1)) and (answer.lower() not in lower_choices): - map(lambda (i, c): print(str(i) + ': ' + c), enumerate(choices)) - answer = answers.next() or '' + map(lambda (i, c): print(str(i) + ': ' + c), enumerate(shown_choices)) + answer = answers.next().strip() or '' + + if answer == str(len(choices)) or answer.lower() == 'other': + answer = '' + while not answer: + answer = answers.next().strip() + break try: return choices[int(answer)] diff --git a/pyqa/questions.spec b/pyqa/questions.spec index 0d892fa..d750ee7 100644 --- a/pyqa/questions.spec +++ b/pyqa/questions.spec @@ -32,3 +32,12 @@ accepts choice by name with upper asks choice multiple times questions.choice(['foo', 'bar', 'baz'], values('zob', '3', '2')) == 'baz' +accepts other choice + questions.choice(['foo', 'bar', 'baz'], values('3', 'booboo')) == 'booboo' + +accepts other choice by name + questions.choice(['foo', 'bar', 'baz'], values('other', 'booboo')) == 'booboo' + +accepts other choice by name with upper + questions.choice(['foo', 'bar', 'baz'], values('oTher', 'booboo')) == 'booboo' +