跳至內容

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]
轉譯成其他語言的編譯器

其他實現舉例: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). 

延伸閱讀

[編輯]

參閲

[編輯]

外部連接

[編輯]