diff --git a/AUTHORS.rst b/AUTHORS.rst index 72dd6aff..8e5282fc 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -80,3 +80,4 @@ Contributors - jwalith4418-Mj, `jwalith4418-Mj@github `_ - jihtsan, `jihtsan@github `_ - Jillur Rahman, `developerjillur@github `_ +- BooGu, `boogu2005@github `_ diff --git a/src/pydash/objects.py b/src/pydash/objects.py index 55a5a17e..df4e8093 100644 --- a/src/pydash/objects.py +++ b/src/pydash/objects.py @@ -2063,12 +2063,13 @@ def to_integer(obj: t.Any) -> int: .. versionadded:: 4.0.0 """ - if type(obj) is int: - return obj + # Keep subclasses exact unless they customize the float conversion protocol. + if isinstance(obj, int) and type(obj).__float__ is int.__float__: + return int.__int__(obj) - if type(obj) is str: + if isinstance(obj, str) and not hasattr(type(obj), "__float__"): try: - return int(obj) + return int(str.__str__(obj)) except ValueError: pass diff --git a/tests/test_objects.py b/tests/test_objects.py index 17089654..ef7c2e7c 100644 --- a/tests/test_objects.py +++ b/tests/test_objects.py @@ -3,6 +3,7 @@ from copy import deepcopy import datetime as dt from decimal import Decimal +from enum import IntEnum from types import SimpleNamespace import pytest @@ -1252,7 +1253,38 @@ def test_to_boolean(case, expected): ], ) def test_to_integer(case, expected): - assert _.to_integer(case) == expected + result = _.to_integer(case) + assert result == expected + assert type(result) is int + + +@parametrize("kind", ["int", "enum", "str"]) +@parametrize("expected", [0, 1, -1, 2**53 + 1, -(2**53 + 1), 10**400, -(10**400)]) +def test_to_integer_preserves_subclass_precision(kind, expected): + class IntegerSubclass(int): + pass + + class StringSubclass(str): + pass + + integer_enum = IntEnum("IntegerEnum", {"VALUE": expected}) + case = { + "int": IntegerSubclass(expected), + "enum": integer_enum.VALUE, + "str": StringSubclass(str(expected)), + }[kind] + + result = _.to_integer(case) + assert result == expected + assert type(result) is int + + +@parametrize("case,expected", [("1.9", 1), ("1e3", 1000), ("foo", 0), ("inf", 0)]) +def test_to_integer_string_subclass_fallback(case, expected): + class StringSubclass(str): + pass + + assert _.to_integer(StringSubclass(case)) == expected def test_to_integer_preserves_float_conversion_protocol():