2
0
mirror of https://github.com/boostorg/python.git synced 2026-01-19 16:32:16 +00:00

cleaning up cvs attic mess

[SVN r9831]
This commit is contained in:
Ralf W. Grosse-Kunstleve
2001-04-18 01:29:23 +00:00
parent dc462cdc1f
commit cbff11296b
11 changed files with 655 additions and 0 deletions

View File

@@ -0,0 +1,128 @@
// Example by Ralf W. Grosse-Kunstleve
/*
This example shows how to convert a class from and to native
Python objects, such as tuples.
We do not want to expose the helper class MillerIndex as an
Extension Class. However, in order to simplify the wrapper code,
we want to define from_python() and to_python() functions for
class MillerIndex.
Consider the alternatives:
- Expose MillerIndex as an Extension Class.
We need a constructor MillerIndex(python::tuple).
Python function calls become more complex:
foo(MillerIndex((1,2,3)) instead of foo((1,2,3))
We need a method such as MillerIndex().as_tuple().
- Define a wrapper function for each function that we
want to expose, e.g.:
void add(const IndexingSet& ixset, const python::tuple PyMIx)
The first alternative introduces a new type that the user has to
deal with. Other modules using Miller indices might organize them in
different ways, for example to increase runtime efficiency for
important procedures. This means, the user has to know how to
convert between the different kinds of Miller index representations.
This can quickly become a nuisance. Relying on native Python data
structures minimizes the number of special types the user has to
learn and convert. Of course, this argument is only valid for
small and relatively simply classes.
If there are many member functions with MillerIndex arguments, the
second alternative is impractical, and concentrating the conversion
mechanism in one central place is essential for code
maintainability. An added benefit is that more convenient (smarter)
conversion functions can be provided without cluttering the rest of
the wrapper code.
*/
#include <string>
#include <vector>
#include <boost/python/class_builder.hpp>
namespace python = boost::python;
namespace { // Avoid cluttering the global namespace.
// The helper class.
//
class MillerIndex {
public:
int v[3];
};
// The main class. Imagine that there are MANY member functions
// like add() and get().
//
class IndexingSet {
private:
std::vector<MillerIndex> VMIx;
public:
void add(const MillerIndex& MIx) { VMIx.push_back(MIx); }
MillerIndex get(std::size_t i) const { return VMIx[i]; }
};
}
BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE
// Convert a Python tuple to a MillerIndex object.
//
MillerIndex from_python(PyObject* p, python::type<const MillerIndex&>)
{
python::tuple tup
= python::tuple(python::ref(p, python::ref::increment_count));
if (tup.size() != 3) {
PyErr_SetString(PyExc_ValueError,
"expecting exactly 3 values in tuple.");
throw python::error_already_set();
}
MillerIndex result;
for (int i = 0; i < 3; i++)
result.v[i] = from_python(tup[i].get(), python::type<int>());
return result;
}
// Similar conversion for MillerIndex objects passed by value.
// Not actually used, but included to show the principle.
//
MillerIndex from_python(PyObject* p, python::type<MillerIndex>)
{
return from_python(p, python::type<const MillerIndex&>());
}
// Convert a MillerIndex object to a Python tuple.
//
PyObject* to_python(const MillerIndex& hkl)
{
python::tuple result(3);
for (int i = 0; i < 3; i++)
result.set_item(i, python::ref(to_python(hkl.v[i])));
return result.reference().release();
}
BOOST_PYTHON_END_CONVERSION_NAMESPACE
BOOST_PYTHON_MODULE_INIT(do_it_yourself_converters)
{
try
{
// Create an object representing this extension module.
python::module_builder this_module("do_it_yourself_converters");
// Create the Python type object for our extension class.
python::class_builder<IndexingSet> ixset_class(this_module, "IndexingSet");
// Add the __init__ function.
ixset_class.def(python::constructor<>());
// Add the member functions.
ixset_class.def(&IndexingSet::add, "add");
ixset_class.def(&IndexingSet::get, "get");
}
catch(...)
{
python::handle_exception(); // Deal with the exception for Python
}
}

