-
Notifications
You must be signed in to change notification settings - Fork 10
Modernise and type-hint str2bool #8
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
Open
pace-gene
wants to merge
5
commits into
symonsoft:master
Choose a base branch
from
pace-gene:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
87d2baf
Convert to UV, add tests, make the lib typed.
pace-gene e332ecc
Update readme
pace-gene 530dbf7
Update release classivfier
pace-gene 92fbb9c
Address PR comments
pace-gene 5ab5e67
Drop support for python 2, increase 3 support to 3.7+
pace-gene File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| # str2bool v.1.1 | ||
| # str2bool | ||
|
|
||
| ## About | ||
| Convert string to boolean. | ||
|
|
||
This file contains hidden or 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,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" |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains hidden or 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 |
|---|---|---|
| @@ -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): | ||
| 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.
This file contains hidden or 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,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) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?