extract.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. # Copyright David Abrahams 2004. Distributed under the Boost
  2. # Software License, Version 1.0. (See accompanying
  3. # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. '''
  5. >>> from extract_ext import *
  6. Just about anything has a truth value in Python
  7. >>> assert check_bool(None)
  8. >>> extract_bool(None)
  9. 0
  10. >>> assert check_bool(2)
  11. >>> extract_bool(2)
  12. 1
  13. >>> assert not check_bool('')
  14. Check that object manager types work properly. These are a different
  15. case because they wrap Python objects instead of being wrapped by them.
  16. >>> assert not check_list(2)
  17. >>> try: x = extract_list(2)
  18. ... except TypeError as x:
  19. ... if str(x) != 'Expecting an object of type list; got an object of type int instead':
  20. ... print(x)
  21. ... else:
  22. ... print('expected an exception, got', x, 'instead')
  23. Can't extract a list from a tuple. Use list(x) to convert a sequence
  24. to a list:
  25. >>> assert not check_list((1, 2, 3))
  26. >>> assert check_list([1, 2, 3])
  27. >>> extract_list([1, 2, 3])
  28. [1, 2, 3]
  29. Can get a char const* from a Python string:
  30. >>> assert check_cstring('hello')
  31. >>> extract_cstring('hello')
  32. 'hello'
  33. Can't get a char const* from a Python int:
  34. >>> assert not check_cstring(1)
  35. >>> try: x = extract_cstring(1)
  36. ... except TypeError: pass
  37. ... else:
  38. ... print('expected an exception, got', x, 'instead')
  39. Extract an std::string (class) rvalue from a native Python type
  40. >>> assert check_string('hello')
  41. >>> extract_string('hello')
  42. 'hello'
  43. Constant references are not treated as rvalues for the purposes of
  44. extract:
  45. >>> assert not check_string_cref('hello')
  46. We can extract lvalues where appropriate:
  47. >>> x = X(42)
  48. >>> check_X(x)
  49. 1
  50. >>> extract_X(x)
  51. X(42)
  52. >>> check_X_ptr(x)
  53. 1
  54. >>> extract_X_ptr(x)
  55. X(42)
  56. >>> extract_X_ref(x)
  57. X(42)
  58. Demonstrate that double-extraction of an rvalue works, and all created
  59. copies of the object are destroyed:
  60. >>> n = count_Xs()
  61. >>> double_X(333)
  62. 666
  63. >>> count_Xs() - n
  64. 0
  65. General check for cleanliness:
  66. >>> del x
  67. >>> count_Xs()
  68. 0
  69. '''
  70. def run(args = None):
  71. import sys
  72. import doctest
  73. if args is not None:
  74. sys.argv = args
  75. return doctest.testmod(sys.modules.get(__name__))
  76. if __name__ == '__main__':
  77. print("running...")
  78. import sys
  79. status = run()[0]
  80. if (status == 0): print("Done.")
  81. sys.exit(status)