dict.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. #include <boost/python/module.hpp>
  5. #define BOOST_ENABLE_ASSERT_HANDLER
  6. #include <boost/assert.hpp>
  7. #include <boost/python/def.hpp>
  8. #include <boost/python/class.hpp>
  9. #include <boost/python/dict.hpp>
  10. #include <exception>
  11. #include <string>
  12. using namespace boost::python;
  13. object new_dict()
  14. {
  15. return dict();
  16. }
  17. object data_dict()
  18. {
  19. dict tmp1;
  20. tmp1["key1"] = "value1";
  21. dict tmp2;
  22. tmp2["key2"] = "value2";
  23. tmp1[1] = tmp2;
  24. return tmp1;
  25. }
  26. object dict_from_sequence(object sequence)
  27. {
  28. return dict(sequence);
  29. }
  30. object dict_keys(dict data)
  31. {
  32. return data.keys();
  33. }
  34. object dict_values(dict data)
  35. {
  36. return data.values();
  37. }
  38. object dict_items(dict data)
  39. {
  40. return data.items();
  41. }
  42. void work_with_dict(dict data1, dict data2)
  43. {
  44. if (!data1.has_key("k1")) {
  45. throw std::runtime_error("dict does not have key 'k1'");
  46. }
  47. data1.update(data2);
  48. }
  49. void test_templates(object print)
  50. {
  51. std::string key = "key";
  52. dict tmp;
  53. tmp[1] = "a test string";
  54. print(tmp.get(1));
  55. //print(tmp[1]);
  56. tmp[1.5] = 13;
  57. print(tmp.get(1.5));
  58. print(tmp.get(44));
  59. print(tmp);
  60. print(tmp.get(2,"default"));
  61. print(tmp.setdefault(3,"default"));
  62. BOOST_ASSERT(!tmp.has_key(key));
  63. //print(tmp[3]);
  64. }
  65. BOOST_PYTHON_MODULE(dict_ext)
  66. {
  67. def("new_dict", new_dict);
  68. def("data_dict", data_dict);
  69. def("dict_keys", dict_keys);
  70. def("dict_values", dict_values);
  71. def("dict_items", dict_items);
  72. def("dict_from_sequence", dict_from_sequence);
  73. def("work_with_dict", work_with_dict);
  74. def("test_templates", test_templates);
  75. }
  76. #include "module_tail.cpp"