45
example/dvect.cpp Normal file
View File

@@ -0,0 +1,45 @@
// Example by Ralf W. Grosse-Kunstleve
// See root/libs/python/doc/cross_module.html for an introduction.
#include "dvect.h"
#include "ivect.h"
#include <boost/python/cross_module.hpp>
namespace python = boost::python;
namespace {
# include "dvect_conversions.cpp"
# include "ivect_conversions.cpp"
vects::ivect dvect_as_ivect(const vects::dvect& dv)
{
vects::ivect iv(dv.size());
vects::ivect::iterator iviter = iv.begin();
for (int i = 0; i < dv.size(); i++) iviter[i] = static_cast<int>(dv[i]);
return iv;
}
}
BOOST_PYTHON_MODULE_INIT(dvect)
{
try
{
python::module_builder this_module("dvect");
python::class_builder<vects::dvect> dvect_class(this_module, "dvect");
python::export_converters(dvect_class);
python::import_converters<vects::ivect> ivect_converters("ivect", "ivect");
dvect_class.def(python::constructor<python::tuple>());
dvect_class.def(&vects::dvect::as_tuple, "as_tuple");
dvect_class.def(dvect_as_ivect, "as_ivect");
# include "dvect_defs.cpp"
# include "ivect_defs.cpp"
}
catch(...)
{
python::handle_exception(); // Deal with the exception for Python
}
}

45
example/ivect.cpp Normal file
View File

@@ -0,0 +1,45 @@
// Example by Ralf W. Grosse-Kunstleve
// See root/libs/python/doc/cross_module.html for an introduction.
#include "dvect.h"
#include "ivect.h"
#include <boost/python/cross_module.hpp>
namespace python = boost::python;
namespace {
# include "dvect_conversions.cpp"
# include "ivect_conversions.cpp"
vects::dvect ivect_as_dvect(const vects::ivect& iv)
{
vects::dvect dv(iv.size());
vects::dvect::iterator dviter = dv.begin();
for (int i = 0; i < iv.size(); i++) dviter[i] = static_cast<double>(iv[i]);
return dv;
}
}
BOOST_PYTHON_MODULE_INIT(ivect)
{
try
{
python::module_builder this_module("ivect");
python::class_builder<vects::ivect> ivect_class(this_module, "ivect");
python::export_converters(ivect_class);
python::import_converters<vects::dvect> dvect_converters("dvect", "dvect");
ivect_class.def(python::constructor<python::tuple>());
ivect_class.def(&vects::ivect::as_tuple, "as_tuple");
ivect_class.def(ivect_as_dvect, "as_dvect");
# include "dvect_defs.cpp"
# include "ivect_defs.cpp"
}
catch(...)
{
python::handle_exception(); // Deal with the exception for Python
}
}

View File

@@ -0,0 +1,25 @@
// Example by Ralf W. Grosse-Kunstleve
// See root/libs/python/doc/cross_module.html for an introduction.
#include <boost/python/cross_module.hpp>
namespace python = boost::python;
#include "noncopyable.h"
BOOST_PYTHON_MODULE_INIT(noncopyable_export)
{
try
{
python::module_builder this_module("noncopyable_export");
python::class_builder<store> store_class(this_module, "store");
python::export_converters_noncopyable(store_class);
store_class.def(python::constructor<int>());
store_class.def(&store::recall, "recall");
}
catch(...)
{
python::handle_exception(); // Deal with the exception for Python
}
}

View File

