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


gtsam
Author(s):
autogenerated on Sat Jun 1 2024 03:06:08