Skip to content

Commit 3e46f9f

Browse files
authored
gh-100268: Add is_integer method to int (#100439)
This improves the lives of type annotation users of `float` - which type checkers implicitly treat as `int|float` because that is what most code actually wants. Before this change a `.is_integer()` method could not be assumed to exist on things annotated as `: float` due to the method not existing on both types.
1 parent a23cb72 commit 3e46f9f

File tree

5 files changed

+45
-1
lines changed

5 files changed

+45
-1
lines changed

Doc/library/stdtypes.rst

+6
Original file line numberDiff line numberDiff line change
@@ -609,6 +609,12 @@ class`. In addition, it provides a few more methods:
609609

610610
.. versionadded:: 3.8
611611

612+
.. method:: int.is_integer()
613+
614+
Returns ``True``. Exists for duck type compatibility with :meth:`float.is_integer`.
615+
616+
.. versionadded:: 3.12
617+
612618
Additional Methods on Float
613619
---------------------------
614620

Lib/test/test_long.py

+5
Original file line numberDiff line numberDiff line change
@@ -1553,6 +1553,11 @@ def test_from_bytes_small(self):
15531553
b = i.to_bytes(2, signed=True)
15541554
self.assertIs(int.from_bytes(b, signed=True), i)
15551555

1556+
def test_is_integer(self):
1557+
self.assertTrue((-1).is_integer())
1558+
self.assertTrue((0).is_integer())
1559+
self.assertTrue((1).is_integer())
1560+
15561561
def test_access_to_nonexistent_digit_0(self):
15571562
# http://bugs.python.org/issue14630: A bug in _PyLong_Copy meant that
15581563
# ob_digit[0] was being incorrectly accessed for instances of a
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add :meth:`int.is_integer` to improve duck type compatibility between :class:`int` and :class:`float`.

Objects/clinic/longobject.c.h

+19-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Objects/longobject.c

+14
Original file line numberDiff line numberDiff line change
@@ -6168,6 +6168,19 @@ long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
61686168
return long_long(self);
61696169
}
61706170

6171+
/*[clinic input]
6172+
int.is_integer
6173+
6174+
Returns True. Exists for duck type compatibility with float.is_integer.
6175+
[clinic start generated code]*/
6176+
6177+
static PyObject *
6178+
int_is_integer_impl(PyObject *self)
6179+
/*[clinic end generated code: output=90f8e794ce5430ef input=7e41c4d4416e05f2]*/
6180+
{
6181+
Py_RETURN_TRUE;
6182+
}
6183+
61716184
static PyMethodDef long_methods[] = {
61726185
{"conjugate", long_long_meth, METH_NOARGS,
61736186
"Returns self, the complex conjugate of any int."},
@@ -6186,6 +6199,7 @@ static PyMethodDef long_methods[] = {
61866199
INT___GETNEWARGS___METHODDEF
61876200
INT___FORMAT___METHODDEF
61886201
INT___SIZEOF___METHODDEF
6202+
INT_IS_INTEGER_METHODDEF
61896203
{NULL, NULL} /* sentinel */
61906204
};
61916205

0 commit comments

Comments
 (0)