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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# str2bool v.1.1
# str2bool

## About
Convert string to boolean.
Expand Down
42 changes: 42 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
[project]
name = "str2bool"
version = "1.2"
description = "Convert string to boolean"
authors = [
{ name = "SymonSoft", email = "symonsoft@gmail.com" },
{ name = "Gene Pasquet", email = "gene.pasquet@flyr.com" },
]
readme = "README.md"
requires-python = ">=3.7"
keywords = [
"str2bool",
"bool",
"boolean",
"convert",
"yes",
"no",
"true",
"false",
]
license = { text = "BSD License" }
classifiers = [
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Topic :: Utilities",
]

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[dependency-groups]
dev = [
"pytest>=7.0",
]

[project.urls]
Homepage = "https://github.com/symonsoft/str2bool"
Download = "https://github.com/symonsoft/str2bool/tarball/1.2"
2 changes: 0 additions & 2 deletions setup.cfg

This file was deleted.

24 changes: 0 additions & 24 deletions setup.py

This file was deleted.

37 changes: 29 additions & 8 deletions str2bool/__init__.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
import sys
from typing import Optional, cast

_true_set = {'yes', 'true', 't', 'y', '1'}
_false_set = {'no', 'false', 'f', 'n', '0'}
_true_set = {"yes", "true", "t", "y", "1"}
_false_set = {"no", "false", "f", "n", "0"}


def str2bool(value, raise_exc=False):
if isinstance(value, str) or sys.version_info[0] < 3 and isinstance(value, basestring):
def str2bool(value: str, raise_exc: bool = False) -> Optional[bool]:
"""
Convert a string to a boolean value.

Args:
value (str): The string to convert.
raise_exc (bool, optional): Whether to raise an exception if the string cannot be converted. Defaults to False.

Returns:
Optional[bool]: The converted boolean value, or None if the string cannot be converted and raise_exc is False.
"""
if isinstance(value, str):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ain't we loosing some backward compatibility?

value = value.lower()
if value in _true_set:
return True
if value in _false_set:
return False

if raise_exc:
raise ValueError('Expected "%s"' % '", "'.join(_true_set | _false_set))
raise ValueError('Expected "{}"'.format('", "'.join(_true_set | _false_set)))

return None


def str2bool_exc(value):
return str2bool(value, raise_exc=True)
def str2bool_exc(value: str) -> bool:
"""
Convert a string to a boolean value, raising an exception if the string cannot be converted.

Args:
value (str): The string to convert.

Returns:
bool: The converted boolean value.
"""
# This is guaranteed to return a bool with `raise_exc=True`
return cast(bool, str2bool(value, raise_exc=True))
Empty file added str2bool/py.typed
Empty file.
116 changes: 116 additions & 0 deletions tests/test_str2bool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import pytest

from str2bool import str2bool, str2bool_exc


class TestStr2Bool:
@pytest.mark.parametrize(
"value,expected",
[
("yes", True),
("true", True),
("t", True),
("y", True),
("1", True),
("YES", True),
("True", True),
("T", True),
("Y", True),
("no", False),
("false", False),
("f", False),
("n", False),
("0", False),
("NO", False),
("False", False),
("F", False),
("N", False),
],
)
def test_valid_inputs(self, value, expected):
"""Test str2bool with valid inputs."""
assert str2bool(value) == expected

@pytest.mark.parametrize(
"value",
[
"invalid",
"maybe",
"2",
"",
None,
123, # Non-string input
True, # Boolean input
],
)
def test_invalid_inputs_no_exception(self, value):
"""Test str2bool with invalid inputs (no exception)."""
assert str2bool(value) is None

@pytest.mark.parametrize(
"value",
[
"invalid",
"maybe",
"2",
"",
None,
123, # Non-string input
True, # Boolean input
],
)
def test_invalid_inputs_with_exception(self, value):
"""Test str2bool with invalid inputs (with exception)."""
with pytest.raises(ValueError):
str2bool(value, raise_exc=True)


class TestStr2BoolExc:
@pytest.mark.parametrize(
"value,expected",
[
("yes", True),
("true", True),
("t", True),
("y", True),
("1", True),
("YES", True),
("True", True),
("T", True),
("Y", True),
("no", False),
("false", False),
("f", False),
("n", False),
("0", False),
("NO", False),
("False", False),
("F", False),
("N", False),
],
)
def test_valid_inputs(self, value, expected):
"""Test str2bool_exc with valid inputs."""
assert str2bool_exc(value) == expected

@pytest.mark.parametrize(
"value",
[
"invalid",
"maybe",
"2",
"",
None,
123, # Non-string input
True, # Boolean input
],
)
def test_invalid_inputs(self, value):
"""Test str2bool_exc with invalid inputs."""
with pytest.raises(ValueError):
str2bool_exc(value)

def test_return_type(self):
"""Test that str2bool_exc returns a bool type."""
result = str2bool_exc("yes")
assert isinstance(result, bool)
Loading