Matching Python 2 int behavior on Python 2 (#1186)
Pybind11's default conversion to int always produces a long on Python 2 (`int`s and `long`s were unified in Python 3). This patch fixes `int` handling to match Python 2 on Python 2; for short types (`size_t` or smaller), the number will be returned as an `int` if possible, otherwise `long`. Requires Python 2.5+.
This is needed for things like `sys.exit`, which refuse to accept a `long`.
diff --git a/tests/test_builtin_casters.py b/tests/test_builtin_casters.py
index 2f311f1..01d0437 100644
--- a/tests/test_builtin_casters.py
+++ b/tests/test_builtin_casters.py
@@ -323,3 +323,16 @@
assert convert(np.bool_(False)) is False
assert noconvert(np.bool_(True)) is True
assert noconvert(np.bool_(False)) is False
+
+
+def test_int_long():
+ """In Python 2, a C++ int should return a Python int rather than long
+ if possible: longs are not always accepted where ints are used (such
+ as the argument to sys.exit()). A C++ long long is always a Python
+ long."""
+
+ import sys
+ must_be_long = type(getattr(sys, 'maxint', 1) + 1)
+ assert isinstance(m.int_cast(), int)
+ assert isinstance(m.long_cast(), int)
+ assert isinstance(m.longlong_cast(), must_be_long)