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

时间:2012-09-09 17:53:46

标签: 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类中添加上述代码?
  3. 我知道这是一件小事,但在我看来,制表完成对生产力有非常积极的影响。

    由于

1 个答案:

答案 0 :(得分:2)

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