container_utils.hpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // (C) Copyright Joel de Guzman 2003.
  2. // Distributed under the Boost Software License, Version 1.0. (See
  3. // accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef PY_CONTAINER_UTILS_JDG20038_HPP
  6. # define PY_CONTAINER_UTILS_JDG20038_HPP
  7. # include <utility>
  8. # include <boost/foreach.hpp>
  9. # include <boost/python/object.hpp>
  10. # include <boost/python/handle.hpp>
  11. # include <boost/python/extract.hpp>
  12. # include <boost/python/stl_iterator.hpp>
  13. namespace boost { namespace python { namespace container_utils {
  14. template <typename Container>
  15. void
  16. extend_container(Container& container, object l)
  17. {
  18. typedef typename Container::value_type data_type;
  19. // l must be iterable
  20. BOOST_FOREACH(object elem,
  21. std::make_pair(
  22. boost::python::stl_input_iterator<object>(l),
  23. boost::python::stl_input_iterator<object>()
  24. ))
  25. {
  26. extract<data_type const&> x(elem);
  27. // try if elem is an exact data_type type
  28. if (x.check())
  29. {
  30. container.push_back(x());
  31. }
  32. else
  33. {
  34. // try to convert elem to data_type type
  35. extract<data_type> x(elem);
  36. if (x.check())
  37. {
  38. container.push_back(x());
  39. }
  40. else
  41. {
  42. PyErr_SetString(PyExc_TypeError, "Incompatible Data Type");
  43. throw_error_already_set();
  44. }
  45. }
  46. }
  47. }
  48. }}} // namespace boost::python::container_utils
  49. #endif