2
0
mirror of https://github.com/boostorg/python.git synced 2026-02-02 21:12:15 +00:00

Toons of changes to improve error handling.

Added attributes function.__name__, function.__signature__, and
the dir(function) feature


[SVN r8313]
This commit is contained in:
Ullrich Köthe
2000-11-23 23:03:24 +00:00
parent f7ad50166d
commit e3fe2d02ee
19 changed files with 1423 additions and 1721 deletions

1002
caller.h

File diff suppressed because it is too large Load Diff

View File

@@ -329,9 +329,9 @@ PyObject* read_only_setattr_function::do_call(PyObject* /*args*/, PyObject* /*ke
return 0;
}
const char* read_only_setattr_function::description() const
PyObject* read_only_setattr_function::description() const
{
return "uncallable";
return BOOST_PYTHON_CONVERSION::to_python("uncallable");
}
extension_class_base::extension_class_base(const char* name)
@@ -469,6 +469,19 @@ operator_dispatcher::create(const ref& object, const ref& self)
return result;
}
namespace {
void set_attribute_error(const char* oper, tuple args)
{
PyErr_Clear();
string message(oper);
message += argument_tuple_as_string(args);
message += " undefined.";
PyErr_SetObject(PyExc_TypeError, message.get());
}
} // anonymous namespace
extern "C"
{
@@ -498,7 +511,7 @@ int operator_dispatcher_coerce(PyObject** l, PyObject** r)
#define PY_DEFINE_OPERATOR(id, symbol) \
PyObject* operator_dispatcher_call_##id(PyObject* left, PyObject* right) \
PyObject* operator_dispatcher_call_##id(PyObject* left, PyObject* right) \
{ \
/* unwrap the arguments from their OperatorDispatcher */ \
PyObject* self; \
@@ -506,17 +519,20 @@ int operator_dispatcher_coerce(PyObject** l, PyObject** r)
int reverse = unwrap_args(left, right, self, other); \
if (reverse == unwrap_exception_code) \
return 0; \
const char * oper = reverse \
? "__r" #id "__" \
: "__" #id "__"; \
\
/* call the function */ \
PyObject* result = \
PyEval_CallMethod(self, \
const_cast<char*>(reverse ? "__r" #id "__" : "__" #id "__"), \
const_cast<char*>(oper), \
const_cast<char*>("(O)"), \
other); \
if (result == 0 && PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_AttributeError)) \
{ \
PyErr_Clear(); \
PyErr_SetString(PyExc_TypeError, "bad operand type(s) for " #symbol); \
tuple args(ref(self, ref::increment_count), ref(other, ref::increment_count)); \
set_attribute_error(oper , args); \
} \
return result; \
}
@@ -562,24 +578,34 @@ PyObject* operator_dispatcher_call_pow(PyObject* left, PyObject* right, PyObject
if (reverse == unwrap_exception_code)
return 0;
const char * oper = (reverse == 0)
? "__pow__"
: (reverse == 1)
? "__rpow__"
: "__rrpow__";
// call the function
PyObject* result =
PyEval_CallMethod(self,
const_cast<char*>((reverse == 0)
? "__pow__"
: (reverse == 1)
? "__rpow__"
: "__rrpow__"),
const_cast<char*>(oper),
const_cast<char*>("(OO)"),
first, second);
if (result == 0 &&
(PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_TypeError) ||
PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_AttributeError)))
{
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "bad operand type(s) for pow()");
}
if (result == 0 && PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_AttributeError))
{
if(m == Py_None)
{
tuple args(ref(self, ref::increment_count), ref(first, ref::increment_count));
set_attribute_error(oper , args);
}
else
{
tuple args(ref(self, ref::increment_count),
ref(first, ref::increment_count),
ref(second, ref::increment_count));
set_attribute_error(oper , args);
}
}
return result;
}
@@ -592,16 +618,23 @@ int operator_dispatcher_call_cmp(PyObject* left, PyObject* right)
if (reverse == unwrap_exception_code)
return -1;
const char * oper = reverse
? "__rcmp__"
: "__cmp__";
// call the function
PyObject* result =
PyEval_CallMethod(self,
const_cast<char*>(reverse ? "__rcmp__" : "__cmp__"),
const_cast<char*>(oper),
const_cast<char*>("(O)"),
other);
if (result == 0 && PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_AttributeError))
{
tuple args(ref(self, ref::increment_count), ref(other, ref::increment_count));
set_attribute_error(oper , args);
}
if (result == 0)
{
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "bad operand type(s) for cmp() or <");
return -1;
}
else

View File

@@ -133,6 +133,39 @@ class class_registry
static std::vector<derived_class_info> static_derived_class_info;
};
template <class T, class H>
no_t* is_plain_aux(type<instance_value_holder<T, H> >);
template <class T, class H>
string forward_python_type_name(python::type<instance_value_holder<T, H> >)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <class T, class H>
no_t* is_plain_aux(type<instance_ptr_holder<T, H> >);
template <class T, class H>
string forward_python_type_name(python::type<instance_ptr_holder<T, H> >)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <class T>
string python_type_name(type<T>)
{
if(class_registry<T>::class_object() == 0)
{
return string("UnknownType");
}
else
{
return class_registry<T>::class_object()->complete_class_name();
}
}
}} // namespace python::detail
BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE
@@ -314,7 +347,9 @@ class read_only_setattr_function : public function
public:
read_only_setattr_function(const char* name);
PyObject* do_call(PyObject* args, PyObject* keywords) const;
const char* description() const;
PyObject* description() const;
string function_name() const
{ return m_name; }
private:
string m_name;
};
@@ -428,7 +463,7 @@ class extension_class
template <class Fn>
inline void def_raw(Fn fn, const char* name)
{
this->add_method(new_raw_arguments_function(fn), name);
this->add_method(new_raw_arguments_function(fn, name), name);
}
// define member functions. In fact this works for free functions, too -
@@ -438,7 +473,7 @@ class extension_class
template <class Fn>
inline void def(Fn fn, const char* name)
{
this->add_method(new_wrapped_function(fn), name);
this->add_method(new_wrapped_function(fn, name), name);
}
// Define a virtual member function with a default implementation.
@@ -447,7 +482,7 @@ class extension_class
template <class Fn, class DefaultFn>
inline void def(Fn fn, const char* name, DefaultFn default_fn)
{
this->add_method(new_virtual_function(type<T>(), fn, default_fn), name);
this->add_method(new_virtual_function(type<T>(), fn, default_fn, name), name);
}
// Provide a function which implements x.<name>, reading from the given
@@ -455,7 +490,7 @@ class extension_class
template <class MemberType>
inline void def_getter(MemberType T::*pm, const char* name)
{
this->add_getter_method(new getter_function<T, MemberType>(pm), name);
this->add_getter_method(new getter_function<T, MemberType>(pm, name), name);
}
// Provide a function which implements assignment to x.<name>, writing to
@@ -463,7 +498,7 @@ class extension_class
template <class MemberType>
inline void def_setter(MemberType T::*pm, const char* name)
{
this->add_setter_method(new setter_function<T, MemberType>(pm), name);
this->add_setter_method(new setter_function<T, MemberType>(pm, name), name);
}
// Expose the given member (pm) of the T obj as a read-only attribute

View File

