-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
84 additions
and
2 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
Empty file.
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,21 @@ | ||
from typing import Any, Optional | ||
|
||
_TRUTHY_VALUES = {"t", "true", "1"} | ||
_FALSY_VALUES = {"f", "false", "0"} | ||
|
||
|
||
def smart_bool_or_none(value: Any) -> Optional[bool]: | ||
if isinstance(value, str): | ||
normalized_value = value.lower() | ||
if normalized_value in _TRUTHY_VALUES: | ||
return True | ||
if normalized_value in _FALSY_VALUES: | ||
return False | ||
return None | ||
if value is None: | ||
return None | ||
return bool(value) | ||
|
||
|
||
def smart_bool(value: Any) -> bool: | ||
return smart_bool_or_none(value) or False |
Empty file.
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,55 @@ | ||
import pytest | ||
|
||
from fzw.util.common import smart_bool, smart_bool_or_none | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"input,output", | ||
( | ||
(False, False), | ||
(True, True), | ||
(0, False), | ||
(1, True), | ||
(1.0, True), | ||
(0.1, True), | ||
("", False), | ||
("none", False), | ||
("nil", False), | ||
("0", False), | ||
("false", False), | ||
("False", False), | ||
("f", False), | ||
("1", True), | ||
("true", True), | ||
("True", True), | ||
("t", True), | ||
), | ||
) | ||
def test_smart_bool(input, output): | ||
assert smart_bool(input) == output | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"input,output", | ||
( | ||
(False, False), | ||
(True, True), | ||
(0, False), | ||
(1, True), | ||
(1.0, True), | ||
(0.1, True), | ||
("", None), | ||
("none", None), | ||
("nil", None), | ||
("0", False), | ||
("false", False), | ||
("False", False), | ||
("f", False), | ||
("1", True), | ||
("true", True), | ||
("True", True), | ||
("t", True), | ||
), | ||
) | ||
def test_smart_bool_or_none(input, output): | ||
assert smart_bool_or_none(input) == output |