0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Boost.Pythonでモジュールをネストさせる

Posted at

やりたいこと

下に示すPythonのモジュール(正確にはパッケージかもしれない)と等価な構造のモジュールをBoost.Pythonで作ります。

mainmodule/
    ├ __init__.py
    ├ submodule1/
    │    ├ __init__.py
    │    └ hoge.py
    ├ submodule2/
    │    ├ __init__.py
    │    └ foo.py
        :
        :

インポートは

import mainmodule
from mainmodule.submodule1 import hogehoge  # mainmodule/submodule1/hoge.pyにhogehogeが定義されている
from mainmodule import submodule2

という感じになります。

この記事の対象者

この記事はBoost.Pythonのかなり込み入った使い方の説明です。
そのため、Boost.Pythonについて一度ぐらいは使ったことがある程度の人を対象としています。

Boost.Pythonを使ったことはないけれど興味があるという方は、こちらletsboost::python - Kmonos.netで予習をどうぞ。

やりたいことの情報元

クラスをネストさせる方法はよく見つかるけど、モジュールのネストはなかなか見つからなかったので、メモ。
もとになったページPackages in Python extension modules

やりかた

ソースコードを見てもらった方が早いと思うので、いきなりソースコードです。

一番外側のモジュールを宣言。

BOOST_PYTHON_MODULE(mainmodule) {
    using namespace boost::python;

    object package = scope();
    package.attr("__path__") = "mainmodule";

    export_submodule1();
    export_submodule2();
        
}

サブモジュールを宣言する関数

void export_submodule1() {
    using namespace boost::python;
    // from mainmodule.submodule1 import の形式で呼び出せるようにする
    object module(handle<>(bp::borrowed(PyImport_AddModule("mainmodule.submodule1"))));
    // from mainmodule import submodule1 を使えるようにする
    scope().attr("submodule1") = module;
    // スコープを設定
    scope scope1 = module;
    // いろいろと必要な関数、クラスを定義する
    def("hogehoge", &hogehoge);
        
}

使い方

通常のPythonのモジュールと同様に利用できるので、特に説明はありません。
インポートは冒頭で示した通りです。

参考

Packages in Python extension modules

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?