diff options
Diffstat (limited to 'natsort/compat/fastnumbers.py')
-rw-r--r-- | natsort/compat/fastnumbers.py | 42 |
1 files changed, 39 insertions, 3 deletions
diff --git a/natsort/compat/fastnumbers.py b/natsort/compat/fastnumbers.py index 049030d..b4ae5cc 100644 --- a/natsort/compat/fastnumbers.py +++ b/natsort/compat/fastnumbers.py @@ -4,11 +4,17 @@ Interface for natsort to access fastnumbers functions without having to worry if it is actually installed. """ import re +from typing import Callable, Iterable, Iterator, Literal, Tuple, Union -__all__ = ["fast_float", "fast_int"] +StrOrFloat = Union[str, float] +StrOrInt = Union[str, int] +__all__ = ["try_float", "try_int"] -def is_supported_fastnumbers(fastnumbers_version: str) -> bool: + +def is_supported_fastnumbers( + fastnumbers_version: str, minimum: Tuple[int, int, int] = (2, 0, 0) +) -> bool: match = re.match( r"^(\d+)\.(\d+)(\.(\d+))?([ab](\d+))?$", fastnumbers_version, @@ -22,7 +28,7 @@ def is_supported_fastnumbers(fastnumbers_version: str) -> bool: (major, minor, patch) = match.group(1, 2, 4) - return (int(major), int(minor), int(patch)) >= (2, 0, 0) + return (int(major), int(minor), int(patch)) >= minimum # If the user has fastnumbers installed, they will get great speed @@ -34,5 +40,35 @@ try: # Require >= version 2.0.0. if not is_supported_fastnumbers(fn_ver): raise ImportError # pragma: no cover + + # For versions of fastnumbers with mapping capability, use that + if is_supported_fastnumbers(fn_ver, (5, 0, 0)): + del fast_float, fast_int + from fastnumbers import try_float, try_int except ImportError: from natsort.compat.fake_fastnumbers import fast_float, fast_int # type: ignore + +# Re-map the old-or-compatibility functions fast_float/fast_int to the +# newer API of try_float/try_int. If we already imported try_float/try_int +# then there is nothing to do. +if "try_float" not in globals(): + + def try_float( # noqa: F811, type: ignore[no-redef] + x: Iterable[str], + map: Literal[True], + nan: float = float("inf"), + on_fail: Callable[[str], str] = lambda x: x, + ) -> Iterator[StrOrFloat]: + assert map is True + return (fast_float(y, nan=nan, key=on_fail) for y in x) + + +if "try_int" not in globals(): + + def try_int( # noqa: F811, type: ignore[no-redef] + x: Iterable[str], + map: Literal[True], + on_fail: Callable[[str], str] = lambda x: x, + ) -> Iterator[StrOrInt]: + assert map is True + return (fast_int(y, key=on_fail) for y in x) |