@@ -0,0 +1,42 @@
// Example by Ralf W. Grosse-Kunstleve
// See root/libs/python/doc/cross_module.html for an introduction.
#include <boost/python/cross_module.hpp>
namespace python = boost::python;
#include "noncopyable.h"
namespace { // Avoid cluttering the global namespace.
// A function with store objects as both input and output parameters.
// Because the copy constructor is disabled, we cannot pass a store
// object by value. Instead, we pass a smart pointer.
std::auto_ptr<store> add_stores(const store& s1, const store& s2)
{
int sum = s1.recall() + s2.recall();
std::auto_ptr<store> ss = std::auto_ptr<store>(new store(sum));
return ss;
}
}
BOOST_PYTHON_MODULE_INIT(noncopyable_import)
{
try
{
python::module_builder this_module("noncopyable_import");
python::import_converters<store>
dvect_converters("noncopyable_export", "store");
// Imagine all the additional classes with member functions
// that have store objects as input and output parameters.
// Lots and lots of them.
// However, to keep this example simple, we only define a
// module-level function.
this_module.def(add_stores, "add_stores");
}
catch(...)
{
python::handle_exception(); // Deal with the exception for Python
}
}

64
example/pickle1.cpp Normal file
View File

@@ -0,0 +1,64 @@
// Example by Ralf W. Grosse-Kunstleve
/*
This example shows how to make an Extension Class "pickleable".
The world class below can be fully restored by passing the
appropriate argument to the constructor. Therefore it is sufficient
to define the pickle interface method __getinitargs__.
For more information refer to boost/libs/python/doc/pickle.html.
*/
#include <string>
#include <boost/python/class_builder.hpp>
namespace python = boost::python;
namespace { // Avoid cluttering the global namespace.
// A friendly class.
class world
{
private:
std::string country;
int secret_number;
public:
world(const std::string& country) : secret_number(0) {
this->country = country;
}
std::string greet() const { return "Hello from " + country + "!"; }
std::string get_country() const { return country; }
};
// Support for pickle.
python::ref world_getinitargs(const world& w) {
python::tuple result(1);
result.set_item(0, w.get_country());
return result.reference();
}
}
BOOST_PYTHON_MODULE_INIT(pickle1)
{
try
{
// Create an object representing this extension module.
python::module_builder this_module("pickle1");
// Create the Python type object for our extension class.
python::class_builder<world> world_class(this_module, "world");
// Add the __init__ function.
world_class.def(python::constructor<std::string>());
// Add a regular member function.
world_class.def(&world::greet, "greet");
// Support for pickle.
world_class.def(world_getinitargs, "__getinitargs__");
}
catch(...)
{
python::handle_exception(); // Deal with the exception for Python
}
}

100
example/pickle2.cpp Normal file
View File

@@ -0,0 +1,100 @@
// Example by Ralf W. Grosse-Kunstleve
/*
This example shows how to make an Extension Class "pickleable".
The world class below contains member data (secret_number) that
cannot be restored by any of the constructors. Therefore it is
necessary to provide the __getstate__/__setstate__ pair of pickle
interface methods.
For simplicity, the __dict__ is not included in the result of
__getstate__. This is not generally recommended, but a valid
approach if it is anticipated that the object's __dict__ will
always be empty. Note that safety guard are provided to catch the
cases where this assumption is not true.
pickle3.cpp shows how to include the object's __dict__ in the
result of __getstate__.
For more information refer to boost/libs/python/doc/pickle.html.
*/
#include <string>
#include <boost/python/class_builder.hpp>
namespace python = boost::python;
namespace { // Avoid cluttering the global namespace.
// A friendly class.
class world
{
public:
world(const std::string& country) : secret_number(0) {
this->country = country;
}
std::string greet() const { return "Hello from " + country + "!"; }
std::string get_country() const { return country; }
void set_secret_number(int number) { secret_number = number; }
int get_secret_number() const { return secret_number; }
private:
std::string country;
int secret_number;
};
// Support for pickle.
using BOOST_PYTHON_CONVERSION::from_python;
python::ref world_getinitargs(const world& w) {
python::tuple result(1);
result.set_item(0, w.get_country());
return result.reference(); // returning the reference avoids the copying.
}
python::ref world_getstate(const world& w) {
python::tuple result(1);
result.set_item(0, w.get_secret_number());
return result.reference(); // returning the reference avoids the copying.
}
void world_setstate(world& w, python::tuple state) {
if (state.size() != 1) {
PyErr_SetString(PyExc_ValueError,
"Unexpected argument in call to __setstate__.");
throw python::error_already_set();
}
int number = from_python(state[0].get(), python::type<int>());
if (number != 42)
w.set_secret_number(number);
}
}
BOOST_PYTHON_MODULE_INIT(pickle2)
{
try
{
// Create an object representing this extension module.
python::module_builder this_module("pickle2");
// Create the Python type object for our extension class.
python::class_builder<world> world_class(this_module, "world");
// Add the __init__ function.
world_class.def(python::constructor<std::string>());
// Add a regular member function.
world_class.def(&world::greet, "greet");
world_class.def(&world::get_secret_number, "get_secret_number");
world_class.def(&world::set_secret_number, "set_secret_number");
// Support for pickle.
world_class.def(world_getinitargs, "__getinitargs__");
world_class.def(world_getstate, "__getstate__");
world_class.def(world_setstate, "__setstate__");
}
catch(...)
{
python::handle_exception(); // Deal with the exception for Python
}
}

