pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

[FEATURE REQUEST]: typing.SupportsInt type hint

Open gentlegiantJGC opened this issue 1 year ago • 1 comments

Required prerequisites

  • [X] Make sure you've read the documentation. Your issue may be addressed there.
  • [X] Search the issue tracker and Discussions to verify that this hasn't already been reported. +1 or comment there if it has.
  • [x] Consider asking first in the Gitter chat room or in a Discussion.

What version (or hash if on master) of pybind11 are you using?

2.12.0

Problem description

It would be nice if functions/methods that accept objects which can be coerced into an int would be typed as such in the docstrings.

Functions that accept a C++ int type currently generate stub files that look like the following.

def test(value: int) -> None:
    ...

The function can also be called with any object that implements __int__ including numpy int types and custom objects.

from numpy import uint16
test(uint16(5))
class MyInt:
    def __int__(self) -> int:
        return 5

test(MyInt())

mypy complains about the function call because they are not subclasses of int.

If the intention of pybind in these cases is to accept any object that can be coerced into an int it would be nice if they could be type hinted as such.

The correct result would look like this

import typing
def test(value: typing.Union[int, typing.SupportsInt]) -> None:
    ...

or just

import typing
def test(value: typing.SupportsInt) -> None:
    ...

Reproducible example code

No response

Is this a regression? Put the last known working version here if it is.

Not a regression

gentlegiantJGC avatar Jun 10 '24 09:06 gentlegiantJGC

Seems like the type hint originates from here but it also effects the return type. I don't know what else that effects. https://github.com/pybind/pybind11/blob/67c9c5687b2488d36a674c5d60d67617fc8c4b91/include/pybind11/cast.h#L244

gentlegiantJGC avatar Jun 10 '24 10:06 gentlegiantJGC