具有“ @property”的类的jupyter笔记本和ipython控制台的自动完成功能

时间:2019-03-01 12:18:01

标签: python jupyter-notebook ipython jupyter jupyter-console

我想在ipython和jupyter中为具有只读类属性(使用@property)的以下代码使用自动完成功能:

class A(object):
    def __init__(self):
        self.__value = 1

    @property
    def value(self):
        return self.__value

class B(object):
    def __init__(self):
        self.a = A()

class C(object):
    def __init__(self):
        self.__a = A()

    @property
    def a(self):
        return self.__a

b = B()
c = C()

两者

>>> b.a.value

>>> c.a.value

做得好。但是ipython和jupyter笔记本的自动完成功能仅适用于

>>> b.a.value

>>> c.a.

没有制表符自动完成功能。

如何在ipython和jupyter笔记本中重写代码以实现c.a.<tab> -> c.a.value自动完成功能?

1 个答案:

答案 0 :(得分:1)

由于IPython(6.x至7.2)+绝地的问题,我的临时破解是

def fix_ipython_autocomplete(enable=True):
    """Change autocomplete behavior for IPython > 6.x

    Parameter
    ---------
    enable : bool (default True)
        Is use the trick.

    Notes
    -----
    Since IPython > 6.x the ``jedi`` package is using for autocomplete by default.
    But in some cases, the autocomplete doesn't work correctly wrong (see e.g.
    `here <https://github.com/ipython/ipython/issues/11653>`_).

    To set the correct behaviour we should use in IPython environment::

        %config Completer.use_jedi = False

    or add to IPython config (``<HOME>\.ipython\profile_default\ipython_config.py``)::

        c.Completer.use_jedi = False
    """

    try:
        __IPYTHON__
    except NameError:
        pass
    else:
        from IPython import __version__      
        major = int(__version__.split('.')[0])
        if major >= 6:
            from IPython import get_ipython
            get_ipython().Completer.use_jedi = not enable

另请参阅https://github.com/ipython/ipython/issues/11653