跳至內容

Python

本頁使用了標題或全文手工轉換
維基百科,自由的百科全書
Python
編程範型多範式程序式結構化模組化反射式物件導向函數式
設計者吉多·范羅蘇姆
實作者Python軟體基金會
釋出時間1991年,​34年前​(1991[1]
目前版本
  • 3.13.5(2025年6月11日;穩定版本)[2]
  • 3.14.0b3(2025年6月17日;測試版本)[3]
編輯維基數據連結
型態系統鴨子型別[4]動態強型別[5]漸進英語gradual typing(自從3.5)[6]
作業系統跨平臺
特許條款Python軟體基金會特許條款
副檔名.py、.pyi、.pyc、.pyd、.pyo(3.5之前)[7]、.pyw、.pyz(自從3.5)[8]
網站www.python.org 編輯維基數據連結
主要實作產品
CPythonPyPyStackless PythonMicroPythonCircuitPython英語CircuitPythonIronPythonJython
衍生副語言
CythonRPython
受影響於
ABC[9]ALGOL 68[10]APL[11]C[12]C++[13]CLU[14]Dylan[15]Haskell[16]Icon[17]Java[18]Lisp[19]Modula-3[13]Perl[20]Standard ML[11]
影響語言
Boo[21]Cobra英語Cobra (programming language)[22]CoffeeScript[23]DF#GDScript[24]GenieGo[25]Groovy[26]JavaScript[27][28]Julia[29]Kotlin[30]Mojo[31]Nim[32]Ruby[33]Starlark英語Bazel (software)#Starlark language[34]Swift[35]

Python英語發音:/ˈpaɪθən/英語發音:/ˈpaɪθɑːn/),是一種廣泛使用的直譯式進階通用程式語言。Python支援多種程式設計範式,包括結構化、程序式、反射式、物件導向和函數式程式設計。它擁有動態型別系統垃圾回收功能,能夠自動管理主記憶體使用,並且其本身擁有一個巨大而廣泛的標準庫。它的語言結構以及物件導向的方法,旨在幫助程式設計師為小型的和大型的專案編寫邏輯清晰的程式碼。

吉多·范羅蘇姆於1980年代後期開始研發Python,作為ABC語言的後繼者[17],它也可以被視為採用了叫做M-表達式英語M-expression中綴表示法的一種LISP方言[36]吉多·范羅蘇姆於1991年首次釋出 Python 0.9.0[37]。Python 2.0於2000 年釋出並引入了新功能。Python 3.0於2008年釋出,它是該語言的主要修訂版,並非完全向下相容。Python 2於2020年隨2.7.18版停止支援[38]

Python的設計哲學,強調程式碼的可讀性和簡潔的語法,尤其是使用空格縮排來劃分程式碼塊。相比於C語言Java,Python讓開發者能夠用更少的代碼表達想法。

Python直譯器本身幾乎可以在所有的作業系統中執行,它的官方直譯器CPython是用C語言編寫的。Python是一個由社群驅動的自由軟體,目前由Python軟體基金會管理。Python是最受歡迎的程式語言之一[39][40][41][42]

歷史

[編輯]
Python創始人吉多·范羅蘇姆在2024年PyCon的相片
Python創始人吉多·范羅蘇姆在2024年PyCon的相片

Python的創始人吉多·范羅蘇姆,在1982年至1995年間,參與了荷蘭數學和電腦科學研究學會多個專案的工作[43]。1989年的聖誕節期間,他決心開發一個新的指令碼解釋程式,作為ABC語言的後繼者,並且用它替代Unix shellC語言來進行系統管理[17],擔負與Amoeba作業系統英語Amoeba (operating system)[44]之間的互動操作並進行例外處理[9]。他是BBC電視劇《Monty Python的飛行馬戲團》的愛好者,所以選取了Python作為這個程式語言的名字[45]。范羅蘇姆作為Python的主要開發者,獨自擔負這個專案的發展決策者職責,直到2018年7月12日,他宣布從終身仁慈獨裁者(BDFL)的職位上「永久休假」[46][47]。他參與了2019年第一屆領導專案發展的五人掌控委員會[48][49]

在1991年2月,范羅蘇姆在Usenet新聞組alt.sources上釋出了最初程式碼(標記為版本0.9.0)[1],這時就已經存在了帶繼承的例外處理函數和核心類型listdictstr等。在這個最初發行中就有了從Modula-3引進的模組系統[50],和例外處理機制[9]。在1994年1月,Python版本1.0釋出[51],其主要新特徵是由Amrit Prem提供的函數式程式設計工具lambdamapfilterreduce[52]。受Modula-3啟發,Python 1.1介入了預設參數值,Python 1.3介入了關鍵字參數。Python 1.4介入了對複數的內建支援,還包含了採取名字修飾的一種基本形式的數據隱藏[53]

在2000年10月,Python 2.0發布,它從函數式程式設計語言Haskell中引進了列表推導式,並且支援了Unicode,還向垃圾回收系統增加了檢測演算法[54]。Python 2.1支援了靜態巢狀作用域閉包[55]。Python 2.2進行了重大革新,將Python中用C語言寫成的類型,和用Python語言寫成的,統一成在同一個層級中,使得Python的對象模型成為純粹而一致的對象模型[56];還介入了迭代器[57],受CLUIcon啟發的生成器[58],和描述器協定[59]。Python 2.3介入了從Dylan引進的方法決定次序[15]。Python 2.4介入了集合英語Set (abstract data type)類型,和函數修飾器[60]。Python 2.5介入了with陳述式[61],並在官方實現中介入了抽象語法樹[62]

在2008年12月,Python 3.0發布,它對語言做了較大修訂而不能完全後向相容[63],儘管提供了進行自動轉換的2to3實用工具,仍有大量現存程式碼不能移植,故而Python 2.7的產品壽命結束延期至2020年元旦。Python 3.4介入了非同步I/O模組[64]。Python 3.5介入了類型提示[65],和採用async/await語法的協程[66]。Python 3.8介入了賦值表達式[67][68]

在2020年10月,Python 3.9介入了內建的針對容器類的泛化別名types.GenericAlias類型[69],並在官方實現中介入了新的語法解析器[70]。Python 3.10介入了從HaskellOCaml等借鑑來的結構式模式匹配[71],和內建的聯合類型types.UnionType[72]。Python 3.11對官方實現進行了最佳化提速[73]。Python 3.12介入了類型參數語法和type陳述式[74],並廢棄或移除了一些過時的模組和功能。

在2024年10月,Python 3.13介入了從PyPy引進的新互動式直譯器,並實驗性的支援了即時編譯器[75]。Python 3.14正式支援了自由線程Python的官方實現建造選項[76]

每個版本首次發行後,享有2年的完全支援,隨後是3年的安全支援。當前只有Python 3的穩定版本3.12與3.13正在被完全支援,但仍提供對3.9、3.10和3.11版本的安全性修正[77]

在2024年12月,活躍的Python核心開發者,選舉Pablo Galindo Salgado、Barry Warsaw、Emily Morehouse、Gregory P. Smith和Donghee Na,為2025年度掌控委員會的五位成員來領導這個專案[78]

特徵與設計哲學

[編輯]

Python是多範式程式語言。它完全支援結構化程式物件導向程式設計,還有很多特徵支援函數式程式設計元程式設計比如元對象協定元類和魔術方法[79])。通過擴充還可以支援很多範式,包括面向方面程式[80]契約式設計[81]邏輯程式[82]

Python使用動態型別,在主記憶體管理上採用的垃圾回收器基於了參照計數[83],並且結合了檢測參照的分代垃圾回收最佳化[84]。它的特徵還有動態名字解析後期繫結英語late binding),即在程式執行期間繫結方法和變量的名字。

Python對遵循LISP傳統的函數式程式設計提供了有限的支援[85],它提供了 mapfilterreduce函數[86]列表推導式字典推導式集合英語Set (abstract data type)推導式生成器表達式。標準庫中的模組functoolsitertools,實現了從HaskellStandard ML借鑑來的函數式工具[87]

Python的設計理念是「優雅」、「明確」、「簡單」,它的一些重要準則被合稱為「Python之禪」。在Python解釋器內運行import this可以獲得完整的列表,下面舉出其中首要:

  • 優美優於醜陋。明瞭優於隱晦。
  • 簡單優於複雜。複雜優於凌亂。
  • 扁平優於巢狀。稀疏優於稠密。
  • 可讀性很重要。

Python開發者的方法論是「用一種方法,最好是只有一種方法來做一件事」,顯著不同於以Perl語言為代表的「不止一種方法去做一件事」風格。Python開發者在設計語言時,如果面臨多種選擇,一般會選擇明確沒有或者很少有歧義的語法。

范羅蘇姆認為ABC語言非常優美和強大,它沒有取得成功的原因是不開放造成的[88],故而將Python本身設計為可擴充的[89]。Python並不把所有的特性和功能都整合到語言核心,而是提供了豐富的API和工具,以便程式設計師能夠輕鬆地使用Python、C語言、Cython來編寫擴充模組。Python還可以通過外界函數介面英語Foreign function interface如標準庫中的ctypes等,來提供C語言相容資料類型,並訪問動態連結庫共用庫中的函數[90],從而對用其他語言編寫的程式進行整合和封裝。

在Python的官方實現CPython中,一般避開不成熟的或者對非重要部位的加快運行速度的優化。在某些對運行速度要求很高的情況,可以使用具備JIT技術的Python實現或安裝JIT擴充模組[91]

語法和語意

[編輯]

Python為了讓程式碼具備高度的可閱讀性,在設計時盡量使用了其它語言常用的符號和英文單字。

行結構

[編輯]

Python程式在詞法分析上被分成若干邏輯行。簡單陳述式包含在一個單一的邏輯行之內,Python支援使用分號作為分隔符,將多個簡單陳述式合併入一個邏輯行之中[92]

註釋開始於並非字串文字英語string literal一部份的一個井號#,並結束於物理行結尾;註釋標示邏輯行的結束,除非已受制於隱式行接續規則;註釋在語法上被忽略[93]

Python支援使用反斜槓作為行接續符,將多個物理行合成為一個邏輯行[94]。在圓括號方括號花括號之中的表達式,可以分裂跨越多於一個物理行而不使用反斜槓,這被稱為「隱式行接續」[94]

縮排

[編輯]

Python語法中的複合陳述式,包含了一些其他陳述式,它們以某種方式影響或控制這些其他陳述式的執行。Python的複合陳述式包含一個或多個子句(clause),子句構成自一個頭部(header)和一個套件(suite)。特定複合陳述式的子句頭部都在同樣的縮排層級上,每個子句頭部開始於一個唯一標識關鍵字,並結束於一個冒號。套件即語法意義上的,是這個子句所控制的一組陳述式。

套件有兩種形式:可以是與頭部在同一行上的一個或多個由分號分隔的簡單陳述式,它們跟隨在這個頭部的冒號之後;或者是遵循越位規則的在連續諸行上的一個或多個縮排的陳述式,只有這種套件形式可以包含巢狀的複合陳述式[95][a]

根據PEP 8的規定[96],使用4個空格來表示每級縮排[b] 縮排層級的變遷,被用來生成語法解析器才能見到的INDENTDEDENT記號[98],增加縮排就生成INDENT記號,減少縮排就生成DEDENT記號。二者的作用相當於C語言家族的花括號,或Pascal語言家族的關鍵字beginend

關鍵字

[編輯]

Python有如下35個關鍵字;它們不能用作識別碼[99]

  • and
  • as
  • assert
  • async
  • await
  • break
  • class
  • continue
  • def
  • del
  • elif
  • else
  • except
  • False
  • finally
  • for
  • from
  • global
  • if
  • import
  • in
  • is
  • lambda
  • None
  • nonlocal
  • not
  • or
  • pass
  • raise
  • return
  • True
  • try
  • while
  • with
  • yield

內建常數TrueFalseNone於Python版本3.0中成為關鍵字,關鍵字nonlocal介入於版本3.0[100],關鍵字asyncawait介入於版本3.5[101],並在版本3.7中成為正式關鍵字[102]

在Python中,將只在特定上下文中保留的識別碼,稱為「軟關鍵字」[103]

  • matchcase萬用字元_,介入於版本3.10,它們在與模式匹配陳述式有關的上下文中,可以在語法上充當關鍵字;但是這種區分只在語法解析器層次進行,並非在詞法分析記號化層次。
  • type,介入於版本3.12,它用在type陳述式之中。

識別碼

[編輯]

識別碼就是名字,在ASCII範圍內(U+0001..U+007F),可用於識別碼的字元為:大寫字母AZ和小寫字母az,底線_以及數字09,但首字不可以用數字。如下命名約定[104],是為「保留識別碼類」[105]

  • _spam(單底線開頭):弱「內部使用」標識。對於from M import *,將不匯入所有以底線開頭的對象。
  • spam_(單底線結尾):為了避免與python關鍵字的命名衝突。
  • __spam(雙底線開頭):在命名一個類特性的時候,採用名字修飾,比如在類SpamEggs內,__spam將變成_SpamEggs__spam[106]
  • __spam__(雙底線開頭雙底線結尾):指那些包含在用戶控制的命名空間中的「魔術」方法或特性,比如__delattr____dir____doc____getattribute____init____new____repr____setattr____sizeof__等。建議永遠不要將這樣的命名方式應用於自己的變量或函數。

陳述式

[編輯]

Python的陳述式包括簡單陳述式:

  • 賦值陳述式,採用的中綴記號是等號=。賦值陳述式被用來將名字繫結(含重新繫結)到值,以及用來修改可變對象特性或專案。賦值陳述式支援鏈式賦值
    • Python還支援增廣賦值陳述式[107],將一個二元運算和一個賦值陳述式合併成一個單一陳述式,例如x += 1
    • Python支援「序列解包」[108]:在等號左側可以是一個表達式列表,其中每個表達式都可求值成能被賦值的東西;在等號右側相應的是一個「可迭代」對象,它在被迭代時產生的值的數量,同於左手側可寫表達式的數量;賦值陳述式對這個對象進行迭代,將產生的每個值分別賦值給左側對應的可賦值者。在等號右側直接包裝出序列解包所要求的元組,就形成了並列賦值[c]
  • 表達式英語Expression (computer science)陳述式,用來互動式的計算並寫出一個值,或者用來呼叫一個過程(即返回無含義結果的函數),在Python中過程返回值None
  • global陳述式,是在整個當前程式碼塊中成立的聲明,它意味着隨後列出的識別碼被直譯為全域變量。
  • nonlocal陳述式,導致隨後列出的識別碼,提及在除了全域作用域之外的最近包圍作用域中的先前繫結變量。
  • del陳述式,遞歸的進行刪除。
  • type陳述式,聲明作為類型別名類型typing.TypeAliasType)的實例的一個類型別名。
  • pass陳述式,充當無操作指令,表示此行為空,不執行任何操作。
  • assert陳述式,用於程式調適階段時測試執行條件是否滿足。
  • continue陳述式,越過這次迭代並繼續進行下個專案。
  • break陳述式,從循環中跳出。
  • raise陳述式,投擲一個例外。
  • return陳述式,用來從函數返回值。當函數執行到return陳述式時,它會停止執行並將指定的值返回給呼叫者。
  • yield陳述式,用來從一個生成器中返回一個值[109]yield陳述式在語意上等價於加圓括號的yield表達式[110],在函數主體中使用yield表達式將導致它成為生成器函數。[d]
    • 通過生成器的send()方法傳入的資訊,就是其中yield表達式的返回值。[e]
    • 自從版本3.3,介入了yield from陳述式,它在語意上等價於加圓括號的yield from表達式,含有此表達式的生成器函數將特定任務委託給另一個子生成器函數,將傳入資訊遞送給它並直接回傳它產生的值[112]
    • 自從版本3.6,在協程函數主體中使用yield表達式將導致它成為非同步生成器函數[113]
  • import陳述式,匯入一個模組或包,它組合了兩種操作,尋找指名的模組,接着將找到的結果繫結到在局部作用域中的名字。匯入陳述式有三種形式(下述陳述式樣本採用了EBNF,這裏的方括號表示其中內容為可選的):
    • import 模块名字 [as 别名],找到一個模組,裝載它,如果有需要的話初始化它;在這個匯入陳述式出現的作用域的局部名字空間中,定義一個名字或一些名字[114]
    • from 模块名字 import 定义1 [as 别名1], 定义2 [as 别名2], …,找到、裝載、必需時初始化一個模組;接着在局部名字空間中,增加到找到指名特性的參照[114]
    • from 模块名字 import *,在匯入陳述式出現的作用域的局部名字空間中,繫結模組中定義的所有公開的名字[115]

