[C++-sig] Boost.Python v2: module objects deprecated

David Abrahams dave at boost-consulting.com
Tue Sep 3 08:01:36 CEST 2002


Boost.Python v2 now supports a free-function version of def which defines
its function in the current scope:

  #include <boost/python/def.hpp>
  #include <boost/python/module_init.hpp>

  BOOST_PYTHON_MODULE_INIT(my_module)
  {
    def("name", function_ptr);
    def("name", function_ptr, call_policies);
    def("name", function_ptr, "documentation string");
    def("name", function_ptr, call_policies, "documentation string");

    def("name", function_ptr, default_stubs);
  }

etc.

Accordingly, the module class is deprecated. I think it still works, but
we're not going to continue to support it, and it will eventually wither
and die. To get access to the current module, you can declare the current
scope:

  #include <boost/python/scope.hpp>

  BOOST_PYTHON_MODULE_INIT(my_module)
  {
    // set the docstring of the current module scope
    scope().attr("__doc__") = "my module's docstring";
    ...

    scope current;
    current.attr("x") = 1; // my_module.x = 1
  }

Of course, you can also set the current scope to any object:

  object some_obj;
  scope within(some_obj);
  def("foo", &foo); // define a function within some_obj as a namespace

Be warned, however, that although you can set the current scope from a
class_<> instance, the class_<>'s def() member function will work properly
in some cases where the free-function def() cannot, since the latter is
missing information about the class type being wrapped.

Enjoy,
Dave

-----------------------------------------------------------
           David Abrahams * Boost Consulting
dave at boost-consulting.com * http://www.boost-consulting.com







More information about the Cplusplus-sig mailing list