150
example/pickle3.cpp Normal file
View File

@@ -0,0 +1,150 @@
// Example by Ralf W. Grosse-Kunstleve
/*
This example shows how to make an Extension Class "pickleable".
The world class below contains member data (secret_number) that
cannot be restored by any of the constructors. Therefore it is
necessary to provide the __getstate__/__setstate__ pair of pickle
interface methods.
The object's __dict__ is included in the result of __getstate__.
This requires more code (compare with pickle2.cpp), but is
unavoidable if the object's __dict__ is not always empty.
For more information refer to boost/libs/python/doc/pickle.html.
*/
#include <string>
#include <boost/python/class_builder.hpp>
namespace python = boost::python;
namespace boost { namespace python {
ref getattr(PyObject* o, const std::string& attr_name) {
return ref(PyObject_GetAttrString(o, const_cast<char*>(attr_name.c_str())));
}
ref getattr(const ref& r, const std::string& attr_name) {
return getattr(r.get(), attr_name);
}
}}
namespace { // Avoid cluttering the global namespace.
// A friendly class.
class world
{
public:
world(const std::string& country) : secret_number(0) {
this->country = country;
}
std::string greet() const { return "Hello from " + country + "!"; }
std::string get_country() const { return country; }
void set_secret_number(int number) { secret_number = number; }
int get_secret_number() const { return secret_number; }
private:
std::string country;
int secret_number;
};
// Support for pickle.
python::ref world_getinitargs(const world& w) {
python::tuple result(1);
result.set_item(0, w.get_country());
return result.reference(); // returning the reference avoids the copying.
}
python::ref world_getstate(python::tuple const & args,
python::dictionary const & keywords);
PyObject* world_setstate(python::tuple const & args,
python::dictionary const & keywords);
}
BOOST_PYTHON_MODULE_INIT(pickle3)
{
try
{
// Create an object representing this extension module.
python::module_builder this_module("pickle3");
// Create the Python type object for our extension class.
python::class_builder<world> world_class(this_module, "world");
// Add the __init__ function.
world_class.def(python::constructor<std::string>());
// Add a regular member function.
world_class.def(&world::greet, "greet");
world_class.def(&world::get_secret_number, "get_secret_number");
world_class.def(&world::set_secret_number, "set_secret_number");
// Support for pickle.
world_class.def(world_getinitargs, "__getinitargs__");
world_class.def_raw(world_getstate, "__getstate__");
world_class.def_raw(world_setstate, "__setstate__");
world_class.getstate_manages_dict();
}
catch(...)
{
python::handle_exception(); // Deal with the exception for Python
}
}
namespace {
using BOOST_PYTHON_CONVERSION::from_python;
using boost::python::type;
using boost::python::ref;
using boost::python::tuple;
using boost::python::list;
using boost::python::dictionary;
using boost::python::getattr;
ref world_getstate(tuple const & args, dictionary const & keywords)
{
if(args.size() != 1 || keywords.size() != 0) {
PyErr_SetString(PyExc_TypeError, "wrong number of arguments");
throw boost::python::argument_error();
}
const world& w = from_python(args[0].get(), type<const world&>());
ref mydict = getattr(args[0], "__dict__");
tuple result(2);
// store the object's __dict__
result.set_item(0, mydict);
// store the internal state of the C++ object
result.set_item(1, w.get_secret_number());
return result.reference(); // returning the reference avoids the copying.
}
PyObject* world_setstate(tuple const & args, dictionary const & keywords)
{
if(args.size() != 2 || keywords.size() != 0) {
PyErr_SetString(PyExc_TypeError, "wrong number of arguments");
throw boost::python::argument_error();
}
world& w = from_python(args[0].get(), type<world&>());
ref mydict = getattr(args[0], "__dict__");
tuple state = from_python(args[1].get(), type<tuple>());
if (state.size() != 2) {
PyErr_SetString(PyExc_ValueError,
"Unexpected argument in call to __setstate__.");
throw python::error_already_set();
}
// restore the object's __dict__
dictionary odict = from_python(mydict.get(), type<dictionary>());
const dictionary& pdict = from_python(state[0].get(), type<const dictionary&>());
list pkeys(pdict.keys());
for (int i = 0; i < pkeys.size(); i++) {
ref k(pkeys[i]);
//odict[k] = pdict[k]; // XXX memory leak!
odict[k] = pdict.get_item(k); // this does not leak.
}
// restore the internal state of the C++ object
int number = from_python(state[1].get(), type<int>());
if (number != 42)
w.set_secret_number(number);
return python::detail::none();
}
}

