Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,4 @@ Contributors
- jwalith4418-Mj, `jwalith4418-Mj@github <https://github.com/jwalith4418-Mj>`_
- jihtsan, `jihtsan@github <https://github.com/jihtsan>`_
- Jillur Rahman, `developerjillur@github <https://github.com/developerjillur>`_
- BooGu, `boogu2005@github <https://github.com/boogu2005>`_
9 changes: 5 additions & 4 deletions src/pydash/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
34 changes: 33 additions & 1 deletion tests/test_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand Down