|
| 1 | +# Copyright (c) MONAI Consortium |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +"""Standalone utility function for string to boolean conversion. |
| 13 | +
|
| 14 | +This module exists separately to avoid circular import dependencies. |
| 15 | +""" |
| 16 | + |
| 17 | + |
| 18 | +def strtobool(s): |
| 19 | + """Convert a string representation of truth to true or false. |
| 20 | +
|
| 21 | + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values |
| 22 | + are 'n', 'no', 'f', 'false', 'off', and '0'. Returns the input if |
| 23 | + already a bool. Returns False if None. |
| 24 | + """ |
| 25 | + if s is None: |
| 26 | + return False |
| 27 | + if isinstance(s, bool): |
| 28 | + return s |
| 29 | + if not isinstance(s, str): |
| 30 | + raise TypeError(f"strtobool expects a string or bool, got {type(s).__name__}: {s!r}") |
| 31 | + |
| 32 | + val = s.lower() |
| 33 | + if val in ('y', 'yes', 't', 'true', 'on', '1'): |
| 34 | + return True |
| 35 | + elif val in ('n', 'no', 'f', 'false', 'off', '0'): |
| 36 | + return False |
| 37 | + else: |
| 38 | + raise ValueError(f"invalid truth value {s!r}") |
0 commit comments