RDKit
Open-source cheminformatics and machine learning.
PySequenceHolder.h
Go to the documentation of this file.
1 //
2 // Copyright (c) 2003-2006 greg Landrum and Rational Discovery LLC
3 //
4 // @@ All Rights Reserved @@
5 // This file is part of the RDKit.
6 // The contents are covered by the terms of the BSD license
7 // which is included in the file license.txt, found at the root
8 // of the RDKit source tree.
9 //
10 
11 #ifndef _RD_PYSEQUENCEHOLDER_H_
12 #define _RD_PYSEQUENCEHOLDER_H_
13 
14 //
15 // Defines a class to hold sequences passed in from Python
16 //
17 #include "Wrap.h"
18 #include <RDGeneral/Invariant.h>
19 
20 namespace python = boost::python;
21 
22 //! \brief Class to hold sequences (lists, tuples, arrays, etc.)
23 //! passed from Python -> C++
24 //!
25 //! PySequenceHolder is templated on the type of the contained object.
26 //!
27 //! The class is \em lazy: elements are not evaluated until requested
28 //! within the C++ code.
29 //!
30 template <typename T>
32 public:
33  PySequenceHolder(python::object seq) {
34  d_seq = seq;
35  };
36 
37  // --------------------------------------------------
38  //! \brief Returns the size of the contained sequence.
39  //!
40  //! NOTE: the sequence must have a \c __len__ attribute, otherwise
41  //! a \c ValueError will be raised.
42  unsigned int size() const {
43  unsigned int res=0;
44  try {
45  res = python::extract<int>(d_seq.attr("__len__")());
46  } catch (...) {
47  throw_value_error("sequence does not support length query");
48  }
49  return res;
50  };
51 
52  // --------------------------------------------------
53  //! \brief Returns an element of the sequence
54  //!
55  //! ARGUMENTS:
56  //! - which: an integer specifying which element should be returned.
57  //!
58  //! NOTES:
59  //! - if the sequence is not \a which elements long, we raise an
60  //! \c IndexError
61  //! - if the element cannot be converted to type \c T, we raise a
62  //! \c ValueError
63  T operator[](unsigned int which) const {
64  if(which > size()){
65  throw_index_error(which);
66  }
67 
68  try{
69  T res = python::extract<T>(d_seq[which]);
70  return res;
71  } catch (...) {
72  throw_value_error("cannot extract desired type from sequence");
73  }
74 
75  POSTCONDITION(0,"cannot reach this point");
76  return static_cast<T>(0);
77  };
78 private:
79  python::object d_seq;
80 };
81 
82 
83 #endif
#define POSTCONDITION(expr, mess)
Definition: Invariant.h:124
Class to hold sequences (lists, tuples, arrays, etc.) passed from Python -> C++.
unsigned int size() const
Returns the size of the contained sequence.
PySequenceHolder(python::object seq)
T operator[](unsigned int which) const
Returns an element of the sequence.