[C++-sig] Retrieving lvalues using custom converters

Ravi lists_ravi at lavabit.com
Wed Oct 1 00:17:40 CEST 2008

  Is there a way to retrieve lvalues from function arguments? For example, 
consider the following code:

void do_something( const array_t &a ) { ... }

  // my_converter is a custom from_python converter for array_t
      my_converter::convertible, my_converter::construct,
      boost::python::type_id<array_t>() );
  boost::python::def( "do_something", &do_something );

This registers a converter which works for calls from python to do_something. 
Everything works as expected. However, if the const is removed in the 
definition of do_something:

void do_something( array_t &a ) { ... }

then, boost.python complains that no converter is found. Now, if the argument 
"a" above to do_something needs to be modified, an ugly const_cast is 
required. Alternatively, one could do something like the following:

void do_something( boost::python::object &obj )
  array_t a = boost::python::extract<array_t>( obj );

The above works reasonably well in the absence of function overloading. In 
essence, the dispatch is now handled manually instead of using boost.python. 
But this approach breaks down in the presence of function overloading because 
we then start needing another intermediate function to dispatch:

int do_something( array1_t & ) { ... }
float do_something( array2_t & ) { ... }
return_type do_something_dispatcher( object &o ) { /*dispatch by type in o*/ } 

However, this new dispatcher still has a problem with different return types 
which I don't know how to solve (short of converting the return type to a 

The problems above can be avoided if boost.python would allow extraction of 
lvalues for objects with custom from_python converters. Is this already 
possible and have I just missed it in the documentation?

Or is extraction of lvalues possible using custom call_policies?


More information about the Cplusplus-sig mailing list