python - 如何使 dir(obj) 在 swig 生成的 python 类中返回非函数成员?

标签 python swig

我正在使用 swig 为 C++ 库生成 python 包装器。 我倾向于使用 ipython 以交互方式使用生成的 python 模块。

假设我有以下 C++ 类:

class test
{
    int num;
    int foo();
};

Swig 用 python 类包装了这个类:

class test:
    def foo():...
    __swig_getmethods__["num"] = ...
    __swig_setmethods__["num"] = ...
    .
    .
    .

与 ipython 交互使用时。我注意到制表符完成将成功找到“foo”,但不是“num”。

经过一点挖掘,我看到 ipython 使用“dir”方法完成制表符。 swig 生成非函数类成员的方式是通过实现 __setattr____getattr__。他们所做的只是检查 __swig_set/getmethods__ 字典并返回值(如果找到)。 这就是为什么在尝试 dir(test) 时不会返回像“num”这样的成员。

理想情况下,如果 swig 可以为其每个类实现 __dir__ 就好了。像这样的东西可以添加到每个 swig 包装器类中:

# Merge the two method dictionaries, and get the keys
__swig_dir__ = dict(__swig_getmethods__.items() + __swig_setmethods__.items()).keys()
# Implement __dir__() to return it plus all of the other members
def __dir__(self):
    return __dict__.keys() + __swig_dir__ 

我的问题:

  1. 有没有简单的方法让 dir() 函数也返回非函数成员?
  2. 如果对 1 的回答是否定的,是否有一种简单的方法可以将上述代码添加到 swig 生成的每个 python 类中?

我知道这是一件小事,但我认为 Tab 补全对工作效率有非常积极的影响。

谢谢

最佳答案

IPython 将 dir 包装在 IPython/core/completer.py 中的新函数 dir2 中

所以你可以尝试重新定义 dir2。像这样的东西:

import IPython.core.completer
old_dir = IPython.core.completer.dir2

def my_dir(obj):
    methods = old_dir(obj)
    #merge your swig methods in
    return methods

IPython.core.completer.dir2 = my_dir

关于python - 如何使 dir(obj) 在 swig 生成的 python 类中返回非函数成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12341468/

相关文章:

python - 有没有办法让 python str.partition 忽略大小写?

python - 如何制作函数 Composer

c++ - 无法捕获异常!

python - 在 Python 中删除一个对象和对它的所有引用?

java - 让 SWIG 理解 char** 以便在 Java 中使用它

python - 如何在 Tensorflow 中执行核密度估计

python - self.assertTrue(response.content 中的 post.text) – 断言错误

Python 自省(introspection) : How to get an 'unsorted' list of object attributes?

python - 在 Mac OS X 上使用 Swig 将 C++ 包装到 Python

python - Swig -outdir 选项不包含 .so 文件