This repository has been archived by the owner on Oct 23, 2019. It is now read-only.
forked from edwardslabs/CloudBot
-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #609 from linuxdaemon/gonzobot+parse-bool
Move str -> bool parsing to text util
- Loading branch information
Showing
2 changed files
with
51 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
from typing import Optional | ||
|
||
__all__ = ('parse_bool',) | ||
|
||
_STR_TO_BOOL = { | ||
"yes": True, | ||
"y": True, | ||
"no": False, | ||
"n": False, | ||
"on": True, | ||
"off": False, | ||
"enable": True, | ||
"disable": False, | ||
"allow": True, | ||
"deny": False, | ||
"true": True, | ||
"false": False, | ||
} | ||
|
||
|
||
def parse_bool(s: str, *, fail_on_unknown: bool = True) -> Optional[bool]: | ||
""" | ||
Parse a string to a boolean value | ||
>>> parse_bool('true') | ||
True | ||
>>> parse_bool('yes') | ||
True | ||
>>> parse_bool('no') | ||
False | ||
>>> parse_bool('maybe', fail_on_unknown=False) | ||
>>> parse_bool('maybe') | ||
Traceback (most recent call last): | ||
[...] | ||
KeyError: 'maybe' | ||
:param s: The string to parse | ||
:param fail_on_unknown: Whether to raise an error if the input can't | ||
be parsed | ||
:return: The parsed value | ||
""" | ||
|
||
try: | ||
return _STR_TO_BOOL[s.lower()] | ||
except KeyError: | ||
if fail_on_unknown: | ||
raise | ||
|
||
return None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters