Search code examples
pythonc++python-2.7boostboost-python

from X import Y with Boost.Python


I want to import a class from another folder. In another python script I would do

from Base.Derived import Class

However I can't figure out how to do this with Boost.Python. The library provides import.hpp which lets you do something like this

object module = import("Base.Derived");

But the equivalent in python is

import Base.Derived

The end goal is to get an instantiated python object into a Base pointer, so using Boost.Python is preferred. Ideally the code would look something like this

object module = some form of "from Base.Derived import Class"

// Get a C++ pointer of the derived python class.
object derived = module.attr("Class")();
Card* card = extract< Card* >(derived);

Solution

  • Each name in a "dotted" notation is an attribute of its parent. And your last piece of code is almost correct (although, I suspect some mix-up with names):

    boost::python::object Class = boost::python::import("Base.Derived").attr("Class");
    boost::python::object class_instance = Class();