20
example/tst_dvect1.py Normal file
View File

@@ -0,0 +1,20 @@
def f():
import dvect
dv = dvect.dvect((1,2,3,4,5))
print dv.as_tuple()
iv = dv.as_ivect()
print iv.as_tuple()
print dvect.const_ivect_reference_as_tuple(iv)
aiv = dvect.ivect_as_auto_ptr(iv)
print dvect.const_ivect_reference_as_tuple(aiv)
siv = dvect.ivect_as_shared_ptr(iv)
print dvect.const_ivect_reference_as_tuple(siv)
print aiv.as_tuple()
print siv.as_tuple()
if (__name__ == "__main__"):
import sys, string
n = 1
if (len(sys.argv) > 1): n = string.atoi(sys.argv[1])
for i in xrange(n):
f()

20
example/tst_ivect1.py Normal file
View File

@@ -0,0 +1,20 @@
def f():
import ivect
iv = ivect.ivect((1,2,3,4,5))
print iv.as_tuple()
dv = iv.as_dvect()
print dv.as_tuple()
print ivect.const_dvect_reference_as_tuple(dv)
adv = ivect.dvect_as_auto_ptr(dv)
print ivect.const_dvect_reference_as_tuple(adv)
sdv = ivect.dvect_as_shared_ptr(dv)
print ivect.const_dvect_reference_as_tuple(sdv)
print adv.as_tuple()
print sdv.as_tuple()
if (__name__ == "__main__"):
import sys, string
n = 1
if (len(sys.argv) > 1): n = string.atoi(sys.argv[1])
for i in xrange(n):
f()

View File

@@ -0,0 +1,16 @@
def f():
import noncopyable_export
import noncopyable_import
s1 = noncopyable_export.store(1)
print s1.recall()
s2 = noncopyable_export.store(2)
print s2.recall()
s3 = noncopyable_import.add_stores(s1, s2)
print s3.recall()
if (__name__ == "__main__"):
import sys, string
n = 1
if (len(sys.argv) > 1): n = string.atoi(sys.argv[1])
for i in xrange(n):
f()