IPython/ target=_blank class=infotextkey>Python 是 Python 的原生交互式 shell 的增強版,可以完成許多不同尋常的任務,比如幫助實現并行化計算;主要使用它提供的交互性幫助,比如代碼著色、改進了的命令行回調、制表符完成、宏功能以及改進了的交互式幫助。
IPython 8.0 醞釀了許久,主要對現有代碼庫和幾個新功能進行了改進。新功能包括在 CLI 中使用 Black 重新格式化代碼、ghost 建議以及突出錯誤節點的更好的回溯,從而使復雜的表達式更易于調試。
追溯改進
之前的錯誤回溯顯示一個散列表(hash),用于編譯 Python AST:
In [1]: def foo():
...: return 3 / 0
...:
In [2]: foo()
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-2-c19b6d9633cf> in <module>
----> 1 foo()
<ipython-input-1-1595a74c32d5> in foo()
1 def foo():
----> 2 return 3 / 0
3
ZeroDivisionError: division by zero
現在錯誤回溯的格式正確,會顯示發生錯誤的單元格編號:
In [1]: def foo():
...: return 3 / 0
...:
Input In [2]: foo()
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
input In [2], in <module>
----> 1 foo()
Input In [1], in foo()
1 def foo():
----> 2 return 3 / 0
ZeroDivisionError: division by zero
第二個回溯改進是 stack_data 包的集成;在回溯中提供更智能的信息;它會突出顯示發生錯誤的 AST 節點,這有助于快速縮小錯誤范圍,比如
def foo(i):
x = [[[0]]]
return x[0][i][0]
def bar():
return foo(0) + foo(
1
) + foo(2)
調用 bar() 會在 IndexError 的返回行上引發一個 foo,IPython 8.0 可以告訴你索引錯誤發生在哪里:
IndexError
Input In [2], in <module>
----> 1 bar()
^^^^^
Input In [1], in bar()
6 def bar():
----> 7 return foo(0) + foo(
^^^^
8 1
^^^^^^^^
9 ) + foo(2)
^^^^
Input In [1], in foo(i)
1 def foo(i):
2 x = [[[0]]]
----> 3 return x[0][i][0]
^^^^^^^
用 ^ 標記的位置在終端會高亮顯示。
第三個回溯改進是最謹慎的,但對生產力有很大影響,在回溯中的文件名后面附加一個冒號 :: 和行號:
ZeroDivisionError Traceback (most recent call last)
File ~/error.py:4, in <module>
1 def f():
2 1/0
----> 4 f()
File ~/error.py:2, in f()
1 def f():
----> 2 1/0
許多終端和編輯器具有的集成功能,允許在使用此語法時直接跳轉到錯誤相關的文件/行。
自動建議
Ptpython 允許用戶在 ptpython/config.py 中啟用自動建議功能,此功能包含豐富的代碼補全建議,如圖:
目前,自動建議僅在 emacs 或 vi 插入編輯模式中顯示:
- ctrl e、ctrl f 和 alt f 快捷鍵默認在 emacs 模式下工作。
- 要在 vi 插入模式下使用這些快捷鍵,必須在 config.py 中創建自定義鍵綁定。
使用“?”和"??"查看對象信息
在 IPDB 中,現在可以使用“?”和”? ?“來顯示對象的信息,在使用 IPython 提示符時也可如此操作:
ipdb> partial?
Init signature: partial(self, /, *args, **kwargs)
Docstring:
partial(func, *args, **keywords) - new function with partial Application
of the given arguments and keywords.
File: ~/.pyenv/versions/3.8.6/lib/python3.8/functools.py
Type: type
Subclasses:
歷史范圍全局功能
之前使用 %history 功能時,用戶可以指定會話和行的范圍,例如:
~8/1-~6/5 # see history from the first line of 8 sessions ago,
# to the fifth line of 6 sessions ago.``
或者可以指定全局模式(global):
-g <pattern> # glob ALL history for the specified pattern.
但無法同時指定兩者,如果用戶確實指定了范圍和全局模式,則將使用 glob 模式(通配所有歷史記錄),并且將忽略范圍。
現在此功能獲得了增強,如果用戶同時指定范圍和 glob 模式,則 glob 模式將應用于指定的歷史范圍。
此外,Ipython 8.0 還取消了對 Python 3.7 的支持,僅支持 3.8 以上版本。有關 Ipython 8.0 的更多新功能,可在發布頁面查看。