MCPcopy Create free account
hub / github.com/davisking/dlib / bind_map_no_default_repr

Function bind_map_no_default_repr

tools/python/src/image_dataset_metadata.cpp:17–77  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

15 // a version of bind_map that doesn't force it's own __repr__ on you.
16template <typename Map, typename holder_type = std::unique_ptr<Map>, typename... Args>
17class_<Map, holder_type> bind_map_no_default_repr(handle scope, const std::string &name, Args&&... args) {
18 using KeyType = typename Map::key_type;
19 using MappedType = typename Map::mapped_type;
20 using Class_ = class_<Map, holder_type>;
21
22 // If either type is a non-module-local bound type then make the map binding non-local as well;
23 // otherwise (e.g. both types are either module-local or converting) the map will be
24 // module-local.
25 auto tinfo = detail::get_type_info(typeid(MappedType));
26 bool local = !tinfo || tinfo->module_local;
27 if (local) {
28 tinfo = detail::get_type_info(typeid(KeyType));
29 local = !tinfo || tinfo->module_local;
30 }
31
32 Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward<Args>(args)...);
33
34 cl.def(init<>());
35
36
37 cl.def("__bool__",
38 [](const Map &m) -> bool { return !m.empty(); },
39 "Check whether the map is nonempty"
40 );
41
42 cl.def("__iter__",
43 [](Map &m) { return make_key_iterator(m.begin(), m.end()); },
44 keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
45 );
46
47 cl.def("items",
48 [](Map &m) { return make_iterator(m.begin(), m.end()); },
49 keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
50 );
51
52 cl.def("__getitem__",
53 [](Map &m, const KeyType &k) -> MappedType & {
54 auto it = m.find(k);
55 if (it == m.end())
56 throw key_error();
57 return it->second;
58 },
59 return_value_policy::reference_internal // ref + keepalive
60 );
61
62 // Assignment provided only if the type is copyable
63 detail::map_assignment<Map, Class_>(cl);
64
65 cl.def("__delitem__",
66 [](Map &m, const KeyType &k) {
67 auto it = m.find(k);
68 if (it == m.end())
69 throw key_error();
70 return m.erase(it);
71 }
72 );
73
74 cl.def("__len__", &Map::size);

Callers

nothing calls this directly

Calls 8

module_localClass · 0.85
make_key_iteratorFunction · 0.85
make_iteratorFunction · 0.85
eraseMethod · 0.80
emptyMethod · 0.45
beginMethod · 0.45
endMethod · 0.45
findMethod · 0.45

Tested by

no test coverage detected