Skip to content

Commit 4cb378a

Browse files
improve up-front typechecking
1 parent 96d1638 commit 4cb378a

File tree

1 file changed

+9
-10
lines changed

1 file changed

+9
-10
lines changed

mypy/config_parser.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,15 @@
1717

1818
from collections.abc import Mapping, MutableMapping, Sequence
1919
from typing import Any, Callable, Final, TextIO, Union
20-
from typing_extensions import TypeAlias as _TypeAlias
20+
from typing_extensions import TypeAlias, Never
2121

2222
from mypy import defaults
2323
from mypy.options import PER_MODULE_OPTIONS, Options
2424

25-
_CONFIG_VALUE_TYPES: _TypeAlias = Union[
25+
_CONFIG_VALUE_TYPES: TypeAlias = Union[
2626
str, bool, int, float, dict[str, str], list[str], tuple[int, int]
2727
]
28-
_INI_PARSER_CALLABLE: _TypeAlias = Callable[[Any], _CONFIG_VALUE_TYPES]
28+
_INI_PARSER_CALLABLE: TypeAlias = Callable[[Any], _CONFIG_VALUE_TYPES]
2929

3030

3131
class VersionTypeError(argparse.ArgumentTypeError):
@@ -60,21 +60,20 @@ def parse_version(v: str | float) -> tuple[int, int]:
6060
return major, minor
6161

6262

63-
def try_split(v: str | Sequence[str] | Any, split_regex: str = "[,]") -> list[str] | Any:
63+
def try_split(v: str | Sequence[str] | Any, split_regex: str = "[,]") -> list[str]:
6464
"""Split and trim a str or sequence (eg: list) of str into a list of str.
65-
Non-str elements will simply be returned untouched. Feel free to one day
66-
fix the typing of the calling code, and remove this caveat and Any."""
65+
If an element of the input is not str, a type error will be raised."""
66+
def complain(x: object, additional_info: str = "") -> Never:
67+
raise argparse.ArgumentTypeError(f"Expected a list or a stringified version thereof, but got: '{x}', of type {type(x)}.{additional_info}")
6768
if isinstance(v, str):
6869
items = [p.strip() for p in re.split(split_regex, v)]
6970
if items and items[-1] == "":
7071
items.pop(-1)
7172
return items
7273
elif isinstance(v, Sequence):
73-
return [p.strip() if isinstance(p, str) else p for p in v]
74+
return [p.strip() if isinstance(p, str) else complain(p, additional_info=" (As an element of the list.)") for p in v]
7475
else:
75-
raise argparse.ArgumentTypeError(
76-
f"Expected a list or a stringified version thereof, but got: '{v}'"
77-
)
76+
complain(v)
7877

7978

8079
def validate_codes(codes: list[str]) -> list[str]:

0 commit comments

Comments
 (0)