【问题标题】:Autocomplete for jupyter notebook and ipython console for classes with "@property"带有“@property”的类的 jupyter notebook 和 ipython 控制台的自动完成
【发布时间】:2019-03-01 12:18:01
【问题描述】:

我想在 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 notebook 的自动完成功能仅适用于

>>> b.a.value

>>> c.a.

没有选项卡自动完成。

如何在ipython和jupyter notebook中重写代码实现c.a.<tab> -> c.a.value自动补全?

【问题讨论】:

  • 我认为这是不可能的,因为当您点击 <tab> 时,自动完成器不会执行表达式 c.a。它无法知道property函数是否有副作用。
  • x=c.a, x.<tab> 可能工作
  • UPD 从 Spyder 启动的 IPython 控制台很好地完成了 c.a.<tab> -> c.a.value。也许 Spyder 使用绳索,但香草 ipython 和 jupyter 使用绝地来做这个?

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


【解决方案1】:

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

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

【讨论】:

  • 在属性上的选项卡完成有同样的问题,运行命令 get_ipython().Completer.use_jedi = False 后已修复
  • 尽管关闭了绝地,但似乎又被打破了。有人解决这个问题吗?
猜你喜欢
  • 2014-02-23
  • 2016-04-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2016-11-25
  • 1970-01-01
  • 2015-10-15
  • 2020-07-23
相关资源
最近更新 更多