### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](logging.xhtml "日志 HOWTO") |
- [上一頁](descriptor.xhtml "實現描述器") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 常用指引](index.xhtml) ?
- $('.inline-search').show(0); |
# 函數式編程指引
作者A. M. Kuchling
發布版本0\.32
本文檔提供恰當的 Python 函數式編程范例,在函數式編程簡單的介紹之后,將簡單介紹Python中關于函數式編程的特性如 [iterator](../glossary.xhtml#term-iterator) 和 [generator](../glossary.xhtml#term-generator) 以及相關庫模塊如 [`itertools`](../library/itertools.xhtml#module-itertools "itertools: Functions creating iterators for efficient looping.") 和 [`functools`](../library/functools.xhtml#module-functools "functools: Higher-order functions and operations on callable objects.") 等。
## 概述
本章介紹函數式編程的基本概念。如您僅想學習 Python 語言的特性,可跳過本章直接查看 [迭代器](#functional-howto-iterators).
編程語言支持通過以下幾種方式來解構具體問題:
- 大多數的編程語言都是 **過程式** 的,所謂程序就是一連串告訴計算機怎樣處理程序輸入的指令。C、Pascal 甚至 Unix shells 都是過程式語言。
- 在 **聲明式** 語言中,你編寫一個用來描述待解決問題的說明,并且這個語言的具體實現會指明怎樣高效的進行計算。 SQL 可能是你最熟悉的聲明式語言了。 一個 SQL 查詢語句描述了你想要檢索的數據集,并且 SQL 引擎會決定是掃描整張表還是使用索引,應該先執行哪些子句等等。
- **面向對象** 程序會操作一組對象。 對象擁有內部狀態,并能夠以某種方式支持請求和修改這個內部狀態的方法。Smalltalk 和 Java 都是面向對象的語言。 C++ 和 Python 支持面向對象編程,但并不強制使用面向對象特性。
- **函數式** 編程則將一個問題分解成一系列函數。 理想情況下,函數只接受輸入并輸出結果,對一個給定的輸入也不會有影響輸出的內部狀態。 著名的函數式語言有 ML 家族(Standard ML,Ocaml 以及其他變種)和 Haskell。
一些語言的設計者選擇強調一種特定的編程方式。 這通常會讓以不同的方式來編寫程序變得困難。其他多范式語言則支持幾種不同的編程方式。Lisp,C++ 和 Python 都是多范式語言;使用這些語言,你可以編寫主要為過程式,面向對象或者函數式的程序和函數庫。在大型程序中,不同的部分可能會采用不同的方式編寫;比如 GUI 可能是面向對象的而處理邏輯則是過程式或者函數式。
在函數式程序里,輸入會流經一系列函數。每個函數接受輸入并輸出結果。函數式風格反對使用帶有副作用的函數,這些副作用會修改內部狀態,或者引起一些無法體現在函數的返回值中的變化。完全不產生副作用的函數被稱作“純函數”。消除副作用意味著不能使用隨程序運行而更新的數據結構;每個函數的輸出必須只依賴于輸入。
一些語言對純潔性要求非常嚴格,以至于沒有像 `a=3` 或 `c = a + b` 這樣的賦值表達式,但是完全消除副作用非常困難。 比如,顯示在屏幕上或者寫到磁盤文件中都是副作用。舉個例子,在 Python 里,調用函數 [`print()`](../library/functions.xhtml#print "print") 或者 [`time.sleep()`](../library/time.xhtml#time.sleep "time.sleep") 并不會返回有用的結果;它們的用途只在于副作用,向屏幕發送一段文字或暫停一秒鐘。
函數式風格的 Python 程序并不會極端到消除所有 I/O 或者賦值的程度;相反,他們會提供像函數式一樣的接口,但會在內部使用非函數式的特性。比如,函數的實現仍然會使用局部變量,但不會修改全局變量或者有其他副作用。
函數式編程可以被認為是面向對象編程的對立面。對象就像是顆小膠囊,包裹著內部狀態和隨之而來的能讓你修改這個內部狀態的一組調用方法,以及由正確的狀態變化所構成的程序。函數式編程希望盡可能地消除狀態變化,只和流經函數的數據打交道。在 Python 里你可以把兩種編程方式結合起來,在你的應用(電子郵件信息,事務處理)中編寫接受和返回對象實例的函數。
函數式設計在工作中看起來是個奇怪的約束。為什么你要消除對象和副作用呢?不過函數式風格有其理論和實踐上的優點:
- 形式證明。
- 模塊化。
- 組合性。
- 易于調試和測試。
### 形式證明
一個理論上的優點是,構造數學證明來說明函數式程序是正確的相對更容易些。
很長時間,研究者們對尋找證明程序正確的數學方法都很感興趣。這和通過大量輸入來測試,并得出程序的輸出基本正確,或者閱讀一個程序的源代碼然后得出代碼看起來沒問題不同;相反,這里的目標是一個嚴格的證明,證明程序對所有可能的輸入都能給出正確的結果。
證明程序正確性所用到的技術是寫出 **不變量**,也就是對于輸入數據和程序中的變量永遠為真的特性。然后對每行代碼,你說明這行代碼執行前的不變量 X 和 Y 以及執行后稍有不同的不變量 X' 和 Y' 為真。如此一直到程序結束,這時候在程序的輸出上,不變量應該會與期望的狀態一致。
函數式編程之所以要消除賦值,是因為賦值在這個技術中難以處理;賦值可能會破壞賦值前為真的不變量,卻并不產生任何可以傳遞下去的新的不變量。
不幸的是,證明程序的正確性很大程度上是經驗性質的,而且和 Python 軟件無關。即使是微不足道的程序都需要幾頁長的證明;一個中等復雜的程序的正確性證明會非常龐大,而且,極少甚至沒有你日常所使用的程序(Python 解釋器,XML 解析器,瀏覽器)的正確性能夠被證明。即使你寫出或者生成一個證明,驗證證明也會是一個問題;里面可能出了差錯,而你錯誤地相信你證明了程序的正確性。
### 模塊化
函數式編程的一個更實用的優點是,它強制你把問題分解成小的方面。因此程序會更加模塊化。相對于一個進行了復雜變換的大型函數,一個小的函數更明確,更易于編寫, 也更易于閱讀和檢查錯誤。
### 易于調試和測試
測試和調試函數式程序相對來說更容易。
調試很簡單是因為函數通常都很小而且清晰明確。當程序無法工作的時候,每個函數都是一個可以檢查數據是否正確的接入點。你可以通過查看中間輸入和輸出迅速找到出錯的函數。
測試更容易是因為每個函數都是單元測試的潛在目標。在執行測試前,函數并不依賴于需要重現的系統狀態;相反,你只需要給出正確的輸入,然后檢查輸出是否和期望的結果一致。
### 組合性
當你編寫函數式風格的程序時,你會寫出很多帶有不同輸入和輸出的函數。其中一些不可避免地會局限于特定的應用,但其他的卻可以廣泛的用在程序中。舉例來說,一個接受文件夾目錄返回所有文件夾中的 XML 文件的函數; 或是一個接受文件名,然后返回文件內容的函數,都可以應用在很多不同的場合。
久而久之你會形成一個個人工具庫。通常你可以重新組織已有的函數來組成新的程序,然后為當前的工作寫一些特殊的函數。
## 迭代器
我會從 Python 的一個語言特性, 編寫函數式風格程序的重要基石開始說起:迭代器。
迭代器是一個表示數據流的對象;這個對象每次只返回一個元素。Python 迭代器必須支持 [`__next__()`](../library/stdtypes.xhtml#iterator.__next__ "iterator.__next__") 方法;這個方法不接受參數,并總是返回數據流中的下一個元素。如果數據流中沒有元素,[`__next__()`](../library/stdtypes.xhtml#iterator.__next__ "iterator.__next__") 會拋出 [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration") 異常。迭代器未必是有限的;完全有理由構造一個輸出無限數據流的迭代器。
內置的 [`iter()`](../library/functions.xhtml#iter "iter") 函數接受任意對象并試圖返回一個迭代器來輸出對象的內容或元素,并會在對象不支持迭代的時候拋出 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") 異常。Python 有幾種內置數據類型支持迭代,最常見的就是列表和字典。如果一個對象能生成迭代器,那么它就會被稱作 [iterable](../glossary.xhtml#term-iterable)。
你可以手動試驗迭代器的接口。
```
>>> L = [1, 2, 3]
>>> it = iter(L)
>>> it #doctest: +ELLIPSIS
<...iterator object at ...>
>>> it.__next__() # same as next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
```
Python 有不少要求使用可迭代的對象的地方,其中最重要的就是 [`for`](../reference/compound_stmts.xhtml#for) 表達式。在表達式 `for X in Y`,Y 要么自身是一個迭代器,要么能夠由 [`iter()`](../library/functions.xhtml#iter "iter") 創建一個迭代器。以下兩種表達是等價的:
```
for i in iter(obj):
print(i)
for i in obj:
print(i)
```
可以用 [`list()`](../library/stdtypes.xhtml#list "list") 或 [`tuple()`](../library/stdtypes.xhtml#tuple "tuple") 這樣的構造函數把迭代器具體化成列表或元組:
```
>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> t = tuple(iterator)
>>> t
(1, 2, 3)
```
序列的解壓操作也支持迭代器:如果你知道一個迭代器能夠返回 N 個元素,你可以把他們解壓到有 N 個元素的元組:
```
>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> a, b, c = iterator
>>> a, b, c
(1, 2, 3)
```
像 [`max()`](../library/functions.xhtml#max "max") 和 [`min()`](../library/functions.xhtml#min "min") 這樣的內置函數可以接受單個迭代器參數,然后返回其中最大或者最小的元素。`"in"` 和 `"not in"` 操作也支持迭代器:如果能夠在迭代器 iterator 返回的數據流中找到 X 的話,則``X in iterator`` 為真。很顯然,如果迭代器是無限的,這么做你就會遇到問題;[`max()`](../library/functions.xhtml#max "max") 和 [`min()`](../library/functions.xhtml#min "min") 永遠也不會返回;如果元素 X 也不出現在數據流中,`"in"` 和 `"not in"` 操作同樣也永遠不會返回。
注意你只能在迭代器中順序前進;沒有獲取前一個元素的方法,除非重置迭代器,或者重新復制一份。迭代器對象可以提供這些額外的功能,但迭代器協議只明確了 [`__next__()`](../library/stdtypes.xhtml#iterator.__next__ "iterator.__next__") 方法。函數可能因此而耗盡迭代器的輸出,如果你要對同樣的數據流做不同的操作,你必須重新創建一個迭代器。
### 支持迭代器的數據類型
我們已經知道列表和元組支持迭代器。實際上,Python 中的任何序列類型,比如字符串,都自動支持創建迭代器。
對字典調用 [`iter()`](../library/functions.xhtml#iter "iter") 會返回一個遍歷字典的鍵的迭代器:
```
>>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
>>> for key in m:
... print(key, m[key])
Jan 1
Feb 2
Mar 3
Apr 4
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
```
注意從 Python 3.7 開始,字典的遍歷順序一定和輸入順序一樣。先前的版本并沒有明確這一點,所以不同的實現可能不一致。
對字典使用 [`iter()`](../library/functions.xhtml#iter "iter") 總是會遍歷鍵,但字典也有返回其他迭代器的方法。如果你只遍歷值或者鍵/值對,你可以明確地調用 [`values()`](../library/stdtypes.xhtml#dict.values "dict.values") 或 [`items()`](../library/stdtypes.xhtml#dict.items "dict.items") 方法得到合適的迭代器。
[`dict()`](../library/stdtypes.xhtml#dict "dict") 構造函數可以接受一個迭代器,然后返回一個有限的 `(key, value)` 元組的數據流:
```
>>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
>>> dict(iter(L))
{'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'}
```
文件也可以通過調用 [`readline()`](../library/io.xhtml#io.TextIOBase.readline "io.TextIOBase.readline") 來遍歷,直到窮盡文件中所有的行。這意味著你可以像這樣讀取文件中的每一行:
```
for line in file:
# do something for each line
...
```
集合可以從可遍歷的對象獲取內容,也可以讓你遍歷集合的元素:
```
S = {2, 3, 5, 7, 11, 13}
for i in S:
print(i)
```
## 生成器表達式和列表推導式
迭代器的輸出有兩個很常見的使用方式,1) 對每一個元素執行操作,2) 選擇一個符合條件的元素子集。比如,給定一個字符串列表,你可能想去掉每個字符串尾部的空白字符,或是選出所有包含給定子串的字符串。
列表推導式和生成器表達時(簡寫:"listcomps" 和 "genexps")讓這些操作更加簡明,這個形式借鑒自函數式程序語言 Haskell(<https://www.haskell.org/>)。你可以用以下代碼去掉一個字符串流中的所有空白字符:
```
line_list = [' line 1\n', 'line 2 \n', ...]
# Generator expression -- returns iterator
stripped_iter = (line.strip() for line in line_list)
# List comprehension -- returns list
stripped_list = [line.strip() for line in line_list]
```
你可以加上條件語句 `"if"` 來選取特定的元素:
```
stripped_list = [line.strip() for line in line_list
if line != ""]
```
通過列表推導式,你會獲得一個 Python 列表;`stripped_list` 就是一個包含所有結果行的列表,并不是迭代器。 生成器表達式會返回一個迭代器,它在必要的時候計算結果,避免一次性生成所有的值。 這意味著,如果迭代器返回一個無限數據流或者大量的數據,列表推導式就不太好用了。 這種情況下生成器表達式會更受青睞。
生成器表達式兩邊使用圓括號 ("()") ,而列表推導式則使用方括號 ("\[\]")。生成器表達式的形式為:
```
( expression for expr in sequence1
if condition1
for expr2 in sequence2
if condition2
for expr3 in sequence3 ...
if condition3
for exprN in sequenceN
if conditionN )
```
再次說明,列表推導式只有兩邊的括號不一樣(方括號而不是圓括號)。
這些生成用于輸出的元素會成為 `expression` 的后繼值。其中 `if` 語句是可選的;如果給定的話 `expression` 只會在符合條件時計算并加入到結果中。
生成器表達式總是寫在圓括號里面,不過也可以算上調用函數時用的括號。如果你想即時創建一個傳遞給函數的迭代器,可以這么寫:
```
obj_total = sum(obj.count for obj in list_all_objects())
```
其中 `for...in` 語句包含了將要遍歷的序列。這些序列并不必須同樣長,因為它們會從左往右開始遍歷,而 **不是** 同時執行。對每個 `sequence1` 中的元素,`sequence2` 會從頭開始遍歷。`sequence3` 會對每個 `sequence1` 和 `sequence2` 的元素對開始遍歷。
換句話說,列表推導式器是和下面的 Python 代碼等價:
```
for expr1 in sequence1:
if not (condition1):
continue # Skip this element
for expr2 in sequence2:
if not (condition2):
continue # Skip this element
...
for exprN in sequenceN:
if not (conditionN):
continue # Skip this element
# Output the value of
# the expression.
```
這說明,如果有多個 `for...in` 語句而沒有 `if` 語句,輸出結果的長度就是所有序列長度的乘積。如果你的兩個列表長度為3,那么輸出的列表長度就是9:
```
>>> seq1 = 'abc'
>>> seq2 = (1, 2, 3)
>>> [(x, y) for x in seq1 for y in seq2] #doctest: +NORMALIZE_WHITESPACE
[('a', 1), ('a', 2), ('a', 3),
('b', 1), ('b', 2), ('b', 3),
('c', 1), ('c', 2), ('c', 3)]
```
為了不讓 Python 語法變得含糊,如果 `expression` 會生成元組,那這個元組必須要用括號括起來。下面第一個列表推導式語法錯誤,第二個則是正確的:
```
# Syntax error
[x, y for x in seq1 for y in seq2]
# Correct
[(x, y) for x in seq1 for y in seq2]
```
## 生成器
生成器是一類用來簡化編寫迭代器工作的特殊函數。普通的函數計算并返回一個值,而生成器返回一個能返回數據流的迭代器。
毫無疑問,你已經對如何在 Python 和 C 中調用普通函數很熟悉了,這時候函數會獲得一個創建局部變量的私有命名空間。當函數到達 `return` 表達式時,局部變量會被銷毀然后把返回給調用者。之后調用同樣的函數時會創建一個新的私有命名空間和一組全新的局部變量。但是,如果在退出一個函數時不扔掉局部變量會如何呢?如果稍后你能夠從退出函數的地方重新恢復又如何呢?這就是生成器所提供的;他們可以被看成可恢復的函數。
這里有簡單的生成器函數示例:
```
>>> def generate_ints(N):
... for i in range(N):
... yield i
```
任何包含了 [`yield`](../reference/simple_stmts.xhtml#yield) 關鍵字的函數都是生成器函數;Python 的 [bytecode](../glossary.xhtml#term-bytecode) 編譯器會在編譯的時候檢測到并因此而特殊處理。
當你調用一個生成器函數,它并不會返回單獨的值,而是返回一個支持生成器協議的生成器對象。當執行 `yield` 表達式時,生成器會輸出 `i` 的值,就像 `return` 表達式一樣。`yield` 和 `return` 最大的區別在于,到達 `yield` 的時候生成器的執行狀態會掛起并保留局部變量。在下一次調用生成器 [`__next__()`](../reference/expressions.xhtml#generator.__next__ "generator.__next__") 方法的時候,函數會恢復執行。
這里有一個 `generate_ints()` 生成器的示例:
```
>>> gen = generate_ints(3)
>>> gen #doctest: +ELLIPSIS
<generator object generate_ints at ...>
>>> next(gen)
0
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
Traceback (most recent call last):
File "stdin", line 1, in <module>
File "stdin", line 2, in generate_ints
StopIteration
```
同樣,你可以寫出 `for i in generate_ints(5)`,或者 `a, b, c = generate_ints(3)`。
在生成器函數里面,`return value` 會觸發從 [`__next__()`](../reference/expressions.xhtml#generator.__next__ "generator.__next__") 方法拋出 `StopIteration(value)` 異常。一旦拋出這個異常,或者函數結束,處理數據的過程就會停止,生成器也不會再生成新的值。
你可以手動編寫自己的類來達到生成器的效果,把生成器的所有局部變量作為實例的成員變量存儲起來。比如,可以這么返回一個整數列表:把 `self.count` 設為0,然后通過 `count`()`。然而,對于一個中等復雜程度的生成器,寫出一個相應的類可能會相當繁雜。
包含在 Python 庫中的測試套件 [Lib/test/test\_generators.py](https://github.com/python/cpython/tree/3.7/Lib/test/test_generators.py) \[https://github.com/python/cpython/tree/3.7/Lib/test/test\_generators.py\] 里有很多非常有趣的例子。這里是一個用生成器實現樹的遞歸中序遍歷示例。:
```
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
if t:
for x in inorder(t.left):
yield x
yield t.label
for x in inorder(t.right):
yield x
```
另外兩個 `test_generators.py` 中的例子給出了 N 皇后問題(在 NxN 的棋盤上放置 N 個皇后,任何一個都不能吃掉另一個),以及馬的遍歷路線(在NxN 的棋盤上給馬找出一條不重復的走過所有格子的路線)的解。
### 向生成器傳遞值
在 Python 2.4 及之前的版本中,生成器只產生輸出。一旦調用生成器的代碼創建一個迭代器,就沒有辦法在函數恢復執行的時候向它傳遞新的信息。你可以設法實現這個功能,讓生成器引用一個全局變量或者一個調用者可以修改的可變對象,但是這些方法都很繁雜。
在 Python 2.5 里有一個簡單的將值傳遞給生成器的方法。[`yield`](../reference/simple_stmts.xhtml#yield) 變成了一個表達式,返回一個可以賦給變量或執行操作的值:
```
val = (yield i)
```
我建議你在處理 `yield` 表達式返回值的時候, **總是** 兩邊寫上括號,就像上面的例子一樣。括號并不總是必須的,但是比起記住什么時候需要括號,寫出來會更容易一點。
([**PEP 342**](https://www.python.org/dev/peps/pep-0342) \[https://www.python.org/dev/peps/pep-0342\] 解釋了具體的規則,也就是 `yield` 表達式必須括起來,除非是出現在最頂級的賦值表達式的右邊。這意味著你可以寫 `val = yield i`,但是必須在操作的時候加上括號,就像``val = (yield i) + 12``)
可以調用 `send(value)()` <generator.send> 方法向生成器發送值。這個方法會恢復執行生成器的代碼,然后 `yield` 表達式返回特定的值。如果調用普通的 `__next__`方法,``yield`()` 會返回 `None`.
這里有一個簡單的每次加1的計數器,并允許改變內部計數器的值。
```
def counter(maximum):
i = 0
while i < maximum:
val = (yield i)
# If value provided, change counter
if val is not None:
i = val
else:
i += 1
```
這是改變計數器的一個示例
```
>>> it = counter(10) #doctest: +SKIP
>>> next(it) #doctest: +SKIP
0
>>> next(it) #doctest: +SKIP
1
>>> it.send(8) #doctest: +SKIP
8
>>> next(it) #doctest: +SKIP
9
>>> next(it) #doctest: +SKIP
Traceback (most recent call last):
File "t.py", line 15, in <module>
it.next()
StopIteration
```
因為 `yield` 很多時候會返回 `None`,所以你應該總是檢查這個情況。不要在表達式中使用 `yield` 的值,除非你確定 [`send()`](../reference/expressions.xhtml#generator.send "generator.send") 是唯一的用來恢復你的生成器函數的方法。
除了 [`send()`](../reference/expressions.xhtml#generator.send "generator.send") 之外,生成器還有兩個其他的方法:
- [`throw(type, value=None, traceback=None)`](../reference/expressions.xhtml#generator.throw "generator.throw") 用于在生成器內部拋出異常;這個異常會在生成器暫停執行的時候由 `yield` 表達式拋出。
- [`generator.close()`](../reference/expressions.xhtml#generator.close "generator.close") 會在生成器內部拋出 [`GeneratorExit`](../library/exceptions.xhtml#GeneratorExit "GeneratorExit") 異常來結束迭代。當接收到這個異常時,生成器的代碼會拋出 [`GeneratorExit`](../library/exceptions.xhtml#GeneratorExit "GeneratorExit") 或者 [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration");捕捉這個異常作其他處理是非法的,并會出發 [`RuntimeError`](../library/exceptions.xhtml#RuntimeError "RuntimeError")。[`close()`](../reference/expressions.xhtml#generator.close "generator.close") 也會在 Python 垃圾回收器回收生成器的時候調用。
如果你要在 [`GeneratorExit`](../library/exceptions.xhtml#GeneratorExit "GeneratorExit") 發生的時候清理代碼,我建議使用 `try: ... finally:` 組合來代替 [`GeneratorExit`](../library/exceptions.xhtml#GeneratorExit "GeneratorExit")。
這些改變的累積效應是,讓生成器從單向的信息生產者變成了既是生產者,又是消費者。
生成器也可以成為 **協程** ,一種更廣義的子過程形式。子過程可以從一個地方進入,然后從另一個地方退出(從函數的頂端進入,從 `return` 語句退出),而協程可以進入,退出,然后在很多不同的地方恢復(`yield` 語句)。
## 內置函數
我們可以看看迭代器常常用到的函數的更多細節。
Python 內置的兩個函數 [`map()`](../library/functions.xhtml#map "map") 和 [`filter()`](../library/functions.xhtml#filter "filter") 復制了生成器表達式的兩個特性:
[`map(f, iterA, iterB, ...)`](../library/functions.xhtml#map "map") 返回一個遍歷序列的迭代器`f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...`.
```
>>> def upper(s):
... return s.upper()
```
```
>>> list(map(upper, ['sentence', 'fragment']))
['SENTENCE', 'FRAGMENT']
>>> [upper(s) for s in ['sentence', 'fragment']]
['SENTENCE', 'FRAGMENT']
```
你當然也可以用列表推導式達到同樣的效果。
[`filter(predicate, iter)`](../library/functions.xhtml#filter "filter") 返回一個遍歷序列中滿足指定條件的元素的迭代器,和列表推導式的功能相似。 **predicate** (謂詞)是一個在特定條件下返回真值的函數;要使用函數 [`filter()`](../library/functions.xhtml#filter "filter"),謂詞函數必須只能接受一個參數。
```
>>> def is_even(x):
... return (x % 2) == 0
```
```
>>> list(filter(is_even, range(10)))
[0, 2, 4, 6, 8]
```
這也可以寫成列表推導式:
```
>>> list(x for x in range(10) if is_even(x))
[0, 2, 4, 6, 8]
```
[`enumerate(iter, start=0)`](../library/functions.xhtml#enumerate "enumerate") 計數可迭代對象中的元素,然后返回包含每個計數(從 **start** 開始)和元素兩個值的元組。:
```
>>> for item in enumerate(['subject', 'verb', 'object']):
... print(item)
(0, 'subject')
(1, 'verb')
(2, 'object')
```
[`enumerate()`](../library/functions.xhtml#enumerate "enumerate") 常常用于遍歷列表并記錄達到特定條件時的下標:
```
f = open('data.txt', 'r')
for i, line in enumerate(f):
if line.strip() == '':
print('Blank line at line #%i' % i)
```
[`sorted(iterable, key=None, reverse=False)`](../library/functions.xhtml#sorted "sorted") 會將 iterable 中的元素收集到一個列表中,然后排序并返回結果。其中 *key* 和 *reverse* 參數會傳遞給所創建列表的 [`sort()`](../library/stdtypes.xhtml#list.sort "list.sort") 方法。:
```
>>> import random
>>> # Generate 8 random numbers between [0, 10000)
>>> rand_list = random.sample(range(10000), 8)
>>> rand_list
[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
>>> sorted(rand_list)
[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
>>> sorted(rand_list, reverse=True)
[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
```
(對排序更詳細的討論可參見 [排序指南](sorting.xhtml#sortinghowto)。)
內置函數 [`any(iter)`](../library/functions.xhtml#any "any") 和 [`all(iter)`](../library/functions.xhtml#all "all") 會查看一個可迭代對象內容的邏輯值。[`any()`](../library/functions.xhtml#any "any") 在可迭代對象中任意一個元素為真時返回 `True`,而 [`all()`](../library/functions.xhtml#all "all") 在所有元素為真時返回 `True`:
```
>>> any([0, 1, 0])
True
>>> any([0, 0, 0])
False
>>> any([1, 1, 1])
True
>>> all([0, 1, 0])
False
>>> all([0, 0, 0])
False
>>> all([1, 1, 1])
True
```
[`zip(iterA, iterB, ...)`](../library/functions.xhtml#zip "zip") 從每個可迭代對象中選取單個元素組成列表并返回:
```
zip(['a', 'b', 'c'], (1, 2, 3)) =>
('a', 1), ('b', 2), ('c', 3)
```
它并不會在內存創建一個列表并因此在返回前而耗盡輸入的迭代器;相反,只有在被請求的時候元組才會創建并返回。(這種行為的技術術語叫惰性計算,參見 [lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation) \[https://en.wikipedia.org/wiki/Lazy\_evaluation\].)
這個迭代器設計用于長度相同的可迭代對象。如果可迭代對象的長度不一致,返回的數據流的長度會和最短的可迭代對象相同
```
zip(['a', 'b'], (1, 2, 3)) =>
('a', 1), ('b', 2)
```
然而,你應該避免這種情況,因為所有從更長的迭代器中取出的元素都會被丟棄。這意味著之后你也無法冒著跳過被丟棄元素的風險來繼續使用這個迭代器。
## itertools 模塊
[`itertools`](../library/itertools.xhtml#module-itertools "itertools: Functions creating iterators for efficient looping.") 模塊包含很多常用的迭代器以及用來組合迭代器的函數。本節會用些小的例子來介紹這個模塊的內容。
這個模塊里的函數大致可以分為幾類:
- 從已有的迭代器創建新的迭代器的函數。
- 接受迭代器元素作為參數的函數。
- 選取部分迭代器輸出的函數。
- 給迭代器輸出分組的函數。
### 創建新的迭代器
[`itertools.count(start, step)`](../library/itertools.xhtml#itertools.count "itertools.count") 返回一個等分的無限數據流。初始值默認為0,間隔默認為1,你也選擇可以指定初始值和間隔:
```
itertools.count() =>
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
itertools.count(10) =>
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
itertools.count(10, 5) =>
10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ...
```
[`itertools.cycle(iter)`](../library/itertools.xhtml#itertools.cycle "itertools.cycle") 保存一份所提供的可迭代對象的副本,并返回一個能產生整個可迭代對象序列的新迭代器。新迭代器會無限重復這些元素。:
```
itertools.cycle([1, 2, 3, 4, 5]) =>
1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
```
[`itertools.repeat(elem, [n])`](../library/itertools.xhtml#itertools.repeat "itertools.repeat") 返回 *n* 次所提供的元素,當 *n* 不存在時,返回無數次所提供的元素。
```
itertools.repeat('abc') =>
abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
itertools.repeat('abc', 5) =>
abc, abc, abc, abc, abc
```
[`itertools.chain(iterA, iterB, ...)`](../library/itertools.xhtml#itertools.chain "itertools.chain") 接受任意數量的可迭代對象作為輸入,首先返回第一個迭代器的所有元素,然后是第二個的所有元素,如此一直進行下去,直到消耗掉所有輸入的可迭代對象。
```
itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
a, b, c, 1, 2, 3
```
[`itertools.islice(iter, [start], stop, [step])`](../library/itertools.xhtml#itertools.islice "itertools.islice") 返回一個所輸入的迭代器切片的數據流。如果只單獨給定 *stop* 參數的話,它會返回從起始算起 *stop* 個數量的元素。如果你提供了起始下標 *start*,你會得到 *stop-start* 個元素;如果你給定了 *step* 參數,數據流會跳過相應的元素。和 Python 里的字符串和列表切片不同,你不能在 *start*, *stop* 或者 *step* 這些參數中使用負數。:
```
itertools.islice(range(10), 8) =>
0, 1, 2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8) =>
2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8, 2) =>
2, 4, 6
```
[`itertools.tee(iter, [n])`](../library/itertools.xhtml#itertools.tee "itertools.tee") 可以復制一個迭代器;它返回 *n* 個能夠返回源迭代器內容的獨立迭代器。如果你不提供參數 *n*,默認值為 2。復制迭代器需要保存源迭代器的一部分內容,因此在源迭代器比較大的時候會顯著地占用內存;同時,在所有新迭代器中,有一個迭代器會比其他迭代器占用更多的內存。
```
itertools.tee( itertools.count() ) =>
iterA, iterB
where iterA ->
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
and iterB ->
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
```
### 在元素上調用函數
[`operator`](../library/operator.xhtml#module-operator "operator: Functions corresponding to the standard operators.") 模塊包含一組對應于 Python 操作符的函數。比如 [`operator.add(a, b)`](../library/operator.xhtml#operator.add "operator.add") (把兩個數加起來),[`operator.ne(a, b)`](../library/operator.xhtml#operator.ne "operator.ne") (和 `a != b` 相同),以及 [`operator.attrgetter('id')`](../library/operator.xhtml#operator.attrgetter "operator.attrgetter") (返回獲取 `.id` 屬性的可調用對象)。
[`itertools.starmap(func, iter)`](../library/itertools.xhtml#itertools.starmap "itertools.starmap") 假定可迭代對象能夠返回一個元組的流,并且利用這些元組作為參數來調用 *func*:
```
itertools.starmap(os.path.join,
[('/bin', 'python'), ('/usr', 'bin', 'java'),
('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
=>
/bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby
```
### 選擇元素
另外一系列函數根據謂詞選取一個迭代器中元素的子集。
[`itertools.filterfalse(predicate, iter)`](../library/itertools.xhtml#itertools.filterfalse "itertools.filterfalse") 和 [`filter()`](../library/functions.xhtml#filter "filter") 相反,返回所有讓 predicate 返回 false 的元素:
```
itertools.filterfalse(is_even, itertools.count()) =>
1, 3, 5, 7, 9, 11, 13, 15, ...
```
[`itertools.takewhile(predicate, iter)`](../library/itertools.xhtml#itertools.takewhile "itertools.takewhile") 返回一直讓 predicate 返回 true 的元素。一旦 predicate 返回 false,迭代器就會發出終止結果的信號。:
```
def less_than_10(x):
return x < 10
itertools.takewhile(less_than_10, itertools.count()) =>
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
itertools.takewhile(is_even, itertools.count()) =>
0
```
[`itertools.dropwhile(predicate, iter)`](../library/itertools.xhtml#itertools.dropwhile "itertools.dropwhile") 在 predicate 返回 true 的時候丟棄元素,并且返回可迭代對象的剩余結果。:
```
itertools.dropwhile(less_than_10, itertools.count()) =>
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
itertools.dropwhile(is_even, itertools.count()) =>
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
```
[`itertools.compress(data, selectors)`](../library/itertools.xhtml#itertools.compress "itertools.compress") 接受兩個迭代器,然后返回 *data* 中使相應地 *selector* 中的元素為真的元素;它會在任一個迭代器耗盡的時候停止:
```
itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =>
1, 2, 5
```
### 組合函數
[`itertools.combinations(iterable, r)`](../library/itertools.xhtml#itertools.combinations "itertools.combinations") 返回一個迭代器,它能給出輸入迭代器中所包含的元素的所有可能的 *r* 元元組的組合。:
```
itertools.combinations([1, 2, 3, 4, 5], 2) =>
(1, 2), (1, 3), (1, 4), (1, 5),
(2, 3), (2, 4), (2, 5),
(3, 4), (3, 5),
(4, 5)
itertools.combinations([1, 2, 3, 4, 5], 3) =>
(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5),
(2, 3, 4), (2, 3, 5), (2, 4, 5),
(3, 4, 5)
```
每個元組中的元素保持著 *可迭代對象* 返回他們的順序。例如,在上面的例子中數字 1 總是會在 2, 3, 4 或 5 前面。一個類似的函數,[`itertools.permutations(iterable, r=None)`](../library/itertools.xhtml#itertools.permutations "itertools.permutations"),取消了保持順序的限制,返回所有可能的長度為 *r* 的排列:
```
itertools.permutations([1, 2, 3, 4, 5], 2) =>
(1, 2), (1, 3), (1, 4), (1, 5),
(2, 1), (2, 3), (2, 4), (2, 5),
(3, 1), (3, 2), (3, 4), (3, 5),
(4, 1), (4, 2), (4, 3), (4, 5),
(5, 1), (5, 2), (5, 3), (5, 4)
itertools.permutations([1, 2, 3, 4, 5]) =>
(1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5),
...
(5, 4, 3, 2, 1)
```
如果你不提供 *r* 參數的值,它會使用可迭代對象的長度,也就是說會排列所有的元素。
注意這些函數會輸出所有可能的位置組合,并不要求 *可迭代對象* 的內容不重復:
```
itertools.permutations('aba', 3) =>
('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),
('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')
```
同一個元組 `('a', 'a', 'b')` 出現了兩次,但是兩個 'a' 字符來自不同的位置。
[`itertools.combinations_with_replacement(iterable, r)`](../library/itertools.xhtml#itertools.combinations_with_replacement "itertools.combinations_with_replacement") 函數放松了一個不同的限制:元組中的元素可以重復。從概念講,為每個元組第一個位置選取一個元素,然后在選擇第二個元素前替換掉它。:
```
itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) =>
(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
(2, 2), (2, 3), (2, 4), (2, 5),
(3, 3), (3, 4), (3, 5),
(4, 4), (4, 5),
(5, 5)
```
### 對元素分組
The last function I'll discuss, [`itertools.groupby(iter, key_func=None)`](../library/itertools.xhtml#itertools.groupby "itertools.groupby"), is the most complicated. `key_func(elem)` is a function that can compute a key value for each element returned by the iterable. If you don't supply a key function, the key is simply each element itself.
[`groupby()`](../library/itertools.xhtml#itertools.groupby "itertools.groupby") collects all the consecutive elements from the underlying iterable that have the same key value, and returns a stream of 2-tuples containing a key value and an iterator for the elements with that key.
```
city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
('Anchorage', 'AK'), ('Nome', 'AK'),
('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
...
]
def get_state(city_state):
return city_state[1]
itertools.groupby(city_list, get_state) =>
('AL', iterator-1),
('AK', iterator-2),
('AZ', iterator-3), ...
where
iterator-1 =>
('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
iterator-2 =>
('Anchorage', 'AK'), ('Nome', 'AK')
iterator-3 =>
('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
```
[`groupby()`](../library/itertools.xhtml#itertools.groupby "itertools.groupby") assumes that the underlying iterable's contents will already be sorted based on the key. Note that the returned iterators also use the underlying iterable, so you have to consume the results of iterator-1 before requesting iterator-2 and its corresponding key.
## The functools module
The [`functools`](../library/functools.xhtml#module-functools "functools: Higher-order functions and operations on callable objects.") module in Python 2.5 contains some higher-order functions. A **higher-order function** takes one or more functions as input and returns a new function. The most useful tool in this module is the [`functools.partial()`](../library/functools.xhtml#functools.partial "functools.partial") function.
For programs written in a functional style, you'll sometimes want to construct variants of existing functions that have some of the parameters filled in. Consider a Python function `f(a, b, c)`; you may wish to create a new function `g(b, c)` that's equivalent to `f(1, b, c)`; you're filling in a value for one of `f()`'s parameters. This is called "partial function application".
The constructor for [`partial()`](../library/functools.xhtml#functools.partial "functools.partial") takes the arguments `(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)`. The resulting object is callable, so you can just call it to invoke `function` with the filled-in arguments.
Here's a small but realistic example:
```
import functools
def log(message, subsystem):
"""Write the contents of 'message' to the specified subsystem."""
print('%s: %s' % (subsystem, message))
...
server_log = functools.partial(log, subsystem='server')
server_log('Unable to open socket')
```
[`functools.reduce(func, iter, [initial_value])`](../library/functools.xhtml#functools.reduce "functools.reduce")cumulatively performs an operation on all the iterable's elements and, therefore, can't be applied to infinite iterables. *func* must be a function that takes two elements and returns a single value. [`functools.reduce()`](../library/functools.xhtml#functools.reduce "functools.reduce")takes the first two elements A and B returned by the iterator and calculates `func(A, B)`. It then requests the third element, C, calculates `func(func(A, B), C)`, combines this result with the fourth element returned, and continues until the iterable is exhausted. If the iterable returns no values at all, a [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") exception is raised. If the initial value is supplied, it's used as a starting point and `func(initial_value, A)` is the first calculation.
```
>>> import operator, functools
>>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
'ABBC'
>>> functools.reduce(operator.concat, [])
Traceback (most recent call last):
...
TypeError: reduce() of empty sequence with no initial value
>>> functools.reduce(operator.mul, [1, 2, 3], 1)
6
>>> functools.reduce(operator.mul, [], 1)
1
```
If you use [`operator.add()`](../library/operator.xhtml#operator.add "operator.add") with [`functools.reduce()`](../library/functools.xhtml#functools.reduce "functools.reduce"), you'll add up all the elements of the iterable. This case is so common that there's a special built-in called [`sum()`](../library/functions.xhtml#sum "sum") to compute it:
```
>>> import functools, operator
>>> functools.reduce(operator.add, [1, 2, 3, 4], 0)
10
>>> sum([1, 2, 3, 4])
10
>>> sum([])
0
```
For many uses of [`functools.reduce()`](../library/functools.xhtml#functools.reduce "functools.reduce"), though, it can be clearer to just write the obvious [`for`](../reference/compound_stmts.xhtml#for) loop:
```
import functools
# Instead of:
product = functools.reduce(operator.mul, [1, 2, 3], 1)
# You can write:
product = 1
for i in [1, 2, 3]:
product *= i
```
A related function is [`itertools.accumulate(iterable, func=operator.add)`](../library/itertools.xhtml#itertools.accumulate "itertools.accumulate"). It performs the same calculation, but instead of returning only the final result, `accumulate()` returns an iterator that also yields each partial result:
```
itertools.accumulate([1, 2, 3, 4, 5]) =>
1, 3, 6, 10, 15
itertools.accumulate([1, 2, 3, 4, 5], operator.mul) =>
1, 2, 6, 24, 120
```
### The operator module
The [`operator`](../library/operator.xhtml#module-operator "operator: Functions corresponding to the standard operators.") module was mentioned earlier. It contains a set of functions corresponding to Python's operators. These functions are often useful in functional-style code because they save you from writing trivial functions that perform a single operation.
Some of the functions in this module are:
- Math operations: `add()`, `sub()`, `mul()`, `floordiv()`, `abs()`, ...
- Logical operations: `not_()`, `truth()`.
- Bitwise operations: `and_()`, `or_()`, `invert()`.
- Comparisons: `eq()`, `ne()`, `lt()`, `le()`, `gt()`, and `ge()`.
- Object identity: `is_()`, `is_not()`.
Consult the operator module's documentation for a complete list.
## Small functions and the lambda expression
When writing functional-style programs, you'll often need little functions that act as predicates or that combine elements in some way.
If there's a Python built-in or a module function that's suitable, you don't need to define a new function at all:
```
stripped_lines = [line.strip() for line in lines]
existing_files = filter(os.path.exists, file_list)
```
If the function you need doesn't exist, you need to write it. One way to write small functions is to use the [`lambda`](../reference/expressions.xhtml#lambda) expression. `lambda` takes a number of parameters and an expression combining these parameters, and creates an anonymous function that returns the value of the expression:
```
adder = lambda x, y: x+y
print_assign = lambda name, value: name + '=' + str(value)
```
An alternative is to just use the `def` statement and define a function in the usual way:
```
def adder(x, y):
return x + y
def print_assign(name, value):
return name + '=' + str(value)
```
Which alternative is preferable? That's a style question; my usual course is to avoid using `lambda`.
One reason for my preference is that `lambda` is quite limited in the functions it can define. The result has to be computable as a single expression, which means you can't have multiway `if... elif... else`comparisons or `try... except` statements. If you try to do too much in a `lambda` statement, you'll end up with an overly complicated expression that's hard to read. Quick, what's the following code doing?
```
import functools
total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
```
You can figure it out, but it takes time to disentangle the expression to figure out what's going on. Using a short nested `def` statements makes things a little bit better:
```
import functools
def combine(a, b):
return 0, a[1] + b[1]
total = functools.reduce(combine, items)[1]
```
But it would be best of all if I had simply used a `for` loop:
```
total = 0
for a, b in items:
total += b
```
Or the [`sum()`](../library/functions.xhtml#sum "sum") built-in and a generator expression:
```
total = sum(b for a, b in items)
```
Many uses of [`functools.reduce()`](../library/functools.xhtml#functools.reduce "functools.reduce") are clearer when written as `for` loops.
Fredrik Lundh once suggested the following set of rules for refactoring uses of `lambda`:
1. Write a lambda function.
2. Write a comment explaining what the heck that lambda does.
3. Study the comment for a while, and think of a name that captures the essence of the comment.
4. Convert the lambda to a def statement, using that name.
5. Remove the comment.
I really like these rules, but you're free to disagree about whether this lambda-free style is better.
## Revision History and Acknowledgements
The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton.
Version 0.1: posted June 30 2006.
Version 0.11: posted July 1 2006. Typo fixes.
Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one. Typo fixes.
Version 0.21: Added more references suggested on the tutor mailing list.
Version 0.30: Adds a section on the `functional` module written by Collin Winter; adds short section on the operator module; a few other edits.
## 引用文獻
### 通用文獻
**Structure and Interpretation of Computer Programs**, Harold Abelson, Gerald Jay Sussman 和 Julie Sussman 著。全文可見 <https://mitpress.mit.edu/sicp/> 。在這部計算機科學的經典教科書中,第二和第三章討論了使用序列和流來組織程序內部的數據傳遞。書中的示例采用 Scheme 語言,但其中這些章節中描述的很多設計方法同樣適用于函數式風格的 Python 代碼。
<http://www.defmacro.org/ramblings/fp.html>: 一個使用 Java 示例的函數式編程的總體介紹,有很長的歷史說明。
[https://en.wikipedia.org/wiki/Functional\_programming](https://en.wikipedia.org/wiki/Functional_programming): 一般性的函數式編程的 Wikipedia 條目。
<https://en.wikipedia.org/wiki/Coroutine>: 協程條目。
<https://en.wikipedia.org/wiki/Currying>: 函數柯里化條目。
### Python 相關
<http://gnosis.cx/TPiP/>:David Mertz 書中的第一章 Text Processing in Python,"Utilizing Higher-Order Functions in Text Processing" 標題部分討論了文本處理的函數式編程。
Mertz 還在 IBM 的 DeveloperWorks 站點上關于函數式編程寫了一系列共3篇文章;參見`part 1<<https://www.ibm.com/developerworks/linux/library/l-prog/index.html>>`\_\_,`part2<<https://www.ibm.com/developerworks/linux/library/l-prog2/index.html>>`\_\_, 和`part 3<<https://www.ibm.com/developerworks/linux/library/l-prog3/index.html>>`\_\_,
### Python 文檔
[`itertools`](../library/itertools.xhtml#module-itertools "itertools: Functions creating iterators for efficient looping.") 模塊文檔。
[`functools`](../library/functools.xhtml#module-functools "functools: Higher-order functions and operations on callable objects.") 模塊文檔。
[`operator`](../library/operator.xhtml#module-operator "operator: Functions corresponding to the standard operators.") 模塊文檔。
[**PEP 289**](https://www.python.org/dev/peps/pep-0289) \[https://www.python.org/dev/peps/pep-0289\]: "Generator Expressions"
[**PEP 342**](https://www.python.org/dev/peps/pep-0342) \[https://www.python.org/dev/peps/pep-0342\]: "Coroutines via Enhanced Generators" 描述了 Python 2.5 中新的生成器特性。
### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](logging.xhtml "日志 HOWTO") |
- [上一頁](descriptor.xhtml "實現描述器") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 常用指引](index.xhtml) ?
- $('.inline-search').show(0); |
? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
- Python文檔內容
- Python 有什么新變化?
- Python 3.7 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- C API 的改變
- 構建的改變
- 性能優化
- 其他 CPython 實現的改變
- 已棄用的 Python 行為
- 已棄用的 Python 模塊、函數和方法
- 已棄用的 C API 函數和類型
- 平臺支持的移除
- API 與特性的移除
- 移除的模塊
- Windows 專屬的改變
- 移植到 Python 3.7
- Python 3.7.1 中的重要變化
- Python 3.7.2 中的重要變化
- Python 3.6 有什么新變化A
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 其他改進
- 棄用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要變化
- Python 3.6.4 中的重要變化
- Python 3.6.5 中的重要變化
- Python 3.6.7 中的重要變化
- Python 3.5 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- Other module-level changes
- 性能優化
- Build and C API Changes
- 棄用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 發布重點
- 新的特性
- 新增模塊
- 改進的模塊
- CPython Implementation Changes
- 棄用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 發布重點
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他語言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 棄用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 多線程
- 性能優化
- Unicode
- Codecs
- 文檔
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 性能優化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他語言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新變化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他語言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他語言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推導式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最終版
- Python 3.7.3 發布候選版 1
- Python 3.7.2 最終版
- Python 3.7.2 發布候選版 1
- Python 3.7.1 最終版
- Python 3.7.1 RC 2版本
- Python 3.7.1 發布候選版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 課前甜點
- 使用 Python 解釋器
- 調用解釋器
- 解釋器的運行環境
- Python 的非正式介紹
- Python 作為計算器使用
- 走向編程的第一步
- 其他流程控制工具
- if 語句
- for 語句
- range() 函數
- break 和 continue 語句,以及循環中的 else 子句
- pass 語句
- 定義函數
- 函數定義的更多形式
- 小插曲:編碼風格
- 數據結構
- 列表的更多特性
- del 語句
- 元組和序列
- 集合
- 字典
- 循環的技巧
- 深入條件控制
- 序列和其它類型的比較
- 模塊
- 有關模塊的更多信息
- 標準模塊
- dir() 函數
- 包
- 輸入輸出
- 更漂亮的輸出格式
- 讀寫文件
- 錯誤和異常
- 語法錯誤
- 異常
- 處理異常
- 拋出異常
- 用戶自定義異常
- 定義清理操作
- 預定義的清理操作
- 類
- 名稱和對象
- Python 作用域和命名空間
- 初探類
- 補充說明
- 繼承
- 私有變量
- 雜項說明
- 迭代器
- 生成器
- 生成器表達式
- 標準庫簡介
- 操作系統接口
- 文件通配符
- 命令行參數
- 錯誤輸出重定向和程序終止
- 字符串模式匹配
- 數學
- 互聯網訪問
- 日期和時間
- 數據壓縮
- 性能測量
- 質量控制
- 自帶電池
- 標準庫簡介 —— 第二部分
- 格式化輸出
- 模板
- 使用二進制數據記錄格式
- 多線程
- 日志
- 弱引用
- 用于操作列表的工具
- 十進制浮點運算
- 虛擬環境和包
- 概述
- 創建虛擬環境
- 使用pip管理包
- 接下來?
- 交互式編輯和編輯歷史
- Tab 補全和編輯歷史
- 默認交互式解釋器的替代品
- 浮點算術:爭議和限制
- 表示性錯誤
- 附錄
- 交互模式
- 安裝和使用 Python
- 命令行與環境
- 命令行
- 環境變量
- 在Unix平臺中使用Python
- 獲取最新版本的Python
- 構建Python
- 與Python相關的路徑和文件
- 雜項
- 編輯器和集成開發環境
- 在Windows上使用 Python
- 完整安裝程序
- Microsoft Store包
- nuget.org 安裝包
- 可嵌入的包
- 替代捆綁包
- 配置Python
- 適用于Windows的Python啟動器
- 查找模塊
- 附加模塊
- 在Windows上編譯Python
- 其他平臺
- 在蘋果系統上使用 Python
- 獲取和安裝 MacPython
- IDE
- 安裝額外的 Python 包
- Mac 上的圖形界面編程
- 在 Mac 上分發 Python 應用程序
- 其他資源
- Python 語言參考
- 概述
- 其他實現
- 標注
- 詞法分析
- 行結構
- 其他形符
- 標識符和關鍵字
- 字面值
- 運算符
- 分隔符
- 數據模型
- 對象、值與類型
- 標準類型層級結構
- 特殊方法名稱
- 協程
- 執行模型
- 程序的結構
- 命名與綁定
- 異常
- 導入系統
- importlib
- 包
- 搜索
- 加載
- 基于路徑的查找器
- 替換標準導入系統
- Package Relative Imports
- 有關 main 的特殊事項
- 開放問題項
- 參考文獻
- 表達式
- 算術轉換
- 原子
- 原型
- await 表達式
- 冪運算符
- 一元算術和位運算
- 二元算術運算符
- 移位運算
- 二元位運算
- 比較運算
- 布爾運算
- 條件表達式
- lambda 表達式
- 表達式列表
- 求值順序
- 運算符優先級
- 簡單語句
- 表達式語句
- 賦值語句
- assert 語句
- pass 語句
- del 語句
- return 語句
- yield 語句
- raise 語句
- break 語句
- continue 語句
- import 語句
- global 語句
- nonlocal 語句
- 復合語句
- if 語句
- while 語句
- for 語句
- try 語句
- with 語句
- 函數定義
- 類定義
- 協程
- 最高層級組件
- 完整的 Python 程序
- 文件輸入
- 交互式輸入
- 表達式輸入
- 完整的語法規范
- Python 標準庫
- 概述
- 可用性注釋
- 內置函數
- 內置常量
- 由 site 模塊添加的常量
- 內置類型
- 邏輯值檢測
- 布爾運算 — and, or, not
- 比較
- 數字類型 — int, float, complex
- 迭代器類型
- 序列類型 — list, tuple, range
- 文本序列類型 — str
- 二進制序列類型 — bytes, bytearray, memoryview
- 集合類型 — set, frozenset
- 映射類型 — dict
- 上下文管理器類型
- 其他內置類型
- 特殊屬性
- 內置異常
- 基類
- 具體異常
- 警告
- 異常層次結構
- 文本處理服務
- string — 常見的字符串操作
- re — 正則表達式操作
- 模塊 difflib 是一個計算差異的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 數據庫
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函數
- 二進制數據服務
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 數據類型
- datetime — 基礎日期/時間數據類型
- calendar — General calendar-related functions
- collections — 容器數據類型
- collections.abc — 容器的抽象基類
- heapq — 堆隊列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 淺層 (shallow) 和深層 (deep) 復制操作
- pprint — 數據美化輸出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 數字和數學模塊
- numbers — 數字的抽象基類
- math — 數學函數
- cmath — Mathematical functions for complex numbers
- decimal — 十進制定點和浮點運算
- fractions — 分數
- random — 生成偽隨機數
- statistics — Mathematical statistics functions
- 函數式編程模塊
- itertools — 為高效循環而創建迭代器的函數
- functools — 高階函數和可調用對象上的操作
- operator — 標準運算符替代函數
- 文件和目錄訪問
- pathlib — 面向對象的文件系統路徑
- os.path — 常見路徑操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路徑操作函數
- 數據持久化
- pickle —— Python 對象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 數據庫 DB-API 2.0 接口模塊
- 數據壓縮和存檔
- zlib — 與 gzip 兼容的壓縮
- gzip — 對 gzip 格式的支持
- bz2 — 對 bzip2 壓縮算法的支持
- lzma — 用 LZMA 算法壓縮
- zipfile — 在 ZIP 歸檔中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件讀寫
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服務
- hashlib — 安全哈希與消息摘要
- hmac — 基于密鑰的消息驗證
- secrets — Generate secure random numbers for managing secrets
- 通用操作系統服務
- os — 操作系統接口模塊
- io — 處理流的核心工具
- time — 時間的訪問和轉換
- argparse — 命令行選項、參數和子命令解析器
- getopt — C-style parser for command line options
- 模塊 logging — Python 的日志記錄工具
- logging.config — 日志記錄配置
- logging.handlers — Logging handlers
- getpass — 便攜式密碼輸入工具
- curses — 終端字符單元顯示的處理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函數庫
- 并發執行
- threading — 基于線程的并行
- multiprocessing — 基于進程的并行
- concurrent 包
- concurrent.futures — 啟動并行任務
- subprocess — 子進程管理
- sched — 事件調度器
- queue — 一個同步的隊列類
- _thread — 底層多線程 API
- _dummy_thread — _thread 的替代模塊
- dummy_threading — 可直接替代 threading 模塊。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 網絡和進程間通信
- asyncio — 異步 I/O
- socket — 底層網絡接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高級 I/O 復用庫
- asyncore — 異步socket處理器
- asynchat — 異步 socket 指令/響應 處理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互聯網數據處理
- email — 電子郵件與 MIME 處理包
- json — JSON 編碼和解碼器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 數據編碼
- binhex — 對binhex4文件進行編碼和解碼
- binascii — 二進制和 ASCII 碼互轉
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 結構化標記處理工具
- html — 超文本標記語言支持
- html.parser — 簡單的 HTML 和 XHTML 解析器
- html.entities — HTML 一般實體的定義
- XML處理模塊
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互聯網協議和支持
- webbrowser — 方便的Web瀏覽器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 處理模塊
- urllib.request — 用于打開 URL 的可擴展庫
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模塊
- http.client — HTTP協議客戶端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP協議客戶端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服務器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服務端與客戶端模塊
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒體服務
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 讀寫 Sun AU 文件
- wave — 讀寫WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推測圖像類型
- sndhdr — 推測聲音文件的類型
- ossaudiodev — Access to OSS-compatible audio devices
- 國際化
- gettext — 多語種國際化服務
- locale — 國際化服務
- 程序框架
- turtle — 海龜繪圖
- cmd — 支持面向行的命令解釋器
- shlex — Simple lexical analysis
- Tk圖形用戶界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滾動文字控件
- IDLE
- 其他圖形用戶界面(GUI)包
- 開發工具
- typing — 類型標注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 單元測試框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自動將 Python 2 代碼轉為 Python 3 代碼
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 調試和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 測量小代碼片段的執行時間
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 軟件打包和分發
- distutils — 構建和安裝 Python 模塊
- ensurepip — Bootstrapping the pip installer
- venv — 創建虛擬環境
- zipapp — Manage executable Python zip archives
- Python運行時服務
- sys — 系統相關的參數和函數
- sysconfig — Provide access to Python's configuration information
- builtins — 內建對象
- main — 頂層腳本環境
- warnings — Warning control
- dataclasses — 數據類
- contextlib — Utilities for with-statement contexts
- abc — 抽象基類
- atexit — 退出處理器
- traceback — Print or retrieve a stack traceback
- future — Future 語句定義
- gc — 垃圾回收器接口
- inspect — 檢查對象
- site — Site-specific configuration hook
- 自定義 Python 解釋器
- code — Interpreter base classes
- codeop — Compile Python code
- 導入模塊
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找腳本使用的模塊
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 語言服務
- parser — Access Python parse trees
- ast — 抽象語法樹
- symtable — Access to the compiler's symbol tables
- symbol — 與 Python 解析樹一起使用的常量
- token — 與Python解析樹一起使用的常量
- keyword — 檢驗Python關鍵字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊縮進檢測
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字節碼反匯編器
- pickletools — Tools for pickle developers
- 雜項服務
- formatter — Generic output formatting
- Windows系統相關模塊
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注冊表訪問
- winsound — Sound-playing interface for Windows
- Unix 專有服務
- posix — The most common POSIX system calls
- pwd — 用戶密碼數據庫
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 終端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 庫例程
- 被取代的模塊
- optparse — Parser for command line options
- imp — Access the import internals
- 未創建文檔的模塊
- 平臺特定模塊
- 擴展和嵌入 Python 解釋器
- 推薦的第三方工具
- 不使用第三方工具創建擴展
- 使用 C 或 C++ 擴展 Python
- 自定義擴展類型:教程
- 定義擴展類型:已分類主題
- 構建C/C++擴展
- 在Windows平臺編譯C和C++擴展
- 在更大的應用程序中嵌入 CPython 運行時
- Embedding Python in Another Application
- Python/C API 參考手冊
- 概述
- 代碼標準
- 包含文件
- 有用的宏
- 對象、類型和引用計數
- 異常
- 嵌入Python
- 調試構建
- 穩定的應用程序二進制接口
- The Very High Level Layer
- Reference Counting
- 異常處理
- Printing and clearing
- 拋出異常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 標準異常
- 標準警告類別
- 工具
- 操作系統實用程序
- 系統功能
- 過程控制
- 導入模塊
- Data marshalling support
- 語句解釋及變量編譯
- 字符串轉換與格式化
- 反射
- 編解碼器注冊與支持功能
- 抽象對象層
- Object Protocol
- 數字協議
- Sequence Protocol
- Mapping Protocol
- 迭代器協議
- 緩沖協議
- Old Buffer Protocol
- 具體的對象層
- 基本對象
- 數值對象
- 序列對象
- 容器對象
- 函數對象
- 其他對象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置變量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 內存管理
- 概述
- 原始內存接口
- Memory Interface
- 對象分配器
- 默認內存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 對象實現支持
- 在堆中分配對象
- Common Object Structures
- Type 對象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使對象類型支持循環垃圾回收
- API 和 ABI 版本管理
- 分發 Python 模塊
- 關鍵術語
- 開源許可與協作
- 安裝工具
- 閱讀指南
- 我該如何...?
- ...為我的項目選擇一個名字?
- ...創建和分發二進制擴展?
- 安裝 Python 模塊
- 關鍵術語
- 基本使用
- 我應如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安裝 pip ?
- ... 只為當前用戶安裝軟件包?
- ... 安裝科學計算類 Python 軟件包?
- ... 使用并行安裝的多個 Python 版本?
- 常見的安裝問題
- 在 Linux 的系統 Python 版本上安裝
- 未安裝 pip
- 安裝二進制編譯擴展
- Python 常用指引
- 將 Python 2 代碼遷移到 Python 3
- 簡要說明
- 詳情
- 將擴展模塊移植到 Python 3
- 條件編譯
- 對象API的更改
- 模塊初始化和狀態
- CObject 替換為 Capsule
- 其他選項
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 實現描述器
- 摘要
- 定義和簡介
- 描述器協議
- 發起調用描述符
- 描述符示例
- Properties
- 函數和方法
- Static Methods and Class Methods
- 函數式編程指引
- 概述
- 迭代器
- 生成器表達式和列表推導式
- 生成器
- 內置函數
- itertools 模塊
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文獻
- 日志 HOWTO
- 日志基礎教程
- 進階日志教程
- 日志級別
- 有用的處理程序
- 記錄日志中引發的異常
- 使用任意對象作為消息
- 優化
- 日志操作手冊
- 在多個模塊中使用日志
- 在多線程中使用日志
- 使用多個日志處理器和多種格式化
- 在多個地方記錄日志
- 日志服務器配置示例
- 處理日志處理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正則表達式HOWTO
- 概述
- 簡單模式
- 使用正則表達式
- 更多模式能力
- 修改字符串
- 常見問題
- 反饋
- 套接字編程指南
- 套接字
- 創建套接字
- 使用一個套接字
- 斷開連接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 關鍵函數
- Operator 模塊函數
- 升序和降序
- 排序穩定性和排序復雜度
- 使用裝飾-排序-去裝飾的舊方法
- 使用 cmp 參數的舊方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包獲取網絡資源
- 概述
- Fetching URLs
- 處理異常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 腳注
- Argparse 教程
- 概念
- 基礎
- 位置參數介紹
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模塊介紹
- 創建 Address/Network/Interface 對象
- 審查 Address/Network/Interface 對象
- Network 作為 Address 列表
- 比較
- 將IP地址與其他模塊一起使用
- 實例創建失敗時獲取更多詳細信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 檢測CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常見問題
- Python常見問題
- 一般信息
- 現實世界中的 Python
- 編程常見問題
- 一般問題
- 核心語言
- 數字和字符串
- 性能
- 序列(元組/列表)
- 對象
- 模塊
- 設計和歷史常見問題
- 為什么Python使用縮進來分組語句?
- 為什么簡單的算術運算得到奇怪的結果?
- 為什么浮點計算不準確?
- 為什么Python字符串是不可變的?
- 為什么必須在方法定義和調用中顯式使用“self”?
- 為什么不能在表達式中賦值?
- 為什么Python對某些功能(例如list.index())使用方法來實現,而其他功能(例如len(List))使用函數實現?
- 為什么 join()是一個字符串方法而不是列表或元組方法?
- 異常有多快?
- 為什么Python中沒有switch或case語句?
- 難道不能在解釋器中模擬線程,而非得依賴特定于操作系統的線程實現嗎?
- 為什么lambda表達式不能包含語句?
- 可以將Python編譯為機器代碼,C或其他語言嗎?
- Python如何管理內存?
- 為什么CPython不使用更傳統的垃圾回收方案?
- CPython退出時為什么不釋放所有內存?
- 為什么有單獨的元組和列表數據類型?
- 列表是如何在CPython中實現的?
- 字典是如何在CPython中實現的?
- 為什么字典key必須是不可變的?
- 為什么 list.sort() 沒有返回排序列表?
- 如何在Python中指定和實施接口規范?
- 為什么沒有goto?
- 為什么原始字符串(r-strings)不能以反斜杠結尾?
- 為什么Python沒有屬性賦值的“with”語句?
- 為什么 if/while/def/class語句需要冒號?
- 為什么Python在列表和元組的末尾允許使用逗號?
- 代碼庫和插件 FAQ
- 通用的代碼庫問題
- 通用任務
- 線程相關
- 輸入輸出
- 網絡 / Internet 編程
- 數據庫
- 數學和數字
- 擴展/嵌入常見問題
- 可以使用C語言中創建自己的函數嗎?
- 可以使用C++語言中創建自己的函數嗎?
- C很難寫,有沒有其他選擇?
- 如何從C執行任意Python語句?
- 如何從C中評估任意Python表達式?
- 如何從Python對象中提取C的值?
- 如何使用Py_BuildValue()創建任意長度的元組?
- 如何從C調用對象的方法?
- 如何捕獲PyErr_Print()(或打印到stdout / stderr的任何內容)的輸出?
- 如何從C訪問用Python編寫的模塊?
- 如何從Python接口到C ++對象?
- 我使用Setup文件添加了一個模塊,為什么make失敗了?
- 如何調試擴展?
- 我想在Linux系統上編譯一個Python模塊,但是缺少一些文件。為什么?
- 如何區分“輸入不完整”和“輸入無效”?
- 如何找到未定義的g++符號__builtin_new或__pure_virtual?
- 能否創建一個對象類,其中部分方法在C中實現,而其他方法在Python中實現(例如通過繼承)?
- Python在Windows上的常見問題
- 我怎樣在Windows下運行一個Python程序?
- 我怎么讓 Python 腳本可執行?
- 為什么有時候 Python 程序會啟動緩慢?
- 我怎樣使用Python腳本制作可執行文件?
- *.pyd 文件和DLL文件相同嗎?
- 我怎樣將Python嵌入一個Windows程序?
- 如何讓編輯器不要在我的 Python 源代碼中插入 tab ?
- 如何在不阻塞的情況下檢查按鍵?
- 圖形用戶界面(GUI)常見問題
- 圖形界面常見問題
- Python 是否有平臺無關的圖形界面工具包?
- 有哪些Python的GUI工具是某個平臺專用的?
- 有關Tkinter的問題
- “為什么我的電腦上安裝了 Python ?”
- 什么是Python?
- 為什么我的電腦上安裝了 Python ?
- 我能刪除 Python 嗎?
- 術語對照表
- 文檔說明
- Python 文檔貢獻者
- 解決 Bug
- 文檔錯誤
- 使用 Python 的錯誤追蹤系統
- 開始為 Python 貢獻您的知識
- 版權
- 歷史和許可證
- 軟件歷史
- 訪問Python或以其他方式使用Python的條款和條件
- Python 3.7.3 的 PSF 許可協議
- Python 2.0 的 BeOpen.com 許可協議
- Python 1.6.1 的 CNRI 許可協議
- Python 0.9.0 至 1.2 的 CWI 許可協議
- 集成軟件的許可和認可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec