Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature(utils): add a basic str2bool util #284

Merged
merged 2 commits into from
May 31, 2024
Merged
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
64 changes: 64 additions & 0 deletions dicogis/utils/str2bool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#! python3 # noqa: E265

"""
Basic string to bool.
"""

# #############################################################################
# ########## Libraries #############
# ##################################

# Standard library
import logging

# #############################################################################
# ########## Globals ###############
# ##################################

_true_set = {"on", "t", "true", "y", "yes", "1"}
_false_set = {"f", "false", "n", "no", "off", "0"}
logger = logging.getLogger(__name__)

# #############################################################################
# ########## Functions #############
# ##################################


def str2bool(input_var: bool | str, raise_exc: bool = False) -> bool | None:
"""Determine if a string is a bool and, if so, convert it.

Args:
input_var (str): value to convert
raise_exc (bool, optional): strict mode, defaults to False. Defaults to False.

Raises:
ValueError: input_var is not in true and false sets
TypeError: if input_var is not a str or a bool

Returns:
bool: True if input_var is in _true_set, False if it's in _false_set.
None or Exception if not in any of two sets.
"""
if isinstance(input_var, str):
value = input_var.lower()
if value in _true_set:
return True
if value in _false_set:
return False

error_message = 'Expected "%s"' % '", "'.join(_true_set | _false_set)
if raise_exc:
raise ValueError(error_message)
else:
logger.error(error_message)
return None
elif isinstance(input_var, bool):
logger.debug(f"Value {input_var} was already a bool.")
return input_var
else:
error_message = f"Value must be a str, not {type(input_var)}"
if raise_exc:
raise TypeError(error_message)
else:
logger.error(error_message)
return None
48 changes: 48 additions & 0 deletions tests/test_utils_str2bool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#! python3 # noqa E265

"""
Usage from the repo root folder:

.. code-block:: bash
# for whole tests
python -m unittest tests.test_utils_str2bool
# for specific test
python -m unittest tests.test_utils_str2bool.TestUtilsStrToBool.test_str2bool
"""

# standard library
import unittest

# project
from dicogis.utils.str2bool import str2bool

# ############################################################################
# ########## Classes #############
# ################################


class TestUtilsStrToBool(unittest.TestCase):
"""Test package utilities."""

def test_str2bool(self):
"""Test str2bool."""
# OK
self.assertTrue(str2bool("True"))
self.assertTrue(str2bool(True))
self.assertFalse(str2bool("False", raise_exc=True))
self.assertIsNone(str2bool("faux", raise_exc=False))

# KO
with self.assertRaises(TypeError):
str2bool(input_var=int(10), raise_exc=True)
self.assertIsNone(str2bool(input_var=int(10), raise_exc=False))

with self.assertRaises(ValueError):
str2bool(input_var="vrai", raise_exc=True)


# ############################################################################
# ####### Stand-alone run ########
# ################################
if __name__ == "__main__":
unittest.main()
Loading