複合陳述式:

  • if陳述式,當條件成立時執行陳述式套件。它經常包含elifelse子句。
  • while陳述式,當條件為真時,重複執行陳述式套件。
  • for陳述式,遍歷列表、字串、字典、集合等迭代器,依次處理迭代器中的每個元素。
  • match陳述式,用於模式匹配
  • class陳述式,是定義的可執行陳述式。[f]
  • def陳述式,是定義函數方法的可執行陳述式。[g]
  • async def陳述式,用於協程函數定義。await表達式、async for陳述式和async with陳述式,只能用在協程函數的主體中。[h]
  • try英語Exception handling syntax陳述式,它經常包含exceptelsefinally子句,處理在程式執行中出現的例外情況。Python 3.11介入了except*子句[116]。Python支援並廣泛使用EAFP(請求原諒比獲得特許更容易)風格的例外處理,作為檢測錯誤狀況和程式中其他「例外」事件的方式。例如:在訪問一個檔案或資源之時,事先不進行測試就嘗試使用它,事後再擷取可能的訪問失敗所引發的例外。[i]
  • with陳述式,把一塊程式碼包裹在一個上下文管理器之內。它允許了RAII(對象初始化時取得資源)方式的行為,可替代常見的try/finally慣用法英語Programming idiom。Python使用with陳述式處理資源[117],例如:在執行一塊程式碼時,事先取得一個,並且事後釋放這個鎖;或事先打開一個檔案,並且事後關閉這個檔案。[j]

塊與模組

[編輯]

在Python的執行英語Execution (computing)模型中,程式構造自(也稱為程式碼塊)。塊是作為一個單元執行的Python程式文字,模組、函數主體和類別定義都是塊。互動式鍵入的每個命令、指令碼檔案和指令碼命令都是塊。傳遞給內建函數eval()exec()執行的字串是塊。塊在執行框架(frame)中執行。框架包含一些用於偵錯的管理資訊,並確定在這個塊執行完成後,執行在何處以及如何繼續。

模組是包含Python定義和陳述式的一個檔案,這個檔案名字是模組名字附加上字尾.py;在一個模組中,模組的名字(作為字串)可獲得為全域變量__name__的值[115](package)是可以包含子模組或遞歸性的子包的模組。包在技術上是具有__path__特性的Python模組。可以將包視為檔案系統上的目錄,而將模組視為這種目錄中的檔案,但是包和模組不必然源自檔案系統[118]

名字即識別碼,是通用的參照持有者,它不關聯於一個固定的資料類型,但是,一個名字在給定時間,總是被繫結到有一個類型的某個對象上,這就是動態型別的特徵。名字的儲存位置不「包含」所指示的值,一個共同的值可以賦值給多個名字,一個名字在任何時候,都可以重新繫結到各種不同類型的對象上,包括字串、過程、具有數據和方法的複雜對象等。

如果一個名字繫結在一個中,它是這個塊的局部變量,除非被聲明為nonlocalglobal。如果一個名字繫結在模組層次,它是全域變量。模組對應的塊的變量,既是局部的也是全域的。如果一個變量使用在一個塊中,卻不定義在這裏,它是自由變量[119][k]

在Python中,賦值所進行的操作,是將一個名字繫結為到一個分立的動態分配的對象的一個參照[l] 作用域定義一個名字在一個中的可見性。如果一個局部變量被定義在一個塊中,它的作用域包括這個塊。如果這個定義出現在一個函數塊中,作用域擴充到在所界定作用域內包含的任何塊,除非所包含的塊為這個名字介入了不同的繫結。對一個塊可見的所有這種作用域的集合,叫做這個這個塊的「環境」[119][m]

