Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions prompt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,47 @@ def string(prompt=None, empty=False):
return string(prompt=prompt, empty=empty)


def boolean(prompt=None, default=None):
"""Prompt a yes or no question.

Parameters
----------
prompt : str, optional
Use an alternative prompt.
default : bool, optional
Set a default response

Returns
-------
bool
A bool indicating the response
"""

if not prompt:
prompt = PROMPT
if default is None:
prompt_addition = ' (y/n): '
elif default:
prompt_addition = ' (Y/n): '
else:
prompt_addition = ' (y/N): '

prompt += prompt_addition
response = None
while response is None:
# Keep asking for a response until either the default or a proper char is used
char = character(prompt, empty=True)
if char is None:
# Use the default if no response. If no default is set, the loop will repeat
response = default
elif char.lower() == 'y':
response = True
elif char.lower() == 'n':
response = False

return response


def _prompt_input(prompt):
if prompt is None:
return input(PROMPT)
Expand Down
11 changes: 11 additions & 0 deletions tests/test_expected.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,14 @@ def test_secret(input_patch):
def test_string(input_patch):
input_patch.do("foo123")
assert prompt.string() == "foo123"


def test_boolean(input_patch):
input_patch.do("Y")
assert prompt.boolean() == True
input_patch.do("y")
assert prompt.boolean() == True
input_patch.do("N")
assert prompt.boolean() == False
input_patch.do("n")
assert prompt.boolean() == False