RDKit
Open-source cheminformatics and machine learning.
Loading...
Searching...
No Matches
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#include <RDGeneral/export.h>
12#ifndef _RD_PYSEQUENCEHOLDER_H_
13#define _RD_PYSEQUENCEHOLDER_H_
14
15//
16// Defines a class to hold sequences passed in from Python
17//
18#include "Wrap.h"
19#include <RDGeneral/Invariant.h>
20
21namespace python = boost::python;
22
23//! \brief Class to hold sequences (lists, tuples, arrays, etc.)
24//! passed from Python -> C++
25//!
26//! PySequenceHolder is templated on the type of the contained object.
27//!
28//! The class is \em lazy: elements are not evaluated until requested
29//! within the C++ code.
30//!
31template <typename T>
33 public:
34 PySequenceHolder(python::object seq) { d_seq = seq; }
35
36 // --------------------------------------------------
37 //! \brief Returns the size of the contained sequence.
38 //!
39 //! NOTE: the sequence must have a \c __len__ attribute, otherwise
40 //! a \c ValueError will be raised.
41 unsigned int size() const {
42 unsigned int res = 0;
43 try {
44 res = python::extract<int>(d_seq.attr("__len__")());
45 } catch (...) {
46 throw_value_error("sequence does not support length query");
47 }
48 return res;
49 }
50
51 // --------------------------------------------------
52 //! \brief Returns an element of the sequence
53 //!
54 //! ARGUMENTS:
55 //! - which: an integer specifying which element should be returned.
56 //!
57 //! NOTES:
58 //! - if the sequence is not \a which elements long, we raise an
59 //! \c IndexError
60 //! - if the element cannot be converted to type \c T, we raise a
61 //! \c ValueError
62 T operator[](unsigned int which) const {
63 if (which > size()) {
64 throw_index_error(which);
65 }
66
67 try {
68 T res = python::extract<T>(d_seq[which]);
69 return res;
70 } catch (...) {
71 throw_value_error("cannot extract desired type from sequence");
72 }
73
74 POSTCONDITION(0, "cannot reach this point");
75 return static_cast<T>(T());
76 }
77
78 private:
79 python::object d_seq;
80};
81
82#endif
#define POSTCONDITION(expr, mess)
Definition Invariant.h:117
Class to hold sequences (lists, tuples, arrays, etc.) passed from Python -> C++.
unsigned int size() const
Returns the size of the contained sequence.
T operator[](unsigned int which) const
Returns an element of the sequence.
PySequenceHolder(python::object seq)