@@ -11,13 +11,35 @@
#include "singleton.h"
#include "objects.h"
#include "errors.h"
#include "extclass.h"
namespace python { namespace detail {
struct function::type_object :
singleton<function::type_object, callable<python::detail::type_object<function> > >
string argument_tuple_as_string(tuple arguments)
{
type_object() : singleton_base(&PyType_Type) {}
string result("(");
for (std::size_t i = 0; i < arguments.size(); ++i)
{
if (i != 0)
result += ", ";
if(arguments[i]->ob_type->ob_type == extension_meta_class())
{
result += downcast<class_base>(arguments[i]->ob_type).get()->complete_class_name();
}
else
{
result += arguments[i]->ob_type->tp_name;
}
}
result += ")";
return result;
}
struct function::type_object :
singleton<function::type_object, getattrable<callable<python::detail::type_object<function> > > >
{
type_object() : singleton_base(&PyType_Type)
{}
};
@@ -56,6 +78,38 @@ function::function()
{
}
PyObject* function::getattr(const char * name) const
{
if(strcmp(name, "__signatures__") == 0)
{
list signatures;
for (const function* f = this; f != 0; f = f->m_overloads.get())
{
signatures.push_back(f->description());
}
return signatures.reference().release();
}
else if(strcmp(name, "__name__") == 0)
{
return function_name().reference().release();
}
else if(strcmp(name, "__dict__") == 0)
{
dictionary items;
items.set_item(string("__name__"), detail::none());
items.set_item(string("__signatures__"), detail::none());
return items.reference().release();
}
else
{
PyErr_SetString(PyExc_AttributeError, name);
return 0;
}
}
PyObject* function::call(PyObject* args, PyObject* keywords) const
{
for (const function* f = this; f != 0; f = f->m_overloads.get())
@@ -69,6 +123,26 @@ PyObject* function::call(PyObject* args, PyObject* keywords) const
}
catch(const argument_error&)
{
if(m_overloads.get() == 0 && rephrase_argument_error() &&
PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_TypeError))
{
PyErr_Clear();
string message("");
string name(this->function_name());
if(name.size() != 0)
{
message += "'";
message += name;
message += "' ";
}
message += "expected argument(s) ";
message += description_as_string();
message += ",\nbut got ";
tuple arguments(ref(args, ref::increment_count));
message += argument_types_as_string(arguments);
message += " instead.";
PyErr_SetObject(PyExc_TypeError, message.get());
}
}
}
@@ -76,27 +150,52 @@ PyObject* function::call(PyObject* args, PyObject* keywords) const
return 0;
PyErr_Clear();
string message("No overloaded functions match (");
tuple arguments(ref(args, ref::increment_count));
for (std::size_t i = 0; i < arguments.size(); ++i)
string message("No variant of overloaded function");
string name(this->function_name());
if(name.size() != 0)
{
if (i != 0)
message += ", ";
message += arguments[i]->ob_type->tp_name;
message += " '";
message += name;
message += "'";
}
message += " matches argument(s):\n";
tuple arguments(ref(args, ref::increment_count));
message += argument_types_as_string(arguments);
message += "). Candidates are:\n";
message += "\nCandidates are:\n";
for (const function* f1 = this; f1 != 0; f1 = f1->m_overloads.get())
{
if (f1 != this)
message += "\n";
message += f1->description();
message += f1->description_as_string();
}
PyErr_SetObject(PyExc_TypeError, message.get());
return 0;
}
string function::description_as_string() const
{
string result("(");
tuple arguments(ref(this->description()));
for (std::size_t i = 0; i < arguments.size(); ++i)
{
if (i != 0)
result += ", ";
result += string(arguments[i]);
}
result += ")";
return result;
}
string function::argument_types_as_string(tuple arguments) const
{
return argument_tuple_as_string(arguments);
}
bound_function* bound_function::create(const ref& target, const ref& fn)
{
bound_function* const result = free_list;

View File

@@ -25,6 +25,8 @@ namespace python { namespace detail {
// forward declaration
class extension_instance;
string argument_tuple_as_string(tuple args);
// function --
// the common base class for all overloadable function and method objects
@@ -38,17 +40,36 @@ class function : public python_object
virtual ~function() {}
PyObject* call(PyObject* args, PyObject* keywords) const;
PyObject* getattr(const char * name) const;
static void add_to_namespace(reference<function> f, const char* name, PyObject* dict);
protected:
virtual PyObject* description() const = 0;
private:
virtual PyObject* do_call(PyObject* args, PyObject* keywords) const = 0;
virtual const char* description() const = 0;
virtual string description_as_string() const;
virtual string argument_types_as_string(tuple args) const;
virtual string function_name() const = 0;
virtual bool rephrase_argument_error() const
{ return true; }
private:
struct type_object;
private:
reference<function> m_overloads;
};
struct named_function : function
{
named_function(const char * name)
: m_name(name)
{}
string function_name() const
{ return m_name; }
string m_name;
};
// wrapped_function_pointer<> --
// A single function or member function pointer wrapped and presented to
// Python as a callable object.
@@ -57,19 +78,19 @@ class function : public python_object
// R - the return type of the function pointer
// F - the complete type of the wrapped function pointer
template <class R, class F>
struct wrapped_function_pointer : function
struct wrapped_function_pointer : named_function
{
typedef F ptr_fun; // pointer-to--function or pointer-to-member-function
wrapped_function_pointer(ptr_fun pf)
: m_pf(pf) {}
wrapped_function_pointer(ptr_fun pf, const char * name)
: named_function(name), m_pf(pf) {}
private:
PyObject* do_call(PyObject* args, PyObject* keywords) const
{ return caller<R>::call(m_pf, args, keywords); }
const char* description() const
{ return typeid(F).name(); }
PyObject* description() const
{ return function_signature(m_pf); }
private:
const ptr_fun m_pf;
@@ -80,15 +101,15 @@ struct wrapped_function_pointer : function
// verbatim to C++ (useful for customized argument parsing and variable
// argument lists)
template <class Ret, class Args, class Keywords>
struct raw_arguments_function : function
struct raw_arguments_function : named_function
{
typedef Ret (*ptr_fun)(Args, Keywords);
raw_arguments_function(ptr_fun pf)
: m_pf(pf) {}
raw_arguments_function(ptr_fun pf, const char * name)
: named_function(name), m_pf(pf) {}
private:
PyObject* do_call(PyObject* args, PyObject* keywords) const
PyObject* do_call(PyObject* args, PyObject* keywords) const
{
ref dict(keywords ?
ref(keywords, ref::increment_count) :
@@ -99,9 +120,17 @@ struct raw_arguments_function : function
from_python(dict.get(), python::type<Keywords>())));
}
const char* description() const
{ return typeid(ptr_fun).name(); }
PyObject* description() const
{
tuple result(1);
result.set_item(0, string("..."));
return result.reference().release();
}
virtual bool rephrase_argument_error() const
{ return false; }
private:
const ptr_fun m_pf;
};
@@ -119,19 +148,20 @@ struct raw_arguments_function : function
// parameter and calls T::f on it /non-virtually/, where V
// approximates &T::f.
template <class T, class R, class V, class D>
class virtual_function : public function
class virtual_function : public named_function
{
public:
virtual_function(V virtual_function_ptr, D default_implementation)
: m_virtual_function_ptr(virtual_function_ptr),
virtual_function(V virtual_function_ptr, D default_implementation, const char * name)
: named_function(name),
m_virtual_function_ptr(virtual_function_ptr),
m_default_implementation(default_implementation)
{}
private:
PyObject* do_call(PyObject* args, PyObject* keywords) const;
const char* description() const
{ return typeid(V).name(); }
PyObject* description() const
{ return function_signature(m_virtual_function_ptr); }
private:
const V m_virtual_function_ptr;
@@ -142,26 +172,26 @@ class virtual_function : public function
// functionality once the return type has already been deduced. R is expected to
// be type<X>, where X is the actual return type of pmf.
template <class F, class R>
function* new_wrapped_function_aux(R, F pmf)
function* new_wrapped_function_aux(R, F pmf, const char * name)
{
// We can't just use "typename R::Type" below because MSVC (incorrectly) pukes.
typedef typename R::type return_type;
return new wrapped_function_pointer<return_type, F>(pmf);
return new wrapped_function_pointer<return_type, F>(pmf, name);
}
// Create and return a new member function object wrapping the given
// pointer-to-member function
template <class F>
inline function* new_wrapped_function(F pmf)
inline function* new_wrapped_function(F pmf, const char * name)
{
// Deduce the return type and pass it off to the helper function above
return new_wrapped_function_aux(return_value(pmf), pmf);
return new_wrapped_function_aux(return_value(pmf), pmf, name);
}
template <class R, class Args, class keywords>
function* new_raw_arguments_function(R (*pmf)(Args, keywords))
function* new_raw_arguments_function(R (*pmf)(Args, keywords), const char * name)
{
return new raw_arguments_function<R, Args, keywords>(pmf);
return new raw_arguments_function<R, Args, keywords>(pmf, name);
}
@@ -170,26 +200,26 @@ function* new_raw_arguments_function(R (*pmf)(Args, keywords))
// be type<X>, where X is the actual return type of V.
template <class T, class R, class V, class D>
inline function* new_virtual_function_aux(
type<T>, R, V virtual_function_ptr, D default_implementation
)
type<T>, R, V virtual_function_ptr, D default_implementation,
const char * name)
{
// We can't just use "typename R::Type" below because MSVC (incorrectly) pukes.
typedef typename R::type return_type;
return new virtual_function<T, return_type, V, D>(
virtual_function_ptr, default_implementation);
virtual_function_ptr, default_implementation, name);
}
// Create and return a new virtual_function object wrapping the given
// virtual_function_ptr and default_implementation
template <class T, class V, class D>
inline function* new_virtual_function(
type<T>, V virtual_function_ptr, D default_implementation
)
type<T>, V virtual_function_ptr, D default_implementation,
const char * name)
{
// Deduce the return type and pass it off to the helper function above
return new_virtual_function_aux(
type<T>(), return_value(virtual_function_ptr),
virtual_function_ptr, default_implementation);
virtual_function_ptr, default_implementation, name);
}
// A function with a bundled "bound target" object. This is what is produced by
@@ -220,37 +250,37 @@ class bound_function : public python_object
// Special functions designed to access data members of a wrapped C++ object.
template <class ClassType, class MemberType>
class getter_function : public function
class getter_function : public named_function
{
public:
typedef MemberType ClassType::* pointer_to_member;
getter_function(pointer_to_member pm)
: m_pm(pm) {}
getter_function(pointer_to_member pm, const char * name)
: named_function(name), m_pm(pm) {}
private:
PyObject* do_call(PyObject* args, PyObject* keywords) const;
const char* description() const
{ return typeid(MemberType (*)(const ClassType&)).name(); }
PyObject* description() const
{ return function_signature((MemberType (*)(const ClassType&))0); }
private:
pointer_to_member m_pm;
};
template <class ClassType, class MemberType>
class setter_function : public function
class setter_function : public named_function
{
public:
typedef MemberType ClassType::* pointer_to_member;
setter_function(pointer_to_member pm)
: m_pm(pm) {}
setter_function(pointer_to_member pm, const char * name)
: named_function(name), m_pm(pm) {}
private:
PyObject* do_call(PyObject* args, PyObject* keywords) const;
const char* description() const
{ return typeid(void (*)(const ClassType&, const MemberType&)).name(); }
PyObject* description() const
{ return function_signature((void (*)(const ClassType&, const MemberType&))0); }
private:
pointer_to_member m_pm;
};

View File

