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


gtsam
Author(s):
autogenerated on Sat Nov 16 2024 04:07:05