當一個名字在一個之中使用,它採用最近包圍作用域來解析。如果一個名字繫結在一個塊中,並且在其中於繫結之前就被使用,會導致一個錯誤。[n]當一個函數或類的定義被巢狀到其他函數的定義之內,它的非局部作用域就是這個包圍函數的局部作用域。nonlocal陳述式導致其列出的識別碼,提及在非局部作用域內先前繫結的名字(即非局部變量英語Non-local variable[119][o]

名字空間是儲存變量的地方,它被實現為字典。有局部名字空間、全域空間即包含這個塊對應的模組的名字空間,和內建名字空間即模組builtins的名字空間;對象的方法是定義在類主體內的函數,它有着巢狀的名字空間。名字空間通過防止命名衝突而支援了模組性,還通過明晰了哪個模組實現了哪個函數而增進可讀性和可維護性。

如果global陳述式出現在一個之中,在這個陳述式中指定的所有名字,提及在頂層名字空間中這些名字的繫結。名字在頂層名字空間解析,首先尋找全域名字空間,未果尋找內建名字空間。global陳述式與在同一個塊中的名字繫結運算有同樣的作用域。如果一個自由變量的最近包圍作用域包含針對它的global陳述式,這個自由變量被當作全域的[119][p]

表達式

[編輯]

Python的表達式英語Expression (computer science)主要包括如下:

  • 在Python中,加圓括號(parenthesized)形式被歸類為原子,它是包圍在圓括號中的可選的表達式列表。加圓括號的表達式列表產生的東西,就是這個表達式列表所產生的:如果這個列表包含至少一個逗號,例如(a,b,c),則它產生一個元組;否則它產生的就是這個單一表達式,例如(a)產生a[122]。要表示僅有單個元素的元組,需要給這個元素字尾一個逗號,例如(a,)。空的圓括號產生空元組對象。元組不是圓括號形成的,而是使用逗號形成的,在沒有歧義的情況下,元組的圓括號是可選的。
  • Python提供了稱為展示(display)的特殊語法來構造列表字典集合英語Set (abstract data type),展示被歸類為原子,並且有兩種方式:要麼其所包容的元素是顯式的列舉出來的,要麼它們是通過叫做「推導式」的特定循環和過濾指令運算出來的。列表展示,是包圍在方括號中的可以為空的一系列表達式,例如[a,b,c]字典展示,是包圍在花括號中的可能為空的一系列的用冒號:分隔的鍵-值對。集合英語Set (abstract data type)展示,是包圍在花括號中的一系列表達式[123][q]
  • Python對容器實例,比如序列類型的列表元組字串,支援形如a[索引]下標,和形如a[开始:停止]a[开始:停止:步长]分片英語array slicing。此二者與函數呼叫和特性參照,一起被歸類為表示語言中最緊密運算繫結的初等項(primary)。這裏的下標索引是基於零的,負數是相對於結尾的。分片範圍自從開始索引,直到但不包括停止索引,分片的第三個步長參數,允許元素被跳過和用負數指示反向。分片的每個元素都是淺層複製英語Object copying的。分片索引可以省略,例如a[:],這返回整個列表的一個複本。[u]
  • 在Python中,算術運算的加法+、減法-、乘法*,與C語言和java相同的。除法和模除%的行為有所不同,在Python中有兩種除法:除法/下取整除法//。Python增加了指數算符**。自從Python 3.5,介入了矩陣乘法算符@[126],它已經用於了NumPy[127]
  • 在Python中,有如下必須用於整數的運算:AND(與)&、OR(或)|、NOT(非)~、XOR(異或)^、右移>>、左移<<
  • 在Python中,有如下比較運算:大於>、小於<、大於等於 >=、小於等於<=、等於==、不等於!=,對兩個值的大小進行比較。Python的isis not算符可以用來比較對象的同一性,也就是比較兩個變量是否參照了同一個對象。而innot in用於判斷一個對象是否屬於另外一個對象。在Python中,比較是可以連結起來的[128],比如a < b < c
  • Python使用andornot表示邏輯運算,不採用C語言和Java中所用的符號&&||!
  • Python的條件表達式表示為x if c else y。意思是當c為真時,表達式的值為x,否則表達式的值為y。 在運算元的次序上不同於很多其他語言中常見的c ? x : y
  • Python的匿名函數實現為lambda表達式。匿名函數體只能是一個表達式。[v]
  • 自從Python 3.8,介入了賦值表達式,其記號是:=[67]。它將一個表達式賦值給一個識別碼,同時還返回這個表達式的值。[w]

Python中運算子具有優先級,下表中的運算子按照從最高(最先繫結)到最低(最後繫結)的次序列出。在相同儲存格中運算子具有相同的優先級,它們從左至右結合,除了指數表達式和條件表達式從右至左結合之外[132]

運算子 描述
(表达式 …)[表达式 …]{: …}{表达式 …} 繫結或加圓括號表達式,列表展示,字典展示,集合展示
x[索引]x[索引:索引]x(参数 …)x.特性 下標,分片,呼叫,特性參照
await x await表達式
** 指數
+x-x~x 取原數,相反數,逐位NOT
*@///% 乘法,矩陣乘法,除法,下取整除法,餘數
+- 加法和減法
<<>> 移位
& 逐位AND
^ 逐位XOR
| 逐位OR
innot inisis not<<=>>=!=== 包含成員關係測試,同一測試,各種比較
not x 布林NOT
and 布林AND
or 布林OR
… if … else … 條件表達式
lambda lambda表達式
:= 賦值表達式

Python為序列提供了串接算符+和倍增算符*[133]。自從Python 3.9,介入了字典合併算符|和字典更新算符|=[134]

Python的文字序列類型,包括字串str位元組序列bytesbytearray。文字序列的文字有多種寫法:

  • 長字串文字,是開始並結束於三個單引號'''或三個雙引號"""的序列。它們可以跨越多行,其功能就像shellPerlRuby中的here文件[x]
  • Python允許多個毗鄰的字串文字或位元組文字(它們以空白分界並可以使用不同的引述約定),在編譯時間於語法層面上串接起來。要在執行時間串接字串,必須使用序列串接算符+[135][z]

自從Python 3.0,字串類str提供了格式化英語Content format方法format()[136],例如"spam={0} eggs={1:04d}".format("blah", 2),它求值為'spam=blah eggs=0002'。格式化方法被推薦用來替代早先的字串對象內建格式化算符%,它在功能上類同於C語言中的printf格式化字串[137],例如"spam=%s eggs=%04d" % ("blah", 2)。在Python 3.6中,提供了字串插值英語String interpolation[138],即「格式化字串文字」或稱為「f字串」,它向字串文字字首上fF[139],例如x="blah"; y=2; f'spam={x} eggs={y:04d}'[aa]

在Python中,在表達式和陳述式之間的區別是嚴格強制性的,陳述式不能成為表達式的一部份,表達式比如列表推導式和字典推導式以及lambda表達式,都不能包含陳述式。這個限制的一個範例:賦值陳述式比如a = 1,不能用作條件陳述式的條件判斷表達式的一部份;這能夠避免C語言程式中的一個常見錯誤,即在條件判斷時把等於算符==誤寫為賦值算符=,這不是預期程式碼卻在語法上有效而能通過C語言編譯器檢查,在Python中這會導致一個語法錯誤。

函數

[編輯]

Python的函數支援遞歸閉包[ab],及其他頭等函數特徵,但不支援函數多載。Python的函數作為頭等對象,具有和普通對象平等的地位。Python官方實現不提供尾呼叫最佳化頭等續體,吉多·范羅蘇姆曾聲稱他不會對其加以支援[140],有第三方庫支援彈跳床英語Trampoline (computing)[141]

Python可以在函數定義時,於形式參數序列中,指定形式參數預設值,即以形式参数=樣式進行一次性初始化。形式參數在初始化之後,保持既有繫結;函數的後續呼叫,可繼續對它進行訪問或變更。[ac]為有預設值的形式參數提供實際參數,在函數呼叫時是可選的。

Python的函數實際參數與形式參數之間的結合,是傳遞「對象參照」,函數在被呼叫的時候,給函數呼叫的實際參數,被介入到一個局部符號表中,實際參數使用傳值呼叫來傳遞,而這個值總是對象參照,而非這個對象的值[142]。如果形式參數繫結到一個可變的對象,則通過形式參數對此對象內容的修改,在函數外也是可見的。如果形式參數繫結到一個不可變的對象,則通過形式參數是不能修改此對象內容,但可以把形式參數重新繫結到其它對象上,這並不影響函數外的對象的值。[ad]

Python支援位置實際參數和關鍵字實際參數。函數呼叫時,實際參數可以如同C語言那樣,按照位置與形式參數匹配;也可以採用命名參數或稱為關鍵字實際參數,即形式参数=樣式的實際參數。使用不對應實際參數的特殊形式參數/*,可以將參數序列分為三部份:唯位置參數、可位置可關鍵字參數和唯關鍵字參數。有預設值的形式參數之後,不能跟隨無預設值的可位置形式參數。[ae]在一個函數呼叫的實際參數序列中,關鍵字實際參數必須出現在位置實際參數之後。

在位置和關鍵字形式參數序列末尾,可以分別有*args**kwargs這樣的加了字首***的形式參數,它們擷取在函數呼叫時提供的,超出形式參數序列規定而無所對應的多個實際參數;在形式參數args前加*號,則args元組類型,它擷取可變量目的位置實際參數;在形式參數kwargs前加**號,則kwargs字典類型,它擷取可變量目的關鍵字實際參數。[af]如果要傳遞給一個函數的一些位置實際參數,已經在一個序列類型如列表或元組的對象中,則可以在函數呼叫中給它字首*來進行可迭代解包;如果要傳遞的一些關鍵字實際參數已經在字典對象中,則可以給它加**號來進行字典解包。

修飾器(decorator)可用來修改一個函數、方法或類別定義的任何可呼叫Python對象。將已定義的原來對象傳遞給修飾器,它返回一個修改後的對象,接着把它繫結到在定義中那個名字。Python修飾器部份受到Java註解的影響,而有類似的語法;使用@作為關鍵字形成修飾詞的語法,是用來應用修飾器的語法糖[ag] 通過在毗連的行上放置多個修飾詞,多個修飾器可以連結起來應用。[ah] 修飾器是一種形式的元程式設計,它們增強它們所修飾的函數或方法的行動。函數修飾器的正規用法包括:用來建立類別方法靜態方法[60]、設置先決條件後置條件、實現多方法、增加函數特性、跟蹤英語Tracing (software)同步[143];此外更遠大的用法包括:尾呼叫消除記憶化[144]

為了增強程式碼的可讀性,可以在函數後書寫「文件字串」(簡稱docstrings),用於直譯函數的作用、參數的類型與意義、返回值類型與取值範圍等。可以使用內建函數help(),列印出函數的使用幫助。[ai]自從Python 3.0,函數可以對參數與返回值增加類型標註[145]。此特性可方便對原始碼進行更深入的分析。[aj]自從Python 3.5,開始支援類型提示[146]

對象及其方法

[編輯]

Python支援大多數物件導向程式設計技術。在Python中所有東西都是對象,包括、函數、數和模組。它允許多型性,不只是在類層級英語Class hierarchy之內,而且通過採用鴨子型別的方式[4]。任何對象可以用於任何類型,只要它有適當的方法特性(attribute)就能工作。Python的繼承支援多重繼承,這可以用來實現混入,為此採用C3線性化或方法決定次序(MRO)演算法。Python支援元類[147],自從Python 3.6,提供了客製化類建立的簡單機制[148]

對象方法,是附屬於這個對象的的函數。對於正常的方法和函數,語法实例.方法(实际参数),是.方法(实例, 实际参数)語法糖。不同於其他一些物件導向程式設計語言比如C++Java有隱式的this英語this (computer programming)關鍵字[149],Python的對象方法沿襲自Modula-3,使用顯式的第一個形式參數來訪問實例特性英語Instance variable,習慣上將其命名為self英語this (computer programming)[ak]

Python支援一些以__開始和結束的特殊方法名,它們用於實現實現多種特殊功能[79],尤其是運算子多載,比如在一個類上定義__add__(),將允許在這個類別的實例上使用+算符。在Python中,定義了一個或多個特殊方法__get__()__set__()__delete__()的類,可以用作描述器(descriptor)[150]。一個類的類別成員若是另一個描述器類別的實例,則它被稱為這個類的屬性(property),使用與特性(attribute)訪問相同的語法,訪問這個類別的實例對象中的屬性。[al]

在Python中,對象的(可寫)特性可以被提取為一個字典[151],並且使用名字修飾,有限的支援私有變量[106]。在Python中,不強制採用訪問子變異子方法,來訪問對象的數據成員。正如Python提供了函數式程式設計構造但不嘗試要求參照透明性,它提供對象系統但不要求物件導向程式設計行為。

Python提供了super()內建函數,在一個類的方法中呼叫此函數返回一個代理(proxy)對象,它將其方法呼叫委託給這個類可溯及到的實現了這個方法的某個確定基礎類別,這是依據方法決定次序(MRO)在類層級中尋找而得到的,次序上居後的基礎類別是居前的基礎類別的父輩類或平輩類[152]。當一個子類的方法覆蓋了其超類方法的時候,可通過呼叫super().方法,來呼叫與子類的self.方法同名的超類別方法。[am]

Python允許通過使用@classmethod@staticmethod修飾詞,來分別建立類別方法靜態方法[60]。給類別方法的第一個實際參數,是對類對象的參照,而非對實例的self參照。靜態方法沒有特定的第一個實際參數,實例或類對象,都不固定的傳遞給靜態方法。[an] Python的property內建函數和@property修飾詞,將一個類中特殊定義的訪問一個特性的那些方法,包裝成的這個類的一個屬性[153][ao]

類型

[編輯]
Python 3的標準類型層級[154]

Python使用鴨子型別,並擁有有類型的對象,和無類型的變量名字。在編譯期不檢查類型約束,而寧願在一個對象上的操作出現可能的失敗,表現出這個給定對象不具有適合的類型。儘管是動態型別系統,Python卻是強型別的,禁止沒有明確定義的操作,比如將一個數和一個字串相加,而不是默默的去嘗試轉換使其有意義。

Python有着範圍廣泛的基本資料類型。同時具備常規的整數和浮點算術,它透明的支援任意精度算術複數十進制浮點數英語Decimal floating point。Python支援種類繁多的字串操作。在Python中,字串是不可變的,所以在其他程式語言中可能就地改變字串的字串操作,比如字元替換,在Python中返回新的字串。

Python有一個非常有用特徵,就是搜集(或稱容器)類型的概念。一般的說,搜集是以一種易於參照或索引的方式,包含其他對象的對象。Python的搜集類型包括了序列對映集合,Python提供了廣泛的搜集操縱能力,比如內建包含檢查和通用迭代器協定

列表動態陣列)、元組字串是序列類型。所有序列類型都有位置索引,並且除了字串,都可以包含任意類型的對象,在同一個序列中可以包括多種類型的對象。字串和元組是不可變的,使得它們成為字典的鍵的完美候選者。列表是可變的,元素可以被插入、刪除、修改、添加或就地排序。

字典是無次序的對映類型,它將一組不可變的鍵,對映到相應的元素上。在字典中的鍵,必須是不可變的Python類型,比如整數或字串,因為在底層它們是通過雜湊函數實現的。字典還是語言內部的中心,因為它們居於所有Python對象和類的核心:在字串類型的變量名字和這個名字所參照的值之間的對映,就儲存為字典,而這些字典可以通過對象的__dict__特性直接訪問。

集合英語Set (abstract data type)是無次序的類型,它包含唯一性的不可變對象作為元素,並且實現了集合論運算,比如併集|交集&相對補集-對稱差^,和子集測試<=真子集測試<超集測試>=真超集測試>。有二種類型的集合:可變的set和不可變的frozenset

Python允許程式者使用,定義自己的類型[56]。類的新實例,是通過呼叫這個類的構造器而建立的,而類型和類都是元類type的實例,元類type更是其自身的實例,這允許了元程式設計反射。Python支援對類型和類的廣泛內省,它們可以被讀取和比較。[ap]

長期規劃是支援漸進類型英語gradual typing[6],並且自從Python 3.5,語言的語法允許指定靜態型別,但在預設實現CPython中不檢查它們[146]。靜態型別檢查器mypy,支援編譯期型別檢查[155]

Python 3內建類型小結
類型 可變性 描述 語法例子
bool 不可變 布林值,有表示值FalseTrue的兩個對象。作為整數類型numbers.Integral的子類型,它們在幾乎所有上下文中,表現得如同01,除了在轉換成字串時轉換為"False""True"之外。 True
False
int 不可變 整數,其大小在理論上無限制,實際上受限於主記憶體[156] 42
float 不可變 雙精度浮點數,確切精度依賴於機器。一般實現為IEEE 754標準binary64浮點數,它有53個二進制有效數碼精度[157] 1.414
complex 不可變 複數,即分別表示實部與虛部的兩個雙精度浮點數的有序對 3+2.7j
range 不可變 數的序列,通常用在for循環中指定循環次數[158] range(1, 10)
range(10, -5, -2)
str 不可變 字串,即Unicode程式碼點序列[159]。其程式碼點都在區間[\u0000, \uffff][\U00010000, \U0010ffff]之内。 'Wiki' "pedia"
"""Spanning
multiple lines"""
bytes 不可變 位元組序列,其專案是8位元位元組,可以用區間[0x00, 0xff]的整數表示。 b'Wiki' b"pedia"
bytes([0x68, 0x65, 0x78])
bytearray 可變 bytearray(b'Wiki' b"pedia")
bytearray([0x68, 0x65, 0x78])
list 可變 列表,可以包含任意的Python對象。 [4.0, 'string', True]
[]
tuple 不可變 元組,可以包含任意的Python對象。 (4.0, 'string', True)
()
dict 可變 字典鍵-值對搜集。鍵在其生存期間是不可變的(稱其為可雜湊的),列表、字典或其它可變對象和包含它們的對象不可以用作鍵。 {'key1': 1.0, 3: False}
{}
set 可變 無序的集合英語Set (abstract data type),包含唯一性的不可變的對象,它們不能用任何下標來索引。 {4.0, 'string', True}
set()
frozenset 不可變 frozenset([4.0, 'string', True])
types.EllipsisType 不可變 這個類型的值是有一個單一對象,它表示為文字英語Literal (computer programming)...或內建名字Ellipsis,它的真值為真。它用於NumPy多維陣列索引[160] ...
Ellipsis
types.NoneType 不可變 這個類型的值是一個單一對象None(相當於其他語言的Null[161],它被用來指示值的缺席,它的真值為假。 None
types.NotImplementedType 不可變 這個類型的值是一個單一對象NotImplemented,它從多載運算子返回指示未支援的運算元類型,它不應該在布林值上下文中求值。 NotImplemented

除了各種資料類型,Python直譯器還內建了很多其他類型,包括可呼叫類型:用戶定義函數、實例方法、生成器函數、協程函數、非同步生成器函數、內建函數、內建方法、類、類別方法;模組,客製化類,類別實例,I/O對象(也叫做檔案對象),和暴露給用戶的一些內部類型:程式碼對象、框架對象、溯回對象、切片對象、靜態方法對象、類別方法對象。

算術運算

[編輯]

Python的算術運算,使用平常的符號+-*/模除%。它還有下取整除法算符//指數算符**矩陣乘法算符@[126]。二元運算先將兩運算元轉為共同類型,加法、減法、乘法、下取整除法和指數運算的結果也採用此類型,比如5**3 == 1259**0.5 == 3.0。這些算符就像在傳統數學中一樣運算,具有同樣的優先級規則中綴算符+-,還可以分別表示取原數和取相反數一元算符。

除法/的表現,隨着版本不同而有着顯著變化[162]。自Python 3.0以來,/總是產生浮點數結果,包括兩個整數相除,比如5/2 == 2.5;而在下取整除法//中,兩個整數相除產生整數,比如7//3 == 27.5//3 == 2.0

下取整除法//修約是朝向負無窮的。向下取整能增加一致性[163],例如這意味着等式(a + n)//n == a//n + 1總是為真。模除%所得出的餘數的符號同於除數,比如-4%3 == 24%-3 == -2。其它多數程式語言比如C99採用截尾取整規則,餘數的符號同於被除數。模除運算結果餘數的定義,確使等式a == (a//n)*n + a%n對於an分別為正數或負數的情況都是有效的[164]。餘數可以為負數,顯著不同於在數學中的歐幾里得除法規則下,餘數總是非負數的情況。

Python提供了round()內建函數,用於把一個浮點數修約成最近的整數[165],自Python 3.0以來,為了打破平局它採用了IEEE 754約半成偶規則:round(1.5)round(2.5)都產生2

Python允許由比較運算連結起來的布林表達式,表現得如在數學中常用的一樣。比如表達式a < b < c,測試a < b and b < c[128]。C語言將它解析為(a < b) < c:即首先求值a < b,其結果為01,接着把這個結果比較於c[166]

Python對所有整數運算,使用任意精度算術。在decimal模組中的Decimal[167],提供十進制浮點數英語Decimal floating point,具有用戶可按需要而更改的預設28個十進制有效數碼精度,並有多種修約方式[168]。在fractions模組中的Fraction類,提供任意精度的有理數[169]。第三方庫gmpy2[170],提供了到任意精度計算GMP/MPIR英語MPIR (mathematics software)MPFR英語GNU MPFR和MPC的介面。

除了求絕對值函數abs()列入內建函數之外,大多數數學函數,處於mathcmath模組內。前者用於實數運算,而後者用於複數運算。[aq]由於Python有着廣泛的數學庫,特別是第三方庫NumPy進一步擴充了原生能力,Python經常被用作科學手稿語言,來處理如數值數據處理和操縱等問題[171][172]

標準庫

[編輯]

Python擁有一個強大的標準庫[173]。Python標準庫包括了如下功能:

程式碼實例

[編輯]

一個在標準輸出裝置上輸出Hello World的簡單程式,這種程式通常作為開始學習程式語言時的第一個程式,可將如下程式碼錄入純文字檔案並隨意命名比如program01.py,然後執行這個程式python3 program01.py

print("Hello, world!")

Python也可以單步直譯執行。執行Python直譯器進入互動式命令列的環境,你可以在提示符號>>>旁輸入print("Hello, world!"),按Enter鍵輸出結果:

>>> print('Hello, world!')
Hello, world!

計算正數的階乘的程式碼:

n = int(input('輸入一個數,就會印出其階乘: '))
if n < 0:
    raise ValueError('錯誤,請輸入一個非負整數')
fact = 1
for i in range(2, n + 1):
    fact *= i
print(fact)

注意,在Python 3.0及以上版本中,print是個函數,需要在要列印的字串前後加上圓括號;在Python 2.6以下版本中,print是一個關鍵字和命令而不加圓括號。

實現

[編輯]

Python是一門跨平台的手稿語言,Python規定了一個Python語法規則,根據該規則可編寫Python直譯器[174]。Python屬於動態語言,其官方實現CPython將Python程式編譯成中間形式的位元組碼[175],並接着在它的虛擬機器上執行[176],執行速度緩慢於C/C++所編譯出的機械碼和在HotSpot JVM上執行的java位元組碼[177]

活躍開發的實現
  • CPython:官方的Python直譯器,需要區別於其他直譯器的時候才以CPython稱呼。CPython預設採用全域直譯器鎖(GIL),以確保在任何時刻只有一個線程執行Python位元組碼;一些擴充模組被設計為在進行計算密集任務時釋放GIL,還有在進行I/O時總是釋放GIL[178]
  • MicroPython:為微控制器而最佳化的Python 3變體,它實現了完整的Python 3.4語法,和補充自版本3.5的async/await關鍵字,以及後來版本的一些選定特徵;它提供了實現Python標準庫模組功能子集的內建模組,和特定於微控制器的一些模組。CircuitPython英語CircuitPythonAdafruit英語Adafruit Industries開發的MicroPython分叉。
  • PyPy:採用了跟蹤JIT英語Tracing just-in-time compilation的Python實現,預設支援stackless模態[179],它是用RPython編寫的,當前支援Python版本3.11和2.7。
  • Numba:使用LLVM JIT的Python最佳化編譯器,它將包括很多NumPy函數的聚焦數值計算的Python子集,翻譯成快速的機械碼,它為在CPU和GPU上並列化Python程式碼提供了大量選項。
  • Codon:高效能且無執行時開銷的Python編譯器[180],它將Python程式碼編譯成本機機械碼,並且支援本機多線程和GPU並列運算,還包括了特徵齊全的完全編譯的內建NumPy實現。它由MIT CSAIL的研究人員開發[181],其語意在資料類型等方面上與CPython有所不同[182]
  • Pyodide:基於WebAssembly/Emscripten的用於瀏覽器Node.js的Python釋出[183],支援任何在PyPIwheel形式的純Python包,並且已經移植了很多具有C語言擴充的包。
  • RustPython:用Rust編寫的Python直譯器[184],它可以嵌入到Rust應用程式中從而將Python用作手稿語言,還可以被編譯成WebAssembly從而在瀏覽器中執行Python程式碼。
  • Brython:用JavaScript編寫的在瀏覽器中執行的Python實現[185],具有到DOM元素和事件的介面。
  • GraalPy:針對JVM的基於GraalVM英語GraalVM的Python高效能實現[186]
轉譯成其他語言的編譯器
  • Cython:將增加了靜態型別聲明的Python超集編譯成CC++的編譯器。Cython補充支援呼叫C語言函數並且在變量和類特性上聲明C語言類型,還支援以OpenMP為後端的本機多線程並列[187]
  • mypyc:將Python模組編譯成C擴充的編譯器[188],它使用標準的Python類型提示生成快速程式碼。mypyc是mypy發行的可選依賴,它使用mypy進行型別檢查類型推論[155]
  • Nuitka英語Nuitka:用Python編寫的到C11(或替補為C++03)的編譯器[189],它依賴於CPython的libpython庫,能完成嵌入所有模組的程式編譯、擴充模組及包編譯和獨立模態程式釋出。
  • Shed Skin英語Shed Skin:將純粹但隱含為靜態型別的Python有限子集程式碼轉譯成最佳化的C++程式碼的編譯器[190],它可以生成獨立程式或者能匯入並用於更大Python程式的擴充模組。
  • Pythran:將聚焦於科學計算的Python子集編譯成C++11提前編譯器英語Ahead-of-time compilation[191],它依賴於Boost和xsimd庫,將標註了介面描述的Python模組編譯為本機共用庫模組,能利於上多核SIMD指令單元。
  • Transcrypt:用Python編寫的Python 3.9到JavaScript編譯器[192],用於在瀏覽器中執行Python程式碼,它被預先編譯為高可讀性且高效的JavaScript程式碼。
  • MyHDL英語MyHDL:將Python編譯成VerilogVHDL[193]

其他實現舉例:Jython,它是用Java實現的Python 2.7。IronPython,它是建造在DLR之上的Python 2.7和Python 3.4實現。Stackless Python,它是實現微線程英語microthread的CPython 3.8分叉。Pyston,它是具有JIT等效能最佳化的CPython 3.8.12的分叉[194]。Pyjion,將Python程式碼編譯成本機CIL的CPython 3.10的JIT擴充[195]。Cinder,它是Meta孵化器釋出的具有包括JIT等很多最佳化的CPython 3.10分叉[196]。Grumpy,它是Python 2.7到Go的轉譯器和執行時系統[197]。py2many,起步於轉譯至Julia的PyJL的將Python轉譯成多種語言的轉譯器[198]

開發環境

[編輯]

通用文字編輯器

[編輯]

很多並非整合式開發環境軟體的文字編輯器,也對Python有不同程度的支援,並且加上專門為Python設計的編輯器外掛程式也會有很高的可用性。

專用開發環境

[編輯]

適用於Python的整合式開發環境(IDE)軟體,除了標準二進制釋出包所附的IDLE之外,還有許多其他選擇。其中有些軟體設計有語法着色、語法檢查、執行偵錯、自動補全、智能感知等便利功能。由於Python的跨平台出身,這些軟體往往也具備各種作業系統的版本或一定的移植性。

  • IDLE:Python「標準」IDE,一般隨Python而安裝,支援較少的編輯功能,偵錯功能也比較弱。
  • Eric:基於PyQt的自由的IDE,支援自動補全、智能感知、自動語法檢查、工程管理、svn/mercurial整合、自動單元測試等功能,具有可延伸的外掛程式系統,通過可選外掛程式支援Git整合。偵錯功能與Visual Studio和Eclipse類似。
  • Spyder:開源的跨平台科學計算IDE。
  • PyCharm:由JetBrains公司出品,具備一般IDE的功能,比如偵錯、語法突顯、Project管理、程式碼跳轉、智能提示、自動完成、單元測試、版本控制等等,另外,它還提供了一些功能用於Django開發,還支援IronPython。它是商業軟體,但也具有社區版和教育版。

第三方擴充包

[編輯]
Python Powered

Python社群提供了大量的功能覆蓋眾多領域的第三方模組,其使用方式與標準庫類似。第三方模組可以使用Python/Cython或者C語言編寫。軟體工具比如SWIG,通過定義介面檔案或規定檔案的方式,可以將C/C++編寫的程式庫包裝為Python模組。Python直譯器本身也可以被整合到其它需要手稿語言的程式內。

Python包索引是公開的軟件套件線上倉庫。pip是官網推薦的以安全方式安裝Python應用及其依賴軟件套件的最流行工具[199]。要安裝在整個作業系統範圍內共用的Python包,現在需要通過作業系統的軟件套件管理系統。要將特定於應用的依賴包隔離於共用的Python安裝,可以使用標準庫的venv[200]或第三方工具virtualenv[201]建立虛擬環境;第三方工具pipenv,能自動為用戶專案建立和管理虛擬環境,並在安裝/卸裝軟件套件的時候,向此專案的Pipfile檔案增加/移除這個軟件套件[202]

網絡程式

[編輯]

Python標準庫對於各種網絡協定的支援很完善,因此適用於編寫伺服器軟體、網絡爬蟲等Web開發。Python定義了WSGI標準應用介面,來協調HTTP伺服器與基於Python的Web程式之間的溝通。比如,通過mod_wsgi英語mod_wsgi模組,Apache HTTP Server可以運行用Python編寫的Web程式。

用Python編寫的一些Web框架,有助於輕鬆地開發和管理複雜的Web程式。重要的第三方網絡程式英語Computer network programming庫和Web框架有:

  • Zope:著名的開源Web應用伺服器
  • Beautiful Soup:用作HTML/XML解析器的一個簡單易用Python包。
  • Twisted事件驅動的網絡程式框架,它支援很多常見的網絡協定並包括了很多不同用途的模組,它支援所有主要的系統事件循環和各種GUI事件循環。
  • Django:MTV架構[203]的Web框架,它注重組件的重用性和「可插拔性」、快速開發DRY法則
  • Tornado:使用單線程事件循環的非同步非阻塞式web伺服器,也是輕量級的Web框架。
  • Flask:微Web框架,不要求特定的工具或庫。
  • Requests:適合於常人使用的HTTP庫,封裝了許多繁瑣的HTTP功能,極大地簡化了HTTP請求所需要的程式碼量。
  • aiohttp:基於asyncio的HTTP客戶端和伺服器二者[204]
  • uvloop:對內建asyncio事件循環的快速的、直截了當的替代者[205],它用Cython實現並在底層使用了libuv
  • FastAPI英語FastAPI:用來建造基於HTTP的網絡服務API的現代高效能web框架[206]
  • PyScript:建立在瀏覽器內的Python應用的框架[207],可採用Pyodide、MicroPythonWebAssembly和當代Web技術。

圖形化使用者介面

[編輯]

Python本身包含了Tkinter庫,它是Python的業界標準GUI並被整合進入了IDLE。Tkinter基於了Tcl命令工具,能夠支援簡單的GUI開發。但是為了讓所開發的軟體執行速度更快,並與用戶的桌面環境更契合,人們一般會選擇採用第三方GUI庫或框架。主要的第三方GUI庫有:

  • PyQtQt的Python繫結庫,由Riverbank Computing公司自從1998年發行,採用GPL特許條款或商業特許條款。
  • PySideQt的Python繫結庫,由Qt公司自從2009年發行,採用LGPL特許條款。
  • PyGObject:替代了PyGTK,它是為Python程式訪問基於GObject的庫而提供的包裝庫[208],GObject是GTKGIO英語GIO (software)GStreamer等庫使用的對象系統。
  • Kivy:用於開發多點觸控應用軟體的開源Python庫,採用了自然用戶介面(NUI)。
  • WxPython:GUI程式框架wxWidgets的Python包裝庫,它與MFC的架構相似。
  • Gooey:將幾乎所有Python 3控制台程式用一行程式碼轉變成GUI應用[209]
  • Dear PyGui:快速而強力的具有極小依賴性的GUI工具箱[210]
  • pywebview:輕量級跨平台的對WebView英語WebView構件的包裝器,允許在其本地GUI窗口中顯示HTML內容[211]

數據科學

[編輯]

重要的數據科學用第三方軟體庫有:

數據視覺化

[編輯]

主要的數據視覺化軟體庫及儀錶板框架有[217]

機器學習

[編輯]

基礎性的機器學習軟體庫及框架有:

其它種類

[編輯]

應用

[編輯]

在很多作業系統裏,Python是標準的系統元件,它被列入了ISO/IEC 23360-1-4:2021 Linux標準規範(LSB)之語言規定[261]。大多數Linux發行版macOS都整合了Python,可以在終端模擬器虛擬控制台英語Virtual console下直接執行Python。第三方工具pipx,可以將Python應用安裝於隔離的環境中並在其中執行它[262]

雖然Python可被粗略地分類為手稿語言,Python的支持者較喜歡稱它為一種高階動態語言,常像「膠水」一樣被用來連接軟體組件,已經顯著的區別於Unix shellWindows PowerShell這樣的語言。基於Python的xonsh,是跨平台的、青睞Unix的shell語言命令列介面[263]

應用程式

[編輯]

一些Linux發行版,使用Python語言編寫安裝器,比如UbuntuUbiquityFedoraAnaconda;或使用它編寫軟件包管理系統,比如GentooPortage。下面舉例使用Python編寫或將它作為嵌入式指令碼的一些應用程式:

人工智能

[編輯]

經由Python開發了眾多的人工智能模型和作為其支撐的軟體庫:

社群流行

[編輯]

自從2003年,Python始終排行於TIOBE程式社區索引英語TIOBE Programming Community Index前十最流行程式語言,在2021年10月它首次達到了第一名最流行語言(居於CJava之前),並被選為2007年、2010年、2018年、2020年、2021年和2024年的年度程式語言[41]。它有如下著名的社群:

  • PyCon:各地社群舉辦的會議,通常每年舉辦。各社群在會議中討論Python相關的議題。
  • Python Discord:參與者眾多的Python社區[276]
  • PyLadies英語PyLadies:由女性社群發起的社群,主要注重於發展Python的女性程式設計社群。
  • Django Girls英語Django Girls:使用Django網頁設計框架,推廣使用Python進行網頁設計的技術。

影響的語言

[編輯]

Python的設計和哲學已經影響了很多其他程式語言:

在Python基礎上開發的程式語言有:

範例與註釋

[編輯]
  1. ^ 縮排範例:
    def is_even(a: int) -> bool:
        """确定数a是否是偶数."""
        if a % 2 == 0:
            print('偶数!')
            return True
        print('奇数!')
        return False
    
    # 参数比后续部份多一层缩进
    def long_function_name(
            var_one, var_two, var_three,
            var_four):
        # 可选的圆括号内后续行多一层缩进
        if (this_is_first_thing
                and that_is_second_thing):
            do_something()
        # 可选的圆括号内后续行不额外缩进
        elif (this_is_third_thing and
              that_is_fourth_thing):
            do_something_different()
    # 参数相对行首缩进一层
    spam = long_function_name(
        arg_one, arg_two,
        arg_three, arg_four)
    # 参数按开括号界定垂直对齐
    eggs = long_function_name(arg_one, arg_two,
                              arg_three, arg_four)
    # 可选的闭括号位置
    my_list = [
        1, 2, 3,
        4, 5, 6,
        ]
    # 可选的闭括号位置
    my_set = {
        1, 2, 3,
        4, 5, 6,
    }
    
  2. ^ tab字元(從左至右)被替代為1至8個空格,使得直到tab之前的諸字元加上這些替代空格的字元總數,是8的倍數(這意圖同於Unix所用規則)。前導於第一個非空白字元的空格的總數,確定了這一行的縮排層級。縮排所用諸字元,不能使用反斜槓來拆分成多個物理行;直到第一個反斜槓之前的空白確定縮排層級。如果原始碼檔案混合了tab和空格,並且在這種方式下縮排的意義依賴於一個tab相當於多少個空格,則這種縮排因不一致性而被報錯並拒絕[97]
  3. ^ 序列解包範例:
    >>> a = [1, 2, 3]
    >>> i, j, k = a
    >>> print(i, j, k)
    1 2 3
    

    採用了並列賦值的斐波那契數列函數範例:

    def fib(n):  # 写出从第0项到第n项的Fibonacci系列
        a, b, i = 0, 1, 0 
        while i <= n:
            print(a, end=' ')
            a, b, i = b, a+b, i+1
        print()
    
  4. ^ 產生素數的惰性生成器的範例:
    from itertools import count
    
    def generate_primes(stop_at=0):
        if stop_at != 1:
            primes = [2]
            yield 2
        for n in count(3, 2):
            if 0 < stop_at < n:
                return # 引发StopIteration例外
            composite = False
            for p in primes:
                if not n % p:
                    composite = True
                    break
                elif p ** 2 > n:
                    break
            if not composite:
                primes.append(n)
                yield n
    

    上述函數的隱式迭代用例:

    for i in generate_primes():  # 迭代于100以内所有素数上
        if i > 100:
            break
        print(i)
    

    在生成器表達式中使用上述函數,定義了一個惰性的、巨大而並非無限的搜集的範例:

    from itertools import islice
    
    primes_under_million = (i for i in generate_primes() if i < 1000000)
    two_thousandth_prime = islice(primes_under_million, 1999, 2000) 
    print(next(two_thousandth_prime))
    
  5. ^ 下面的範例用生成器模擬協程[111]
    def produce(n):
        try:
            for item in range(n):
                print(f'producing item {item} ->') 
                yield item
        except GeneratorExit:
            return
    
    def consume():
        item = None
        try:
            while True:
                item = yield item
                print(f'consuming item {item} <-')
        except GeneratorExit:
            return
    
    def main():
        r = []
        t1 = produce(10)
        t2 = consume()
        try:
            next(t2)
            while True:
                p = next(t1)
                r += [t2.send(p)]
        except StopIteration:
            t2.close()
        print(f'result items: {r}')
    
    main()
    
  6. ^ class陳述式的類衍化列給出基礎類列表,沒有衍化列的類,預設繼承基礎類object。類的套件接着在新的執行框架(frame)中執行,它使用新建的局部名字空間和原來的全域名字空間。當這個類套件完成執行之時,丟棄它的執行框架並儲存它的局部名字空間。一個類對象接着被建立,其基礎類採用衍化列,其特性字典採用儲存的局部名字空間。類名字接着在原來的局部名字空間中,被繫結到這個類對象。
  7. ^ def陳述式的執行,在當前局部名字空間中,將函數名字繫結到一個函數對象(對函數的可執行程式碼的包裝器)。這個函數對象包含到當前全域名字空間的參照,作為呼叫這個函數時使用的全域名字空間。
  8. ^ 原生的協程範例:
    import asyncio
    import random
    
    async def produce(queue, n):
        for item in range(n):
            # 生产一个项目,使用sleep模拟I/O操作
            print(f'producing item {item} ->') 
            await asyncio.sleep(random.random())
            # 将项目放入队列
            await queue.put(item)
        # 指示生产完毕
        await queue.put(None)
    
    async def consume(queue):
        while True:
            # 等待来自生产者的项目
            item = await queue.get()
            if item is None:
                break
            # 消费这个项目,使用sleep模拟I/O操作
            print(f'consuming item {item} <-')
            await asyncio.sleep(random.random()) 
    
    async def main():
        queue = asyncio.Queue()
        task1 = asyncio.create_task(produce(queue, 10))
        task2 = asyncio.create_task(consume(queue))
        await task1
        await task2
    
    asyncio.run(main())
    
  9. ^ 遵循EAFP(請求原諒比獲得特許更容易)風格的例外處理範例:
    f = None
    try:
        f = open("aFileName", mode="w")
        f.write(could_make_error()) # 不存在could_make_error()则产生错误
    except IOError as error:
        print(error)
        print("不能打开文件")
    except:  # 捕获所有例外
        print("未预期的错误")
    else:  # 在没有出现例外时执行
        print("文件写入完全成功")
    finally:  # 清除行动,总是执行
        if f:
            f.close()
    
  10. ^ 使用with將檔案作為資源來管理的範例:
    from contextlib import contextmanager
    @contextmanager
    def opened(filename, mode="r"):
        try:
            f = open(filename, mode)
        except IOError as error:
            print(error)
            yield None
        else:
            try:
                yield f
            finally:
                f.close()
    
    with opened("aFileName", mode="w") as f:
        try:
            f.write(could_make_error()) # 不存在could_make_error()则产生错误
        except AttributeError:
            print("不能打开文件")
        except:  # 捕获所有例外
            print("未预期的错误")
        else:  # 在没有出现例外时执行
            print("文件写入完全成功")
    
  11. ^ 內建vars()函數,返回一個模組、類、實例或任何具有字典特性__dict__的對象的字典特性。內建globals()函數,返回實現當前模組的名字空間的一個字典。內建locals()函數,更新並返回表示當前局部符號表的一個字典。在函數塊中而非類塊中呼叫locals()之時,它返回自由變量。在模組層級上,locals()globals()返回同一個字典。內建dir()函數,在無參數時,返回在當前局部作用域內的名字列表;在有一個參數時,嘗試返回這個對象的有效特性的列表。[120]
  12. ^ 除了在塊中出現的每個賦值陳述式或匯入陳述式之外,下列構造也繫結名字:給函數的形式參數、類別定義、函數定義、賦值表達式、在for陳述式頭部中和各種as關鍵字之後的識別碼目標(target),as關鍵字出現在import陳述式、with陳述式、except子句、except*子句和結構式模式匹配的as模式之中。
  13. ^ 完整的Python程式,在一個極小初始化的環境中執行:所有內建和標準模組均可獲得,但除了sys(各種系統服務)、builtins(內建函數、例外None)和__main__之外都未被初始化。__main__用來為完整程式的執行提供局部和全域名字。當直譯器被呼叫在互動模態下的時候,它一次一個的讀取並執行陳述式;初始環境同於完整程式,每個陳述式都在__main__的名字空間中執行。
    頂層程式碼是啟動執行的首個用戶指定Python模組。__main__是頂層程式碼執行所在的環境。從命令列使用-m參數,作為頂層指令碼執行的模組(作為模組__main__)是塊。此時__name__變量被設置為"__main__",籍此可在這個模組中增加直接執行時候執行的程式碼[115][121]
  14. ^ 局部變量範例:
    >>> def spam():
    ...     print(a)
    ... 
    >>> a = 10
    >>> spam()
    10
    >>> def spam():
    ...     a = 100
    ...     print(a)
    ... 
    >>> spam()
    100
    >>> a
    10
    >>> def spam():
    ...     a *= 10
    ...     print(a)
    ... 
    >>> spam()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in spam
    UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
    
  15. ^ 非局部變量範例:
    >>> def spam():
    ...     def eggs():
    ...         nonlocal a
    ...         a *= 10
    ...         print(a)
    ...     a = 10
    ...     eggs()
    ... 
    >>> spam()
    100
    >>> def spam():
    ...     def eggs():
    ...         nonlocal a
    ...         a *= 10
    ...         print(a)
    ...     global a
    ...     eggs()
    ... 
      File "<stdin>", line 3
    SyntaxError: no binding for nonlocal 'a' found
    
  16. ^ 全域變量範例:
    >>> def spam():
    ...     global a
    ...     a *= 10
    ...     print(a)
    ... 
    >>> a = 10
    >>> spam()
    100
    >>> a
    100
    >>> def spam():
    ...     def eggs():
    ...         print(a)
    ...     global a
    ...     eggs()
    ... 
    >>> a = 10
    >>> spam()
    10
    >>> def spam():
    ...     def eggs():
    ...         a *= 10
    ...         print(a)
    ...     global a
    ...     eggs()
    ... 
    >>> spam()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 6, in spam
      File "<stdin>", line 3, in eggs
    UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
    
  17. ^ 通過列表展示建立列表範例:
    a_list = [1, 2, 3, 'a dog']
    

    通過表達式列表建立元組範例:

    a_tuple = 1, 2, 3, 'four'
    

    通過集合展示建立集合範例:

    some_set = {0, (), False}
    

    通過字典展示建立字典範例:

    a_dictionary = {'key 1': 'value 1', 2: 3, 4: []}
    
  18. ^ 列表的推導式範例。比如:
    >>> [x + 3 for x in range(4)]
    [3, 4, 5, 6]
    

    快速排序演算法可以優雅的(儘管不高效的)使用列表推導式表達為:

    def qsort(L):
        if L == []:
            return []
        pivot = L[0]
        return (qsort([x for x in L[1:] if x < pivot]) +
                [pivot] +
                qsort([x for x in L[1:] if x >= pivot]))
    

    生成器表達式範例。比如:

    >>> sum(x * x for x in range(10))
    285
    >>> dict((n, n*n) for n in range(5))
    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
    >>> set(n*n for n in range(5))
    {0, 1, 4, 9, 16}
    
  19. ^ 字典推導式{expr1: expr2 for k, v in d},等價於:
    result={}
    for k, v in d.items():
        result[expr1]=expr2
    return result
    
    >>> {x: x + 3 for x in range(4)}
    {0: 3, 1: 4, 2: 5, 3: 6}
    

    集合推導式{expr1 for x in stuff},等價於:

    result = set()
    for x in stuff:
        result.add(expr1)
    return result
    
    >>> {x + 3 for x in range(4)}
    {3, 4, 5, 6}
    
  20. ^ 可迭代解包和字典解包範例:
    >>> a = [1, 2, 3]; b = [4, 5]
    >>> c = [*a, b]
    >>> c
    [1, 2, 3, [4, 5]]
    >>> d = {*a, *b}
    >>> d
    {1, 2, 3, 4, 5}
    >>> e = (*a, *b)
    >>> e
    (1, 2, 3, 4, 5)
    >>> f = {'as':1, 'bs':2 }; g = {'cs':3, 'ds':4}
    >>> h = {**f, **g}
    >>> h
    {'as': 1, 'bs': 2, 'cs': 3, 'ds': 4}
    
  21. ^ 下面幾個判斷陳述式為真,表示列表分片結果符合預期:
    >>> nums = [1, 3, 5, 7, 8, 13, 20]
    >>> nums[2:5] == [5, 7, 8] #从下标为2的元素切割到下标为5的元素,但不包含下标为5的元素。
    True
    >>> nums[1:] == [3, 5, 7, 8, 13, 20] #切割到最后一个元素。
    True
    >>> nums[:-3] == [1, 3, 5, 7] #从最开始的元素一直切割到倒数第3个元素。
    True
    >>> nums[:] == [1, 3, 5, 7, 8, 13, 20] #返回所有元素。改变新的列表不会影响到nums。
    True
    >>> nums[1:5:2] == [3, 7] #从下标为1的元素切割到下标为5的元素,但不包含下标为5的元素,且步长为2。
    True
    
  22. ^ 匿名函數範例:
    >>> from functools import reduce
    >>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 
    15
    >>> fac = lambda n: (1 if n<2 else n*fac(n-1))
    >>> fac(5)
    120
    >>> [*map(fac, [1, 2, 3, 4, 5])]
    [1, 2, 6, 24, 120]
    

    不動點組合子範例:

    >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
    >>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
    >>> Y(fac)(5)
    120
    >>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
    >>> Y(fib)(6)
    8
    >>> [*map((lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))))(lambda f: lambda n: (1 if n<2 else n*f(n-1))), [1, 2, 3, 4, 5])]
    [1, 2, 6, 24, 120]
    

    上述Y組合子程式碼源出自Rosetta Code[129],其原理可參見專門介紹[130]

  23. ^ 賦值表達式在用作子表達式,即位於分片表達式、條件表達式、lambda表達式、關鍵字參數中的表達式和推導式中的if表達式之中,以及在assertwith陳述式之中的時候,必須圍繞着圓括號。在它們可以使用的所有其他地方,包括在ifwhile陳述式之中,都不要求圓括號[131]
  24. ^ 多行字串文字帶有字串插值英語String interpolation(使用了format方法)的範例:
    print("""亲爱的{recipient},
    
    我希望你离开Sunnydale并永不返回.
    
    不是很爱你的,
    {sender}
    """.format(sender="吸血鬼猎人Buffy", recipient="Spike"))
    
  25. ^ 原始字串的範例:
    >>> # Windows路径,即使是原始字符串也不能结束于反斜杠
    >>> r"C:\Spam\Eggs\Ham\"
      File "<stdin>", line 1
        r"C:\Spam\Eggs\Ham\"
                           ^
    SyntaxError: EOL while scanning string literal
    >>> dos_path = r"C:\Spam\Eggs\Ham\ " # 通过增加尾随的空格
    >>> dos_path.rstrip()              # 并接着移除它来避免错误
    'C:\\Spam\\Eggs\\Ham\\'
    >>> quoted_dos_path = r'"{}"'.format(dos_path)
    >>> quoted_dos_path
    '"C:\\Spam\\Eggs\\Ham\\ "'
    >>> # 匹配具有可能的反斜杠引述的引述字符串的正则表达式
    >>> import re
    >>> re.match(r'"(([^"\\]|\\.)*)"', quoted_dos_path).group(1).rstrip()
    'C:\\Spam\\Eggs\\Ham\\'
    >>> code = 'spam(2, eggs)'
    >>> # 反转有二个参数的函数调用的两个实际参数
    >>> re.sub(r'\(([^,]*),\s*([^,]*)\)', r'(\2, \1)', code)
    'spam(eggs, 2)'
    >>> # 注意如果实际参数中有圆括号或逗号则上例无效。
    
  26. ^ 字串文字串接範例:
    >>> print("hello " 'world')
    hello world
    >>> str1="hello "; str2='world'
    >>> print(str1 + str2)
    hello world
    
  27. ^ 格式化字串的範例,例如下列命令列echo命令:
    num="3"; printer="HP Laserjet"
    echo "I just printed ${num} pages to the printer ${printer}"
    

    等價於如下Python中的任何一種print函數呼叫:

    num = 3; printer="HP Laserjet"
    print(f"I just printed {num} pages to the printer {printer}")
    
    print("I just printed {} pages to the printer {}".format(num, printer))
    print("I just printed {0} pages to the printer {1}".format(num, printer))
    print("I just printed {num} pages to the printer {printer}".format(num=num, printer=printer))
    
    print("I just printed %s pages to the printer %s" % (num, printer))
    print("I just printed %(num)s pages to the printer %(printer)s" % {"num": num, "printer": printer})
    
  28. ^ 詞法閉包的例子:
    def f(x):
        def g(y):
            return x + y
        return g  # 返回一个闭包。
    
    h = lambda x: lambda y: x + y
    
    # 将指定闭包赋值给变量。
    a = f(1)
    b = h(1)
    c = f(2)
    # 使用存储在变量中的闭包。
    assert a(5) == 6
    assert b(5) == 6
    assert c(5) == 7
    # 使用闭包而不事先把它们绑定到变量。
    assert f(1)(5) == 6  # f(1)是个闭包。
    assert h(1)(5) == 6  # h(1)是个闭包。
    assert f(2)(5) == 7  # f(2)是个闭包。
    
  29. ^ 函數的形式參數預設值的永續性範例:
    >>> def f(a, L=[]):
    ...     L.append(a)
    ...     return L
    ... 
    >>> print(f(1))
    [1]
    >>> print(f(2))
    [1, 2]
    >>> print(f(3))
    [1, 2, 3]
    
  30. ^ 函數的形實參數二者結合範例。例如:
    >>> def spam(a):
    ...     a.append('LovelySpam')
    ...     
    >>> def eggs(b):
    ...     b=100 #实际上是重新绑定了另一个整型对象100
    ... 
    >>> a=[]
    >>> b=10
    >>> spam(a)
    >>> eggs(b)
    >>> print(a)
    ['LovelySpam']
    >>> print(b)
    10
    
  31. ^ 函數的形式參數預設值的定義範例:
    >>> from inspect import getfullargspec
    >>> def func(p1, /, p2, p3="x", *, p4): pass
    ... 
    >>> getfullargspec(func)
    FullArgSpec(args=['p1', 'p2', 'p3'], varargs=None, varkw=None, defaults=('x',), kwonlyargs=['p4'], kwonlydefaults=None, annotations={})
    
  32. ^ 函數的可變參數的定義範例:
    >>> from inspect import getfullargspec
    >>> def func(p1, /, p2, *args, p3, **kwargs): pass
    ... 
    >>> getfullargspec(func)
    FullArgSpec(args=['p1', 'p2'], varargs='args', varkw='kwargs', defaults=None, kwonlyargs=['p3'], kwonlydefaults=None, annotations={})
    
  33. ^ 定義修飾器的範例:
    def viking_chorus(myfunc):
        def inner_func(*args, **kwargs):
            for i in range(3):
                myfunc(*args, **kwargs)
        return inner_func
    

    呼叫修飾器的範例:

    @viking_chorus    
    def menu_item(*args):
        print(", ".join(args)+", and spam")
    

    它等價於:

    def menu_item(*args):
        print(", ".join(args)+", and spam")
    
    menu_item = viking_chorus(menu_item)
    

    viking_chorus修飾後的menu_item將原來定義執行3次:

    >>> menu_item("egg","bacon")
    egg, bacon, and spam
    egg, bacon, and spam
    egg, bacon, and spam
    
  34. ^ 修飾器工廠範例,這裏的favourite_colour接受一個實際參數,並返回一個修飾器:
    def favourite_colour(colour):
        def decorator(func):
            def wrapper(*args, **kwargs):
                print(f"My favourite colour is {colour}.")
                func(*args, **kwargs)
            return wrapper
        return decorator
    
    def invincible(func):
        def wrapper(*args, **kwargs):
            print("I'm invincible!")
            func(*args, **kwargs)
        return wrapper
    

    使用毗連的修飾詞連結修飾器範例:

    @invincible
    @favourite_colour("blue")
    def black_knight():
        print("None shall pass.")
    

    它等價於:

    black_knight = invincible(favourite_colour("blue")(black_knight))
    

    black_knight英語Black Knight (Monty Python)()結果為:

    >>> black_knight()
    I'm invincible!
    My favourite colour is blue.
    None shall pass.
    
  35. ^ 呼叫函數使用幫助資訊範例。比如:
    >>> def randint(a, b):
    ...     "Return random integer in range [a, b], including both end points."
    ...
    >>> help(randint)
    Help on function randint in module __main__:   
    
    randint(a, b)
        Return random integer in range [a, b], including both end points.
    
  36. ^ 如下這樣給參數增加類型標註的提示資訊:
    >>> def greeting(name: str) -> str:
    ...     return 'Hello ' + name
    ... 
    >>> greeting.__annotations__
    {'name': <class 'str'>, 'return': <class 'str'>}
    
  37. ^ 對象的方法範例:
    >>> class Fish(object):
    ...     hungry = True
    ...     def eat(self, food):
    ...         if food is not None:
    ...             self.hungry=False
    ... 
    ... def status(self):
    ...     print("Hungray!" if self.hungry else "Not hungray!")
    ... 
    >>> e = Fish()
    >>> Fish.hungry = False
    >>> e.hungry
    False
    >>> Fish.hungry = True
    >>> e.hungry
    True
    >>> e.__dict__
    {}
    >>> status(e)
    Hungray!
    >>> Fish.status = status
    >>> type(Fish.status)
    <class 'function'>
    >>> type(e.status)
    <class 'method'>
    >>> e.status()
    Hungray!
    >>> e.eat("earthworm")
    >>> e.__dict__
    {'hungry': False}
    >>> e.status()
    Not hungray!
    >>> Fish.hungry
    True
    
  38. ^ 在類中採用數據描述器的範例:
    >>> class RevealAccess:
    ...     """正常的设置和返回值的数据描述器,
    ...        它还打印记录这次访问的一个消息。
    ...     """
    ...     def __init__(self, initval=None, name='var'):
    ...         self.val = initval
    ...         self.name = name
    ...     def __get__(self, obj, objtype):
    ...         print('Retrieving', self.name)
    ...         return self.val
    ...     def __set__(self, obj, val):
    ...         print('Updating', self.name)
    ...         self.val = val
    ... 
    >>> class MyClass:
    ...     x = RevealAccess(10, 'var "x"')
    ...     y = 5
    ...
    >>> m = MyClass()
    >>> m.x
    Retrieving var "x"
    10
    >>> vars(m)
    {}
    >>> MyClass.__dict__['x'].val
    10
    >>> m.x = 20
    Updating var "x"
    >>> vars(m)
    {}
    >>> MyClass.__dict__['x'].val
    20
    >>> m.y
    5
    >>> vars(m)
    {}
    >>> m.y = 5
    >>> vars(m)
    {'y': 5}
    
  39. ^ 特殊方法和子類呼叫超類別方法的例子:
    >>> class Thought(object):
    ...     cls_name = "类型Thought"
    ...     def __init_subclass__(cls):
    ...         cls.cls_name = "类型Thought的子类型"
    ...     def __init__(self, *args, **kwargs):
    ...         print(f"我是{type(self).cls_name}的新对象!")
    ...         if len(args) != 0 or len(kwargs) != 0:
    ...             print(f"init: nargs={len(args)}, nkwargs={len(kwargs)}")
    ...         self.notion = "我觉得我在平行宇宙中把车停歪了."
    ...     def message(self, *args):
    ...         print(self.notion)
    ...         if len(args) != 0:
    ...             print("\n".join(args))
    ... 
    >>> class Advice(Thought):
    ...     def message(self):
    ...         super().message("警告: 日历里的日期比它们看起来更近!")
    ... 
    >>> t = Thought()
    我是类型Thought的新对象!
    >>> t.message()
    我觉得我在平行宇宙中把车停歪了.
    >>> a = Advice()
    我是类型Thought的子类型的新对象!
    >>> a.message()
    我觉得我在平行宇宙中把车停歪了.
    警告: 日历里的日期比它们看起来更近!
    >>> # 内省一下:
    >>> [*super.__dict__]
    ['__new__', '__repr__', '__getattribute__', '__get__', '__init__', '__thisclass__', '__self__', '__self_class__', '__doc__']
    >>> [*super(Advice).__thisclass__.__dict__]
    ['__module__', 'message', '__doc__', 'cls_name']
    >>> super(Advice).__thisclass__.__dict__['cls_name']
    '类型Thought的子类型'
    >>> [*super(Advice, a).__self__.__dict__]
    ['notion']
    >>> super(Advice, a).__self_class__.__dict__['cls_name']
    '类型Thought的子类型'
    >>> super(Advice, a).message()
    我觉得我在平行宇宙中把车停歪了.
    >>> super(Advice).__get__(a).message()
    我觉得我在平行宇宙中把车停歪了.
    
  40. ^ 特殊方法、類別方法和靜態方法(__new__())範例:
    >>> from weakref import WeakValueDictionary
    >>> class D:
    ...     _template = {}
    ...     _obj_dict = WeakValueDictionary()
    ...     def __new__(cls, *args, **kwargs):
    ...         obj = super(D, cls).__new__(cls)
    ...         cls._obj_dict[id(obj)] = obj
    ...         return obj
    ...     @classmethod
    ...     def load(cls, dict):
    ...         cls._template.update(dict)
    ...     @classmethod
    ...     def create(cls, *args, **kwargs):
    ...         return cls(cls._template, *args, **kwargs)
    ...     @classmethod
    ...     def count(cls):
    ...         return len(cls._obj_dict)
    ...     def __init__(self, dict={}, /, *args, **kwargs):
    ...         self.__dict__.update(dict)
    ...         self.__dict__.update(kwargs)
    ...     def __call__(self, *args, **kwargs):
    ...         self.__dict__.update(kwargs)
    ...         return self.__dict__.copy()
    ...     def __len__(self):
    ...         return len(self.__dict__)
    ...     def __getitem__(self, key):
    ...         return self.__dict__[key]
    ...     def __setitem__(self, key, value):
    ...         self.__dict__[key] = value
    ... 
    >>> a = {'ak': 1, 'bk': 2, 'ck': 3}
    >>> d = D(a, dk=4)
    >>> d()
    {'ak': 1, 'bk': 2, 'ck': 3, 'dk': 4}
    >>> D.load(a)
    >>> e = D.create(ck=4)
    >>> e()
    {'ak': 1, 'bk': 2, 'ck': 4}
    >>> f = D(ak=1, bk=2)
    >>> f(ck=3)
    {'ak': 1, 'bk': 2, 'ck': 3}
    >>> f['ak']
    1
    >>> f['ak'] = 5
    >>> f()
    {'ak': 5, 'bk': 2, 'ck': 3}
    >>> len(f)
    3
    >>> D.count()
    3
    >>> del f
    >>> D.count()
    2
    >>> d.__weakref__ in D._obj_dict.valuerefs()
    True
    
  41. ^ 在類中呼叫property()的例子:
    >>> class C:
    ...     def __init__(self):
    ...         self.__x = None
    ...     def getx(self):
    ...         return self.__x
    ...     def setx(self, value):
    ...         self.__x = value
    ...     def delx(self):
    ...         del self.__x
    ...     x = property(getx, setx, delx, "I'm the 'x' property.")
    ... 
    >>> c = C()
    >>> vars(c)
    {'_C__x': None}
    >>> {*C.__dict__}
    {'__init__', 'setx', '__weakref__', 'delx', 'x', 'getx', '__doc__', '__module__', '__dict__'}
    

    上述程式碼可以採用修飾詞進一步的書寫為:

    >>> class C:
    ...     def __init__(self):
    ...         self.__x = None
    ...     @property
    ...     def x(self):
    ...         """I'm the 'x' property."""
    ...         return self.__x
    ...     @x.setter
    ...     def x(self, value):
    ...         self.__x = value
    ...     @x.deleter
    ...     def x(self):
    ...         del self.__x
    ... 
    >>> c = C()
    >>> vars(c)
    {'_C__x': None}
    >>> {*C.__dict__}
    {'__init__', '__weakref__', 'x', '__doc__', '__module__', '__dict__'}
    
  42. ^ 兩個類及元類等的實例關係(藍色連接)與繼承關係(綠色連接)示意圖:
     
    r = object
    c = type
    class M(c): pass
    
    class A(metaclass=M): pass
    
    class B(A): pass
    
    b = B()
    
    >>> type(b)
    <class '__main__.B'>
    >>> print(type(B), B.__bases__)
    <class '__main__.M'> (<class '__main__.A'>,)
    >>> print(type(A), A.__bases__)
    <class '__main__.M'> (<class 'object'>,)
    >>> print(type(M), M.__bases__)
    <class 'type'> (<class 'type'>,)
    >>> print(type(c), c.__bases__)
    <class 'type'> (<class 'object'>,)
    >>> print(type(r), r.__bases__)
    <class 'type'> ()
    
  43. ^ 數學運算範例。比如:
    >>> def mean(seq):
    ...     return sum(seq) / len(seq)
    ... 
    >>> mean([3, 4])
    3.5
    >>> import math
    >>> print(math.sin(math.pi/2))
    1.0
    

參照

[編輯]
  1. ^ 1.0 1.1 GitHub repository of Python 0.9.1 source. [2023-02-25]. (原始內容存檔於2023-03-05). 
    HISTORY. Python source distribution. Python Foundation. [2017-11-23]. (原始內容存檔於2017-12-01). 
  2. ^ "Python 3.13.5 is now available!"; 作者姓名字串: Thomas Wouters; 出版日期: 2025年6月11日; 檢索日期: 2025年6月11日.
  3. ^ "Python 3.14.0 beta 3 is here!"; 作者姓名字串: Hugo; 出版日期: 2025年6月17日; 檢索日期: 2025年6月20日.
  4. ^ 4.0 4.1 Glossary — duck-typing. [2023-06-28]. (原始內容存檔於2020-06-25). 
  5. ^ Why is Python a dynamic language and also a strongly typed language - Python Wiki. wiki.python.org. [2021-01-27]. (原始內容存檔於2021-03-14). 
  6. ^ 6.0 6.1 PEP 483 – The Theory of Type Hints. [2023-03-16]. (原始內容存檔於2023-03-26). 
  7. ^ File extension .pyo was removed in Python 3.5. See PEP 0488頁面存檔備份,存於互聯網檔案館
  8. ^ Holth, Moore. PEP 0441 -- Improving Python ZIP Application Support. 2014-03-30 [2015-11-12]. (原始內容存檔於2018-12-26). 
  9. ^ 9.0 9.1 9.2 Why was Python created in the first place?. Python FAQ. [2007-03-22]. (原始內容存檔於2008-02-23). 
  10. ^ Andrew Kuchling, Guido van Rossum. LJ Interviews Guido van Rossum. 1998-11-01 [2023-03-21]. (原始內容存檔於2023-03-30). String slicing came from Algol-68 and Icon. 
  11. ^ 11.0 11.1 The Python Standard Library - Functional Programming Modules - itertools — Functions creating iterators for efficient looping. [2020-04-22]. (原始內容存檔於2020-06-14). 
  12. ^ van Rossum, Guido. An Introduction to Python for UNIX/C Programmers. Proceedings of the NLUUG Najaarsconferentie (Dutch UNIX Users Group). 1993 [2021-03-14]. (原始內容存檔於2013-06-17). even though the design of C is far from ideal, its influence on Python is considerable. 
  13. ^ 13.0 13.1 The Python Tutorial - 9. Classes. [2012-02-20]. (原始內容存檔於2012-10-23). Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++ and Modula-3. 
  14. ^ Fredrik Lundh. Python-list mailing list - passing by refference. [2023-03-06]. (原始內容存檔於2023-03-06). replace "CLU" with "Python", "record" with "instance", and "procedure" with "function or method", and you get a pretty accurate description of Python's object model. 
  15. ^ 15.0 15.1 Simionato, Michele. The Python 2.3 Method Resolution Order. Python Software Foundation. [2021-03-14]. (原始內容存檔於2020-08-20). The C3 method itself has nothing to do with Python, since it was invented by people working on Dylan and it is described in a paper intended for lispers. 
  16. ^ Kuchling, A. M. Functional Programming HOWTO. Python v2.7.2 documentation. Python Software Foundation. [2012-02-09]. (原始內容存檔於2012-10-24). 
  17. ^ 17.0 17.1 17.2 Guido van Rossum. Python Reference Manual - Version 1.2 (PDF). CWI Report CS-R9525. May 1995 [2023-03-04]. (原始內容存檔 (PDF)於2023-03-05). Python is a simple, yet powerful, interpreted programming language that bridges the gap between C and shell programming, and is thus ideally suited for "throw-away英語Software_prototyping#Throwaway_prototyping programming" and rapid prototyping. Its syntax is put together from constructs borrowed from a variety of other languages; most prominent are influences from ABC, C, Modula-3 and Icon.
    The Python interpreter is easily extended with new functions and data types implemented in C. Python is also suitable as an extension language for highly customizable C applications such as editors or window managers.
     
  18. ^ Smith, Kevin D.; Jewett, Jim J.; Montanaro, Skip; Baxter, Anthony. PEP 318 – Decorators for Functions and Methods. Python Enhancement Proposals. Python Software Foundation. 2004-09-02 [2012-02-24]. (原始內容存檔於2020-06-03). 
  19. ^ More Control Flow Tools. Python 3 documentation. Python Software Foundation. [2015-07-24]. (原始內容存檔於2016-06-04). 
  20. ^ re — Regular expression operations. docs.python.org. [2022-09-06]. (原始內容存檔於2018-07-18). This module provides regular expression matching operations similar to those found in Perl. 
  21. ^ 21.0 21.1 Gotchas for Python Users. boo.codehaus.org. Codehaus Foundation. [2008-11-24]. (原始內容存檔於2008-12-11). 
  22. ^ 22.0 22.1 Esterbrook, Charles. Acknowledgements. cobra-language.com. Cobra Language. [2010-04-07]. (原始內容存檔於2008-02-08). 
  23. ^ 23.0 23.1 CoffeeScript for Python Programmers. CoffeeScript is a programming language whose syntax is clearly designed to match much of Python (with additional inspirations from Perl, ECMAScript, Ruby, etc.). 
  24. ^ 24.0 24.1 FAQ: What is GDScript and why should I use it?. [2020-09-13]. (原始內容存檔於2020-05-19). 
  25. ^ 25.0 25.1 Frequently Asked Questions (FAQ) - The Go Programming Language. The Go Programming Language. [2016-02-26]. (原始內容存檔於2020-05-03). 
  26. ^ 26.0 26.1 Strachan, James. Groovy – the birth of a new dynamic language for the Java platform. 2003-08-29 [2007-06-11]. (原始內容存檔於2007-04-05). 
  27. ^ Perl and Python influences in JavaScript. www.2ality.com. 2013-02-24 [2015-05-15]. (原始內容存檔於2018-12-26). 
  28. ^ Rauschmayer, Axel. Chapter 3: The Nature of JavaScript; Influences. O'Reilly, Speaking JavaScript. [2015-05-15]. (原始內容存檔於2018-12-26). 
  29. ^ 29.0 29.1 Home · The Julia Language. docs.julialang.org. [2018-08-15]. (原始內容存檔於2021-01-11) (英語). 
  30. ^ 30.0 30.1 Jalan, Nishant Aanjaney. Programming in Kotlin. CodeX. 2022-11-10 [2024-04-29]. (原始內容存檔於2024-11-30) (英語). 
  31. ^ 31.0 31.1 Krill, Paul. Mojo language marries Python and MLIR for AI development. InfoWorld. 2023-05-04 [2023-05-05]. (原始內容存檔於2023-05-05) (英語). 
  32. ^ 32.0 32.1 Yegulalp, Serdar. Nim language draws from best of Python, Rust, Go, and Lisp. InfoWorld. 2017-01-16 [2020-09-13]. (原始內容存檔於2018-10-13). Nim's syntax is strongly reminiscent of Python's, as it uses indented code blocks and some of the same syntax (such as the way if/elif/then/else blocks are constructed). 
  33. ^ 33.0 33.1 Bini, Ola. Practical JRuby on Rails Web 2.0 Projects: Bringing Ruby on Rails to Java. Berkeley: APress. 2007: 3. ISBN 978-1-59059-881-8. It draws primarily on features from Perl, Smalltalk, Python, Lisp, Dylan, and CLU. 
  34. ^ 34.0 34.1 Starlark Language. [2019-05-25]. (原始內容存檔於2020-06-15). 
  35. ^ 35.0 35.1 Lattner, Chris. Chris Lattner's Homepage. Chris Lattner. 2014-06-03 [2014-06-03]. (原始內容存檔於2018-12-25). Of course, it also greatly benefited from the experiences hard-won by many other languages in the field, drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list. 
  36. ^ 彼德·諾米格. Python for Lisp Programmers. [2020-04-21]. (原始內容存檔於2020-06-14). Python can be seen as a dialect of Lisp with "traditional" syntax (what Lisp people call "infix" or "m-lisp" syntax). 
  37. ^ Rossum, Guido Van. The History of Python: A Brief Timeline of Python. The History of Python. 2009-01-20 [2021-03-05]. (原始內容存檔於2020-06-05). 
  38. ^ Peterson, Benjamin. Python Insider: Python 2.7.18, the last release of Python 2. Python Insider. 2020-04-20 [2020-04-27]. (原始內容存檔於2020-04-26). 
  39. ^ Stack Overflow Developer Survey 2024. JavaScript, Python and SQL are all highly-desired and admired programming languages 
  40. ^ the State of Developer Ecosystem Report 2024. 
  41. ^ 41.0 41.1 TIOBE Index. TIOBE - The Software Quality Company. [2021-10-06]. (原始內容存檔於2020-06-14). 
  42. ^ PYPL PopularitY of Programming Language index. pypl.github.io. [2021-03-26]. (原始內容存檔於2017-03-14) (英語). 
  43. ^ Guido van Rossum - Resume. [2022-10-12]. (原始內容存檔於2022-12-21). 
  44. ^ amoeba operating system. [2023-02-25]. (原始內容存檔於2023-03-05). 
  45. ^ Whetting Your Appetite. The Python Tutorial. Python Software Foundation. [2012-02-20]. (原始內容存檔於2012-10-26). 
  46. ^ Benevolent dictator for life. Linux Format. 2005-02-01 [2007-11-01]. (原始內容存檔於2006-10-01). 
  47. ^ Transfer of power. [2020-11-29]. (原始內容存檔於2018-07-12). 
  48. ^ PEP 8100. python. Python Software Foundation. [2019-05-04]. (原始內容存檔於2020-06-04). 
  49. ^ Steering Council nomination: Guido van Rossum (2020 term). [2020-10-11]. (原始內容存檔於2019-12-29). 
  50. ^ The Making of Python. Artima Developer. [2007-03-22]. (原始內容存檔於2016-09-01). 
  51. ^ Older source releases (1.0.1 - 1.6). [2023-03-05]. (原始內容存檔於2023-03-05). 
  52. ^ HISTORY. [2020-09-12]. (原始內容存檔於2017-12-01). Lambda expressions are particularly useful in combination with map(), filter() and reduce(), described below. Thanks to Amrit Prem for submitting this code (as well as map(), filter(), reduce() and xrange())! 
  53. ^ LJ #37: Python 1.4 Update. [2007-04-29]. (原始內容存檔於2007-05-01). 
  54. ^ Kuchling, A. M.; Zadka, Moshe. What's New in Python 2.0. Python Software Foundation. 2000-10-16 [2012-02-11]. (原始內容存檔於2012-10-23). 
  55. ^ Hylton, Jeremy. PEP 227 - Statically Nested Scopes. 2000-11-01 [2007-03-22]. (原始內容存檔於2007-03-29). 
  56. ^ 56.0 56.1 Guido van Rossum. Unifying types and classes in Python 2.2. [2020-09-26]. (原始內容存檔於2019-09-28). 
  57. ^ What’s New in Python 2.2 - PEP 234: Iterators. [2020-10-21]. (原始內容存檔於2021-02-07). 
  58. ^ What’s New in Python 2.2 - PEP 255: Simple Generators. [2020-10-21]. (原始內容存檔於2021-02-07). 
  59. ^ What’s New in Python 2.2 - Descriptors. [2020-10-21]. (原始內容存檔於2021-02-07). 
  60. ^ 60.0 60.1 60.2 What’s New in Python 2.4 - PEP 318: Decorators for Functions and Methods. [2020-10-21]. (原始內容存檔於2021-02-07). 
  61. ^ What’s New in Python 2.5 - PEP 343: The ‘with’ statement. [2020-10-21]. (原始內容存檔於2021-02-07). 
  62. ^ PEP 339 – Design of the CPython Compiler. 2005 [2023-03-06]. (原始內容存檔於2023-03-06). 
  63. ^ Guido van Rossum. What’s New In Python 3.0. [2023-02-18]. (原始內容存檔於2012-11-02). 
  64. ^ What’s New In Python 3.4 - asyncio. [2023-02-22]. (原始內容存檔於2023-06-13). 
  65. ^ What’s New In Python 3.5 - PEP 484 - Type Hints. [2023-02-25]. (原始內容存檔於2016-06-18). 
  66. ^ PEP 492 - Coroutines with async and await syntax. [2019-11-21]. (原始內容存檔於2019-01-05). 
  67. ^ 67.0 67.1 What’s New in Python 3.8 - Assignment expressions. [2023-03-08]. (原始內容存檔於2021-06-01). 
  68. ^ Paul Krill, Guido Van Rossum. Guido van Rossum resigns: What’s next for Python. 2018-07-27 [2023-03-19]. (原始內容存檔於2023-03-19). 
  69. ^ PEP 585 – Type Hinting Generics In Standard Collections. [2023-03-17]. (原始內容存檔於2023-05-25). 
    The Python Standard Library - Built-in Types - Generic Alias Type. [2023-03-17]. (原始內容存檔於2020-06-14). 
  70. ^ What’s New In Python 3.9 - New Parser. [2023-02-22]. (原始內容存檔於2020-10-07). 
  71. ^ What’s New In Python 3.10 - PEP 634: Structural Pattern Matching. [2023-02-22]. (原始內容存檔於2023-06-11). 
  72. ^ PEP 604 – Allow writing union types as X | Y. [2023-03-17]. (原始內容存檔於2023-05-26). 
    The Python Standard Library - Built-in Types - Union Type. [2023-03-17]. (原始內容存檔於2020-06-14). 
  73. ^ What’s New In Python 3.11 - Faster CPython. [2023-03-24]. (原始內容存檔於2023-06-13). 
  74. ^ What’s New In Python 3.12 — PEP 695: Type Parameter Syntax. [2023-10-20]. (原始內容存檔於2023-11-13). 
  75. ^ What’s New In Python 3.13. [2024-09-17]. (原始內容存檔於2024-09-29). 
  76. ^ What’s new in Python 3.14. 
  77. ^ Python Developer's Guide — Status of Python Version. devguide.python.org. [2022-08-26]. (原始內容存檔於2022-08-26). 
  78. ^ PEP 8106 – 2025 Term Steering Council election. Python Software Foundation. [2024-12-11]. (原始內容存檔於2025-01-30). 
  79. ^ 79.0 79.1 The Python Language Reference - 3. Data model - Special method names. [2020-09-25]. (原始內容存檔於2012-10-26). 
  80. ^ aspectlib. aspectlib is an aspect-oriented programming, monkey-patch and decorators library. It is useful when changing behavior in existing code is desired. It includes tools for debugging and testing: simple mock/record and a complete capture/replay framework. 
  81. ^ PEP 316 -- Programming by Contract for Python. [2021-01-17]. (原始內容存檔於2021-01-22). 
    • Deal. [2021-06-20]. (原始內容存檔於2021-07-16). python library for design by contract (DbC) and checking values, exceptions, and side-effects. 
    • icontract. [2021-01-17]. (原始內容存檔於2021-01-21). icontract provides design-by-contract to Python3 with informative violation messages and inheritance. 
  82. ^ PyDatalog. [2012-07-22]. (原始內容存檔於2020-06-13). 
  83. ^ Extending Python with C or C++ — Reference Counting in Python. Docs.python.org. [2020-06-05]. (原始內容存檔於2012-10-18) (英語). 
  84. ^ CPython’s internals — Garbage collector design — Optimization: generations. [2024-09-17]. (原始內容存檔於2025-01-03). 
  85. ^ Functional Programming HOWTO. [2020-09-26]. (原始內容存檔於2012-10-24). 
  86. ^ van Rossum, Guido. The fate of reduce() in Python 3000. Artima Developer. [2007-03-22]. (原始內容存檔於2007-04-07). 
  87. ^ Functional Programming Modules. Docs.python.org. [2020-09-26]. (原始內容存檔於2020-09-20). 
  88. ^ Guido van Rossum. Foreword for "Programming Python" (1st ed.). 1996-05-01 [2020-09-12]. (原始內容存檔於2014-07-24). Despite all its elegance and power and the availability of a free implementation, ABC never became popular in the Unix/C world. I can only speculate about the reasons, but here's a likely one: the difficulty of adding new "primitive" operations to ABC. 
  89. ^ Guido van Rossum. Extending and Embedding the Python Interpreter - Version 1.2 (PDF). CWI Report CS-R9527. May 1995 [2023-03-05]. (原始內容存檔 (PDF)於2023-03-05). Python is an interpreted object oriented programming language. This document describes how to write modules in C or C++ to extend the Python interpreter with new modules. Those modules can define new functions but also new object types and their methods. The document also describes how to embed the Python interpreter in another application, for use as an extension language. Finally, it shows how to compile and link extension modules so that they can be loaded dynamically (at run time) into the interpreter, if the underlying operating system supports this feature. 
  90. ^ The Python Standard Library - Generic Operating System Services - ctypes — A foreign function library for Python. [2022-01-14]. (原始內容存檔於2022-04-27). 
  91. ^ PEP 523 – Adding a frame evaluation API to CPython. [2022-08-29]. (原始內容存檔於2022-08-29). 
  92. ^ The Python Language Reference - 7. Simple statements. [2020-10-30]. (原始內容存檔於2023-06-06). 
    The Python Language Reference - 10. Full Grammar specification. [2023-02-17]. (原始內容存檔於2023-06-06).
    simple_stmts:
        | simple_stmt !';' NEWLINE # Not needed, there for speedup
        | ';'.simple_stmt+ [';'] NEWLINE
     
  93. ^ The Python Language Reference - 2. Lexical analysis - Comments. [2023-03-11]. (原始內容存檔於2018-01-09). 
  94. ^ 94.0 94.1 The Python Language Reference - 2. Lexical analysis - Explicit line joining. [2023-02-17]. (原始內容存檔於2018-01-09). 
  95. ^ The Python Language Reference - 8. Compound statements. [2023-02-18]. (原始內容存檔於2019-11-27). 
  96. ^ PEP 8 – Style Guide for Python Code - Indentation. [2020-09-26]. (原始內容存檔於2018-07-13). 
  97. ^ The Python Language Reference - 2. Lexical analysis - Indentation. [2023-02-18]. (原始內容存檔於2018-01-09). 
  98. ^ The Python Language Reference - 10. Full Grammar specification. [2023-02-17]. (原始內容存檔於2023-06-06).
    statements: statement+
    statement: compound_stmt | simple_stmts
    ……
    block:
        | NEWLINE INDENT statements DEDENT
        | simple_stmts
     
  99. ^ The Python Language Reference - 2. Lexical analysis - Keywords. [2020-09-26]. (原始內容存檔於2018-01-09). 
  100. ^ What’s New In Python 3.0 - Overview Of Syntax Changes. [2023-02-18]. (原始內容存檔於2012-11-02). 
  101. ^ What’s What’s New In Python 3.5 - New Keywords. [2016-06-01]. (原始內容存檔於2016-06-18). 
  102. ^ What’s New In Python 3.7. [2019-11-21]. (原始內容存檔於2019-11-28). 
  103. ^ The Python Language Reference - 2. Lexical analysis - Soft Keywords. [2023-03-03]. (原始內容存檔於2018-01-09). 
  104. ^ PEP 8 – Style Guide for Python Code - Naming Conventions. [2017-10-06]. (原始內容存檔於2018-07-13). 
  105. ^ The Python Language Reference - 2. Lexical analysis - Reserved classes of identifiers. [2023-03-03]. (原始內容存檔於2018-01-09). 
  106. ^ 106.0 106.1 9.6. Private Variables. [2020-09-27]. (原始內容存檔於2012-10-23). 
  107. ^ The Python Language Reference - 7. Simple statements - Augmented assignment statements. [2023-03-08]. (原始內容存檔於2023-06-06). 
  108. ^ The Python Tutorial - 5. Data Structures - Tuples and Sequences. [2018-10-17]. (原始內容存檔於2020-06-10). 
  109. ^ The Python Language Reference - 7. Simple statements - The yield statement. [2023-03-15]. (原始內容存檔於2023-06-06). 
  110. ^ The Python Language Reference - 6. Expressions - Yield expressions. [2023-03-15]. (原始內容存檔於2022-09-07). 
  111. ^ PEP 342 - Coroutines via Enhanced Generators. [2019-11-21]. (原始內容存檔於2020-05-29). 
  112. ^ PEP 380 - Syntax for Delegating to a Subgenerator. [2019-11-21]. (原始內容存檔於2020-06-04). 
  113. ^ PEP 525 – Asynchronous Generators. [2023-03-16]. (原始內容存檔於2023-05-21). 
  114. ^ 114.0 114.1 The Python Language Reference - 7. Simple statements - The import Statement. [2020-10-30]. (原始內容存檔於2021-02-07). 
  115. ^ 115.0 115.1 115.2 The Python Tutorial - 6. Modules. [2020-10-30]. (原始內容存檔於2021-02-06). 
  116. ^ What’s New In Python 3.11 - PEP 654: Exception Groups and except*. [2023-10-20]. (原始內容存檔於2023-06-13). 
  117. ^ PEP 343 – The “with” Statement. [2020-09-26]. (原始內容存檔於2014-12-14). 
  118. ^ The Python Language Reference - 5. The import system - Packages. [2023-03-07]. (原始內容存檔於2022-08-27). 
  119. ^ 119.0 119.1 119.2 119.3 The Python Language Reference - 4. Execution model - Naming and binding. [2023-03-06]. (原始內容存檔於2022-09-08). 
  120. ^ The Python Standard Library - Built-in Functions. [2020-09-25]. (原始內容存檔於2012-10-25). 
  121. ^ The Python Standard Library - Python Runtime Services - __main__ — Top-level code environment. [2020-10-30]. (原始內容存檔於2021-02-07). 
  122. ^ The Python Language Reference - 6. Expressions - Parenthesized forms. [2023-03-13]. (原始內容存檔於2022-09-07). 
  123. ^ The Python Language Reference - 6. Expressions - Displays for lists, sets and dictionaries. [2023-03-13]. (原始內容存檔於2022-09-07). 
  124. ^ Hettinger, Raymond. PEP 289 – Generator Expressions. Python Enhancement Proposals. Python Software Foundation. 2002-01-30 [2012-02-19]. (原始內容存檔於2020-06-14). 
  125. ^ What’s New In Python 3.5 - PEP 448 - Additional Unpacking Generalizations. [2023-03-08]. (原始內容存檔於2016-06-18). 
  126. ^ 126.0 126.1 What’s New In Python 3.5 - PEP 465 - A dedicated infix operator for matrix multiplication. [2023-03-08]. (原始內容存檔於2016-06-18). 
  127. ^ NumPy Reference - Routines - Linear algebra (numpy.linalg) - numpy.matmul. [2022-01-18]. (原始內容存檔於2022-04-10). 
  128. ^ 128.0 128.1 The Python Language Reference - 6. Expressions - Comparison. [2023-03-21]. (原始內容存檔於2022-09-07). 
  129. ^ Rosetta Code. [2020-10-21]. (原始內容存檔於2021-01-11). 
  130. ^ Equational derivations of the Y combinator and Church encodings in Python. [2020-10-21]. (原始內容存檔於2020-11-12). 
  131. ^ The Python Language Reference - 6. Expressions - Assignment expressions. [2023-03-08]. (原始內容存檔於2022-09-07). 
  132. ^ The Python Language Reference - 6. Expressions - Operator precedence. [2023-03-12]. (原始內容存檔於2022-09-07). 
  133. ^ The Python Standard Library - Built-in Types - Common Sequence Operations. [2023-03-17]. (原始內容存檔於2020-06-14). 
  134. ^ What’s New in Python 3.9 - Dictionary Merge & Update Operators. [2021-06-12]. (原始內容存檔於2020-10-07). 
  135. ^ The Python Language Reference - 2. Lexical analysis - String literal concatenation. [2023-03-12]. (原始內容存檔於2018-01-09). 
  136. ^ What’s New In Python 3.0 - PEP 3101: Advanced String Formatting. [2023-03-19]. (原始內容存檔於2012-11-02). 
    The Python Standard Library - Text Processing Services - string — Common string operations - Format String Syntax. [2023-03-21]. (原始內容存檔於2023-06-06). 
  137. ^ The Python Standard Library - Built-in Types - printf-style String Formatting. [2023-03-21]. (原始內容存檔於2020-06-14). 
  138. ^ PEP 498 - Literal String Interpolation. python.org. [2017-03-08]. (原始內容存檔於2020-06-15). 
  139. ^ The Python Language Reference - 2. Lexical analysis - Formatted string literals. [2023-03-13]. (原始內容存檔於2018-01-09). 
  140. ^ van Rossum, Guido. Language Design Is Not Just Solving Puzzles. Artima forums. Artima. 2006-02-09 [2007-03-21]. (原始內容存檔於2020-01-17). the complexity introduced by a solution to a design problem must be somehow proportional to the problem's importance. …… Mathematicians don't mind these -- a proof is a proof is a proof, no matter whether it contains 2 or 2000 steps, or requires an infinite-dimensional space to prove something about integers. …… Features of a programming language, whether syntactic or semantic, are all part of the language's user interface. And a user interface can handle only so much complexity or it becomes unusable. This is also the reason why Python will never have continuations, and even why I'm uninterested in optimizing tail recursion. 
    van Rossum, Guido. Tail Recursion Elimination. Neopythonic.blogspot.be. 2009-04-22 [2012-12-03]. (原始內容存檔於2018-05-19). Once tail recursion elimination exists, developers will start writing code that depends on it, and their code won't run on implementations that don't provide it …… I don't believe in recursion as the basis of all programming. This is a fundamental belief of certain computer scientists, especially those who love Scheme and like to teach programming by starting with a "cons" cell and recursion. 
  141. ^ returns documentation — Trampolines. [2024-09-28]. (原始內容存檔於2024-12-23). 
  142. ^ The Python Tutorial - 4. More Control Flow Tools - Defining Functions. [2023-03-06]. (原始內容存檔於2023-06-10). 
  143. ^ Python 2.4 Decorators: Reducing code duplication and consolidating knowledge. Dr. Dobb's. 2005-05-01 [2007-02-08]. (原始內容存檔於2007-02-06). 
  144. ^ The Python Standard Library - Functional Programming Modules - functools — Higher-order functions and operations on callable objects. [2023-03-18]. (原始內容存檔於2021-06-02). 
  145. ^ PEP 3107 -- Function Annotations. [2021-03-01]. (原始內容存檔於2015-01-06). 
  146. ^ 146.0 146.1 PEP 484 -- Type Hints. [2021-03-01]. (原始內容存檔於2021-02-09). 
  147. ^ PEP 3115 – Metaclasses in Python 3000. [2023-03-21]. (原始內容存檔於2023-04-02). 
  148. ^ The Python Language Reference - 3. Data model - Customizing class creation. [2023-03-21]. (原始內容存檔於2012-10-26). 
    PEP 487 – Simpler customisation of class creation. [2023-03-21]. (原始內容存檔於2023-03-21). 
  149. ^ Why must 'self' be used explicitly in method definitions and calls?. Design and History FAQ. Python Software Foundation. [2012-02-19]. (原始內容存檔於2012-10-24). 
  150. ^ Descriptor HowTo Guide. [2020-09-26]. (原始內容存檔於2020-09-18). 
  151. ^ The Python Language Reference — Data model — Class instances. 
  152. ^ The Python Standard Library - Built-in Functions - class super. [2020-09-25]. (原始內容存檔於2018-10-26). 
  153. ^ The Python Standard Library - Built-in Functions - class property. [2020-09-25]. (原始內容存檔於2018-10-26). 
  154. ^ The Python Language Reference - 3. Data model - The standard type hierarchy. 
  155. ^ 155.0 155.1 mypy - Optional Static Typing for Python. [2017-01-28]. (原始內容存檔於2020-06-06). 
  156. ^ Moshe Zadka, Guido van Rossum. PEP 237 - Unifying Long Integers and Integers. 2001-03-11. (原始內容存檔於2020-05-28). 
  157. ^ The Python Tutorial - 15. Floating Point Arithmetic: Issues and Limitations. [2023-03-23]. (原始內容存檔於2023-06-02). almost all platforms map Python floats to IEEE-754 「double precision」. 
  158. ^ The Python Standard Library - Built-in Types - Ranges. [2019-10-03]. (原始內容存檔於2020-06-14). 
  159. ^ Python HOWTOs — Unicode HOWTO. 
  160. ^ NumPy fundamentals - Indexing on ndarrays - Dimensional indexing tools. [2023-03-23]. (原始內容存檔於2023-06-01). 
  161. ^ The Python Standard Library - Built-in Types - The Null Object. [2023-03-24]. (原始內容存檔於2023-03-24). 
  162. ^ Moshe Zadka, Guido van Rossum. PEP 238 - Changing the Division Operator. 2001-03-11 [2013-10-23]. (原始內容存檔於2020-05-28). 
  163. ^ Guido van Rossum. Why Python's Integer Division Floors. 2010-08-24 [2010-08-25]. (原始內容存檔於2020-06-05). 
  164. ^ Guido van Rossum. Python Reference Manual - Version 1.2 (PDF). CWI Report CS-R9525. May 1995 [2023-03-04]. (原始內容存檔 (PDF)於2023-03-05). The modulo operator always yields a result with the same sign as its second operand (or zero); …… The integer division and modulo operators are connected by the following identity: x == (x/y)*y + (x%y). 
  165. ^ The Python Standard Library - Built-in Functions - round(), [2023-03-21], (原始內容存檔於2012-10-25) 
  166. ^ Brian Kernighan, Dennis Ritchie. The C Programming Language, Second Edition (PDF). Prentice Hall. 1988 [2023-03-23]. (原始內容存檔 (PDF)於2023-03-25). The relational operators group left-to-right, but this fact is not useful; a<b<c is parsed as (a<b)<c, and evaluates to either 0 or 1. 
  167. ^ PEP 327 – Decimal Data Type. [2015-09-26]. (原始內容存檔於2020-06-04). 
  168. ^ The Python Standard Library - Numeric and Mathematical Modules - decimal — Decimal fixed point and floating point arithmetic. [2023-03-21]. (原始內容存檔於2023-06-13). 
  169. ^ The Python Standard Library - Numeric and Mathematical Modules - fractions — Rational numbers. [2023-03-21]. (原始內容存檔於2023-05-26). 
  170. ^ gmpy2 is an optimized, C-coded Python extension module that supports fast multiple-precision arithmetic. [2024-10-14]. (原始內容存檔於2024-12-19). 
  171. ^ 10 Reasons Python Rocks for Research (And a Few Reasons it Doesn't) – Hoyt Koepke. www.stat.washington.edu. [2019-02-03]. (原始內容存檔於2020-05-31). 
  172. ^ Shell, Scott. An introduction to Python for scientific computing (PDF). 2014-06-17 [2019-02-03]. (原始內容存檔 (PDF)於2019-02-04). 
  173. ^ The Python Standard Library. [2023-03-09]. (原始內容存檔於2023-06-06). 
  174. ^ Python Interpreters Benchmarks. [2022-08-30]. (原始內容存檔於2022-08-20). 
  175. ^ Python Bytecode Instructions. Docs.python.org. [2016-02-16]. (原始內容存檔於2020-06-05). 
    Python module to generate and modify bytecode. [2023-02-22]. (原始內容存檔於2023-04-04). 
  176. ^ Obi Ike-Nwosu. Inside The Python Virtual Machine. [2023-01-29]. (原始內容存檔於2021-01-29).  version 2019-03-02 (PDF). [2023-01-30]. (原始內容存檔 (PDF)於2023-03-05).  中文翻译. [2023-01-30]. (原始內容存檔於2023-03-05). 
  177. ^ The Computer Language Benchmarks Game. 
  178. ^ Glossary — global interpreter lock. [2023-09-19]. (原始內容存檔於2020-06-25). 
  179. ^ Application-level Stackless features. 
  180. ^ Codon - A high-performance, zero-overhead, extensible Python compiler with built-in NumPy support. [2023-03-24]. (原始內容存檔於2023-05-25). 
  181. ^ Rachel Gordon. Python-based compiler achieves orders-of-magnitude speedups. MIT CSAIL. 2023-03-14 [2023-03-25]. (原始內容存檔於2023-03-26). 
  182. ^ Differences with Python. [2024-09-26]. (原始內容存檔於2023-05-25). 
  183. ^ Pyodide is a Python distribution for the browser and Node.js based on WebAssembly. [2023-12-28]. (原始內容存檔於2024-04-03). 
  184. ^ RustPython. [2022-03-04]. (原始內容存檔於2022-04-24). 
  185. ^ Brython (Browser Python) is an implementation of Python 3 running in the browser. [2023-06-17]. (原始內容存檔於2023-10-28). 
  186. ^ GraalPy – A high-performance embeddable Python 3 runtime for Java. 
  187. ^ Cython Users Guide — Using Parallelism. [2023-09-19]. (原始內容存檔於2023-10-11). 
  188. ^ mypyc — Compile type annotated Python to fast C extensions. [2024-09-26]. (原始內容存檔於2025-01-20). 
  189. ^ Nuitka is a Python compiler written in Python. [2023-09-18]. (原始內容存檔於2023-11-11). 
  190. ^ Shed Skin is a restricted-Python-to-C++ compiler. 
  191. ^ Pythran - Ahead of Time compiler for numeric kernels. [2022-08-29]. (原始內容存檔於2022-08-29). 
  192. ^ Transcrypt — Python 3.9 to JavaScript compiler - Lean, fast, open!. [2023-09-18]. (原始內容存檔於2023-09-19). 
  193. ^ MyHDL - From Python to Silicon!. [2023-03-05]. (原始內容存檔於2023-06-05). 
  194. ^ Pyston - A faster and highly-compatible implementation of the Python programming language. [2022-08-29]. (原始內容存檔於2022-08-29). Pyston was started at Dropbox in 2014 ……. …… In 2017 …… Pyston project was shut down. …… In 2019 the Pyston developers regrouped ……. …… In mid-2021 the Pyston developers joined Anaconda ……. 
  195. ^ Pyjion - A JIT for Python based upon CoreCLR. [2022-08-29]. (原始內容存檔於2022-08-29). 
  196. ^ Cinder is Meta's internal performance-oriented production version of CPython. [2022-08-26]. (原始內容存檔於2021-05-04). 
  197. ^ Grumpy is a Python to Go source code transcompiler and runtime. 
  198. ^ py2many: Python to many CLike languages transpiler. 
  199. ^ Tool recommendations. python.org. [2022-04-21]. (原始內容存檔於2022-09-06) (英語). 
  200. ^ venv — Creation of virtual environments. [2023-05-07]. (原始內容存檔於2023-06-13). 
  201. ^ virtualenv — A tool for creating isolated virtual python environments. [2023-05-07]. (原始內容存檔於2023-06-11). 
  202. ^ Pipenv — Python Development Workflow for Humans. [2022-08-29]. (原始內容存檔於2019-11-17). 
  203. ^ FAQ: Django appears to be a MVC framework, but you call the Controller the “view”, and the View the “template”. How come you don’t use the standard names?. [2022-09-01]. (原始內容存檔於2022-09-02). 
  204. ^ Asynchronous HTTP Client/Server for asyncio and Python. [2021-01-14]. (原始內容存檔於2021-01-15). 
  205. ^ uvloop is a fast, drop-in replacement of the built-in asyncio event loop. [2023-03-24]. (原始內容存檔於2023-05-25). 
  206. ^ FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints. 
  207. ^ PyScript is an open source platform for Python in the browser. [2024-09-26]. (原始內容存檔於2025-01-18). 
  208. ^ PyGObject is a Python package which provides bindings for GObject based libraries such as GTK, GStreamer, WebKitGTK, GLib, GIO and many more. [2023-03-05]. (原始內容存檔於2023-06-07). 
  209. ^ Gooey - Turn (almost) any Python command line program into a full GUI application with one line. [2022-08-28]. (原始內容存檔於2022-08-28). 
  210. ^ Dear PyGui: A fast and powerful Graphical User Interface Toolkit for Python with minimal dependencies. [2023-03-18]. (原始內容存檔於2023-05-18). 
  211. ^ pywebview is a lightweight cross-platform wrapper around a webview component that allows to display HTML content in its own native GUI window. [2023-03-18]. (原始內容存檔於2023-05-06). 
  212. ^ NumPy Fundamentals and usage — Broadcasting. [2023-09-20]. (原始內容存檔於2022-07-03). The term broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is 「broadcast」 across the larger array so that they have compatible shapes. 
  213. ^ CuPy: NumPy & SciPy for GPU. [2022-08-31]. (原始內容存檔於2022-08-31). 
  214. ^ DataFrame. [2022-09-01]. (原始內容存檔於2022-09-01). DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object. 
  215. ^ Python tools for data visualization — High-level tools. [2023-09-19]. (原始內容存檔於2023-09-28). 
  216. ^ Dask - Parallel computing with task scheduling. [2022-08-31]. (原始內容存檔於2022-08-31). 
  217. ^ Python tools for data visualization. [2022-09-21]. (原始內容存檔於2024-05-04). 
  218. ^ VisPy - interactive scientific visualization in Python. [2022-08-30]. (原始內容存檔於2022-07-13). 
  219. ^ glumpy — Python+Numpy+OpenGL: fast, scalable and beautiful scientific visualization. [2023-09-18]. (原始內容存檔於2023-09-19). 
  220. ^ seaborn: statistical data visualization. [2024-09-24]. (原始內容存檔於2020-12-03). 
  221. ^ Vega-Altair: Declarative Visualization in Python. [2024-09-25]. (原始內容存檔於2025-02-02). 
  222. ^ Bokeh — Interactive Data Visualization in the browser, from Python. [2023-09-19]. (原始內容存檔於2023-10-12). 
  223. ^ plotly.py is an interactive, open-source, and browser-based graphing library for Python. [2024-09-24]. (原始內容存檔於2025-01-24). 
  224. ^ Dash - Analytical Web Apps for Python, R, Julia, and Jupyter. [2022-09-21]. (原始內容存檔於2022-12-05). 
  225. ^ Plotly.js - Open-source JavaScript charting library behind Plotly and Dash. [2022-09-21]. (原始內容存檔於2022-12-21). 
  226. ^ Panel - A high-level app and dashboarding solution for Python. [2022-09-21]. (原始內容存檔於2023-01-16). 
  227. ^ Using Panel in Pyodide & PyScript. 
  228. ^ HoloViz — High-level tools to simplify visualization in Python. [2023-09-19]. (原始內容存檔於2023-10-11). 
  229. ^ Streamlit — The fastest way to build data apps in Python. [2022-09-21]. (原始內容存檔於2023-01-17). 
  230. ^ Voilà - Voilà turns Jupyter notebooks into standalone web applications. [2022-09-21]. (原始內容存檔於2022-12-31). 
  231. ^ Joblib: running Python functions as pipeline jobs. [2022-09-19]. (原始內容存檔於2022-12-07). 
  232. ^ Thread-pool Controls. [2022-09-19]. (原始內容存檔於2022-11-02). 
  233. ^ TensorFlow API Documentation - Module: tf. [2022-08-31]. (原始內容存檔於2022-09-05). 
  234. ^ TensorFlow API Documentation - Module: tf.keras. [2022-08-31]. (原始內容存檔於2020-01-22). 
  235. ^ JAX - Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more. [2022-08-28]. (原始內容存檔於2021-02-05). 
  236. ^ Autograd - Efficiently computes derivatives of numpy code. [2022-08-28]. (原始內容存檔於2022-07-18). 
  237. ^ XLA: Optimizing Compiler for Machine Learning. [2022-08-28]. (原始內容存檔於2022-09-01). 
  238. ^ PEG parser generator for Python. [2023-02-22]. (原始內容存檔於2023-03-05). 
    Pablo Galindo Salgado. Guide to the Parser. [2023-02-22]. (原始內容存檔於2023-05-24). 
    Bryan Ford. The Packrat Parsing and Parsing Expression Grammars Page. [2023-04-18]. (原始內容存檔於2023-06-02). 
  239. ^ PeachPy - Portable Efficient Assembly Code-generator in Higher-level Python. [2023-04-04]. (原始內容存檔於2023-04-04). 
  240. ^ llvmlite — A lightweight LLVM python binding for writing JIT compilers. [2024-09-21]. (原始內容存檔於2025-02-06). 
  241. ^ xDSL is a Python-native compiler framework built around SSA-based intermediate representations (IRs). 
  242. ^ SimPy — Discrete event simulation for Python. [2023-08-17]. (原始內容存檔於2016-12-12). 
  243. ^ PyOpenGL is the most common cross platform Python binding to OpenGL and related APIs. [2022-01-07]. (原始內容存檔於2011-06-15). 
  244. ^ ModernGL - Modern OpenGL binding for python. [2022-01-07]. (原始內容存檔於2022-04-15). 
  245. ^ CUDA Python Manual. [2022-08-30]. (原始內容存檔於2022-08-30). 
  246. ^ PyCUDA gives you easy, Pythonic access to Nvidia’s CUDA parallel computation API. [2022-05-29]. (原始內容存檔於2022-06-28). 
  247. ^ PyOpenCL gives you easy, Pythonic access to the OpenCL parallel computation API. [2021-07-29]. (原始內容存檔於2022-03-08). 
  248. ^ PySPH — A framework for Smoothed Particle Hydrodynamics in Python. [2023-12-26]. (原始內容存檔於2023-12-26). 
  249. ^ Kompute: Blazing fast, mobile-enabled, asynchronous, and optimized for advanced GPU processing usecases. [2025-01-22]. (原始內容存檔於2025-01-24). 
  250. ^ Graphene — GraphQL framework for Python. [2023-12-20]. (原始內容存檔於2024-04-28). 
  251. ^ GQL — A GraphQL client in Python. [2023-12-25]. (原始內容存檔於2024-04-24). 
  252. ^ Pillow — Python Imaging Library (Fork). 
  253. ^ Fabric - Pythonic remote execution. [2013-04-08]. (原始內容存檔於2014-04-11). 
  254. ^ Prefect - The easiest way to coordinate your dataflow. [2022-09-22]. (原始內容存檔於2023-01-11). 
  255. ^ SDL Language Bindings. [2022-02-16]. (原始內容存檔於2019-03-12). 
  256. ^ Arcade — Easy to use Python library for creating 2D arcade games. [2023-10-10]. (原始內容存檔於2023-11-08). 
  257. ^ Pymunk is a easy-to-use pythonic 2d physics library that can be used whenever you need 2d rigid body physics from Python. [2024-09-24]. (原始內容存檔於2024-11-26). 
  258. ^ Panda3D Manual. [2022-09-04]. (原始內容存檔於2018-12-29). 
  259. ^ pythonnet - Python.NET. [2022-08-30]. (原始內容存檔於2022-09-01). 
  260. ^ PyInstaller bundles a Python application and all its dependencies into a single package. [2021-03-13]. (原始內容存檔於2021-06-07). 
  261. ^ LSB — Runtime Languages — Python Interpreter. [2023-06-16]. (原始內容存檔於2016-05-01). The default installed Python version shall be 2.4.2 or greater. 
  262. ^ pipx — Install and Run Python Applications in Isolated Environmentspipenv. [2023-05-07]. (原始內容存檔於2023-06-05). 
  263. ^ XONSH is a Python-powered shell. [2022-08-28]. (原始內容存檔於2022-09-03). 
  264. ^ Data Mining Fruitful and Fun - Open source machine learning and data visualization. Build data analysis workflows visually, with a large, diverse toolbox.. [2023-06-14]. (原始內容存檔於2023-06-06). 
  265. ^ Mayavi: 3D scientific data visualization and plotting in Python. [2023-09-20]. (原始內容存檔於2023-10-11). 
  266. ^ Ray - Effortlessly scale your most complex workloads. [2022-09-19]. (原始內容存檔於2022-12-13). 
  267. ^ Kornia - Open Source Differentiable Computer Vision Library. [2022-09-22]. (原始內容存檔於2023-01-10). 
  268. ^ spaCy: Industrial-strength NLP. [2023-09-22]. (原始內容存檔於2023-10-11). 
  269. ^ Open source ecosystem for neural machine translation and neural sequence learning. 
  270. ^ Generative Models by Stability AI. [2023-10-14]. (原始內容存檔於2023-11-11). 
  271. ^ CLIP (Contrastive Language-Image Pretraining), Predict the most relevant text snippet given an image. [2023-10-18]. (原始內容存檔於2023-09-05). 
  272. ^ Transformers — State-of-the-art Machine Learning for PyTorch, TensorFlow, and JAX. [2023-10-19]. (原始內容存檔於2023-09-27). 
  273. ^ Gradio: The New Frontier in Interactive Python Data Apps. [2023-12-22]. (原始內容存檔於2023-12-22). 
  274. ^ Python library for easily interacting with trained machine learning models https://pypi.org/project/gradio/頁面存檔備份,存於互聯網檔案館
  275. ^ Buniatyan, Davit. Code Understanding Using LangChain. Activeloop. 2023 [2023-12-22]. (原始內容存檔於2023-12-16). 
  276. ^ Python Discord is a large community focused around the Python programming language. [2021-01-13]. (原始內容存檔於2021-02-01). 
  277. ^ Snek — a tiny python-inspired language for embedded computing. 
  278. ^ Taichi — Productive, portable, and performant GPU programming in Python. [2025-01-23]. (原始內容存檔於2025-01-09). 
  279. ^ Coconut — Simple, elegant, Pythonic functional programming. [2024-09-27]. (原始內容存檔於2025-01-20). 

延伸閱讀

[編輯]

參閲

[編輯]

外部連接

[編輯]