mirror of
https://github.com/pybind/pybind11.git
synced 2026-05-11 08:50:31 +00:00
Added pybind11::make_key_iterator for map iteration
This allows exposing a dict-like interface to python code, allowing
iteration over keys via:
for k in custommapping:
...
while still allowing iteration over pairs, so that you can also
implement 'dict.items()' functionality which returns a pair iterator,
allowing:
for k, v in custommapping.items():
...
example-sequences-and-iterators is updated with a custom class providing
both types of iteration.
This commit is contained in:
@@ -116,6 +116,34 @@ private:
|
||||
float *m_data;
|
||||
};
|
||||
|
||||
// Interface of a map-like object that isn't (directly) an unordered_map, but provides some basic
|
||||
// map-like functionality.
|
||||
class StringMap {
|
||||
public:
|
||||
StringMap(std::unordered_map<std::string, std::string> init = {})
|
||||
: map(std::move(init)) {}
|
||||
|
||||
void set(std::string key, std::string val) {
|
||||
map[key] = val;
|
||||
}
|
||||
|
||||
std::string get(std::string key) const {
|
||||
return map.at(key);
|
||||
}
|
||||
|
||||
size_t size() const {
|
||||
return map.size();
|
||||
}
|
||||
|
||||
private:
|
||||
std::unordered_map<std::string, std::string> map;
|
||||
|
||||
public:
|
||||
decltype(map.cbegin()) begin() const { return map.cbegin(); }
|
||||
decltype(map.cend()) end() const { return map.cend(); }
|
||||
};
|
||||
|
||||
|
||||
void init_ex_sequences_and_iterators(py::module &m) {
|
||||
py::class_<Sequence> seq(m, "Sequence");
|
||||
|
||||
@@ -164,6 +192,25 @@ void init_ex_sequences_and_iterators(py::module &m) {
|
||||
.def(py::self != py::self);
|
||||
// Could also define py::self + py::self for concatenation, etc.
|
||||
|
||||
py::class_<StringMap> map(m, "StringMap");
|
||||
|
||||
map .def(py::init<>())
|
||||
.def(py::init<std::unordered_map<std::string, std::string>>())
|
||||
.def("__getitem__", [](const StringMap &map, std::string key) {
|
||||
try { return map.get(key); }
|
||||
catch (const std::out_of_range&) {
|
||||
throw py::key_error("key '" + key + "' does not exist");
|
||||
}
|
||||
})
|
||||
.def("__setitem__", &StringMap::set)
|
||||
.def("__len__", &StringMap::size)
|
||||
.def("__iter__", [](const StringMap &map) { return py::make_key_iterator(map.begin(), map.end()); },
|
||||
py::keep_alive<0, 1>())
|
||||
.def("items", [](const StringMap &map) { return py::make_iterator(map.begin(), map.end()); },
|
||||
py::keep_alive<0, 1>())
|
||||
;
|
||||
|
||||
|
||||
#if 0
|
||||
// Obsolete: special data structure for exposing custom iterator types to python
|
||||
// kept here for illustrative purposes because there might be some use cases which
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import print_function
|
||||
import sys
|
||||
sys.path.append('.')
|
||||
|
||||
from example import Sequence
|
||||
from example import Sequence, StringMap
|
||||
|
||||
s = Sequence(5)
|
||||
print("s = " + str(s))
|
||||
@@ -29,6 +29,24 @@ for i in rev:
|
||||
print(i, end=' ')
|
||||
print('')
|
||||
|
||||
m = StringMap({ 'hi': 'bye', 'black': 'white' })
|
||||
print(m['hi'])
|
||||
print(len(m))
|
||||
print(m['black'])
|
||||
try:
|
||||
print(m['orange'])
|
||||
print('Error: should have thrown exception')
|
||||
except KeyError:
|
||||
pass
|
||||
m['orange'] = 'banana'
|
||||
print(m['orange'])
|
||||
|
||||
for k in m:
|
||||
print("key = %s, value = %s" % (k, m[k]))
|
||||
|
||||
for k,v in m.items():
|
||||
print("item: (%s, %s)" % (k,v))
|
||||
|
||||
from example import ConstructorStats
|
||||
cstats = ConstructorStats.get(Sequence)
|
||||
print("Instances not destroyed:", cstats.alive())
|
||||
|
||||
@@ -13,9 +13,19 @@ rev[0], rev[1], rev[2], rev[3], rev[4] = 0.000000 56.779999 0.000000 0.000000 12
|
||||
0.0 56.779998779296875 0.0 0.0 12.34000015258789
|
||||
0.0 56.779998779296875 0.0 0.0 12.34000015258789
|
||||
True
|
||||
### Sequence @ 0x153c4b0 created of size 3 from std::vector
|
||||
### Sequence @ 0x153c4b0 destroyed
|
||||
### Sequence @ 0x1b4d1f0 created of size 3 from std::vector
|
||||
### Sequence @ 0x1b4d1f0 destroyed
|
||||
2.0 56.779998779296875 2.0 0.0 2.0
|
||||
bye
|
||||
2
|
||||
white
|
||||
banana
|
||||
key = orange, value = banana
|
||||
key = hi, value = bye
|
||||
key = black, value = white
|
||||
item: (orange, banana)
|
||||
item: (hi, bye)
|
||||
item: (black, white)
|
||||
Instances not destroyed: 3
|
||||
### Sequence @ 0x1535b00 destroyed
|
||||
Instances not destroyed: 2
|
||||
|
||||
Reference in New Issue
Block a user