test_pytypes.py
Go to the documentation of this file.
1 import contextlib
2 import sys
3 import types
4 
5 import pytest
6 
7 import env
8 from pybind11_tests import detailed_error_messages_enabled
9 from pybind11_tests import pytypes as m
10 
11 
13  assert m.obj_class_name(None) == "NoneType"
14  assert m.obj_class_name(list) == "list"
15  assert m.obj_class_name([]) == "list"
16 
17 
19  assert m.handle_from_move_only_type_with_operator_PyObject_ncnst()
20  assert m.handle_from_move_only_type_with_operator_PyObject_const()
21 
22 
23 def test_bool(doc):
24  assert doc(m.get_bool) == "get_bool() -> bool"
25 
26 
27 def test_int(doc):
28  assert doc(m.get_int) == "get_int() -> int"
29 
30 
31 def test_iterator(doc):
32  assert doc(m.get_iterator) == "get_iterator() -> Iterator"
33 
34 
35 @pytest.mark.parametrize(
36  ("pytype", "from_iter_func"),
37  [
38  (frozenset, m.get_frozenset_from_iterable),
39  (list, m.get_list_from_iterable),
40  (set, m.get_set_from_iterable),
41  (tuple, m.get_tuple_from_iterable),
42  ],
43 )
44 def test_from_iterable(pytype, from_iter_func):
45  my_iter = iter(range(10))
46  s = from_iter_func(my_iter)
47  assert type(s) == pytype
48  assert s == pytype(range(10))
49 
50 
51 def test_iterable(doc):
52  assert doc(m.get_iterable) == "get_iterable() -> Iterable"
53 
54 
55 def test_float(doc):
56  assert doc(m.get_float) == "get_float() -> float"
57 
58 
59 def test_list(capture, doc):
60  assert m.list_no_args() == []
61  assert m.list_ssize_t() == []
62  assert m.list_size_t() == []
63  lins = [1, 2]
64  m.list_insert_ssize_t(lins)
65  assert lins == [1, 83, 2]
66  m.list_insert_size_t(lins)
67  assert lins == [1, 83, 2, 57]
68 
69  with capture:
70  lst = m.get_list()
71  assert lst == ["inserted-0", "overwritten", "inserted-2"]
72 
73  lst.append("value2")
74  m.print_list(lst)
75  assert (
76  capture.unordered
77  == """
78  Entry at position 0: value
79  list item 0: inserted-0
80  list item 1: overwritten
81  list item 2: inserted-2
82  list item 3: value2
83  """
84  )
85 
86  assert doc(m.get_list) == "get_list() -> list"
87  assert doc(m.print_list) == "print_list(arg0: list) -> None"
88 
89 
90 def test_none(doc):
91  assert doc(m.get_none) == "get_none() -> None"
92  assert doc(m.print_none) == "print_none(arg0: None) -> None"
93 
94 
95 def test_set(capture, doc):
96  s = m.get_set()
97  assert isinstance(s, set)
98  assert s == {"key1", "key2", "key3"}
99 
100  s.add("key4")
101  with capture:
102  m.print_anyset(s)
103  assert (
104  capture.unordered
105  == """
106  key: key1
107  key: key2
108  key: key3
109  key: key4
110  """
111  )
112 
113  m.set_add(s, "key5")
114  assert m.anyset_size(s) == 5
115 
116  m.set_clear(s)
117  assert m.anyset_empty(s)
118 
119  assert not m.anyset_contains(set(), 42)
120  assert m.anyset_contains({42}, 42)
121  assert m.anyset_contains({"foo"}, "foo")
122 
123  assert doc(m.get_set) == "get_set() -> set"
124  assert doc(m.print_anyset) == "print_anyset(arg0: anyset) -> None"
125 
126 
127 def test_frozenset(capture, doc):
128  s = m.get_frozenset()
129  assert isinstance(s, frozenset)
130  assert s == frozenset({"key1", "key2", "key3"})
131 
132  with capture:
133  m.print_anyset(s)
134  assert (
135  capture.unordered
136  == """
137  key: key1
138  key: key2
139  key: key3
140  """
141  )
142  assert m.anyset_size(s) == 3
143  assert not m.anyset_empty(s)
144 
145  assert not m.anyset_contains(frozenset(), 42)
146  assert m.anyset_contains(frozenset({42}), 42)
147  assert m.anyset_contains(frozenset({"foo"}), "foo")
148 
149  assert doc(m.get_frozenset) == "get_frozenset() -> frozenset"
150 
151 
152 def test_dict(capture, doc):
153  d = m.get_dict()
154  assert d == {"key": "value"}
155 
156  with capture:
157  d["key2"] = "value2"
158  m.print_dict(d)
159  assert (
160  capture.unordered
161  == """
162  key: key, value=value
163  key: key2, value=value2
164  """
165  )
166 
167  assert not m.dict_contains({}, 42)
168  assert m.dict_contains({42: None}, 42)
169  assert m.dict_contains({"foo": None}, "foo")
170 
171  assert doc(m.get_dict) == "get_dict() -> dict"
172  assert doc(m.print_dict) == "print_dict(arg0: dict) -> None"
173 
174  assert m.dict_keyword_constructor() == {"x": 1, "y": 2, "z": 3}
175 
176 
178  d = {"key": None}
179 
180  def __contains__(self, m):
181  return m in self.d
182 
183 
184 @pytest.mark.parametrize(
185  ("arg", "func"),
186  [
187  (set(), m.anyset_contains),
188  ({}, m.dict_contains),
189  (CustomContains(), m.obj_contains),
190  ],
191 )
192 @pytest.mark.xfail("env.PYPY and sys.pypy_version_info < (7, 3, 10)", strict=False)
194  class Unhashable:
195  __hash__ = None
196 
197  with pytest.raises(TypeError) as exc_info:
198  func(arg, Unhashable())
199  assert "unhashable type:" in str(exc_info.value)
200 
201 
203  assert m.tuple_no_args() == ()
204  assert m.tuple_ssize_t() == ()
205  assert m.tuple_size_t() == ()
206  assert m.get_tuple() == (42, None, "spam")
207 
208 
210  ns = m.get_simple_namespace()
211  assert ns.attr == 42
212  assert ns.x == "foo"
213  assert ns.right == 2
214  assert not hasattr(ns, "wrong")
215 
216 
217 def test_str(doc):
218  assert m.str_from_char_ssize_t().encode().decode() == "red"
219  assert m.str_from_char_size_t().encode().decode() == "blue"
220  assert m.str_from_string().encode().decode() == "baz"
221  assert m.str_from_bytes().encode().decode() == "boo"
222 
223  assert doc(m.str_from_bytes) == "str_from_bytes() -> str"
224 
225  class A:
226  def __str__(self):
227  return "this is a str"
228 
229  def __repr__(self):
230  return "this is a repr"
231 
232  assert m.str_from_object(A()) == "this is a str"
233  assert m.repr_from_object(A()) == "this is a repr"
234  assert m.str_from_handle(A()) == "this is a str"
235 
236  s1, s2 = m.str_format()
237  assert s1 == "1 + 2 = 3"
238  assert s1 == s2
239 
240  malformed_utf8 = b"\x80"
241  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
242  assert m.str_from_object(malformed_utf8) is malformed_utf8
243  else:
244  assert m.str_from_object(malformed_utf8) == "b'\\x80'"
245  assert m.str_from_handle(malformed_utf8) == "b'\\x80'"
246 
247  assert m.str_from_string_from_str("this is a str") == "this is a str"
248  ucs_surrogates_str = "\udcc3"
249  with pytest.raises(UnicodeEncodeError):
250  m.str_from_string_from_str(ucs_surrogates_str)
251 
252 
253 @pytest.mark.parametrize(
254  "func",
255  [
256  m.str_from_bytes_input,
257  m.str_from_cstr_input,
258  m.str_from_std_string_input,
259  ],
260 )
262  input_str = "\ud83d\ude4f".encode("utf-8", "surrogatepass")
263  with pytest.raises(UnicodeDecodeError):
264  func(input_str)
265 
266 
267 def test_bytes(doc):
268  assert m.bytes_from_char_ssize_t().decode() == "green"
269  assert m.bytes_from_char_size_t().decode() == "purple"
270  assert m.bytes_from_string().decode() == "foo"
271  assert m.bytes_from_str().decode() == "bar"
272 
273  assert doc(m.bytes_from_str) == "bytes_from_str() -> bytes"
274 
275 
277  assert m.bytearray_from_char_ssize_t().decode() == "$%"
278  assert m.bytearray_from_char_size_t().decode() == "@$!"
279  assert m.bytearray_from_string().decode() == "foo"
280  assert m.bytearray_size() == len("foo")
281 
282 
283 def test_capsule(capture):
284  pytest.gc_collect()
285  with capture:
286  a = m.return_capsule_with_destructor()
287  del a
288  pytest.gc_collect()
289  assert (
290  capture.unordered
291  == """
292  creating capsule
293  destructing capsule
294  """
295  )
296 
297  with capture:
298  a = m.return_renamed_capsule_with_destructor()
299  del a
300  pytest.gc_collect()
301  assert (
302  capture.unordered
303  == """
304  creating capsule
305  renaming capsule
306  destructing capsule
307  """
308  )
309 
310  with capture:
311  a = m.return_capsule_with_destructor_2()
312  del a
313  pytest.gc_collect()
314  assert (
315  capture.unordered
316  == """
317  creating capsule
318  destructing capsule: 1234
319  """
320  )
321 
322  with capture:
323  a = m.return_capsule_with_destructor_3()
324  del a
325  pytest.gc_collect()
326  assert (
327  capture.unordered
328  == """
329  creating capsule
330  destructing capsule: 1233
331  original name: oname
332  """
333  )
334 
335  with capture:
336  a = m.return_renamed_capsule_with_destructor_2()
337  del a
338  pytest.gc_collect()
339  assert (
340  capture.unordered
341  == """
342  creating capsule
343  renaming capsule
344  destructing capsule: 1234
345  """
346  )
347 
348  with capture:
349  a = m.return_capsule_with_name_and_destructor()
350  del a
351  pytest.gc_collect()
352  assert (
353  capture.unordered
354  == """
355  created capsule (1234, 'pointer type description')
356  destructing capsule (1234, 'pointer type description')
357  """
358  )
359 
360  with capture:
361  a = m.return_capsule_with_explicit_nullptr_dtor()
362  del a
363  pytest.gc_collect()
364  assert (
365  capture.unordered
366  == """
367  creating capsule with explicit nullptr dtor
368  """
369  )
370 
371 
373  class SubTestObject:
374  attr_obj = 1
375  attr_char = 2
376 
377  class TestObject:
378  basic_attr = 1
379  begin_end = [1, 2, 3]
380  d = {"operator[object]": 1, "operator[char *]": 2}
381  sub = SubTestObject()
382 
383  def func(self, x, *args):
384  return self.basic_attr + x + sum(args)
385 
386  d = m.accessor_api(TestObject())
387  assert d["basic_attr"] == 1
388  assert d["begin_end"] == [1, 2, 3]
389  assert d["operator[object]"] == 1
390  assert d["operator[char *]"] == 2
391  assert d["attr(object)"] == 1
392  assert d["attr(char *)"] == 2
393  assert d["missing_attr_ptr"] == "raised"
394  assert d["missing_attr_chain"] == "raised"
395  assert d["is_none"] is False
396  assert d["operator()"] == 2
397  assert d["operator*"] == 7
398  assert d["implicit_list"] == [1, 2, 3]
399  assert all(x in TestObject.__dict__ for x in d["implicit_dict"])
400 
401  assert m.tuple_accessor(()) == (0, 1, 2)
402 
403  d = m.accessor_assignment()
404  assert d["get"] == 0
405  assert d["deferred_get"] == 0
406  assert d["set"] == 1
407  assert d["deferred_set"] == 1
408  assert d["var"] == 99
409 
410 
412  inc_refs = m.accessor_moves()
413  if inc_refs:
414  assert inc_refs == [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
415  else:
416  pytest.skip("Not defined: PYBIND11_HANDLE_REF_DEBUG")
417 
418 
420  """C++ default and converting constructors are equivalent to type calls in Python"""
421  types = [bytes, bytearray, str, bool, int, float, tuple, list, dict, set]
422  expected = {t.__name__: t() for t in types}
423  assert m.default_constructors() == expected
424 
425  data = {
426  bytes: b"41", # Currently no supported or working conversions.
427  bytearray: bytearray(b"41"),
428  str: 42,
429  bool: "Not empty",
430  int: "42",
431  float: "+1e3",
432  tuple: range(3),
433  list: range(3),
434  dict: [("two", 2), ("one", 1), ("three", 3)],
435  set: [4, 4, 5, 6, 6, 6],
436  frozenset: [4, 4, 5, 6, 6, 6],
437  memoryview: b"abc",
438  }
439  inputs = {k.__name__: v for k, v in data.items()}
440  expected = {k.__name__: k(v) for k, v in data.items()}
441 
442  assert m.converting_constructors(inputs) == expected
443  assert m.cast_functions(inputs) == expected
444 
445  # Converting constructors and cast functions should just reference rather
446  # than copy when no conversion is needed:
447  noconv1 = m.converting_constructors(expected)
448  for k in noconv1:
449  assert noconv1[k] is expected[k]
450 
451  noconv2 = m.cast_functions(expected)
452  for k in noconv2:
453  assert noconv2[k] is expected[k]
454 
455 
457  non_converting_test_cases = [
458  ("bytes", range(10)),
459  ("none", 42),
460  ("ellipsis", 42),
461  ("type", 42),
462  ]
463  for t, v in non_converting_test_cases:
464  for move in [True, False]:
465  with pytest.raises(TypeError) as excinfo:
466  m.nonconverting_constructor(t, v, move)
467  expected_error = (
468  f"Object of type '{type(v).__name__}' is not an instance of '{t}'"
469  )
470  assert str(excinfo.value) == expected_error
471 
472 
474  # specifically to exercise pybind11::str::raw_str
475  cvt = m.convert_to_pybind11_str
476  assert cvt("Str") == "Str"
477  assert cvt(b"Bytes") == "b'Bytes'"
478  assert cvt(None) == "None"
479  assert cvt(False) == "False"
480  assert cvt(True) == "True"
481  assert cvt(42) == "42"
482  assert cvt(2**65) == "36893488147419103232"
483  assert cvt(-1.50) == "-1.5"
484  assert cvt(()) == "()"
485  assert cvt((18,)) == "(18,)"
486  assert cvt([]) == "[]"
487  assert cvt([28]) == "[28]"
488  assert cvt({}) == "{}"
489  assert cvt({3: 4}) == "{3: 4}"
490  assert cvt(set()) == "set()"
491  assert cvt({3}) == "{3}"
492 
493  valid_orig = "DZ"
494  valid_utf8 = valid_orig.encode("utf-8")
495  valid_cvt = cvt(valid_utf8)
496  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
497  assert valid_cvt is valid_utf8
498  else:
499  assert type(valid_cvt) is str
500  assert valid_cvt == "b'\\xc7\\xb1'"
501 
502  malformed_utf8 = b"\x80"
503  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
504  assert cvt(malformed_utf8) is malformed_utf8
505  else:
506  malformed_cvt = cvt(malformed_utf8)
507  assert type(malformed_cvt) is str
508  assert malformed_cvt == "b'\\x80'"
509 
510 
512  """Tests implicit casting when assigning or appending to dicts and lists."""
513  z = m.get_implicit_casting()
514  assert z["d"] == {
515  "char*_i1": "abc",
516  "char*_i2": "abc",
517  "char*_e": "abc",
518  "char*_p": "abc",
519  "str_i1": "str",
520  "str_i2": "str1",
521  "str_e": "str2",
522  "str_p": "str3",
523  "int_i1": 42,
524  "int_i2": 42,
525  "int_e": 43,
526  "int_p": 44,
527  }
528  assert z["l"] == [3, 6, 9, 12, 15]
529 
530 
531 def test_print(capture):
532  with capture:
533  m.print_function()
534  assert (
535  capture
536  == """
537  Hello, World!
538  1 2.0 three True -- multiple args
539  *args-and-a-custom-separator
540  no new line here -- next print
541  flush
542  py::print + str.format = this
543  """
544  )
545  assert capture.stderr == "this goes to stderr"
546 
547  with pytest.raises(RuntimeError) as excinfo:
548  m.print_failure()
549  assert str(excinfo.value) == "Unable to convert call argument " + (
550  "'1' of type 'UnregisteredType' to Python object"
551  if detailed_error_messages_enabled
552  else "'1' to Python object (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)"
553  )
554 
555 
556 def test_hash():
557  class Hashable:
558  def __init__(self, value):
559  self.value = value
560 
561  def __hash__(self):
562  return self.value
563 
564  class Unhashable:
565  __hash__ = None
566 
567  assert m.hash_function(Hashable(42)) == 42
568  with pytest.raises(TypeError):
569  m.hash_function(Unhashable())
570 
571 
573  for a, b in [(1, 1), (3, 5)]:
574  li = [
575  a == b,
576  a != b,
577  a < b,
578  a <= b,
579  a > b,
580  a >= b,
581  a + b,
582  a - b,
583  a * b,
584  a / b,
585  a | b,
586  a & b,
587  a ^ b,
588  a >> b,
589  a << b,
590  ]
591  assert m.test_number_protocol(a, b) == li
592 
593 
595  li = list(range(100))
596  assert li[::2] == m.test_list_slicing(li)
597 
598 
600  # See issue #2361
601  assert m.issue2361_str_implicit_copy_none() == "None"
602  with pytest.raises(TypeError) as excinfo:
603  assert m.issue2361_dict_implicit_copy_none()
604  assert "NoneType" in str(excinfo.value)
605  assert "iterable" in str(excinfo.value)
606 
607 
608 @pytest.mark.parametrize(
609  ("method", "args", "fmt", "expected_view"),
610  [
611  (m.test_memoryview_object, (b"red",), "B", b"red"),
612  (m.test_memoryview_buffer_info, (b"green",), "B", b"green"),
613  (m.test_memoryview_from_buffer, (False,), "h", [3, 1, 4, 1, 5]),
614  (m.test_memoryview_from_buffer, (True,), "H", [2, 7, 1, 8]),
615  (m.test_memoryview_from_buffer_nativeformat, (), "@i", [4, 7, 5]),
616  ],
617 )
618 def test_memoryview(method, args, fmt, expected_view):
619  view = method(*args)
620  assert isinstance(view, memoryview)
621  assert view.format == fmt
622  assert list(view) == list(expected_view)
623 
624 
625 @pytest.mark.xfail("env.PYPY", reason="getrefcount is not available")
626 @pytest.mark.parametrize(
627  "method",
628  [
629  m.test_memoryview_object,
630  m.test_memoryview_buffer_info,
631  ],
632 )
634  buf = b"\x0a\x0b\x0c\x0d"
635  ref_before = sys.getrefcount(buf)
636  view = method(buf)
637  ref_after = sys.getrefcount(buf)
638  assert ref_before < ref_after
639  assert list(view) == list(buf)
640 
641 
643  view = m.test_memoryview_from_buffer_empty_shape()
644  assert isinstance(view, memoryview)
645  assert view.format == "B"
646  assert bytes(view) == b""
647 
648 
650  with pytest.raises(RuntimeError):
651  m.test_memoryview_from_buffer_invalid_strides()
652 
653 
655  with pytest.raises(ValueError):
656  m.test_memoryview_from_buffer_nullptr()
657 
658 
660  view = m.test_memoryview_from_memory()
661  assert isinstance(view, memoryview)
662  assert view.format == "B"
663  assert bytes(view) == b"\xff\xe1\xab\x37"
664 
665 
667  assert m.get_len(list(range(42))) == 42
668  with pytest.raises(TypeError) as exc_info:
669  m.get_len(i for i in range(42))
670  assert str(exc_info.value) in [
671  "object of type 'generator' has no len()",
672  "'generator' has no length",
673  ] # PyPy
674 
675 
677  assert m.isinstance_pybind11_bytes(b"")
678  assert not m.isinstance_pybind11_bytes("")
679 
680  assert m.isinstance_pybind11_str("")
681  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
682  assert m.isinstance_pybind11_str(b"")
683  else:
684  assert not m.isinstance_pybind11_str(b"")
685 
686 
688  assert m.pass_to_pybind11_bytes(b"Bytes") == 5
689  with pytest.raises(TypeError):
690  m.pass_to_pybind11_bytes("Str")
691 
692  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
693  assert m.pass_to_pybind11_str(b"Bytes") == 5
694  else:
695  with pytest.raises(TypeError):
696  m.pass_to_pybind11_str(b"Bytes")
697  assert m.pass_to_pybind11_str("Str") == 3
698 
699  assert m.pass_to_std_string(b"Bytes") == 5
700  assert m.pass_to_std_string("Str") == 3
701 
702  malformed_utf8 = b"\x80"
703  if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
704  assert m.pass_to_pybind11_str(malformed_utf8) == 1
705  else:
706  with pytest.raises(TypeError):
707  m.pass_to_pybind11_str(malformed_utf8)
708 
709 
710 @pytest.mark.parametrize(
711  ("create_weakref", "create_weakref_with_callback"),
712  [
713  (m.weakref_from_handle, m.weakref_from_handle_and_function),
714  (m.weakref_from_object, m.weakref_from_object_and_function),
715  ],
716 )
717 def test_weakref(create_weakref, create_weakref_with_callback):
718  from weakref import getweakrefcount
719 
720  # Apparently, you cannot weakly reference an object()
721  class WeaklyReferenced:
722  pass
723 
724  callback_called = False
725 
726  def callback(_):
727  nonlocal callback_called
728  callback_called = True
729 
730  obj = WeaklyReferenced()
731  assert getweakrefcount(obj) == 0
732  wr = create_weakref(obj)
733  assert getweakrefcount(obj) == 1
734 
735  obj = WeaklyReferenced()
736  assert getweakrefcount(obj) == 0
737  wr = create_weakref_with_callback(obj, callback) # noqa: F841
738  assert getweakrefcount(obj) == 1
739  assert not callback_called
740  del obj
741  pytest.gc_collect()
742  assert callback_called
743 
744 
745 @pytest.mark.parametrize(
746  ("create_weakref", "has_callback"),
747  [
748  (m.weakref_from_handle, False),
749  (m.weakref_from_object, False),
750  (m.weakref_from_handle_and_function, True),
751  (m.weakref_from_object_and_function, True),
752  ],
753 )
754 def test_weakref_err(create_weakref, has_callback):
755  class C:
756  __slots__ = []
757 
758  def callback(_):
759  pass
760 
761  ob = C()
762  # Should raise TypeError on CPython
763  with pytest.raises(TypeError) if not env.PYPY else contextlib.nullcontext():
764  _ = create_weakref(ob, callback) if has_callback else create_weakref(ob)
765 
766 
768  assert m.tuple_iterator() == 12
769  assert m.dict_iterator() == 305 + 711
770  assert m.passed_iterator(iter((-7, 3))) == -4
771 
772 
774  lst = [39, 43, 92, 49, 22, 29, 93, 98, 26, 57, 8]
775  tup = tuple(lst)
776  assert m.sequence_item_get_ssize_t(lst) == 43
777  assert m.sequence_item_set_ssize_t(lst) is None
778  assert lst[1] == "peppa"
779  assert m.sequence_item_get_size_t(lst) == 92
780  assert m.sequence_item_set_size_t(lst) is None
781  assert lst[2] == "george"
782  assert m.list_item_get_ssize_t(lst) == 49
783  assert m.list_item_set_ssize_t(lst) is None
784  assert lst[3] == "rebecca"
785  assert m.list_item_get_size_t(lst) == 22
786  assert m.list_item_set_size_t(lst) is None
787  assert lst[4] == "richard"
788  assert m.tuple_item_get_ssize_t(tup) == 29
789  assert m.tuple_item_set_ssize_t() == ("emely", "edmond")
790  assert m.tuple_item_get_size_t(tup) == 93
791  assert m.tuple_item_set_size_t() == ("candy", "cat")
792 
793 
795  r1 = m.square_float_(2.0)
796  assert r1 == 4.0
797 
798 
800  pop = 1000
801  tup = tuple(range(pop))
802  m.tuple_rvalue_getter(tup)
803 
804 
806  pop = 1000
807  my_list = list(range(pop))
808  m.list_rvalue_getter(my_list)
809 
810 
812  pop = 1000
813  my_dict = {i: i for i in range(pop)}
814  assert m.populate_dict_rvalue(pop) == my_dict
815 
816 
818  pop = 1000
819  o = types.SimpleNamespace(**{str(i): i for i in range(pop)})
820  new_o = m.populate_obj_str_attrs(o, pop)
821  new_attrs = {k: v for k, v in new_o.__dict__.items() if not k.startswith("_")}
822  assert all(isinstance(v, str) for v in new_attrs.values())
823  assert len(new_attrs) == pop
824 
825 
826 @pytest.mark.parametrize(
827  ("a", "b"),
828  [("foo", "bar"), (1, 2), (1.0, 2.0), (list(range(3)), list(range(3, 6)))],
829 )
831  expected = a + b
832  assert m.inplace_append(a, b) == expected
833 
834 
835 @pytest.mark.parametrize(
836  ("a", "b"), [(3, 2), (3.0, 2.0), (set(range(3)), set(range(2)))]
837 )
839  expected = a - b
840  assert m.inplace_subtract(a, b) == expected
841 
842 
843 @pytest.mark.parametrize(("a", "b"), [(3, 2), (3.0, 2.0), ([1], 3)])
845  expected = a * b
846  assert m.inplace_multiply(a, b) == expected
847 
848 
849 @pytest.mark.parametrize(("a", "b"), [(6, 3), (6.0, 3.0)])
851  expected = a / b
852  assert m.inplace_divide(a, b) == expected
853 
854 
855 @pytest.mark.parametrize(
856  ("a", "b"),
857  [
858  (False, True),
859  (
860  set(),
861  {
862  1,
863  },
864  ),
865  ],
866 )
867 def test_inplace_or(a, b):
868  expected = a | b
869  assert m.inplace_or(a, b) == expected
870 
871 
872 @pytest.mark.parametrize(
873  ("a", "b"),
874  [
875  (True, False),
876  (
877  {1, 2, 3},
878  {
879  1,
880  },
881  ),
882  ],
883 )
885  expected = a & b
886  assert m.inplace_and(a, b) == expected
887 
888 
889 @pytest.mark.parametrize(("a", "b"), [(8, 1), (-3, 2)])
891  expected = a << b
892  assert m.inplace_lshift(a, b) == expected
893 
894 
895 @pytest.mark.parametrize(("a", "b"), [(8, 1), (-2, 2)])
897  expected = a >> b
898  assert m.inplace_rshift(a, b) == expected
test_pytypes.test_dict
def test_dict(capture, doc)
Definition: test_pytypes.py:152
test_pytypes.test_populate_dict_rvalue
def test_populate_dict_rvalue()
Definition: test_pytypes.py:811
test_pytypes.test_implicit_casting
def test_implicit_casting()
Definition: test_pytypes.py:511
test_pytypes.test_str
def test_str(doc)
Definition: test_pytypes.py:217
encode
int encode(Index i, Index j)
Definition: indexed_view.cpp:45
test_pytypes.test_obj_class_name
def test_obj_class_name()
Definition: test_pytypes.py:12
bytes
Definition: pytypes.h:1620
set
Definition: pytypes.h:2185
test_pytypes.test_iterator
def test_iterator(doc)
Definition: test_pytypes.py:31
test_pytypes.test_pybind11_str_raw_str
def test_pybind11_str_raw_str()
Definition: test_pytypes.py:473
test_pytypes.test_frozenset
def test_frozenset(capture, doc)
Definition: test_pytypes.py:127
list
Definition: pytypes.h:2124
test_pytypes.test_test_memoryview_from_buffer_invalid_strides
def test_test_memoryview_from_buffer_invalid_strides()
Definition: test_pytypes.py:649
test_pytypes.test_test_memoryview_from_buffer_nullptr
def test_test_memoryview_from_buffer_nullptr()
Definition: test_pytypes.py:654
test_pytypes.test_bytearray
def test_bytearray()
Definition: test_pytypes.py:276
test_pytypes.test_inplace_or
def test_inplace_or(a, b)
Definition: test_pytypes.py:867
test_pytypes.test_populate_obj_str_attrs
def test_populate_obj_str_attrs()
Definition: test_pytypes.py:817
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:853
test_pytypes.test_memoryview_refcount
def test_memoryview_refcount(method)
Definition: test_pytypes.py:633
type
Definition: pytypes.h:1491
test_pytypes.test_inplace_rshift
def test_inplace_rshift(a, b)
Definition: test_pytypes.py:896
test_pytypes.test_hash
def test_hash()
Definition: test_pytypes.py:556
test_pytypes.test_bool
def test_bool(doc)
Definition: test_pytypes.py:23
test_pytypes.CustomContains
Definition: test_pytypes.py:177
test_pytypes.test_builtin_functions
def test_builtin_functions()
Definition: test_pytypes.py:666
test_pytypes.test_tuple
def test_tuple()
Definition: test_pytypes.py:202
test_pytypes.test_list
def test_list(capture, doc)
Definition: test_pytypes.py:59
test_pytypes.test_pass_bytes_or_unicode_to_string_types
def test_pass_bytes_or_unicode_to_string_types()
Definition: test_pytypes.py:687
test_pytypes.test_memoryview_from_memory
def test_memoryview_from_memory()
Definition: test_pytypes.py:659
test_pytypes.test_constructors
def test_constructors()
Definition: test_pytypes.py:419
test_pytypes.test_external_float_
def test_external_float_()
Definition: test_pytypes.py:794
test_pytypes.test_print
def test_print(capture)
Definition: test_pytypes.py:531
gtsam::range
Double_ range(const Point2_ &p, const Point2_ &q)
Definition: slam/expressions.h:30
doc
Annotation for documentation.
Definition: attr.h:45
test_pytypes.test_unhashable_exceptions
def test_unhashable_exceptions(arg, func)
Definition: test_pytypes.py:193
A
Definition: test_numpy_dtypes.cpp:298
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:825
gtwrap.interface_parser.function.__repr__
str __repr__(self)
Definition: interface_parser/function.py:53
test_pytypes.CustomContains.d
d
Definition: test_pytypes.py:178
test_pytypes.test_set
def test_set(capture, doc)
Definition: test_pytypes.py:95
Eigen::all
static const Eigen::internal::all_t all
Definition: IndexedViewHelper.h:171
test_pytypes.test_implementation_details
def test_implementation_details()
Definition: test_pytypes.py:773
test_pytypes.test_cpp_iterators
def test_cpp_iterators()
Definition: test_pytypes.py:767
func
int func(const int &a)
Definition: testDSF.cpp:221
decode
IndexPair decode(Index ij)
Definition: indexed_view.cpp:49
test_pytypes.test_tuple_rvalue_getter
def test_tuple_rvalue_getter()
Definition: test_pytypes.py:799
test_pytypes.test_accessors
def test_accessors()
Definition: test_pytypes.py:372
bytearray
Definition: pytypes.h:1714
test_pytypes.test_inplace_lshift
def test_inplace_lshift(a, b)
Definition: test_pytypes.py:890
test_pytypes.test_handle_from_move_only_type_with_operator_PyObject
def test_handle_from_move_only_type_with_operator_PyObject()
Definition: test_pytypes.py:18
test_pytypes.test_int
def test_int(doc)
Definition: test_pytypes.py:27
gtwrap.interface_parser.function.__init__
def __init__(self, Union[Type, TemplatedType] ctype, str name, ParseResults default=None)
Definition: interface_parser/function.py:41
test_pytypes.test_accessor_moves
def test_accessor_moves()
Definition: test_pytypes.py:411
test_pytypes.test_none
def test_none(doc)
Definition: test_pytypes.py:90
str
Definition: pytypes.h:1524
test_pytypes.test_list_rvalue_getter
def test_list_rvalue_getter()
Definition: test_pytypes.py:805
test_pytypes.test_bytes
def test_bytes(doc)
Definition: test_pytypes.py:267
C
Matrix< Scalar, Dynamic, Dynamic > C
Definition: bench_gemm.cpp:50
test_pytypes.test_weakref_err
def test_weakref_err(create_weakref, has_callback)
Definition: test_pytypes.py:754
test_pytypes.test_weakref
def test_weakref(create_weakref, create_weakref_with_callback)
Definition: test_pytypes.py:717
test_pytypes.test_inplace_and
def test_inplace_and(a, b)
Definition: test_pytypes.py:884
test_pytypes.test_from_iterable
def test_from_iterable(pytype, from_iter_func)
Definition: test_pytypes.py:44
iter
iterator iter(handle obj)
Definition: pytypes.h:2428
tuple
Definition: pytypes.h:2035
test_pytypes.test_simple_namespace
def test_simple_namespace()
Definition: test_pytypes.py:209
test_pytypes.test_inplace_divide
def test_inplace_divide(a, b)
Definition: test_pytypes.py:850
test_pytypes.test_memoryview_from_buffer_empty_shape
def test_memoryview_from_buffer_empty_shape()
Definition: test_pytypes.py:642
test_pytypes.test_inplace_append
def test_inplace_append(a, b)
Definition: test_pytypes.py:830
test_pytypes.CustomContains.__contains__
def __contains__(self, m)
Definition: test_pytypes.py:180
test_pytypes.test_iterable
def test_iterable(doc)
Definition: test_pytypes.py:51
test_pytypes.test_memoryview
def test_memoryview(method, args, fmt, expected_view)
Definition: test_pytypes.py:618
test_pytypes.test_float
def test_float(doc)
Definition: test_pytypes.py:55
test_pytypes.test_inplace_multiply
def test_inplace_multiply(a, b)
Definition: test_pytypes.py:844
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2399
func
Definition: benchGeometry.cpp:23
test_pytypes.test_non_converting_constructors
def test_non_converting_constructors()
Definition: test_pytypes.py:456
align_3::t
Point2 t(10, 10)
frozenset
Definition: pytypes.h:2200
test_pytypes.test_surrogate_pairs_unicode_error
def test_surrogate_pairs_unicode_error(func)
Definition: test_pytypes.py:261
test_pytypes.test_list_slicing
def test_list_slicing()
Definition: test_pytypes.py:594
test_pytypes.test_inplace_subtract
def test_inplace_subtract(a, b)
Definition: test_pytypes.py:838
test_pytypes.test_isinstance_string_types
def test_isinstance_string_types()
Definition: test_pytypes.py:676
test_pytypes.test_number_protocol
def test_number_protocol()
Definition: test_pytypes.py:572
test_pytypes.test_capsule
def test_capsule(capture)
Definition: test_pytypes.py:283
test_pytypes.test_issue2361
def test_issue2361()
Definition: test_pytypes.py:599


gtsam
Author(s):
autogenerated on Tue Jun 25 2024 03:05:29