@@ -31,6 +31,7 @@ body_sections = (
# include <boost/config.hpp>
# include "signatures.h"
# include "none.h"
# include "objects.h"
namespace python {
@@ -56,9 +57,25 @@ struct caller<void>
''',
'''};
}
namespace detail
{
// create signature tuples
inline''',
'''
// member functions
''',
'''
// const member functions
''',
'''
// free functions
''',
'''} // namespace detail
#endif
} // namespace python
#endif // CALLER_DWA05090_H_
''')
#'
@@ -87,6 +104,34 @@ free_function = '''%{ template <%(class A%n%:, %)>
'''
function_signature = '''%{template <%}%(class A%n%:, %)%{>%}
PyObject* function_signature(%(type<A%n>%:, %)) {
%( static const bool is_plain_A%n = BOOST_PYTHON_IS_PLAIN(A%n);
%) tuple result(%x);
%( result.set_item(%N, python_type_name_selector<is_plain_A%n>::get(type<A%n>()));
%)
return result.reference().release();
}
'''
member_function_signature = '''template <class R, class T%(, class A%n%)>
inline PyObject* function_signature(R (T::*pmf)(%(A%n%:, %))%1) {
return function_signature(
python::type<T>()%(,
python::type<A%n>()%));
}
'''
free_function_signature = '''template <class R%(, class A%n%)>
inline PyObject* function_signature(R (*f)(%(A%n%:, %))) {
return function_signature(%(
python::type<A%n>()%:,%));
}
'''
def gen_caller(member_function_args, free_function_args = None):
if free_function_args is None:
free_function_args = member_function_args + 1
@@ -118,6 +163,16 @@ def gen_caller(member_function_args, free_function_args = None):
+ gen_functions(free_function, free_function_args,
'void', '', return_none)
+ body_sections[6]
# create lists describing the function signatures
+ gen_functions(function_signature, free_function_args)
+ body_sections[7]
+ gen_functions(member_function_signature, member_function_args, '')
+ body_sections[8]
+ gen_functions(member_function_signature, member_function_args, ' const')
+ body_sections[9]
+ gen_functions(free_function_signature, free_function_args)
+ body_sections[10]
)
if __name__ == '__main__':

View File

@@ -138,6 +138,39 @@ class class_registry
static std::vector<derived_class_info> static_derived_class_info;
};
template <class T, class H>
no_t* is_plain_aux(type<instance_value_holder<T, H> >);
template <class T, class H>
string forward_python_type_name(python::type<instance_value_holder<T, H> >)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <class T, class H>
no_t* is_plain_aux(type<instance_ptr_holder<T, H> >);
template <class T, class H>
string forward_python_type_name(python::type<instance_ptr_holder<T, H> >)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <class T>
string python_type_name(type<T>)
{
if(class_registry<T>::class_object() == 0)
{
return string("UnknownType");
}
else
{
return class_registry<T>::class_object()->complete_class_name();
}
}
}} // namespace python::detail
BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE
@@ -319,7 +352,9 @@ class read_only_setattr_function : public function
public:
read_only_setattr_function(const char* name);
PyObject* do_call(PyObject* args, PyObject* keywords) const;
const char* description() const;
PyObject* description() const;
string function_name() const
{ return m_name; }
private:
string m_name;
};
@@ -433,7 +468,7 @@ class extension_class
template <class Fn>
inline void def_raw(Fn fn, const char* name)
{
this->add_method(new_raw_arguments_function(fn), name);
this->add_method(new_raw_arguments_function(fn, name), name);
}
// define member functions. In fact this works for free functions, too -
@@ -443,7 +478,7 @@ class extension_class
template <class Fn>
inline void def(Fn fn, const char* name)
{
this->add_method(new_wrapped_function(fn), name);
this->add_method(new_wrapped_function(fn, name), name);
}
// Define a virtual member function with a default implementation.
@@ -452,7 +487,7 @@ class extension_class
template <class Fn, class DefaultFn>
inline void def(Fn fn, const char* name, DefaultFn default_fn)
{
this->add_method(new_virtual_function(type<T>(), fn, default_fn), name);
this->add_method(new_virtual_function(type<T>(), fn, default_fn, name), name);
}
// Provide a function which implements x.<name>, reading from the given
@@ -460,7 +495,7 @@ class extension_class
template <class MemberType>
inline void def_getter(MemberType T::*pm, const char* name)
{
this->add_getter_method(new getter_function<T, MemberType>(pm), name);
this->add_getter_method(new getter_function<T, MemberType>(pm, name), name);
}
// Provide a function which implements assignment to x.<name>, writing to
@@ -468,7 +503,7 @@ class extension_class
template <class MemberType>
inline void def_setter(MemberType T::*pm, const char* name)
{
this->add_setter_method(new setter_function<T, MemberType>(pm), name);
this->add_setter_method(new setter_function<T, MemberType>(pm, name), name);
}
// Expose the given member (pm) of the T obj as a read-only attribute

View File

@@ -35,6 +35,8 @@ def _gen_arg(template, n, args, delimiter = '%'):
if key == 'n':
result = result + `n`
elif key == 'N':
result = result + `n-1`
else:
result = result + _gen_common_key(key, n, args)
@@ -55,8 +57,13 @@ def gen_function(template, n, *args, **keywords):
%n is transformed into the string representation of 1..n for each repetition
of n.
%x, where x is a digit, is transformed into the corresponding additional
%N is transformed into the string representation of 0..(n-1) for each repetition
of n.
%i, where i is a digit, is transformed into the corresponding additional
argument.
%x is transformed into the number of the current repetition
for example,

View File

@@ -130,6 +130,8 @@ private: // override function hook
PyObject* do_call(PyObject* args, PyObject* keywords) const;
private:
virtual instance_holder_base* create_holder(extension_instance* self, PyObject* tail_args, PyObject* keywords) const = 0;
string description_as_string() const;
string argument_types_as_string(tuple args) const;
};
""" + gen_functions("""
@@ -145,8 +147,20 @@ struct init%x : init
python::detail::reference_parameter<A%n>(from_python(a%n, type<A%n>()))%)
);
}
const char* description() const
{ return typeid(void (*)(T&%(, A%n%%))).name(); }
PyObject* description() const
{
return function_signature(python::type<T>()%(,
python::type<A%n>()%));
}
string function_name() const
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
string result(python_type_name_selector<is_plain>::get(python::type<T>()));
result += ".__init__";
return result;
}
};""", args) + """
}} // namespace python::detail

View File

@@ -33,4 +33,24 @@ namespace python { namespace detail {
return none();
}
string init::description_as_string() const
{
tuple arguments(ref(this->description()));
string result("(");
for (std::size_t i = 1; i < arguments.size(); ++i)
{
if (i != 1)
result += ", ";
result += string(arguments[i]);
}
result += ")";
return result;
}
string init::argument_types_as_string(tuple arguments) const
{
return argument_tuple_as_string(arguments.slice(1,arguments.size()));
}
}} // namespace python::detail

View File

@@ -110,11 +110,6 @@ template <class T, class A1, class A2> struct init2;
template <class T, class A1, class A2, class A3> struct init3;
template <class T, class A1, class A2, class A3, class A4> struct init4;
template <class T, class A1, class A2, class A3, class A4, class A5> struct init5;
template <class T, class A1, class A2, class A3, class A4, class A5, class A6> struct Init6;
template <class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7> struct Init7;
template <class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> struct Init8;
template <class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> struct Init9;
template <class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> struct Init10;
template <class T>
struct init_function
@@ -162,71 +157,6 @@ struct init_function
detail::parameter_traits<A4>::const_reference,
detail::parameter_traits<A5>::const_reference>;
}
template <class A1, class A2, class A3, class A4, class A5, class A6>
static init* create(signature6<A1, A2, A3, A4, A5, A6>) {
return new Init6<T,
detail::parameter_traits<A1>::const_reference,
detail::parameter_traits<A2>::const_reference,
detail::parameter_traits<A3>::const_reference,
detail::parameter_traits<A4>::const_reference,
detail::parameter_traits<A5>::const_reference,
detail::parameter_traits<A6>::const_reference>;
}
template <class A1, class A2, class A3, class A4, class A5, class A6, class A7>
static init* create(signature7<A1, A2, A3, A4, A5, A6, A7>) {
return new Init7<T,
detail::parameter_traits<A1>::const_reference,
detail::parameter_traits<A2>::const_reference,
detail::parameter_traits<A3>::const_reference,
detail::parameter_traits<A4>::const_reference,
detail::parameter_traits<A5>::const_reference,
detail::parameter_traits<A6>::const_reference,
detail::parameter_traits<A7>::const_reference>;
}
template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8>
static init* create(signature8<A1, A2, A3, A4, A5, A6, A7, A8>) {
return new Init8<T,
detail::parameter_traits<A1>::const_reference,
detail::parameter_traits<A2>::const_reference,
detail::parameter_traits<A3>::const_reference,
detail::parameter_traits<A4>::const_reference,
detail::parameter_traits<A5>::const_reference,
detail::parameter_traits<A6>::const_reference,
detail::parameter_traits<A7>::const_reference,
detail::parameter_traits<A8>::const_reference>;
}
template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9>
static init* create(signature9<A1, A2, A3, A4, A5, A6, A7, A8, A9>) {
return new Init9<T,
detail::parameter_traits<A1>::const_reference,
detail::parameter_traits<A2>::const_reference,
detail::parameter_traits<A3>::const_reference,
detail::parameter_traits<A4>::const_reference,
detail::parameter_traits<A5>::const_reference,
detail::parameter_traits<A6>::const_reference,
detail::parameter_traits<A7>::const_reference,
detail::parameter_traits<A8>::const_reference,
detail::parameter_traits<A9>::const_reference>;
}
template <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10>
static init* create(signature10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>) {
return new Init10<T,
detail::parameter_traits<A1>::const_reference,
detail::parameter_traits<A2>::const_reference,
detail::parameter_traits<A3>::const_reference,
detail::parameter_traits<A4>::const_reference,
detail::parameter_traits<A5>::const_reference,
detail::parameter_traits<A6>::const_reference,
detail::parameter_traits<A7>::const_reference,
detail::parameter_traits<A8>::const_reference,
detail::parameter_traits<A9>::const_reference,
detail::parameter_traits<A10>::const_reference>;
}
};
class init : public function
@@ -235,6 +165,8 @@ private: // override function hook
PyObject* do_call(PyObject* args, PyObject* keywords) const;
private:
virtual instance_holder_base* create_holder(extension_instance* self, PyObject* tail_args, PyObject* keywords) const = 0;
string description_as_string() const;
string argument_types_as_string(tuple args) const;
};
@@ -248,8 +180,19 @@ struct init0 : init
return new T(self
);
}
const char* description() const
{ return typeid(void (*)(T&)).name(); }
PyObject* description() const
{
return function_signature(python::type<T>());
}
string function_name() const
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
string result(python_type_name_selector<is_plain>::get(python::type<T>()));
result += ".__init__";
return result;
}
};
template <class T, class A1>
@@ -264,8 +207,20 @@ struct init1 : init
python::detail::reference_parameter<A1>(from_python(a1, type<A1>()))
);
}
const char* description() const
{ return typeid(void (*)(T&, A1)).name(); }
PyObject* description() const
{
return function_signature(python::type<T>(),
python::type<A1>());
}
string function_name() const
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
string result(python_type_name_selector<is_plain>::get(python::type<T>()));
result += ".__init__";
return result;
}
};
template <class T, class A1, class A2>
@@ -282,8 +237,21 @@ struct init2 : init
python::detail::reference_parameter<A2>(from_python(a2, type<A2>()))
);
}
const char* description() const
{ return typeid(void (*)(T&, A1, A2)).name(); }
PyObject* description() const
{
return function_signature(python::type<T>(),
python::type<A1>(),
python::type<A2>());
}
string function_name() const
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
string result(python_type_name_selector<is_plain>::get(python::type<T>()));
result += ".__init__";
return result;
}
};
template <class T, class A1, class A2, class A3>
@@ -302,8 +270,22 @@ struct init3 : init
python::detail::reference_parameter<A3>(from_python(a3, type<A3>()))
);
}
const char* description() const
{ return typeid(void (*)(T&, A1, A2, A3)).name(); }
PyObject* description() const
{
return function_signature(python::type<T>(),
python::type<A1>(),
python::type<A2>(),
python::type<A3>());
}
string function_name() const
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
string result(python_type_name_selector<is_plain>::get(python::type<T>()));
result += ".__init__";
return result;
}
};
template <class T, class A1, class A2, class A3, class A4>
@@ -324,8 +306,23 @@ struct init4 : init
python::detail::reference_parameter<A4>(from_python(a4, type<A4>()))
);
}
const char* description() const
{ return typeid(void (*)(T&, A1, A2, A3, A4)).name(); }
PyObject* description() const
{
return function_signature(python::type<T>(),
python::type<A1>(),
python::type<A2>(),
python::type<A3>(),
python::type<A4>());
}
string function_name() const
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
string result(python_type_name_selector<is_plain>::get(python::type<T>()));
result += ".__init__";
return result;
}
};
template <class T, class A1, class A2, class A3, class A4, class A5>
@@ -348,160 +345,27 @@ struct init5 : init
python::detail::reference_parameter<A5>(from_python(a5, type<A5>()))
);
}
const char* description() const
{ return typeid(void (*)(T&, A1, A2, A3, A4, A5)).name(); }
};
template <class T, class A1, class A2, class A3, class A4, class A5, class A6>
struct Init6 : init
{
virtual instance_holder_base* create_holder(extension_instance* self, PyObject* args, PyObject* /*keywords*/) const
{
PyObject* a1;
PyObject* a2;
PyObject* a3;
PyObject* a4;
PyObject* a5;
PyObject* a6;
if (!PyArg_ParseTuple(args, const_cast<char*>("OOOOOO"), &a1, &a2, &a3, &a4, &a5, &a6))
throw argument_error();
return new T(self,
python::detail::reference_parameter<A1>(from_python(a1, type<A1>())),
python::detail::reference_parameter<A2>(from_python(a2, type<A2>())),
python::detail::reference_parameter<A3>(from_python(a3, type<A3>())),
python::detail::reference_parameter<A4>(from_python(a4, type<A4>())),
python::detail::reference_parameter<A5>(from_python(a5, type<A5>())),
python::detail::reference_parameter<A6>(from_python(a6, type<A6>()))
);
PyObject* description() const
{
return function_signature(python::type<T>(),
python::type<A1>(),
python::type<A2>(),
python::type<A3>(),
python::type<A4>(),
python::type<A5>());
}
const char* description() const
{ return typeid(void (*)(T&, A1, A2, A3, A4, A5, A6)).name(); }
};
template <class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7>
struct Init7 : init
{
virtual instance_holder_base* create_holder(extension_instance* self, PyObject* args, PyObject* /*keywords*/) const
{
PyObject* a1;
PyObject* a2;
PyObject* a3;
PyObject* a4;
PyObject* a5;
PyObject* a6;
PyObject* a7;
if (!PyArg_ParseTuple(args, const_cast<char*>("OOOOOOO"), &a1, &a2, &a3, &a4, &a5, &a6, &a7))
throw argument_error();
return new T(self,
python::detail::reference_parameter<A1>(from_python(a1, type<A1>())),
python::detail::reference_parameter<A2>(from_python(a2, type<A2>())),
python::detail::reference_parameter<A3>(from_python(a3, type<A3>())),
python::detail::reference_parameter<A4>(from_python(a4, type<A4>())),
python::detail::reference_parameter<A5>(from_python(a5, type<A5>())),
python::detail::reference_parameter<A6>(from_python(a6, type<A6>())),
python::detail::reference_parameter<A7>(from_python(a7, type<A7>()))
);
string function_name() const
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
string result(python_type_name_selector<is_plain>::get(python::type<T>()));
result += ".__init__";
return result;
}
const char* description() const
{ return typeid(void (*)(T&, A1, A2, A3, A4, A5, A6, A7)).name(); }
};
template <class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8>
struct Init8 : init
{
virtual instance_holder_base* create_holder(extension_instance* self, PyObject* args, PyObject* /*keywords*/) const
{
PyObject* a1;
PyObject* a2;
PyObject* a3;
PyObject* a4;
PyObject* a5;
PyObject* a6;
PyObject* a7;
PyObject* a8;
if (!PyArg_ParseTuple(args, const_cast<char*>("OOOOOOOO"), &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8))
throw argument_error();
return new T(self,
python::detail::reference_parameter<A1>(from_python(a1, type<A1>())),
python::detail::reference_parameter<A2>(from_python(a2, type<A2>())),
python::detail::reference_parameter<A3>(from_python(a3, type<A3>())),
python::detail::reference_parameter<A4>(from_python(a4, type<A4>())),
python::detail::reference_parameter<A5>(from_python(a5, type<A5>())),
python::detail::reference_parameter<A6>(from_python(a6, type<A6>())),
python::detail::reference_parameter<A7>(from_python(a7, type<A7>())),
python::detail::reference_parameter<A8>(from_python(a8, type<A8>()))
);
}
const char* description() const
{ return typeid(void (*)(T&, A1, A2, A3, A4, A5, A6, A7, A8)).name(); }
};
template <class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9>
struct Init9 : init
{
virtual instance_holder_base* create_holder(extension_instance* self, PyObject* args, PyObject* /*keywords*/) const
{
PyObject* a1;
PyObject* a2;
PyObject* a3;
PyObject* a4;
PyObject* a5;
PyObject* a6;
PyObject* a7;
PyObject* a8;
PyObject* a9;
if (!PyArg_ParseTuple(args, const_cast<char*>("OOOOOOOOO"), &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9))
throw argument_error();
return new T(self,
python::detail::reference_parameter<A1>(from_python(a1, type<A1>())),
python::detail::reference_parameter<A2>(from_python(a2, type<A2>())),
python::detail::reference_parameter<A3>(from_python(a3, type<A3>())),
python::detail::reference_parameter<A4>(from_python(a4, type<A4>())),
python::detail::reference_parameter<A5>(from_python(a5, type<A5>())),
python::detail::reference_parameter<A6>(from_python(a6, type<A6>())),
python::detail::reference_parameter<A7>(from_python(a7, type<A7>())),
python::detail::reference_parameter<A8>(from_python(a8, type<A8>())),
python::detail::reference_parameter<A9>(from_python(a9, type<A9>()))
);
}
const char* description() const
{ return typeid(void (*)(T&, A1, A2, A3, A4, A5, A6, A7, A8, A9)).name(); }
};
template <class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10>
struct Init10 : init
{
virtual instance_holder_base* create_holder(extension_instance* self, PyObject* args, PyObject* /*keywords*/) const
{
PyObject* a1;
PyObject* a2;
PyObject* a3;
PyObject* a4;
PyObject* a5;
PyObject* a6;
PyObject* a7;
PyObject* a8;
PyObject* a9;
PyObject* a10;
if (!PyArg_ParseTuple(args, const_cast<char*>("OOOOOOOOOO"), &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10))
throw argument_error();
return new T(self,
python::detail::reference_parameter<A1>(from_python(a1, type<A1>())),
python::detail::reference_parameter<A2>(from_python(a2, type<A2>())),
python::detail::reference_parameter<A3>(from_python(a3, type<A3>())),
python::detail::reference_parameter<A4>(from_python(a4, type<A4>())),
python::detail::reference_parameter<A5>(from_python(a5, type<A5>())),
python::detail::reference_parameter<A6>(from_python(a6, type<A6>())),
python::detail::reference_parameter<A7>(from_python(a7, type<A7>())),
python::detail::reference_parameter<A8>(from_python(a8, type<A8>())),
python::detail::reference_parameter<A9>(from_python(a9, type<A9>())),
python::detail::reference_parameter<A10>(from_python(a10, type<A10>()))
);
}
const char* description() const
{ return typeid(void (*)(T&, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)).name(); }
};
}} // namespace python::detail
#endif // INIT_FUNCTION_DWA052000_H_

View File

@@ -18,8 +18,6 @@ namespace python {
class module_builder
{
typedef PyObject * (*raw_function_ptr)(python::tuple const &, python::dictionary const &);
public:
// Create a module. REQUIRES: only one module_builder is created per module.
module_builder(const char* name);
@@ -32,13 +30,13 @@ class module_builder
template <class Fn>
void def_raw(Fn fn, const char* name)
{
add(detail::new_raw_arguments_function(fn), name);
add(detail::new_raw_arguments_function(fn, name), name);
}
template <class Fn>
void def(Fn fn, const char* name)
{
add(detail::new_wrapped_function(fn), name);
add(detail::new_wrapped_function(fn, name), name);
}
static string name();

146
objects.h
View File

@@ -293,6 +293,152 @@ struct list::slice_proxy
int m_low, m_high;
};
namespace detail
{
#define BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(T, name) \
inline string python_type_name(python::type<T >) \
{ return string(#name); }
#if 0
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(long, types.IntType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(unsigned long, types.IntType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(int, types.IntType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(unsigned int, types.IntType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(short, types.IntType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(unsigned short, types.IntType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(signed char, types.IntType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(unsigned char, types.IntType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(bool, types.IntType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(float, types.FloatType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(double, types.FloatType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(void, types.NoneType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(const char *, types.StringType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(std::string, types.StringType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(PyObject, AnyType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(reference<PyObject>, AnyType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(list, types.ListType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(tuple, types.TupleType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(dictionary, types.DictionaryType);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(string, types.StringType);
#endif /* #if 0 */
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(long, int);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(unsigned long, int);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(int, int);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(unsigned int, int);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(short, int);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(unsigned short, int);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(signed char, int);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(unsigned char, int);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(bool, int);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(float, float);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(double, float);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(void, None);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(const char *, string);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(std::string, string);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(PyObject, any);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(reference<PyObject>, any);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(list, list);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(tuple, tuple);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(dictionary, dictionary);
BOOST_PYTHON_OVERLOAD_TYPENAME_FUNCTION(string, string);
typedef char no_t[1];
typedef char yes_t[2];
yes_t* is_plain_aux(...);
template <class T>
no_t* is_plain_aux(type<T *>);
template <class T>
no_t* is_plain_aux(type<T const *>);
template <class T>
no_t* is_plain_aux(type<T &>);
template <class T>
no_t* is_plain_aux(type<T const &>);
template <class T>
no_t* is_plain_aux(type<std::auto_ptr<T> >);
template <class T>
no_t* is_plain_aux(type<boost::shared_ptr<T> >);
template <class T>
no_t* is_plain_aux(type<reference<T> >);
#define BOOST_PYTHON_IS_PLAIN(T) \
(sizeof(*python::detail::is_plain_aux(python::type<T>())) == \
sizeof(python::detail::yes_t))
template <bool is_plain>
struct python_type_name_selector
{
template <class T>
static string get(python::type<T> t)
{ return python_type_name(t); }
};
template <class T>
string forward_python_type_name(python::type<T&>)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <class T>
string forward_python_type_name(python::type<const T&>)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <class T>
string forward_python_type_name(python::type<T*>)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <class T>
string forward_python_type_name(python::type<const T*>)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <class T>
string forward_python_type_name(python::type<std::auto_ptr<T> >)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <class T>
string forward_python_type_name(python::type<boost::shared_ptr<T> >)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <class T>
string forward_python_type_name(python::type<reference<T> >)
{
static const bool is_plain = BOOST_PYTHON_IS_PLAIN(T);
return python_type_name_selector<is_plain>::get(python::type<T>());
}
template <>
struct python_type_name_selector<false>
{
template <class T>
static string get(python::type<T> t)
{ return forward_python_type_name(t); }
};
} // namespace detail
} // namespace python
BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE

View File

@@ -197,8 +197,7 @@ namespace detail
};
};
// Fully specialize define_operator for all operators defined in operator_id above.
// Every specialization defines one function object for normal operator calls and one
// for operator calls with operands reversed ("__r*__" function variants).
@@ -214,15 +213,20 @@ namespace detail
{ \
PyObject* do_call(PyObject* arguments, PyObject* /* keywords */) const \
{ \
tuple args(ref(arguments, ref::increment_count)); \
tuple args(ref(arguments, ref::increment_count)); \
\
return BOOST_PYTHON_CONVERSION::to_python( \
BOOST_PYTHON_CONVERSION::from_python(args[0].get(), python::type<Left>()) oper \
BOOST_PYTHON_CONVERSION::from_python(args[1].get(), python::type<Right>())); \
} \
\
const char* description() const \
{ return "__" #id "__"; } \
string function_name() const \
{ return string(name()); } \
\
PyObject* description() const \
{ \
return function_signature(python::type<Left>(), python::type<Right>()); \
} \
}; \
\
template <class Right, class Left> \
@@ -230,15 +234,20 @@ namespace detail
{ \
PyObject* do_call(PyObject* arguments, PyObject* /* keywords */) const \
{ \
tuple args(ref(arguments, ref::increment_count)); \
tuple args(ref(arguments, ref::increment_count)); \
\
return BOOST_PYTHON_CONVERSION::to_python( \
return BOOST_PYTHON_CONVERSION::to_python( \
BOOST_PYTHON_CONVERSION::from_python(args[1].get(), python::type<Left>()) oper \
BOOST_PYTHON_CONVERSION::from_python(args[0].get(), python::type<Right>())); \
} \
\
const char* description() const \
{ return "__r" #id "__"; } \
string function_name() const \
{ return string(rname()); } \
\
PyObject* description() const \
{ \
return function_signature(python::type<Left>(), python::type<Right>()); \
} \
\
}; \
\
@@ -255,14 +264,19 @@ namespace detail
{ \
PyObject* do_call(PyObject* arguments, PyObject* /* keywords */) const \
{ \
tuple args(ref(arguments, ref::increment_count)); \
tuple args(ref(arguments, ref::increment_count)); \
\
return BOOST_PYTHON_CONVERSION::to_python( \
return BOOST_PYTHON_CONVERSION::to_python( \
oper(BOOST_PYTHON_CONVERSION::from_python(args[0].get(), python::type<operand>()))); \
} \
\
const char* description() const \
{ return "__" #id "__"; } \
string function_name() const \
{ return string(name()); } \
\
PyObject* description() const \
{ \
return function_signature(python::type<operand>()); \
} \
}; \
\
static const char * name() { return "__" #id "__"; } \
@@ -317,8 +331,13 @@ namespace detail
BOOST_PYTHON_CONVERSION::from_python(args[1].get(), python::type<Right>())));
}
const char* description() const
{ return "__pow__"; }
string function_name() const
{ return string(name()); }
PyObject* description() const
{
return function_signature(python::type<Left>(), python::type<Right>());
}
};
@@ -331,7 +350,7 @@ namespace detail
if (args.size() == 3 && args[2]->ob_type != Py_None->ob_type)
{
PyErr_SetString(PyExc_TypeError, "bad operand type(s) for pow()");
PyErr_SetString(PyExc_TypeError, "'__pow__' expected 2 arguments, got 3.");
throw argument_error();
}
@@ -340,8 +359,13 @@ namespace detail
BOOST_PYTHON_CONVERSION::from_python(args[0].get(), python::type<Right>())));
}
const char* description() const
{ return "__rpow__"; }
string function_name() const
{ return string(rname()); }
PyObject* description() const
{
return function_signature(python::type<Left>(), python::type<Right>());
}
};
@@ -374,8 +398,13 @@ namespace detail
return res;
}
const char* description() const
{ return "__divmod__"; }
string function_name() const
{ return string(name()); }
PyObject* description() const
{
return function_signature(python::type<Left>(), python::type<Right>());
}
};
@@ -399,9 +428,13 @@ namespace detail
return res;
}
const char* description() const
{ return "__rdivmod__"; }
string function_name() const
{ return string(rname()); }
PyObject* description() const
{
return function_signature(python::type<Left>(), python::type<Right>());
}
};
static const char * name() { return "__divmod__"; }
@@ -430,8 +463,13 @@ namespace detail
0) ;
}
const char* description() const
{ return "__cmp__"; }
string function_name() const
{ return string(name()); }
PyObject* description() const
{
return function_signature(python::type<Left>(), python::type<Right>());
}
};
@@ -452,8 +490,13 @@ namespace detail
0) ;
}
const char* description() const
{ return "__rcmp__"; }
string function_name() const
{ return string(rname()); }
PyObject* description() const
{
return function_signature(python::type<Left>(), python::type<Right>());
}
};
@@ -488,8 +531,13 @@ namespace detail
#endif
}
const char* description() const
{ return "__str__"; }
string function_name() const
{ return string(name()); }
PyObject* description() const
{
return function_signature(python::type<operand>());
}
};

View File

@@ -18,7 +18,7 @@ namespace detail {
// A stand-in for the built-in void. This one can be passed to functions and
// (under MSVC, which has a bug, be used as a default template type parameter).
struct void_t {};
}
} // namespace detail
// An envelope in which type information can be delivered for the purposes
// of selecting an overloaded from_python() function. This is needed to work

View File

@@ -1,598 +1,136 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/REC-html40/strict.dtd">
<title>
Special Method and Operator Support
Special Method Name Support
</title>
<div>
<h1>
<img width="277" height="86" id="_x0000_i1025" align="center" src=
"c++boost.gif" alt="c++boost.gif (8819 bytes)">Special Method and
Operator Support
"c++boost.gif" alt="c++boost.gif (8819 bytes)">Special Method Name
Support
</h1>
<h2>
Overview
</h2>
<p>
Py_cpp is able to wrap suitable C++ functions and C++ operators into
Python operators. It supports all of the standard <a href=
Py_cpp is able to wrap suitable C++ functions and C++ operators into Python operators.
It supports all of the standard <a href=
"http://www.pythonlabs.com/pub/www.python.org/doc/current/ref/specialnames.html">
special method names</a> supported by real Python class instances <em>
except</em> <code>__complex__</code> (more on the reasons <a href=
"#reasons">below</a>). Supported operators include <a href="#general">
general</a>, <a href="#numeric">numeric</a>, and <a href=
"#sequence_and_mapping">sequence and mapping</a> operators. In
addition, py_cpp provides a simple way to export member variables and
define attributes by means of <a href="#getter_setter">getters and
setters</a>.
<h2>
<a name="general">General Operators</a>
</h2>
Python provides a number of special operatos for basic customization of a
class:
<dl>
<dt>
<b><tt class='method'>__repr__:</tt></b>
<dd>
create a string representation from which the object can be
reconstructed
<dt>
<b><tt class='method'>__str__:</tt></b>
<dd>
create a string representation which is suitable for printing
<dt>
<b><tt class='method'>__cmp__:</tt></b>
<dd>
three-way compare function, used to implement comparison operators
(&lt; etc.)
<dt>
<b><tt class='method'>__hash__:</tt></b>
<dd>
needed to use the object as a dictionary key (only allowed if __cmp__
is also defined)
<dt>
<b><tt class='method'>__nonzero__:</tt></b>
<dd>
called if the object is used as a truth value (e.g. in an if
statement)
<dt>
<b><tt class='method'>__call__:</tt></b>
<dd>
make instances of the class callable like a function
</dl>
If we have a suitable C++ function that supports any of these features,
we can export it like any other function, using its Python special name.
For example, suppose that class <code>Foo</code> provides a string
conversion function:
<pre>
std::string to_string(Foo const &amp; f)
{
std::ostringstream s;
s &lt;&lt; f;
return s.str();
}
</pre>
This function would be wrapped like this:
<pre>
python::class_builder&lt;Foo&gt; foo_class(my_module, "Foo");
foo_class.def(&amp;to_string, "__str__");
</pre>
special method names</a> supported by real Python class instances <em>except</em>
<code>__complex__</code> (more on the reasons <a href="#reasons">below</a>).
<h2>Numeric Operators</h2>
There are two fundamental ways to define numeric operators within py_cpp: automatic wrapping
and manual wrapping. Suppose, C++ defines an addition operator for type <code>Rational</code>, so that we can write:
Note that py_cpp also supports <em>automatic wrapping</em> of
"__str__" and "__cmp__". This is explained in the <a href="#numeric">next
section</a> and the <a href="#numeric_table">table of numeric
operators</a>.
<h2>
<a name="numeric">Numeric Operators</a>
</h2>
There are two fundamental ways to define numeric operators within py_cpp:
manual wrapping (as is done with <a href="#general">general
operators</a>) and automatic wrapping. Lets start with the second
possibility. Suppose, C++ defines a class <code>Int</code> (which might
represent an infinite-precision integer) which supports addition, so that
we can write (in C++):
<pre>
Int a, b, c;
Rational a, b, c;
...
c = a + b;
</pre>
To enable the same functionality in Python, we first wrap the <code>
Int</code> class as usual:
To enable the same functionality in Python, we first wrap the Rational class as usual:
<pre>
python::class_builder&lt;Int&gt; int_class(my_module, "Int");
int_class.def(python::constructor&lt;&gt;());
py::ClassWrapper&lt;Rational&gt; rational_class(my_module, "Rational");
rational_class.def(py::Constructor&lt;&gt;());
...
</pre>
Then we export the addition operator like this:
Then we export the addition operator like this:
<pre>
int_class.def(python::operators&lt;python::op_add&gt;());
rational_class.def(py::operators&lt;py::op_add&gt;());
</pre>
Since Int also supports subtraction, multiplication, adn division, we
want to export those also. This can be done in a single command by
'or'ing the operator identifiers together (a complete list of these
identifiers and the corresponding operators can be found in the <a href=
"#numeric_table">table</a>):
Since Rational also supports subtraction, multiplication, adn division, we want to export those also. This can be done in a single command by 'or'ing the operator identifiers together (a complete list of these identifiers and the corresponding operators can be found in the <a href="#numeric_table">table</a>):
<pre>
int_class.def(python::operators&lt;(python::op_sub | python::op_mul | python::op_div)&gt;());
rational_class.def(py::operators&lt;(py::op_sub | py::op_mul | py::op_div)&gt;());
</pre>
Note that the or-expression must be enclosed in parentheses. This form of
operator definition will wrap homogeneous operators, i.e. operators whose
left and right operand have the same type. Now, suppose that our C++
library also supports addition of Ints and plain integers:
Note that the or-expression must be enclosed in parentheses. This form of operator definition will wrap homogeneous operators, that is operators whose left and right operand have the same type. Now, suppose that our C++ library also supports addition of Rationals and integers:
<pre>
Int a, b;
Rational a, b;
int i;
...
a = b + i;
a = i + b;
</pre>
To wrap these heterogeneous operators (left and right hand side have
different types), we need a possibility to specify a different type for
one of the operands. This is done using the <code>right_operand</code>
and <code>left_operand</code> templates:
To wrap these heterogeneous operators (left and right hand side have different types), we need a possibility to specify a different operand type. This is done using the <code>right_operand</code> and <code>left_operand</code> templates:
<pre>
int_class.def(python::operators&lt;python::op_add&gt;(), python::right_operand&lt;int&gt;());
int_class.def(python::operators&lt;python::op_add&gt;(), python::left_operand&lt;int&gt;());
rational_class.def(py::operators&lt;py::op_add&gt;(), py::right_operand&lt;int&gt;());
rational_class.def(py::operators&lt;py::op_add&gt;(), py::left_operand&lt;int&gt;());
</pre>
Py_cpp uses overloading to register several variants of the same
operation (more on this in the context of <a href="#coercion">
coercion</a>). Again, several operators can be exported at once:
Py_cpp uses overloading to register several variants of the same operation (more on this in the context of <a href="#coercion">coercion</a>). Again, several operators can be exported at once:
<pre>
int_class.def(python::operators&lt;(python::op_sub | python::op_mul | python::op_div)&gt;(),
python::right_operand&lt;int&gt;());
int_class.def(python::operators&lt;(python::op_sub | python::op_mul | python::op_div)&gt;(),
python::left_operand&lt;int&gt;());
rational_class.def(py::operators&lt;(py::op_sub | py::op_mul | py::op_div)&gt;(),
py::right_operand&lt;int&gt;());
rational_class.def(py::operators&lt;(py::op_sub | py::op_mul | py::op_div)&gt;(),
py::left_operand&lt;int&gt;());
</pre>
The type of the operand not mentioned is taken from the class object. In
our example, the class object is <code>int_class</code>, and thus the
other operand's type is `<code>Int const &amp;</code>'. You can override
this default by explicitly specifying a type in the <code>
operators</code> template:
The type of the operand not mentioned is taken from the class object. In our example, the class object is <code>rational_class</code>, and thus the other operand's type is `<code>Rational const &amp;</code>'. You can override this default by explicitly specifying a type in the <code>operators</code> template:
<pre>
int_class.def(python::operators&lt;python::op_add, Int&gt;(), python::right_operand&lt;int&gt;());
rational_class.def(py::operators&lt;py::op_add, Rational&gt;(), py::right_operand&lt;int&gt;());
</pre>
Here, `<code>Int</code>' would be used instead of `<code>Int const
&amp;</code>'.
<p>
Note that automatic wrapping doesn't need any specific form of <code>
operator+()</code> (or one of the other operators), but rather wraps
the <em>expression</em> `<code>left + right</code>'. That is, this
mechanism can be used for any definition of <code>operator+()</code>,
such as a free function `<code>Int operator+(Int, Int)</code>' or a
member function `<code>Int Int::operator+(Int)</code>'.
<p>
For the Python operators <code>pow()</code> and <code>abs()</code>,
there is no corresponding C++ operator. Instead, automatic wrapping
attempts to wrap C++ functions of the same name. This only works if
those functions are known in namespace <code>python::detail</code>.
Thus it might be necessary to add a using declaration prior to
wrapping:
Here, `<code>Rational</code>' would be used instead of `<code>Rational const &amp;</code>'.
<p>
Note that automatic wrapping doesn't need any specific form of <code>operator+()</code> (or any other operator), but rather wraps the <em>expression</em> `<code>left + right</code>'. That is, this mechanism can be used for any definition of <code>operator+()</code>, such as a free function `<code>Rational operator+(Rational, Rational)</code>' or a member function `<code>Rational Rational::operator+(Rational)</code>'.
<p>
In some cases, automatic wrapping of operators is not possible or not desirable. Suppose, for example, that the power operation for Rationals is defined by a set of functions <code>pow()</code>:
<pre>
namespace python {
namespace detail {
using my_namespace::pow;
using my_namespace::abs;
}}
Rational pow(Rational const &amp; left, Rational const &amp; right);
Rational pow(Rational const &amp; left, int right);
Rational pow(int left, Rational const &amp; right);
</pre>
<p>
In some cases, automatic wrapping of operators is not possible or not
desirable. Suppose, for example, that the modulo operation for Ints is
defined by a set of functions <code>mod()</code> (for automatic
wrapping, we would need <code>operator%()</code>):
In order to create the Python operator "pow" from these functions, we have to wrap them manually:
<pre>
Int mod(Int const &amp; left, Int const &amp; right);
Int mod(Int const &amp; left, int right);
Int mod(int left, Int const &amp; right);
rational_class.def((Rational (*)(Rational const &amp;, Rational const &amp;))&amp;pow, "__pow__");
rational_class.def((Rational (*)(Rational const &amp;, int))&amp;pow, "__pow__");
</pre>
In order to create the Python operator "__mod__" from these functions, we
have to wrap them manually:
The third form (with <code>int</code> as left operand) cannot be wrapped this way. We must first create a function <code>rpow()</code> with the operands reversed:
<pre>
int_class.def((Int (*)(Int const &amp;, Int const &amp;))&amp;mod, "__mod__");
int_class.def((Int (*)(Int const &amp;, int))&amp;mod, "__mod__");
</pre>
The third form (with <code>int</code> as left operand) cannot be wrapped
this way. We must first create a function <code>rmod()</code> with the
operands reversed:
<pre>
Int rmod(Int const &amp; right, int left)
Rational rpow(Rational const &amp; right, int left)
{
return mod(left, right);
return pow(left, right);
}
</pre>
This function must be wrapped under the name "__rmod__":
This function must be wrapped under the name "__rpow__":
<pre>
int_class.def(&amp;rmod, "__rmod__");
rational_class.def(&amp;rpow, "__rpow__");
</pre>
A list of the possible operator names is also found in the <a href=
"#numeric_table">table</a>. Special treatment is necessary to export the
<a href="#ternary_pow">ternary pow</a> operator.
<p>
Automatic and manual wrapping can be mixed arbitrarily. Note that you
cannot overload the same operator for a given extension class on both
`<code>int</code>' and `<code>float</code>', because Python implicitly
converts these types into each other. Thus, the overloaded variant
found first (be it `<code>int</code>' or `<code>float</code>') will be
used for either of the two types.
<h4>
<a name="coercion">Coercion</a>
</h4>
Plain Python can only execute operators with identical types on the left
and right hand side. If it encounters an expression where the types of
the left and right operand differ, it tries to coerce these type to a
common type before invoking the actual operator. Implementing good
coercion functions can be difficult if many type combinations must be
supported.
<p>
In contrast, py_cpp provides <em><a href="overloading.html">
overloading</a></em>. By means of overloading, operator calling can be
simplyfied drastically: you just register operators for all desired
type combinations, and py_cpp automatically ensures that the correct
function is called in each case. User defined coercion functions are
<em>not necessary</em>. To enable operator overloading, py_cpp provides
a standard coercion which is <em>implicitly registered</em> whenever
automatic operator wrapping is used.
<p>
If you wrap all operator functions manually, but still want to use
operator overloading, you have to register the standard coercion
function explicitly:
<pre>
// this is not necessary if automatic operator wrapping is used
int_class.def_standard_coerce();
</pre>
In case you encounter a situation where you absolutely need a customized
coercion, you can overload the "__coerce__" operator itself. The
signature of a coercion function must look like this:
<pre>
python::tuple custom_coerce(PyObject * left, PyObject * right);
</pre>
The resulting <code>tuple</code> must contain two elements which
represent the values of <code>left</code> and <code>right</code>
converted to the same type. Such a function is wrapped as usual:
<pre>
some_class.def(&amp;custom_coerce, "__coerce__");
</pre>
Note that the custom coercion function is only used if it is defined <em>
before</em> any automatic operator wrapping on the given class or a call
to `<code>some_class.def_standard_coerce()</code>'.
<h4>
<a name="ternary_pow">The Ternary <code>pow()</code> Operator</a>
</h4>
In addition to the usual binary <code>pow()</code>-operator (meaning
<code>x^y</code>), Python also provides a ternary variant that implements
<code>(x^y) % z</code> (presumably using a more efficient algorithm than
concatenation of power and modulo operators). Automatic operator wrapping
can only be used with the binary variant. Ternary <code>pow()</code> must
always be wrapped manually. For a homgeneous ternary <code>pow()</code>,
this is done as usual:
<pre>
Int power(Int const &amp; first, Int const &amp; second, Int const &amp; module);
typedef Int (ternary_function1)(const Int&amp;, const Int&amp;, const Int&amp;);
...
int_class.def((ternary_function1)&amp;power, "__pow__");
</pre>
In case you want to support this function with non-uniform argument
types, wrapping is a little more involved. Suppose, you have to wrap:
<pre>
Int power(Int const &amp; first, int second, int module);
Int power(int first, Int const &amp; second, int module);
Int power(int first, int second, Int const &amp; module);
</pre>
The first variant can be wrapped as usual:
<pre>
typedef Int (ternary_function2)(const Int&amp;, int, int);
int_class.def((ternary_function2)&amp;power, "__pow__");
</pre>
In the second variant, however, <code>Int</code> appears only as second
argument, and in the last one it is the third argument. Therefor we must
first provide functions where the argumant order is changed so that
<code>Int</code> appears in first place:
<pre>
Int rpower(Int const &amp; second, int first, int module)
{
return power(first, second, third);
}
Int rrpower(Int const &amp; third, int first, int second)
{
return power(first, second, third);
}
</pre>
These functions must be wrapped under the names "__rpow__" and
"__rrpow__" respectively:
<pre>
int_class.def((ternary_function2)&amp;rpower, "__rpow__");
int_class.def((ternary_function2)&amp;rrpower, "__rrpow__");
</pre>
Note that "__rrpow__" is an extension not present in plain Python.
<h4>
<a name="numeric_table">Table of Numeric Operators</a>
</h4>
<p>
Py_cpp supports the <a href=
"http://www.pythonlabs.com/pub/www.python.org/doc/current/ref/numeric-types.html">
Python operators</a> listed in the following table. Note that
comparison (__cmp__) and string conversion (__str__) operators are
included in the list, although they are not strictly "numeric".
<p>
<table summary="special numeric methods" cellpadding="5" border="1"
width="100%">
<tr>
<td align="center">
<b>Python Operator Name</b>
<td align="center">
<b>Python Expression</b>
<td align="center">
<b>C++ Operator Id</b>
<td align="center">
<b>C++ Expression Used For Automatic Wrapping</b><br>
with <code>cpp_left = from_python(left,
type&lt;Left&gt;())</code>,<br>
<code>cpp_right = from_python(right,
type&lt;Right&gt;())</code>,<br>
and <code>cpp_oper = from_python(oper, type&lt;Oper&gt;())</code>
<tr>
<td>
<code>__add__, __radd__</code>
<td>
<code>left + right</code>
<td>
<code>python::op_add</code>
<td>
<code>cpp_left + cpp_right</code>
<tr>
<td>
<code>__sub__, __rsub__</code>
<td>
<code>left - right</code>
<td>
<code>python::op_sub</code>
<td>
<code>cpp_left - cpp_right</code>
<tr>
<td>
<code>__mul__, __rmul__</code>
<td>
<code>left * right</code>
<td>
<code>python::op_mul</code>
<td>
<code>cpp_left * cpp_right</code>
<tr>
<td>
<code>__div__, __rdiv__</code>
<td>
<code>left / right</code>
<td>
<code>python::op_div</code>
<td>
<code>cpp_left / cpp_right</code>
<tr>
<td>
<code>__mod__, __rmod__</code>
<td>
<code>left % right</code>
<td>
<code>python::op_mod</code>
<td>
<code>cpp_left % cpp_right</code>
<tr>
<td>
<code>__divmod__, __rdivmod__</code>
<td>
<code>(quotient, remainder)<br>
= divmod(left, right)</code>
<td>
<code>python::op_divmod</code>
<td>
<code>cpp_left / cpp_right </code> and <code> cpp_left %
cpp_right</code>
<tr>
<td>
<code>__pow__, __rpow__</code>
<td>
<code>pow(left, right)</code><br>
(binary power)
<td>
<code>python::op_pow</code>
<td>
<code>pow(cpp_left, cpp_right)</code>
<tr>
<td>
<code>__pow__</code>
<td>
<code>pow(left, right, modulo)</code><br>
(ternary power modulo)
<td colspan="2">
no automatic wrapping, <a href="#ternary_pow">special treatment</a>
required
<tr>
<td>
<code>__lshift__, __rlshift__</code>
<td>
<code>left &lt;&lt; right</code>
<td>
<code>python::op_lshift</code>
<td>
<code>cpp_left &lt;&lt; cpp_right</code>
<tr>
<td>
<code>__rshift__, __rrshift__</code>
<td>
<code>left &gt;&gt; right</code>
<td>
<code>python::op_rshift</code>
<td>
<code>cpp_left &gt;&gt; cpp_right</code>
<tr>
<td>
<code>__and__, __rand__</code>
<td>
<code>left &amp; right</code>
<td>
<code>python::op_and</code>
<td>
<code>cpp_left &amp; cpp_right</code>
<tr>
<td>
<code>__xor__, __rxor__</code>
<td>
<code>left ^ right</code>
<td>
<code>python::op_xor</code>
<td>
<code>cpp_left ^ cpp_right</code>
<tr>
<td>
<code>__or__, __ror__</code>
<td>
<code>left | right</code>
<td>
<code>python::op_or</code>
<td>
<code>cpp_left | cpp_right</code>
<tr>
<td>
<code>__cmp__, __rcmp__</code>
<td>
<code>cmp(left, right)</code> (3-way compare)<br>
<code>left &lt; right</code><br>
<code>left &lt;= right</code><br>
<code>left &gt; right</code><br>
<code>left &gt;= right</code><br>
<code>left == right</code><br>
<code>left != right</code>
<td>
<code>python::op_cmp</code>
<td>
<code>cpp_left &lt; cpp_right </code> and <code> cpp_right &lt;
cpp_left</code>
<tr>
<td>
<code>__neg__</code>
<td>
<code>-oper </code> (unary negation)
<td>
<code>python::op_neg</code>
<td>
<code>-cpp_oper</code>
<tr>
<td>
<code>__pos__</code>
<td>
<code>+oper </code> (identity)
<td>
<code>python::op_pos</code>
<td>
<code>+cpp_oper</code>
<tr>
<td>
<code>__abs__</code>
<td>
<code>abs(oper) </code> (absolute value)
<td>
<code>python::op_abs</code>
<td>
<code>abs(cpp_oper)</code>
<tr>
<td>
<code>__invert__</code>
<td>
<code>~oper </code> (bitwise inversion)
<td>
<code>python::op_invert</code>
<td>
<code>~cpp_oper</code>
<tr>
<td>
<code>__int__</code>
<td>
<code>int(oper) </code> (integer conversion)
<td>
<code>python::op_int</code>
<td>
<code>long(cpp_oper)</code>
<tr>
<td>
<code>__long__</code>
<td>
<code>long(oper) </code><br>
(infinite precision integer conversion)
<td>
<code>python::op_long</code>
<td>
<code>PyLong_FromLong(cpp_oper)</code>
<tr>
<td>
<code>__float__</code>
<td>
<code>float(oper) </code> (float conversion)
<td>
<code>python::op_float</code>
<td>
<code>double(cpp_oper)</code>
<tr>
<td>
<code>__oct__</code>
<td>
<code>oct(oper) </code> (octal conversion)
<td colspan="2">
must be wrapped manually (wrapped function should return a string)
<tr>
<td>
<code>__hex__</code>
<td>
<code>hex(oper) </code> (hex conversion)
<td colspan="2">
must be wrapped manually (wrapped function should return a string)
<tr>
<td>
<code>__str__</code>
<td>
<code>str(oper) </code> (string conversion)
<td>
<code>python::op_str</code>
<td>
<code>std::ostringstream s; s &lt;&lt; oper;</code>
<tr>
<td>
<code>__coerce__</code>
<td>
<code>coerce(left, right)</code>
<td colspan="2">
usually defined automatically, otherwise <a href="#coercion">
special treatment</a> required
</table>
A list of the possible operator names is also found in the <a href="#numeric_table">table</a>.
Special treatment is necessary to define the <a href="#ternary_pow">ternary pow</a>.
<a name="coercion">
<h4>Coercion</h4></a>
So, for example, we can wrap a
<code>std::map&lt;std::size_t,std::string&gt;</code> as follows:
<h2>
<a name="sequence_and_mapping">Sequence and Mapping Operators</a>
Example
</h2>
Sequence and mapping operators let wrapped objects behave in accordance
to Python's iteration and access protocols. These protocols differ
considerably from the ones found in C++. For example, Python's typically
iteration idiom looks like  "<code>for i in S:</code>" , while in C++ one
uses  "<code>for(iterator i = S.begin(); i != S.end(); ++i)</code>". One
could try to wrap C++ iterators in order to carry the C++ idiom into
Python. However, this does not work very well because (1) it leads to
non-uniform Python code (wrapped types must be used in a different way
than Python built-in types) and (2) iterators are often implemented as
plain C++ pointers which cannot be wrapped easily because py_cpp is
designed to handle objects only.
<p>
Thus, it is a good idea to provide sequence and mapping operators for
your wrapped containers. These operators have to be wrapped manually
because there are no corresponding C++ operators that could be used for
automatic wrapping. The Python documentation lists the relevant <a
href=
"http://www.pythonlabs.com/pub/www.python.org/doc/current/ref/sequence-types.html">
container operators</a>. In particular, expose __getitem__, __setitem__
and remember to throw the <code>PyExc_IndexError</code> when the index
is out-of-range in order to enable the  "<code>for i in S:</code>" 
idiom.
<p>
Here is an example. Suppose, we want to wrap a <code>
std::map&lt;std::size_t,std::string&gt;</code>. This is done as follows
as follows:
<blockquote>
<pre>
typedef std::map&lt;std::size_t, std::string&gt; StringMap;
@@ -606,8 +144,8 @@ void throw_key_error_if_end(
{
if (p == m.end())
{
PyErr_SetObject(PyExc_KeyError, python::converters::to_python(key));
throw python::error_already_set();
PyErr_SetObject(PyExc_KeyError, py::converters::to_python(key));
throw py::ErrorAlreadySet();
}
}
@@ -636,8 +174,8 @@ void StringMapPythonClass::del_item(StringMap&amp; self, std::size_t key)
self.erase(p);
}
class_builder&lt;StringMap&gt; string_map(my_module, "StringMap");
string_map.def(python::constructor&lt;&gt;());
ClassWrapper&lt;StringMap&gt; string_map(my_module, "StringMap");
string_map.def(py::Constructor&lt;&gt;());
string_map.def(&amp;StringMap::size, "__len__");
string_map.def(get_item, "__getitem__");
string_map.def(set_item, "__setitem__");
@@ -667,19 +205,9 @@ Traceback (innermost last):
KeyError: 2
&gt;&gt;&gt; len(m)
0
&gt;&gt;&gt; m[0] = 'zero'
&gt;&gt;&gt; m[1] = 'one'
&gt;&gt;&gt; m[2] = 'two'
&gt;&gt;&gt; m[3] = 'three'
&gt;&gt;&gt; m[3] = 'farther'
&gt;&gt;&gt; len(m)
4
&gt;&gt;&gt; for i in m:
... print i
...
zero
one
two
three
1
</pre>
</blockquote>
<h2>
@@ -688,10 +216,10 @@ three
<p>
Py_cpp extension classes support some additional "special method"
protocols not supported by built-in Python classes. Because writing
<code>__getattr__</code>, <code> __setattr__</code>, and <code>
__delattr__</code> functions can be tedious in the common case where
the attributes being accessed are known statically, py_cpp checks the
special names
<code>__getattr__</code>, <code> __setattr__</code>, and
<code>__delattr__</code> functions can be tedious in the common case
where the attributes being accessed are known statically, py_cpp checks
the special names
<ul>
<li>
<code>__getattr__<em>&lt;name&gt;</em>__</code>
@@ -717,15 +245,15 @@ three
6
</pre>
</blockquote>
<h4>
<h2>
Direct Access to Data Members
</h4>
</h2>
<p>
Py_cpp uses the special <code>
__xxxattr__<em>&lt;name&gt;</em>__</code> functionality described above
to allow direct access to data members through the following special
functions on <code>class_builder&lt;&gt;</code> and <code>
extension_class&lt;&gt;</code>:
functions on <code>ClassWrapper&lt;&gt;</code> and <code>
ExtensionClass&lt;&gt;</code>:
<ul>
<li>
<code>def_getter(<em>pointer-to-member</em>, <em>name</em>)</code> //
@@ -761,9 +289,9 @@ long second(const Pil&amp; x) { return x.second; }
my_module.def(first, "first");
my_module.def(second, "second");
class_builder&lt;Pil&gt; pair_int_long(my_module, "Pair");
pair_int_long.def(python::constructor&lt;&gt;());
pair_int_long.def(python::constructor&lt;int,long&gt;());
ClassWrapper&lt;Pil&gt; pair_int_long(my_module, "Pair");
pair_int_long.def(py::Constructor&lt;&gt;());
pair_int_long.def(py::Constructor&lt;int,long&gt;());
pair_int_long.def_read_write(&amp;Pil::first, "first");
pair_int_long.def_read_write(&amp;Pil::second, "second");
</pre>
@@ -788,29 +316,184 @@ pair_int_long.def_read_write(&amp;Pil::second, "second");
</pre>
</blockquote>
<h2>
<a name="reasons">And what about <code>__complex__</code>?</a>
<a name="numerics">Numeric Method Support</a>
</h2>
<p>
That, dear reader, is one problem we don't know how to solve. The
Python source contains the following fragment, indicating the
special-case code really is hardwired:
<blockquote>
Py_cpp supports the following <a href=
"http://www.pythonlabs.com/pub/www.python.org/doc/current/ref/numeric-types.html">
Python special numeric method names</a>:
<p>
<table summary="special numeric methods" cellpadding="5" border="1">
<thead>
<tr>
<td>
Name
<td>
Notes
<tr>
<td>
<code>__add__(self,&nbsp;other)</code>
<td>
<code>operator+(const T&amp;,&nbsp;const T&amp;)</code>
<tr>
<td>
<code>__sub__(self,&nbsp;other)</code>
<td>
<code>operator-(const T&amp;,&nbsp;const T&amp;)</code>
<tr>
<td>
<code>__mul__(self,&nbsp;other)</code>
<td>
<code>operator*(const T&amp;,&nbsp;const T&amp;)</code>
<tr>
<td>
<code>__div__(self,&nbsp;other)</code>
<td>
<code>operator/(const T&amp;,&nbsp;const T&amp;)</code>
<tr>
<td>
<code>__mod__(self,&nbsp;other)</code>
<td>
<code>operator%(const T&amp;,&nbsp;const T&amp;)</code>
<tr>
<td>
<code>__divmod__(self,&nbsp;other)</code>
<td>
return a <code> py::Tuple</code> initialized with <code>
(</code><em>quotient</em><code>,</code> <em>
remainder</em><code>)</code>.
<tr>
<td>
<code>__pow__(self,&nbsp;other&nbsp;[,&nbsp;modulo])</code>
<td>
use <a href="overloading.html">overloading</a> to support both
forms of __pow__
<tr>
<td>
<code>__lshift__(self,&nbsp;other)</code>
<td>
<code>operator&lt;&lt;(const T&amp;,&nbsp;const T&amp;)</code>
<tr>
<td>
<code>__rshift__(self,&nbsp;other)</code>
<td>
<code>operator&gt;&gt;(const T&amp;,&nbsp;const T&amp;)</code>
<tr>
<td>
<code>__and__(self,&nbsp;other)</code>
<td>
<code>operator&amp;(const T&amp;,&nbsp;const T&amp;)</code>
<tr>
<td>
<code>__xor__(self,&nbsp;other)</code>
<td>
<code>operator^(const T&amp;,&nbsp;const T&amp;)</code>
<tr>
<td>
<code>__or__(self,&nbsp;other)</code>
<td>
<code>operator|(const T&amp;,&nbsp;const T&amp;)</code>
<tr>
<td>
<code>__neg__(self)</code>
<td>
<code>operator-(const T&amp;)</code> (unary negation)
<tr>
<td>
<code>__pos__(self)</code>
<td>
<code>operator+(const T&amp;)</code> (identity)
<tr>
<td>
<code>__abs__(self)</code>
<td>
Called to implement the built-in function abs()
<tr>
<td>
<code>__invert__(self)</code>
<td>
<code>operator~(const T&amp;)</code>
<tr>
<td>
<code>__int__(self)</code>
<td>
<code>operator long() const</code>
<tr>
<td>
<code>__long__(self)</code>
<td>
Should return a Python <code>long</code> object. Can be
implemented with <code>PyLong_FromLong(<em>value</em>)</code>,
for example.
<tr>
<td>
<code>__float__(self)</code>
<td>
<code>operator double() const</code>
<tr>
<td>
<code>__oct__(self)</code>
<td>
Called to implement the built-in function oct(). Should return a
string value.
<tr>
<td>
<code>__hex__(self)</code>
<td>
Called to implement the built-in function hex(). Should return a
string value.
<tr>
<td>
<code>__coerce__(self,&nbsp;other)</code>
<td>
Should return a Python 2-<em>tuple</em> (C++ code may return a
<code>py::Tuple</code>) where the elements represent the values
of <code> self</code> and <code>other</code> converted to the
same type.
</table>
<h2><a name="reasons">Where are the <code>__r</code><i>&lt;name&gt;</i><code>__</code>
functions?</a></h2>
<p>
At first we thought that supporting <code>__radd__</code> and its ilk would be
impossible, since Python doesn't supply any direct support and in fact
implements a special case for its built-in class instances. <a
href="http://starship.python.net/crew/arcege/extwriting/pyextnum.html">This
article</a> gives a pretty good overview of the direct support for numerics
that Python supplies for extension types. We've since discovered that it can
be done, but there are some pretty convincing <a
href="http://starship.python.net/crew/lemburg/CoercionProposal.html">arguments</a>
out there that this arrangement is less-than-ideal. Instead of supplying a
sub-optimal solution for the sake of compatibility with built-in Python
classes, we're doing the neccessary research so we can "do it right". This
will also give us a little time to hear from users about what they want. The
direction we're headed in is based on the idea of <a
href="http://www.sff.net/people/neelk/open-source/Multimethod.py">multimethods</a>
rather than on trying to find a coercion function bound to one of the
arguments.
<h3>And what about <code>__complex__</code>?</h3>
<p>That, dear reader, is one problem we don't know how to solve. The Python
source contains the following fragment, indicating the special-case code really
is hardwired:
<blockquote>
<pre>
/* XXX Hack to support classes with __complex__ method */
if (PyInstance_Check(r)) { ...
</pre>
</blockquote>
</blockquote>
<p>
Previous: <a href="inheritance.html">Inheritance</a> Next: <a href=
"under-the-hood.html">A Peek Under the Hood</a> Up: <a href=
Previous: <a href="inheritance.html">Inheritance</a> Next: <a
href="under-the-hood.html">A Peek Under the Hood</a> Up: <a href=
"py_cpp.html">Top</a>
<p>
&copy; Copyright David Abrahams and Ullrich K&ouml;the 2000.
Permission to copy, use, modify, sell and distribute this document is
granted provided this copyright notice appears in all copies. This
document is provided "as is" without express or implied warranty, and
with no claim as to its suitability for any purpose.
&copy; Copyright David Abrahams 2000. Permission to copy, use, modify,
sell and distribute this document is granted provided this copyright
notice appears in all copies. This document is provided "as is" without
express or implied warranty, and with no claim as to its suitability
for any purpose.
<p>
Updated: Nov 21, 2000
Updated: Oct 19, 2000
</div>

View File

@@ -67,7 +67,7 @@ namespace {
ref global_class_reduce()
{
static ref result(detail::new_wrapped_function(class_reduce));
static ref result(detail::new_wrapped_function(class_reduce, "__reduce__"));
return result;
}
@@ -111,7 +111,7 @@ namespace {
ref global_instance_reduce()
{
static ref result(detail::new_wrapped_function(instance_reduce));
static ref result(detail::new_wrapped_function(instance_reduce, "__reduce__"));
return result;
}
}
@@ -225,14 +225,21 @@ namespace detail {
// Mostly copied wholesale from Python's classobject.c
PyObject* class_base::repr() const
{
unsigned long address = reinterpret_cast<unsigned long>(this);
string result = string("<extension class %s at %lx>") % tuple(complete_class_name(), address);
return result.reference().release();
}
// Mostly copied wholesale from Python's classobject.c
string class_base::complete_class_name() const
{
PyObject *mod = PyDict_GetItemString(
m_name_space.get(), const_cast<char*>("__module__"));
unsigned long address = reinterpret_cast<unsigned long>(this);
string result = (mod == NULL || !PyString_Check(mod))
? string("<extension class %s at %lx>") % tuple(m_name, address)
: string("<extension class %s.%s at %lx>") % tuple(ref(mod, ref::increment_count), m_name, address);
return result.reference().release();
return (mod == NULL || !PyString_Check(mod))
? m_name
: string("%s.%s") % tuple(ref(mod, ref::increment_count), m_name);
}

View File

@@ -97,6 +97,9 @@ namespace detail {
int setattr(const char* name, PyObject* value);
PyObject* repr() const;
void add_base(ref base);
// get the complete class name (i.e. "module.class")
virtual string complete_class_name() const;
protected:
bool initialize_instance(instance* obj, PyObject* args, PyObject* keywords);

View File

@@ -10,15 +10,18 @@ r'''
Automatic checking of the number and type of arguments. Foo's constructor takes
a single long parameter.
>>> ext = Foo()
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: function requires exactly 1 argument; 0 given
>>> try: ext = Foo()
... except TypeError, err:
... assert re.match(
... "'demo.Foo.__init__' expected argument\(s\) \(int\),\n"
... "but got \(\) instead.", str(err))
... else: print 'no exception'
>>> try: ext = Foo('foo')
... except TypeError, err:
... assert re.match(
... '(illegal argument type for built-in operation)|(an integer is required)', str(err))
... "'demo.Foo.__init__' expected argument\(s\) \(int\),\n"
... "but got \(string\) instead.", str(err))
... else: print 'no exception'
>>> ext = Foo(1)
@@ -160,10 +163,16 @@ a Bar parameter:
But objects not derived from Bar cannot:
>>> baz.pass_bar(baz)
Traceback (innermost last):
...
TypeError: extension class 'Baz' is not convertible into 'Bar'.
>>> try: baz.pass_bar(baz)
... except TypeError, err:
... assert re.match(
... "'pass_bar' expected argument\(s\) \(demo.Baz, demo.Bar\),\n"
... "but got \(demo.Baz, demo.Baz\) instead.", str(err))
... else: print 'no exception'
(this error was:
TypeError: extension class 'Baz' is not convertible into 'Bar'.
)
The clone function on Baz returns a smart pointer; we wrap it into an
extension_instance and make it look just like any other Baz obj.
@@ -354,7 +363,11 @@ Some simple overloading tests:
>>> try: r = Range('yikes')
... except TypeError, e:
... assert re.match(
... 'No overloaded functions match [(]Range, string[)]\. Candidates are:\n.*\n.*',
... "No variant of overloaded function 'demo.Range.__init__' matches argument\(s\):\n"
... "\(string\)\n"
... "Candidates are:\n"
... "\(int\)\n"
... "\(int, int\)",
... str(e))
... else: print 'no exception'
@@ -564,7 +577,17 @@ Testing overloaded free functions
15
>>> try: overloaded(1, 'foo')
... except TypeError, err:
... assert re.match("No overloaded functions match \(int, string\)\. Candidates are:",
... assert re.match(
... "No variant of overloaded function 'overloaded' matches argument\(s\):\n"
... "\(int, string\)\n"
... "Candidates are:\n"
... "\(\)\n"
... "\(int\)\n"
... "\(string\)\n"
... "\(int, int\)\n"
... "\(int, int, int\)\n"
... "\(int, int, int, int\)\n"
... "\(int, int, int, int, int\)",
... str(err))
... else:
... print 'no exception'
@@ -594,7 +617,17 @@ Testing overloaded constructors
5
>>> try: over = OverloadTest(1, 'foo')
... except TypeError, err:
... assert re.match("No overloaded functions match \(OverloadTest, int, string\)\. Candidates are:",
... assert re.match(
... "No variant of overloaded function 'demo.OverloadTest.__init__' matches argument\(s\):\n"
... "\(int, string\)\n"
... "Candidates are:\n"
... "\(\)\n"
... "\(demo.OverloadTest\)\n"
... "\(int\)\n"
... "\(int, int\)\n"
... "\(int, int, int\)\n"
... "\(int, int, int, int\)\n"
... "\(int, int, int, int, int\)",
... str(err))
... else:
... print 'no exception'
@@ -616,16 +649,35 @@ Testing overloaded methods
5
>>> try: over.overloaded(1,'foo')
... except TypeError, err:
... assert re.match("No overloaded functions match \(OverloadTest, int, string\)\. Candidates are:",
... assert re.match(
... "No variant of overloaded function 'overloaded' matches argument\(s\):\n"
... "\(demo.OverloadTest, int, string\)\n"
... "Candidates are:\n"
... "\(demo.OverloadTest\)\n"
... "\(demo.OverloadTest, int\)\n"
... "\(demo.OverloadTest, int, int\)\n"
... "\(demo.OverloadTest, int, int, int\)\n"
... "\(demo.OverloadTest, int, int, int, int\)\n"
... "\(demo.OverloadTest, int, int, int, int, int\)",
... str(err))
... else:
... print 'no exception'
Testing base class conversions
>>> testUpcast(over)
Traceback (innermost last):
TypeError: extension class 'OverloadTest' is not convertible into 'Base'.
>>> try: testUpcast(over)
... except TypeError, err:
... assert re.match(
... "'testUpcast' expected argument\(s\) \(demo.Base\),\n"
... "but got \(demo.OverloadTest\) instead.",
... str(err))
... else:
... print 'no exception'
(this error was:
TypeError: extension class 'OverloadTest' is not convertible into 'Base'.
)
>>> der1 = Derived1(333)
>>> der1.x()
333
@@ -634,18 +686,37 @@ Testing base class conversions
>>> der1 = derived1Factory(1000)
>>> testDowncast1(der1)
1000
>>> testDowncast2(der1)
Traceback (innermost last):
>>> try: testDowncast2(der1)
... except TypeError, err:
... assert re.match(
... "'testDowncast2' expected argument\(s\) \(demo.Derived2\),\n"
... "but got \(demo.Base\) instead.",
... str(err))
... else:
... print 'no exception'
(this error was:
TypeError: extension class 'Base' is not convertible into 'Derived2'.
)
>>> der2 = Derived2(444)
>>> der2.x()
444
>>> testUpcast(der2)
444
>>> der2 = derived2Factory(1111)
>>> testDowncast2(der2)
Traceback (innermost last):
>>> try: testDowncast2(der2)
... except TypeError, err:
... assert re.match(
... "'testDowncast2' expected argument\(s\) \(demo.Derived2\),\n"
... "but got \(demo.Base\) instead.",
... str(err))
... else:
... print 'no exception'
(this error was:
TypeError: extension class 'Base' is not convertible into 'Derived2'.
)
Testing interaction between callbacks, base declarations, and overloading
- testCallback() calls callback() (within C++)
@@ -656,10 +727,14 @@ Testing interaction between callbacks, base declarations, and overloading
>>> c = CallbackTest()
>>> c.testCallback(1)
2
>>> c.testCallback('foo')
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: illegal argument type for built-in operation
>>> try: c.testCallback('foo')
... except TypeError, err:
... assert re.match(
... "'testCallback' expected argument\(s\) \(demo.CallbackTestBase, int\),\n"
... "but got \(demo.CallbackTest, string\) instead.",
... str(err))
... else:
... print 'no exception'
>>> c.callback(1)
2
>>> c.callback('foo')
@@ -678,10 +753,14 @@ Testing interaction between callbacks, base declarations, and overloading
-1
>>> r.callback('foo')
'foo 1'
>>> r.testCallback('foo')
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: illegal argument type for built-in operation
>>> try: r.testCallback('foo')
... except TypeError, err:
... assert re.match(
... "'testCallback' expected argument\(s\) \(demo.CallbackTestBase, int\),\n"
... "but got \(demo.RedefineCallback, string\) instead.",
... str(err))
... else:
... print 'no exception'
>>> r.testCallback(1)
-1
>>> testCallback(r, 1)
@@ -969,15 +1048,33 @@ test inheritB2
>>> j = pow(i, 5)
>>> j.i()
32
>>> j = pow(i, 5, k)
Traceback (innermost last):
TypeError: bad operand type(s) for pow()
>>> j = pow(i, 5, 5)
Traceback (innermost last):
TypeError: bad operand type(s) for pow()
>>> try: j = pow(i, 5, k)
... except TypeError, err:
... assert re.match(
... "No variant of overloaded function '__pow__' matches argument\(s\):\n"
... "\(demo.Int, int, demo.Int\)\n"
... "Candidates are:\n"
... "\(demo.Int, demo.Int\)\n"
... "\(demo.Int, demo.Int, demo.Int\)\n"
... "\(demo.Int, int\)",
... str(err))
... else:
... print 'no exception'
>>> try: j = pow(i, 5, 5)
... except TypeError, err:
... assert re.match(
... "No variant of overloaded function '__pow__' matches argument\(s\):\n"
... "\(demo.Int, int, int\)\n"
... "Candidates are:\n"
... "\(demo.Int, demo.Int\)\n"
... "\(demo.Int, demo.Int, demo.Int\)\n"
... "\(demo.Int, int\)",
... str(err))
... else:
... print 'no exception'
>>> j = i/1
Traceback (innermost last):
TypeError: bad operand type(s) for /
TypeError: __div__(demo.Int, int) undefined.
>>> j = 1+i
>>> j.i()
3
@@ -993,10 +1090,10 @@ test inheritB2
-1
>>> j = 1/i
Traceback (innermost last):
TypeError: bad operand type(s) for /
TypeError: __rdiv__(demo.Int, int) undefined.
>>> pow(1,i)
Traceback (innermost last):
TypeError: bad operand type(s) for pow()
TypeError: __rpow__(demo.Int, int) undefined.
Test operator export to a subclass