You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.8 KiB

  1. import gc
  2. def test_alias_delay_initialization1(capture):
  3. """A only initializes its trampoline class when we inherit from it; if we just
  4. create and use an A instance directly, the trampoline initialization is bypassed
  5. and we only initialize an A() instead (for performance reasons).
  6. """
  7. from pybind11_tests import A, call_f
  8. class B(A):
  9. def __init__(self):
  10. super(B, self).__init__()
  11. def f(self):
  12. print("In python f()")
  13. # C++ version
  14. with capture:
  15. a = A()
  16. call_f(a)
  17. del a
  18. gc.collect()
  19. assert capture == "A.f()"
  20. # Python version
  21. with capture:
  22. b = B()
  23. call_f(b)
  24. del b
  25. gc.collect()
  26. assert capture == """
  27. PyA.PyA()
  28. PyA.f()
  29. In python f()
  30. PyA.~PyA()
  31. """
  32. def test_alias_delay_initialization2(capture):
  33. """A2, unlike the above, is configured to always initialize the alias; while
  34. the extra initialization and extra class layer has small virtual dispatch
  35. performance penalty, it also allows us to do more things with the trampoline
  36. class such as defining local variables and performing construction/destruction.
  37. """
  38. from pybind11_tests import A2, call_f
  39. class B2(A2):
  40. def __init__(self):
  41. super(B2, self).__init__()
  42. def f(self):
  43. print("In python B2.f()")
  44. # No python subclass version
  45. with capture:
  46. a2 = A2()
  47. call_f(a2)
  48. del a2
  49. gc.collect()
  50. assert capture == """
  51. PyA2.PyA2()
  52. PyA2.f()
  53. A2.f()
  54. PyA2.~PyA2()
  55. """
  56. # Python subclass version
  57. with capture:
  58. b2 = B2()
  59. call_f(b2)
  60. del b2
  61. gc.collect()
  62. assert capture == """
  63. PyA2.PyA2()
  64. PyA2.f()
  65. In python B2.f()
  66. PyA2.~PyA2()
  67. """