Blame view

3rdparty/boost_1_81_0/libs/python/test/dict.cpp 1.74 KB
73ef4ff3   Hu Chunming   提交三方库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
  // Copyright David Abrahams 2004. Distributed under the Boost
  // Software License, Version 1.0. (See accompanying
  // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  #include <boost/python/module.hpp>
  #define BOOST_ENABLE_ASSERT_HANDLER
  #include <boost/assert.hpp>
  
  #include <boost/python/def.hpp>
  #include <boost/python/class.hpp>
  #include <boost/python/dict.hpp>
  #include <exception>
  #include <string>
  
  using namespace boost::python;
  
  object new_dict()
  {
      return dict();
  }
  
  object data_dict()
  {
      dict tmp1;
  
      dict tmp2;
      tmp2["key2"] = "value2";
      tmp1[1] = tmp2;
  
      tmp1["key1"] = "value1";
  
      return tmp1;
  }
  
  object dict_from_sequence(object sequence)
  {
      return dict(sequence);
  }
  
  object dict_keys(dict data)
  {
      return data.keys();
  }
  
  object dict_values(dict data)
  {
      return data.values();
  }
  
  object dict_items(dict data)
  {
      return data.items();
  }
  
  void work_with_dict(dict data1, dict data2)
  {
      if (!data1.has_key("k1")) {
          throw std::runtime_error("dict does not have key 'k1'");
      }
      data1.update(data2);
  }
  
  void test_templates(object print)
  {
      std::string key = "key";
  
      dict tmp;
      tmp[1.5] = 13;
      print(tmp.get(1.5));
      tmp[1] = "a test string";
      print(tmp.get(1));
      print(tmp.get(44));
      print(tmp);
      print(tmp.get(2,"default"));
      print(tmp.setdefault(3,"default"));
  
      BOOST_ASSERT(!tmp.has_key(key));
  }
  
  BOOST_PYTHON_MODULE(dict_ext)
  {
      def("new_dict", new_dict);
      def("data_dict", data_dict);
      def("dict_keys", dict_keys);
      def("dict_values", dict_values);
      def("dict_items", dict_items);
      def("dict_from_sequence", dict_from_sequence);
      def("work_with_dict", work_with_dict);
      def("test_templates", test_templates);
  }
  
  #include "module_tail.cpp"