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.

80 lines
1.9 KiB

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