test_callbacks.py
Go to the documentation of this file.
1 from __future__ import annotations
2 
3 import sys
4 import time
5 from threading import Thread
6 
7 import pytest
8 
9 import env # noqa: F401
10 from pybind11_tests import callbacks as m
11 from pybind11_tests import detailed_error_messages_enabled
12 
13 
15  from functools import partial
16 
17  def func1():
18  return "func1"
19 
20  def func2(a, b, c, d):
21  return "func2", a, b, c, d
22 
23  def func3(a):
24  return f"func3({a})"
25 
26  assert m.test_callback1(func1) == "func1"
27  assert m.test_callback2(func2) == ("func2", "Hello", "x", True, 5)
28  assert m.test_callback1(partial(func2, 1, 2, 3, 4)) == ("func2", 1, 2, 3, 4)
29  assert m.test_callback1(partial(func3, "partial")) == "func3(partial)"
30  assert m.test_callback3(lambda i: i + 1) == "func(43) = 44"
31 
32  f = m.test_callback4()
33  assert f(43) == 44
34  f = m.test_callback5()
35  assert f(number=43) == 44
36 
37 
39  # Bound Python method:
40  class MyClass:
41  def double(self, val):
42  return 2 * val
43 
44  z = MyClass()
45  assert m.test_callback3(z.double) == "func(43) = 86"
46 
47  z = m.CppBoundMethodTest()
48  assert m.test_callback3(z.triple) == "func(43) = 129"
49 
50 
52  def f(*args, **kwargs):
53  return args, kwargs
54 
55  assert m.test_tuple_unpacking(f) == (("positional", 1, 2, 3, 4, 5, 6), {})
56  assert m.test_dict_unpacking(f) == (
57  ("positional", 1),
58  {"key": "value", "a": 1, "b": 2},
59  )
60  assert m.test_keyword_args(f) == ((), {"x": 10, "y": 20})
61  assert m.test_unpacking_and_keywords1(f) == ((1, 2), {"c": 3, "d": 4})
62  assert m.test_unpacking_and_keywords2(f) == (
63  ("positional", 1, 2, 3, 4, 5),
64  {"key": "value", "a": 1, "b": 2, "c": 3, "d": 4, "e": 5},
65  )
66 
67  with pytest.raises(TypeError) as excinfo:
68  m.test_unpacking_error1(f)
69  assert "Got multiple values for keyword argument" in str(excinfo.value)
70 
71  with pytest.raises(TypeError) as excinfo:
72  m.test_unpacking_error2(f)
73  assert "Got multiple values for keyword argument" in str(excinfo.value)
74 
75  with pytest.raises(RuntimeError) as excinfo:
76  m.test_arg_conversion_error1(f)
77  assert str(excinfo.value) == "Unable to convert call argument " + (
78  "'1' of type 'UnregisteredType' to Python object"
79  if detailed_error_messages_enabled
80  else "'1' to Python object (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)"
81  )
82 
83  with pytest.raises(RuntimeError) as excinfo:
84  m.test_arg_conversion_error2(f)
85  assert str(excinfo.value) == "Unable to convert call argument " + (
86  "'expected_name' of type 'UnregisteredType' to Python object"
87  if detailed_error_messages_enabled
88  else "'expected_name' to Python object "
89  "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)"
90  )
91 
92 
94  m.test_lambda_closure_cleanup()
95  cstats = m.payload_cstats()
96  assert cstats.alive() == 0
97  assert cstats.copy_constructions == 1
98  assert cstats.move_constructions >= 1
99 
100 
102  alive_counts = m.test_cpp_callable_cleanup()
103  assert alive_counts == [0, 1, 2, 1, 2, 1, 0]
104 
105 
107  """Test if passing a function pointer from C++ -> Python -> C++ yields the original pointer"""
108 
109  assert (
110  m.test_dummy_function(m.dummy_function) == "matches dummy_function: eval(1) = 2"
111  )
112  assert (
113  m.test_dummy_function(m.roundtrip(m.dummy_function))
114  == "matches dummy_function: eval(1) = 2"
115  )
116  assert (
117  m.test_dummy_function(m.dummy_function_overloaded)
118  == "matches dummy_function: eval(1) = 2"
119  )
120  assert m.roundtrip(None, expect_none=True) is None
121  assert (
122  m.test_dummy_function(lambda x: x + 2)
123  == "can't convert to function pointer: eval(1) = 3"
124  )
125 
126  with pytest.raises(TypeError) as excinfo:
127  m.test_dummy_function(m.dummy_function2)
128  assert "incompatible function arguments" in str(excinfo.value)
129 
130  with pytest.raises(TypeError) as excinfo:
131  m.test_dummy_function(lambda x, y: x + y)
132  assert any(
133  s in str(excinfo.value)
134  for s in ("missing 1 required positional argument", "takes exactly 2 arguments")
135  )
136 
137 
139  assert doc(m.test_callback3) == "test_callback3(arg0: Callable[[int], int]) -> str"
140  assert doc(m.test_callback4) == "test_callback4() -> Callable[[int], int]"
141 
142 
144  assert m.callback_with_movable(lambda _: None) is True
145 
146 
147 @pytest.mark.skipif(
148  "env.PYPY",
149  reason="PyPy segfaults on here. See discussion on #1413.",
150 )
152  """Test if python builtins like sum() can be used as callbacks"""
153  assert m.test_sum_builtin(sum, [1, 2, 3]) == 6
154  assert m.test_sum_builtin(sum, []) == 0
155 
156 
157 @pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads")
159  # serves as state for async callback
160  class Item:
161  def __init__(self, value):
162  self.value = value
163 
164  res = []
165 
166  # generate stateful lambda that will store result in `res`
167  def gen_f():
168  s = Item(3)
169  return lambda j: res.append(s.value + j)
170 
171  # do some work async
172  work = [1, 2, 3, 4]
173  m.test_async_callback(gen_f(), work)
174  # wait until work is done
175  from time import sleep
176 
177  sleep(0.5)
178  assert sum(res) == sum(x + 3 for x in work)
179 
180 
181 @pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads")
183  t = Thread(target=test_async_callbacks)
184  t.start()
185  t.join()
186 
187 
189  # Super-simple micro-benchmarking related to PR #2919.
190  # Example runtimes (Intel Xeon 2.2GHz, fully optimized):
191  # num_millions 1, repeats 2: 0.1 secs
192  # num_millions 20, repeats 10: 11.5 secs
193  one_million = 1000000
194  num_millions = 1 # Try 20 for actual micro-benchmarking.
195  repeats = 2 # Try 10.
196  rates = []
197  for rep in range(repeats):
198  t0 = time.time()
199  m.callback_num_times(lambda: None, num_millions * one_million)
200  td = time.time() - t0
201  rate = num_millions / td if td else 0
202  rates.append(rate)
203  if not rep:
204  print()
205  print(
206  f"callback_num_times: {num_millions:d} million / {td:.3f} seconds = {rate:.3f} million / second"
207  )
208  if len(rates) > 1:
209  print("Min Mean Max")
210  print(f"{min(rates):6.3f} {sum(rates) / len(rates):6.3f} {max(rates):6.3f}")
211 
212 
214  assert m.custom_function(4) == 36
215  assert m.roundtrip(m.custom_function)(4) == 36
216 
217 
218 @pytest.mark.skipif(
219  m.custom_function2 is None, reason="Current PYBIND11_INTERNALS_VERSION too low"
220 )
222  assert m.custom_function2(3) == 27
223  assert m.roundtrip(m.custom_function2)(3) == 27
224 
225 
227  assert (
228  m.test_tuple_unpacking.__doc__.strip()
229  == "test_tuple_unpacking(arg0: Callable) -> object"
230  )
Eigen::internal::print
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
Definition: NEON/PacketMath.h:3115
test_callbacks.test_movable_object
def test_movable_object()
Definition: test_callbacks.py:143
test_callbacks.test_custom_func
def test_custom_func()
Definition: test_callbacks.py:213
test_callbacks.test_function_signatures
def test_function_signatures(doc)
Definition: test_callbacks.py:138
test_callbacks.test_callback_docstring
def test_callback_docstring()
Definition: test_callbacks.py:226
test_callbacks.test_async_callbacks
def test_async_callbacks()
Definition: test_callbacks.py:158
test_trampoline.func2
def func2()
Definition: test_trampoline.py:14
gtsam::range
Double_ range(const Point2_ &p, const Point2_ &q)
Definition: slam/expressions.h:30
test_callbacks.test_lambda_closure_cleanup
def test_lambda_closure_cleanup()
Definition: test_callbacks.py:93
doc
Annotation for documentation.
Definition: attr.h:45
test_callbacks.test_callbacks
def test_callbacks()
Definition: test_callbacks.py:14
test_callbacks.test_cpp_callable_cleanup
def test_cpp_callable_cleanup()
Definition: test_callbacks.py:101
test_callbacks.test_python_builtins
def test_python_builtins()
Definition: test_callbacks.py:151
test_callbacks.test_async_async_callbacks
def test_async_async_callbacks()
Definition: test_callbacks.py:182
gtwrap.interface_parser.function.__init__
def __init__(self, Union[Type, TemplatedType] ctype, str name, ParseResults default=None)
Definition: interface_parser/function.py:41
str
Definition: pytypes.h:1560
tree::f
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
Definition: testExpression.cpp:218
test_callbacks.test_cpp_function_roundtrip
def test_cpp_function_roundtrip()
Definition: test_callbacks.py:106
test_callbacks.test_bound_method_callback
def test_bound_method_callback()
Definition: test_callbacks.py:38
test_callbacks.test_custom_func2
def test_custom_func2()
Definition: test_callbacks.py:221
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2448
test_callbacks.test_keyword_args_and_generalized_unpacking
def test_keyword_args_and_generalized_unpacking()
Definition: test_callbacks.py:51
test_callbacks.test_callback_num_times
def test_callback_num_times()
Definition: test_callbacks.py:188


gtsam
Author(s):
autogenerated on Thu Apr 10 2025 03:06:04