我正在使用 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__
我的问题:
- 有没有简单的方法让 dir() 函数也返回非函数成员?
- 如果对 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/