Skip to content

Commit

Permalink
Replace deprecated strtobool function (#3760)
Browse files Browse the repository at this point in the history
The `distutils` module has been deprecated in Python 3.10 and removed in
Python 3.12, [see docs
distutils](https://docs.python.org/3/library/distutils.html).

The [migration
advice](https://peps.python.org/pep-0632/#migration-advice):
> For these functions, and any others not mentioned here, you will need
to reimplement the functionality yourself.
> `distutils.util.strtobool`

Copied the strtobool function from 3.11 and adjusted it to return
booleans, like our function did.
  • Loading branch information
koopmant authored Dec 19, 2024
1 parent 8b24beb commit 9982797
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 4 deletions.
18 changes: 14 additions & 4 deletions app/grandchallenge/core/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from distutils.util import strtobool as strtobool_i
from functools import wraps


Expand All @@ -16,6 +15,17 @@ def wrapper(*args, **kwargs):
return wrapper


def strtobool(val) -> bool:
"""Return disutils.util.strtobool as a boolean."""
return bool(strtobool_i(val))
def strtobool(val):
"""Convert a string representation of truth to true or false.
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return True
elif val in ("n", "no", "f", "false", "off", "0"):
return False
else:
raise ValueError(f"invalid truth value {val}")
39 changes: 39 additions & 0 deletions app/tests/core_tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import pytest

from grandchallenge.core.utils import strtobool


@pytest.mark.parametrize(
"val, result",
[
("y", True),
("Y", True),
("yes", True),
("Yes", True),
("true", True),
("True", True),
("t", True),
("T", True),
("on", True),
("On", True),
("1", True),
("n", False),
("N", False),
("no", False),
("No", False),
("false", False),
("False", False),
("f", False),
("F", False),
("off", False),
("Off", False),
("0", False),
],
)
def test_strtobool(val, result):
assert strtobool(val) is result


def test_strtobool_exception():
with pytest.raises(ValueError):
strtobool("foobar")

0 comments on commit 9982797

Please sign in to comment.