Python

通用高級編程語言

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

Python
編程範型多範式程序式結構化模組化反射式物件導向函數式
設計者吉多·范羅蘇姆
實作者Python軟體基金會
釋出時間1991年,​33年前​(1991[1]
目前版本
  • 3.12.3 (2024年4月9日;穩定版本)[2]
  • 3.13.0a6 (2024年4月9日;預覽版本)[2]
編輯維基數據連結
型態系統鴨子型別[3]動態強型別[4]漸進英語gradual typing(自從3.5)[5]
作業系統跨平臺
特許條款Python軟體基金會特許條款
副檔名.py、.pyi、.pyc、.pyd、.pyo(3.5之前)[6]、.pyw、.pyz(自從3.5)[7]
網站www.python.org 編輯維基數據連結
主要實作產品
CPythonPyPyStackless PythonMicroPythonCircuitPython英語CircuitPython、Pyston[8]、RustPython[9]IronPythonJython
衍生副語言
CythonRPythonStarlark英語Bazel (software)[10]
啟發語言
ABC[11]ALGOL 68[12]APL[13]C[14]C++[15]CLU[16]Dylan[17]Haskell[18]Icon[19]Java[20]Lisp[21]Modula-3[15]Perl[22]Standard ML[13]
影響語言
BooCobra英語Cobra (programming language)CoffeeScript[23]DF#Genie[24]GoGroovyJavaScript[25][26]Julia[27]NimRuby[28]Swift[29]

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

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

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

歷史 編輯

 
Python創始人吉多·范羅蘇姆在2006年O'Reilly開源大會英語O'Reilly Open Source Convention(OSCON)的相片

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

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

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

在2008年12月,Python 3.0發佈,它對語言做了較大修訂而不能完全後向相容[57]。Python 3發行包括了2to3實用工具,它(至少部份的)自動將Python 2程式碼轉換成Python 3程式碼[58]。Python 3.4介入了非同步I/O模組[59]。Python 3.5介入了類型提示[60],和採用async/await語法的協程[61]。Python 3.8介入了賦值表達式[62][63]。Python 3.9介入了內建的針對容器類的泛化別名types.GenericAlias類型[64],並在官方實現中介入了新的語法解析器[65]。Python 3.10介入了結構式模式匹配[66],和內建的聯合類型types.UnionType[67]。Python 3.11對官方實現進行了最佳化提速[68],並介入了except*子句[69]。Python 3.12介入了類型參數語法和type陳述式[70],並廢棄或移除了一些過時的模組和功能。

Python 2.7的產品壽命結束日期最初設定為2015年,由於大量現存程式碼不能移植到Python 3,而延期支援至2020年[71]。當前只有Python 3的穩定版本3.11和3.12與預覽版本3.13正在被完全支援,但仍提供對3.8、3.9和3.10版本的安全性修正[72]

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

特徵與設計哲學 編輯

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

Python使用動態型別,在記憶體管理上採用參照計數和環檢測相結合的垃圾回收器[78]。它的特徵還有動態名字解析後期繫結英語late binding),即在程式執行期間繫結方法和變數的名字。

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

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

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

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

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

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

語法和語意 編輯

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

行結構 編輯

Python支援使用反斜槓作為行接續符,將多個物理行合成為一個邏輯行[86]。在圓括號方括號花括號之中的表達式,可以分裂跨越多於一個物理行而不使用反斜槓,這被稱為「隱式行接續」[87]註釋開始於並非字串文字英語string literal一部份的一個井號#,並結束於物理行結尾;註釋標示邏輯行的結束,除非已受制於隱式行接續規則;註釋在語法上被忽略[88]

簡單陳述式包含在一個單一的邏輯行之內,Python支援使用分號作為分隔符,將多個簡單陳述式合併入語法意義上的一行之中[89]

縮排 編輯

Python語法中的複合陳述式,包含(成組的)其他陳述式;它們以某種方式影響或控制這些其他陳述式的執行。Python的複合陳述式包含一個或多個子句(clause),子句構成自一個頭部(header)和一個套件(suite)。特定複合陳述式的子句頭部都在同樣的縮排層級上,每個子句頭部開始於一個唯一標識關鍵字,並結束於一個冒號。套件是這個子句所控制的一組陳述式,套件有兩種形式,可以是與頭部在同一行上的一個或多個由分號分隔的簡單陳述式,它們跟隨在這個頭部的冒號之後;或者是在後續諸行上的一個或多個縮排的陳述式,只有這種套件形式可以包含巢狀的複合陳述式[90]

Python語言遵循越位規則,利用縮排來形成陳述式套件,即語法意義上的。連續諸行的縮排層級,被用來生成語法解析器才能見到的INDENTDEDENT記號[91],二者的作用相當於C語言家族的花括號,或Pascal語言家族的關鍵字beginend。增加縮排就生成INDENT記號,減少縮排就生成DEDENT記號。根據PEP 8的規定[92],使用4個空格來表示每級縮排[a]

tab字元(從左至右)被替代為1至8個空格,使得直到tab之前的諸字元加上這些替代空格的字元總數,是8的倍數(這意圖同於Unix所用規則)。前導於第一個非空白字元的空格的總數,確定了這一行的縮排層級。縮排所用諸字元,不能使用反斜槓來拆分成多個物理行;直到第一個反斜槓之前的空白確定縮排層級。如果原始碼檔案混合了tab和空格,並且在這種方式下縮排的意義依賴於一個tab相當於多少個空格,則這種縮排因不一致性而被報錯並拒絕[93]

關鍵字 編輯

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

  • 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[95],關鍵字asyncawait介入於版本3.5[96],並在版本3.7中成為正式關鍵字[97]

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

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

識別碼 編輯

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

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

在Python文獻中經常使用的元語法變數英語metasyntactic variablespam和eggs英語Spam (Monty Python)而非傳統的foo和bar[101]

陳述式 編輯

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

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

複合陳述式:

  • if陳述式,當條件成立時執行陳述式套件。它經常包含elifelse子句。
  • while陳述式,當條件為真時,重複執行陳述式套件。
  • for陳述式,遍歷列表、字串、字典、集合等迭代器,依次處理迭代器中的每個元素。
  • match陳述式,用於模式匹配
  • try英語Exception handling syntax陳述式,它經常包含exceptelsefinally子句,處理在程式執行中出現的異常情況。Python支援並廣泛使用例外處理,作為檢測錯誤狀況和程式中其他「例外」事件的方式,並提倡在可能出現錯誤狀況的任何時候都使用例外。習慣上訪問一個檔案或資源不在使用之前進行測試,而是先行嘗試使用它,再擷取訪問被拒絕引發的例外。[e]
  • with陳述式,把一塊程式碼包裹在一個上下文管理器之內。它允許了資源取得即初始化(RAII)式行為,可替代常見的try/finally慣用法。Python使用with陳述式處理資源[113],在進入一個作用域的時候呼叫一個函數,而在離開它的時候呼叫另一個函數,例如:在一塊程式碼執行之前取得一個,並且在此後釋放這個鎖;或事先打開一個檔案,並且事後關閉它。[f]
  • class陳述式,是定義的可執行陳述式。類的衍化列給出基礎類列表,沒有衍化列的類,預設繼承基礎類object。類的套件接着在新的執行框架(frame)中執行,它使用新建的局部名字空間和原來的全域名字空間。當這個類套件完成執行之時,丟棄它的執行框架並儲存它的局部名字空間。一個類對象接着被建立,其基礎類採用衍化列,其特性字典採用儲存的局部名字空間。類名字接着在原來的局部名字空間中,被繫結到這個類對象。
  • def陳述式,是定義函數方法的可執行陳述式。它的執行在當前局部名字空間中,將函數名字繫結到一個函數對象(對函數的可執行程式碼的包裝器)。這個函數對象包含到當前全域名字空間的參照,作為呼叫這個函數時使用的全域名字空間。
  • async def陳述式,用於協程函數定義。await表達式、async for陳述式和async with陳述式,只能用在協程函數的主體中。[g]

塊與模組 編輯

Python程式構造自程式碼。塊是作為一個單元執行的Python程式文字,模組、函數主體和類別定義都是塊。互動式鍵入的每個命令、指令碼檔案和指令碼命令都是程式碼塊。傳遞給內建函數eval()exec()執行的字串是程式碼塊。

程式碼塊在執行框架(frame)中執行。框架包含一些用於偵錯的管理資訊,並確定在這個程式碼塊執行完成後,執行在何處以及如何繼續。名字空間是儲存變數的地方,它被實現為字典。有局部名字空間、全域空間即包含此程式碼塊的那個模組的名字空間,和內建名字空間即模組builtins的名字空間;對象的方法是定義在類主體內的函數,它有着巢狀的名字空間。名字空間通過防止命名衝突而支援了模組性,還通過明晰了哪個模組實現了哪個函數而增進可讀性和可維護性。

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

完整的Python程式,在一個極小初始化的環境中執行:所有內建和標準模組均可獲得,但除了sys(各種系統服務)、builtins(內建函數、例外None)和__main__之外都未被初始化。__main__用來為完整程式的執行提供局部和全域名字。當直譯器被呼叫在互動模態下的時候,它一次一個的讀取並執行陳述式;初始環境同於完整程式,每個陳述式都在__main__的名字空間中執行。

頂層程式碼是啟動執行的首個用戶指定Python模組。__main__是頂層程式碼執行所在的環境。從命令列使用-m參數,作為頂層指令碼執行的模組(作為模組__main__)是程式碼塊。此時__name__變數被設置為"__main__",籍此可在這個模組中增加直接執行時候執行的程式碼[112][115]

名字是通用的參照持有者,它不關聯於一個固定的資料類型,但是,一個名字在給定時間,總是被繫結到有一個類型的某個對象上,這就是動態型別的特徵。名字的儲存位置不「包含」所指示的值,一個共同的值可以賦值給多個名字,一個名字在任何時候,都可以重新繫結到各種不同類型的對象上,包括字串、過程、具有數據和方法的複雜對象等。如果一個名字繫結在一個中,它是這個塊的局部變數,除非被聲明為nonlocalglobal。如果一個名字繫結在模組層次,它是全域變數。模組程式碼塊的變數,既是局部的也是全域的。如果一個變數使用在一個程式碼塊中,卻不定義在這裏,它是自由變數[116]

內建vars()函數,返回一個模組、類、實例或任何具有字典特性__dict__的對象的字典特性。內建globals()函數,返回實現當前模組的名字空間的一個字典。內建locals()函數,更新並返回表示當前局部符號表的一個字典。在函數塊中而非類塊中呼叫locals()之時,它返回自由變數。在模組層級上,locals()globals()返回同一個字典。內建dir()函數,在無參數時,返回在當前局部作用域內的名字列表;在有一個參數時,嘗試返回這個對象的有效特性的列表。[117]

在Python中賦值所進行的操作,是將一個名字繫結為到一個分立的動態分配的對象的一個參照。除了在塊中出現的每個賦值陳述式或匯入陳述式之外,下列構造也繫結名字:給函數的形式參數、類別定義、函數定義、賦值表達式、在for陳述式頭部中和各種as關鍵字之後的識別碼目標(target),as關鍵字出現在import陳述式、with陳述式、except子句、except*子句和結構式模式匹配的as模式之中。

作用域定義一個名字在一個中的可見性。如果一個局部變數被定義在一個塊中,它的作用域包括這個塊。如果這個定義出現在一個函數塊中,作用域擴充到在所界定作用域內包含的任何塊,除非所包含的塊為這個名字介入了不同的繫結。當一個名字在一個程式碼塊之中使用,它採用最近包圍作用域來解析。對一個程式碼塊可見的所有這種作用域的集合,叫做這個這個塊的「環境」[116]

如果一個名字繫結在一個塊中,並且在其中於繫結之前就被使用,會導致一個錯誤。[h] 如果global陳述式出現在一個塊之中,在這個陳述式中指定的所有名字,提及在頂層名字空間中這些名字的繫結。名字在頂層名字空間解析,首先尋找全域名字空間,未果尋找內建名字空間。global陳述式與在同一個塊中的名字繫結運算有同樣的作用域。如果一個自由變數的最近包圍作用域包含針對它的global陳述式,這個自由變數被當作全域的[116][i] 當一個函數或類的定義被巢狀到其他函數的定義之內,它的非局部作用域就是這個包圍函數的局部作用域。nonlocal陳述式導致其列出的識別碼,提及在非局部作用域內先前繫結的名字(即非局部變數英語Non-local variable[116][j]

表達式 編輯

Python中很多表達式英語Expression (computer science)C語言和java類似,而另一些則與之不同。

  • 在Python中,算術運算的加法+、減法-、乘法*取模%是與C語言和java相同的,但是除法的行為不同。在Python中有兩種除法,它們是下取整除法(或整數除法)//和浮點除法/。Python增加了指數算符**。自從Python 3.5,介入了矩陣乘法算符@[118],它已經用於了NumPy[119]
  • 在Python中,有如下必須用於整數的運算:&與(AND),|或(OR),~非(NOT),^異或(XOR),>>右移, <<左移。
  • 在Python中,有如下比較運算:大於>,小於<,等於==,不等於!=,小於等於<=,大於等於 >===按值比較。Python的isis not算符可以用來比較對象的同一性(按參照比較),也就是比較兩個變數是否參照了同一個對象。而innot in用於判斷一個對象是否屬於另外一個對象。在Python中,比較是可以連結起來的[120],比如a < b < c
  • Python使用andornot表示邏輯運算與、或、非,不採用C語言和Java中所用的符號&&||!
  • 在Python中,由逗號,分隔的一組表達式,叫做表達式列表。Python為構造列表、字典或集合,提供了叫做「顯示」的特殊語法,它們每個都有兩種方式:包容內容要麼顯式列舉出來;要麼通過一組迴圈和過濾指令計算而來,這叫做「推導式」。列表顯示是包圍在方括號中的可以為空的一系列表達式,一個例子列表可寫為[1,2,3]。字典顯示是包圍在花括號中的可能為空的一系列的鍵/數據項對。集合顯示用花括號來指示,與字典顯示的區別是缺少分隔鍵與值的分號[121]。自從Python 3.5,增加了在表達式列表中的「可迭代解包」*,和在字典顯示中的「字典解包」**[122][k]
  • 在Python中,加圓括號形式(parenthesized form),是包圍在圓括號中的一個可選表達式列表。加圓括號的表達式列表產生的東西,就是這個表達式列表所產生的:如果這個列表包含至少一個逗號,它產生一個元組;否則它產生構成這個表達式列表的那個單一表達式[124]。一個例子元組可寫為(1,2,3)。元組不是圓括號形成的,而是使用逗號形成的,在沒有歧義的情況下,元組的圓括號是可選的。空的圓括號對產生空元組對象。使用序列串接算符+來串接二個元組,產生包含給定元組二者的元素的一個新元組。
  • Python支援在序列對象(比如字串、元組或列表)上的下標(subscription)表達式:a[索引],和分片英語array slicing表達式:a[开始:停止]a[开始:停止:步长]。下標索引是基於零的,負數是相對於結尾的。分片範圍自從「開始」索引,直到但不包括「停止」索引。分片的第三個參數叫做「步長」(step)或「間隔」(stride),允許元素被跳過和用負數指示反向。分片索引可以省略,例如a[:],這返回整個列表的一個複本。[o]分片的每個元素都是淺層複製英語Object copying的。
  • Python的條件表達式表示為x if c else y。意思是當c為真時,表達式的值為x,否則表達式的值為y。 在運算元的次序上不同於很多其他語言中常見的c ? x : y
  • Python的匿名函數實現為lambda表達式。匿名函數體只能是一個表達式。[p]
  • 自從Python 3.8,介入了賦值表達式,其記號是:=[62]。它將一個表達式賦值給一個識別碼,同時還返回這個表達式的值。賦值表達式在用作子表達式,即位於分片表達式、條件表達式、lambda表達式、關鍵字參數中的表達式和推導式中的if表達式之中,以及在assertwith陳述式之中的時候,必須圍繞着圓括號。在它們可以使用的所有其他地方,包括在ifwhile陳述式之中,都不要求圓括號[125]

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

運算子 描述
(表达式...)[表达式...]{: ...}{表达式...} 加圓括號表達式,列表顯示,字典顯示,集合顯示
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提供了序列串接算符+和序列倍增算符*[127]。自從Python 3.9,介入了字典合併算符|和字典更新算符|=[128]

Python的文字序列類型,包括字串str和位元組序列bytesbytearray字串文字英語string literal有多種寫法,字串對象有一個內建格式算符%

  • 短字串文字,由單引號'或雙引號"界定。不同於Unix shellPerl和受Perl影響的語言,單引號和雙引號功能相同。這二種字串都使用反斜槓\作為跳脫字元
  • 長字串文字,是開始並結束於三個單引號'''或三個雙引號"""的序列。它們可以跨越多行,其功能就像shellPerlRuby中的here文件[q]
  • Python允許多個毗鄰的字串文字或位元組文字(它們以空白分界並可以使用不同的引述約定),在編譯時間於語法層面上串接起來。要在執行時間串接字串,必須使用序列串接算符+[129][s]
  • Python中的「字串格式」算符%,在功能上類同於C語言中的printf格式化字串[130],例如"spam=%s eggs=%04d" % ("blah", 2),求值為'spam=blah eggs=0002'。自從Python 3.0,str類提供了可供替代的format()方法[131],例如"spam={0} eggs={1:04d}".format("blah", 2)。在Python 3.6中,提供了「格式化字串文字」或稱為「f字串」,它向字串文字字首上fF[132],這是一種字串插值英語String interpolation[133],例如x="blah"; y=2; f'spam={x} eggs={y:04d}'[t]

在Python中,在表達式和陳述式之間的區別是嚴格強制性的,這對比於語言如Common LispSchemeRuby。故而Python中個別構造存在功能重複,比如:列表推導式相當for迴圈;條件表達式相當if陳述式;內建函數eval()相當exec(),前者用於表達式,後者用於陳述式。

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

函數 編輯

Python的函數支援遞歸閉包[u] ,及其他頭等函數特徵,但不支援函數多載。Python的函數作為頭等對象,具有和普通對象平等的地位。Python官方實現不提供尾呼叫最佳化或頭等續體,吉多·范羅蘇姆曾聲稱永遠都不會加以支援[134],目前只有第三方庫支援[135]

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

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

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

在位置和關鍵字形式參數序列末尾,可以分別有*args**kwargs這樣的形式參數,它們對應於在函數呼叫時提供的,超出形式參數序列規定而無所對應的多個實際參數;在形式參數名字前加一個*號,該形式參數argstuple類型,對應可變數目的位置實際參數;在形式參數名字前加**號,該形式參數kwargsdict類型,對應可變數目的關鍵字實際參數。[y]如果位置實際參數已經在一個序列類型如列表或元組的對象中,在參照它的變數前加一個*號傳遞給函數,則其中所有元素解包為多個位置實際參數;如果關鍵字實際參數在字典中,則加**號來傳遞給函數。

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

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

對象及其方法 編輯

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

Python使用名字修飾,有限的支援私有變數。對象的(可寫)特性可以被提取為一個字典[144]。在Python中,不強制使用訪問子變異子方法,來訪問數據成員的物件導向程式設計信條。就像Python提供函數式程式設計構造,但不嘗試要求參照透明性英語referential transparency一樣,它提供對象系統,但不要求物件導向程式設計行為。

對象方法,是附屬於這個對象的的函數。對於正常的方法和函數,語法instance.method(arguments),是Class.method(instance, arguments)語法糖。Python的方法有顯式的self英語this (computer programming)形式參數,用來訪問實例數據;這借鑑自Modula-3,對立於隱式的selfthis英語this (computer programming)關鍵字,它們用在其他一些物件導向程式設計語言,比如C++JavaObjective-CRuby之中[145]。在Python中,self可以被看作是一個習慣用法,它可以被換為任何其它合法的參數名。[ad]

Python提供了super()內建函數,在一個類的方法中呼叫此函數返回一個代理(proxy)對象,它將其方法呼叫委託給這個類的父類別或兄弟類[146],當一個子類的方法覆蓋超類方法的時候,可通過呼叫super().method,來呼叫與子類的self.method方法同名超類別方法。[ae] Python支援一些以__開始和結束的特殊方法名,它們用於實現運算子多載,以及實現多種特殊功能[74]。在Python中,可以通過定義特殊方法來多載運算子,比如在一個類上定義__add__(),將允許在這個類別的實例上使用+算符。

在Python中,定義了一個或多個特殊方法__get__()__set__()__delete__()的類,可以用作描述器(descriptor)[147]。建立一個描述器的實例,作為另一個類的一個類別成員,使得這個實例成為此另一個類的屬性(property)。使用與特性(attribute)訪問相同的語法,訪問一個實例對象中的這個成員屬性。[af]

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

類型 編輯

 
Python 3的標準類型層級[149]

Python使用鴨子型別,並擁有有類型的對象,和無類型的變數名字。在編譯期不檢查類型約束,而寧願在一個對象上的操作出現可能的失敗,表現出這個給定對象不具有適合的類型。儘管是動態型別系統,Python卻是強型別的,禁止沒有明確定義的操作(比如加一個數到一個字串),而不是默默的去嘗試轉換使其有意義。Python支援廣泛的類型和類的內省。類型是type的實例,可以被讀取和比較。

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

Python有一個非常有用特徵,就是搜集(或稱容器)類型的概念。一般的說,搜集是以一種易於參照或索引的方式,包含其他對象的對象。搜集有二種基本形式:序列和對映。Python對建立容器類型的對象有着語法上的支援。[ai]Python還提供了廣泛的搜集操縱能力,比如內建的包含元素檢查和通用迭代協定

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

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

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

Python允許程式者使用,定義自己的類型[50],類是在物件導向程式設計中最經常使用的。類的新實例,是通過呼叫這個類的構造器而建立的,而類都是元類type的實例,typetype元類自身的實例,這允許了元程式設計反射[aj]

在版本3.0之前,Python有兩種類:舊式的和新式的[150]。二種樣式的語法是一樣的,不同在於是否直接或間接的繼承自類object,所有新式類都從object繼承,並且是type的實例。在Python 2系列2.2以上,二種類都可以使用[50]。在Python 3.0中淘汰了舊式類。

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

Python 3內建類型小結
類型 可變性 描述 語法例子
bool 不可變 布林值,有表示值FalseTrue的兩個對象。作為整數類型numbers.Integral的子類型,它們在幾乎所有上下文中,表現得如同01,除了在轉換成字串時轉換為"False""True"之外。 True
False
int 不可變 整數,其大小在理論上無限制,實際上受限於記憶體[152] 42
float 不可變 雙精度浮點數,確切精度依賴於機器。一般實現為IEEE 754標準binary64浮點數,它有53個二進制有效數碼精度[153] 1.414
complex 不可變 複數,即分別表示實部與虛部的兩個雙精度浮點數的有序對 3+2.7j
range 不可變 數的序列,通常用在for迴圈中指定迴圈次數[154] range(1, 10)
range(10, -5, -2)
str 不可變 字串,即Unicode程式碼點序列。字串中的程式碼點都在範圍U+0000..U+10FFFF之內。Python沒有char類型,這些程式碼點都表示為長度為1的字串對象。
'Wikipedia'
"Wikipedia"
"""Spanning
multiple lines"""
bytes 不可變 位元組序列,其專案是8位元位元組,用範圍0 <= x < 256的整數表示。 b'Some ASCII'
b"Some ASCII"
bytes([0x53, 0x74, 0x72])
bytearray 可變 bytearray(b'Some ASCII')
bytearray(b"Some ASCII")
bytearray([0x53, 0x74, 0x72])
list 可變 列表,可以包含任意的Python對象。 [4.0, 'string', True]
[]
tuple 不可變 元組,可以包含任意的Python對象。只有一個專案的元組,可以通過向表達式字尾一個逗號來形成。 (4.0, 'string', True)
('single element',)
()
dict 可變 鍵-值關聯陣列(常稱為字典),即由任意索引集合來索引的對象的有限集合英語Set (abstract data type)。不可接受為鍵的值,是列表或字典,或按值而非對象同一性比較的其他可變類型的值,其雜湊值不能保持恆定。 {'key1': 1.0, 3: False}
{}
set 可變 無序有限集合英語Set (abstract data type),包含唯一性的不可變的對象,它們不能用任何下標來索引。 {4.0, 'string', True}
set()
frozenset 不可變 frozenset([4.0, 'string', True])
types.EllipsisType 不可變 這個類型有一個單一對象作為值,它通過文字...或內建名字Ellipsis英語Ellipsis (programming operator)來訪問,它的真值為真。它用於NumPy多維陣列索引[155] ...
Ellipsis
types.NoneType 不可變 這個類型有叫做None的一個單一對象Null作為值[156],它被用來指示值的缺席,比如不返回任何東西的函數返回它,它的真值為假。 None
types.NotImplementedType 不可變 這個類型有一個單一對象NotImplemented作為值。數值方法和細化比較方法,在它們仍未對提供的運算元實現這個運算之時,返回這個值。它不應該在布林值上下文中求值。 NotImplemented

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

數學 編輯

Python的算術運算,使用平常的符號+-*/模除%(這裏的餘數可以是負數,比如4 % -3 == -2)。它還有下取整除法算符//指數算符**,比如5**3 == 1259**0.5 == 3.0,和矩陣乘法算符@[118]。這些算符就像在傳統數學中一樣運算,具有同樣的優先級規則中綴算符+-,還可以分別表示取原數和取相反數一元算符。

在整數之間的除法/,產生浮點數結果。除法/的表現,隨着版本不同而有着顯著變化[157]。 Python提供了round()內建函數,用於把一個浮點數修約成最近的整數[158]

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

Python對所有整數運算,使用任意精度算術。在decimal模組中的Decimal[160],提供十進制浮點數英語Decimal floating point,具有用戶可按需要而更改的預設28個十進制有效數碼精度,並有多種修約方式[161]。在fractions模組中的Fraction類,提供任意精度的有理數[162]

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

標準庫 編輯

Python擁有一個強大的標準庫[165]。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直譯器[166]。Python屬於動態語言,其官方實現將Python程式編譯成中間形式的位元組碼[167],並接着在它的虛擬機器上執行[168],相較於C/C++和java的等編譯語言而言執行速度較慢[169]

活躍開發的實現
  • CPython:官方的直譯器,需要區別於其他直譯器的時候才以CPython稱呼。CPython採用了全域直譯器鎖(GIL),確保在任何時刻只有一個線程執行Python位元組碼;一些擴充模組被設計為在進行計算密集任務時釋放GIL,還有在進行I/O時總是釋放GIL[170]
  • PyPy:用RPython編寫的Python實現,相容至CPython版本3.10、3.9和2.7,它採用了跟蹤JIT英語Tracing just-in-time compilation,預設支援stackless模態。
  • MicroPython:為微控制器而最佳化的Python 3變體,它實現了完整的Python 3.4語法,和補充自版本3.5的async/await關鍵字,和後來版本的一些選定特徵;它提供了實現Python標準庫模組功能子集的內建模組,和特定於微控制器的一些模組。CircuitPython英語CircuitPythonAdafruit英語Adafruit Industries開發的MicroPython分叉。
  • Pyston:CPython 3.8.12的分叉,具有包括JIT的效能最佳化[8]。其JIT部份,單獨發行為擴充模組pyston_lite_autoload,它支援Python3.7—3.10[171]
  • Cinder:由Meta開源釋出,它是Meta內部使用的面向效能的CPython 3.10分叉,具有包括JIT的很多最佳化[172]
  • Codon:使用了LLVM的高效能Python編譯器[173],它將Python程式碼編譯成本機機械碼,不帶有任何執行時開銷,並且支援本機多線程,它由MIT CSAIL的研究人員開發[174]
  • Pyodide:基於WebAssembly/Emscripten的用於瀏覽器Node.js的Python釋出[175],支援任何在PyPIwheel形式的純Python包,並且已經移植了很多具有C語言擴充的包。
  • RustPython:用Rust編寫的Python直譯器[9],它可以嵌入到Rust應用程式中從而將Python用作手稿語言,還可以被編譯成WebAssembly從而在瀏覽器中執行Python程式碼。
  • Brython:用JavaScript編寫的在瀏覽器中執行的Python 3實現[176],具有到DOM元素和事件的介面。
到其他語言的交叉編譯器

仍在維護中的舊版本實現有:Stackless Python,它是實現微線程英語microthread的CPython 3.8分叉;IronPython,它是建造在動態語言執行時(DLR)之上的Python 2.7和Python 3.4實現;Jython,它是用Java實現的Python 2.7。

開發環境 編輯

通用文字編輯器 編輯

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

專用開發環境 編輯

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

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

第三方擴充包 編輯

 
Python Powered

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

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

網絡服務 編輯

Python定義了WSGI標準應用介面,來協調HTTP伺服器與基於Python的Web程式之間的溝通。比如,通過mod_wsgi英語mod_wsgi模組,Apache可以運行用Python編寫的Web程式。Zope是著名的用Python編寫的開源的Web應用伺服器Tornado是用Python語言寫成的非阻塞式web伺服器,也是輕量級的Web框架。

Python對於各種網絡協定的支援很完善,因此適用於編寫伺服器軟體、網絡爬蟲等Web開發。用Python編寫的一些Web框架,有助於輕鬆地開發和管理複雜的Web程式。著名的第三方Web框架和函數庫:

  • Django:MTV架構[187]的Web開發框架,注重組件的重用性和「可插拔性」、快速開發DRY法則
  • web2py:MVC架構的全棧Web框架,聚焦於快速開發,偏好約定優於組態方式。
  • Pyramid:極簡主義的Web框架,不預定持久化方式,它是Pylons計劃的一部分。
  • Flask:微Web框架,不要求特定的工具或庫。
  • Twisted事件驅動的網絡程式框架。它支援多數標準的網絡協定(包含客戶端和伺服器),並且提供了多種工具,適用於編寫高效能的伺服器軟體。
  • Requests:適合於常人使用的HTTP庫,封裝了許多繁瑣的HTTP功能,極大地簡化了HTTP請求所需要的程式碼量。
  • Beautiful Soup:用來解析HTML/XML的一個簡單易用Python包。
  • uvloop:是對內建asyncio事件迴圈的快速的、直截了當的替代者[188],它用Cython實現並在底層使用了libuv
  • aiohttp:基於asyncio的HTTP客戶端和伺服器二者[189]

圖形化使用者介面 編輯

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的庫而提供的包裝庫[190],GObject是GTKGIO英語GIO (software)GStreamer等庫使用的對象系統。
  • Kivy:用於開發多點觸控應用軟體的開源Python庫,採用了自然用戶介面(NUI)。
  • WxPython:GUI程式框架wxWidgets的Python包裝庫,它與MFC的架構相似。
  • PySimpleGUI:將Tkinter、Qt、WxPython和Remi[191]的GUI框架變換成簡單的介面[192]
  • Gooey:將幾乎所有Python 3控制台程式用一行程式碼轉變成GUI應用[193]
  • Dear PyGui:快速而強力的具有極小依賴性的GUI工具箱[194]
  • pywebview:輕量級跨平台的對WebView英語WebView構件的包裝器,允許在其本地GUI窗口中顯示HTML內容[195]

數據科學 編輯

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

數據視覺化 編輯

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

  • Bokeh:針對現代Web瀏覽器的互動式數據視覺化[202],它提供了優雅而簡明的功能各異的圖形構造,並跨越大型或串流數據集提供高效的互動性。
  • HoloViz:提供了一組Python軟件套件使得數據視覺化更加容易、精確和強力[203]:Panel用來為出自任何支援的繪圖庫的繪圖製作應用和儀錶板[204],hvPlot用來快速的從數據生成互動式繪圖,HoloViews用來使所有數據即刻視覺化,GeoViews用來將HoloViews擴充至地理數據,Datashader用來呈現非常巨大的數據集,Lumen用來從簡單的YAML規定建造數據驅動的儀錶板,Param用來建立聲明式用戶可組態的對象,Colorcet提供在感知上均勻的顏色對映。
  • Dash:將現代用戶介面元素如下拉選單滑動條英語Slider (computing)圖形,直接連結至分析型Python程式碼的框架[205],它基於ReactFlaskPlotly英語Plotly公司的Plotly.js[206]
  • Streamlit:迅速將數據指令碼轉變為可共用Web應用的框架[207]
  • Voilà:將Jupyter Notebook轉變為獨立的Web應用的框架[208]
  • VisPy:高效能互動式2D/3D數據視覺化[209],它通過OpenGL庫利用現代GPU的計算能力,來顯示非常大的數據集
  • glumpy:用於科學數據視覺化的快速、可伸縮且美觀的Python庫[210],它提供了在NumPy與現代OpenGL之間的自然介面。

機器學習 編輯

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

其它種類 編輯

應用 編輯

在很多作業系統裏,Python是標準的系統元件,它被列入Linux標準規範之中[240]。大多數Linux發行版macOS都整合了Python,可以在終端模擬器虛擬控制台英語Virtual console下直接執行Python。pipx可以將Python應用安裝於隔離的環境中並在其中執行它[241]

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

應用程式 編輯

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

人工智能 編輯

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

社群流行 編輯

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

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

影響的語言 編輯

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

Ruby的建立者松本行弘曾說過:「我想要一種手稿語言,比Perl更加強力而且比Python更加物件導向,因此我決定設計自己的語言」[28]Julia設計原則中有一條是:「像Python一樣可用於通用程式」[27]

程式碼範例 編輯

  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. ^ 採用了並列賦值的斐波那契數列函數範例:
    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()
    
  3. ^ 產生素數的惰性生成器的範例:
    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))
    
  4. ^ 用生成器模擬協程範例:
    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()
    
  5. ^ 遵循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()
    
  6. ^ 使用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("文件写入完全成功")
    
  7. ^ 原生的協程範例:
    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())
    
  8. ^ 局部變數範例:
    >>> 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
    
  9. ^ 全域變數範例:
    >>> 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
    
  10. ^ 非局部變數範例:
    >>> 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
    
  11. ^ 序列解包、可迭代解包和字典解包範例:
    >>> a = [1, 2, 3]; b = [4, 5]
    >>> i, j, k = a
    >>> print(i, j, k)
    1 2 3
    >>> 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}
    
  12. ^ 列表的推導式範例。比如:
    >>> [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]))
    
  13. ^ 生成器表達式範例。比如:
    >>> 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}
    
  14. ^ 字典推導式{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}
    
  15. ^ 下面幾個判斷陳述式為真,表示列表分片結果符合預期:
    >>> 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
    
  16. ^ 匿名函數範例:
    >>> 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. [2020-10-21]. (原始內容存檔於2021-01-11). 其原理可參見Equational derivations of the Y combinator and Church encodings in Python. [2020-10-21]. (原始內容存檔於2020-11-12). 

  17. ^ 多行字串文字帶有字串插值英語String interpolation(使用了format方法)的範例:
    print("""亲爱的{recipient},
    
    我希望你离开Sunnydale并永不返回.
    
    不是很爱你的,
    {sender}
    """.format(sender="吸血鬼猎人Buffy", recipient="Spike"))
    
  18. ^ 原始字串的範例:
    >>> # 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)'
    >>> # 注意如果实际参数中有圆括号或逗号则上例无效。
    
  19. ^ 字串文字串接範例:
    >>> print("hello " 'world')
    hello world
    >>> str1="hello "; str2='world'
    >>> print(str1 + str2)
    hello world
    
  20. ^ 格式化字串的範例,例如下列命令列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})
    
  21. ^ 詞法閉包的例子:
    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)是个闭包。
    
  22. ^ 函數的形式參數預設值的永續性範例:
    >>> def f(a, L=[]):
    ...     L.append(a)
    ...     return L
    ... 
    >>> print(f(1))
    [1]
    >>> print(f(2))
    [1, 2]
    >>> print(f(3))
    [1, 2, 3]
    
  23. ^ 函數的形實參數二者結合範例。例如:
    >>> 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
    
  24. ^ 函數的形式參數預設值的定義範例:
    >>> 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={})
    
  25. ^ 函數的可變參數的定義範例:
    >>> 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={})
    
  26. ^ 定義修飾器的範例:
    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
    
  27. ^ 修飾器工廠範例,這裏的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.")
    

    使用中間變數連結修飾器範例:

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

    它們等價於:

    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.
    
  28. ^ 呼叫函數使用幫助資訊範例。比如:
    >>> 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.
    
  29. ^ 如下這樣給參數增加類型標註的提示資訊:
    >>> def greeting(name: str) -> str:
    ...     return 'Hello ' + name
    ... 
    >>> greeting.__annotations__
    {'name': <class 'str'>, 'return': <class 'str'>}
    
  30. ^ 對象的方法範例:
    >>> 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()
    >>> status(e)
    Hungray!
    >>> Fish.hungry = False
    >>> from types import MethodType
    >>> e.status = MethodType(status, e)
    >>> e.status()
    Not hungray!
    >>> Fish.hungry = True
    >>> Fish.status = status
    >>> f = Fish()
    >>> Fish.status(f)
    Hungray!
    >>> f.eat("earthworm")
    >>> f.status()
    Not hungray!
    
  31. ^ 特殊方法和子類呼叫超類別方法的例子:
    >>> 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()
    我觉得我在平行宇宙中把车停歪了.
    
  32. ^ 在類中採用數據描述器的範例:
    >>> 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}
    
  33. ^ 特殊方法、類別方法和靜態方法(__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
    
  34. ^ 在類中呼叫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__'}
    
  35. ^ 建立列表的特殊語法範例:
    a_list = [1, 2, 3, 'a dog']
    

    採用正常的對象建立方式的範例:

    a_second_list = list()
    a_second_list.append(4)
    a_second_list.append(5)
    

    建立元組的特殊語法範例:

    a_tuple = 1, 2, 3, 'four'
    

    建立集合的特殊語法範例:

    some_set = {0, (), False}
    

    建立字典的特殊語法範例:

    a_dictionary = {'key 1': 'value 1', 2: 3, 4: []}
    
  36. ^ 兩個類及元類等的實例關係(藍色連接)與繼承關係(綠色連接)示意圖:
     
    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'> ()
    
  37. ^ 數學運算範例。比如:
    >>> 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. ^ 2.0 2.1 Python 3.12.3 and 3.13.0a6 released. 2024年4月9日 [2024年4月9日] (英語). 
  3. ^ 3.0 3.1 Glossary — duck-typing. [2023-06-28]. (原始內容存檔於2020-06-25). 
  4. ^ Why is Python a dynamic language and also a strongly typed language - Python Wiki. wiki.python.org. [2021-01-27]. (原始內容存檔於2021-03-14). 
  5. ^ 5.0 5.1 PEP 483 – The Theory of Type Hints. [2023-03-16]. (原始內容存檔於2023-03-26). 
  6. ^ File extension .pyo was removed in Python 3.5. See PEP 0488頁面存檔備份,存於互聯網檔案館
  7. ^ Holth, Moore. PEP 0441 -- Improving Python ZIP Application Support. 2014-03-30 [2015-11-12]. (原始內容存檔於2018-12-26). 
  8. ^ 8.0 8.1 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 ……. 
  9. ^ 9.0 9.1 RustPython. [2022-03-04]. (原始內容存檔於2022-04-24). 
  10. ^ Starlark Language. [25 May 2019]. (原始內容存檔於2020-06-15). 
  11. ^ 11.0 11.1 11.2 Why was Python created in the first place?. Python FAQ. [2007-03-22]. (原始內容存檔於2008-02-23). 
  12. ^ Andrew Kuchling, Guido van Rossum. LJ Interviews Guido van Rossum. November 1, 1998 [2023-03-21]. (原始內容存檔於2023-03-30). String slicing came from Algol-68 and Icon. 
  13. ^ 13.0 13.1 The Python Standard Library - Functional Programming Modules - itertools — Functions creating iterators for efficient looping. [2020-04-22]. (原始內容存檔於2020-06-14). 
  14. ^ 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. 
  15. ^ 15.0 15.1 The Python Tutorial - 9. Classes. [20 February 2012]. (原始內容存檔於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. 
  16. ^ 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. 
  17. ^ 17.0 17.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. 
  18. ^ Kuchling, A. M. Functional Programming HOWTO. Python v2.7.2 documentation. Python Software Foundation. [9 February 2012]. (原始內容存檔於2012-10-24). 
  19. ^ 19.0 19.1 19.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.
     
  20. ^ Smith, Kevin D.; Jewett, Jim J.; Montanaro, Skip; Baxter, Anthony. PEP 318 – Decorators for Functions and Methods. Python Enhancement Proposals. Python Software Foundation. 2 September 2004 [24 February 2012]. (原始內容存檔於2020-06-03). 
  21. ^ More Control Flow Tools. Python 3 documentation. Python Software Foundation. [24 July 2015]. (原始內容存檔於2016-06-04). 
  22. ^ 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. 
  23. ^ CoffeeScript. coffeescript.org. [2021-03-14]. (原始內容存檔於2020-06-12). 
  24. ^ The Genie Programming Language Tutorial. [28 February 2020]. (原始內容存檔於2020-06-01). 
  25. ^ Perl and Python influences in JavaScript. www.2ality.com. 24 February 2013 [15 May 2015]. (原始內容存檔於2018-12-26). 
  26. ^ Rauschmayer, Axel. Chapter 3: The Nature of JavaScript; Influences. O'Reilly, Speaking JavaScript. [15 May 2015]. (原始內容存檔於2018-12-26). 
  27. ^ 27.0 27.1 Why We Created Julia. Julia website. February 2012 [2014-06-05]. (原始內容存檔於2020-05-02). We want something as usable for general programming as Python [...] 
  28. ^ 28.0 28.1 An Interview with the Creator of Ruby. Linuxdevcenter.com. [2012-12-03]. (原始內容存檔於2018-04-28). 
  29. ^ 29.0 29.1 Lattner, Chris. Chris Lattner's Homepage. Chris Lattner. 3 June 2014 [3 June 2014]. (原始內容存檔於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. 
  30. ^ 彼德·諾米格. 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). 
  31. ^ Rossum, Guido Van. The History of Python: A Brief Timeline of Python. The History of Python. 2009-01-20 [2021-03-05]. (原始內容存檔於5 June 2020). 
  32. ^ Peterson, Benjamin. Python Insider: Python 2.7.18, the last release of Python 2. Python Insider. 20 April 2020 [27 April 2020]. (原始內容存檔於26 April 2020). 
  33. ^ Stack Overflow Developer Survey 2020. Stack Overflow. [2021-03-05]. (原始內容存檔於2 March 2021). 
  34. ^ The State of Developer Ecosystem in 2020 Infographic. JetBrains: Developer Tools for Professionals and Teams. [2021-03-05]. (原始內容存檔於1 March 2021) (英語). 
  35. ^ index | TIOBE - The Software Quality Company. www.tiobe.com. [2021-02-02]. (原始內容存檔於25 February 2018). Python has won the TIOBE programming language of the year award! This is for the fourth time in the history, which is a record! The title is awarded to the programming language that has gained most popularity in one year. 
  36. ^ PYPL PopularitY of Programming Language index. pypl.github.io. [2021-03-26]. (原始內容存檔於14 March 2017) (英語). 
  37. ^ Guido van Rossum - Resume. [2022-10-12]. (原始內容存檔於2022-12-21). 
  38. ^ amoeba operating system. [2023-02-25]. (原始內容存檔於2023-03-05). 
  39. ^ Whetting Your Appetite. The Python Tutorial. Python Software Foundation. [2012-02-20]. (原始內容存檔於2012-10-26). 
  40. ^ Benevolent dictator for life. Linux Format. 2005-02-01 [2007-11-01]. (原始內容存檔於2006-10-01). 
  41. ^ Transfer of power. [2020-11-29]. (原始內容存檔於2018-07-12). 
  42. ^ PEP 8100. python. Python Software Foundation. [2019-05-04]. (原始內容存檔於2020-06-04). 
  43. ^ Steering Council nomination: Guido van Rossum (2020 term). [2020-10-11]. (原始內容存檔於2019-12-29). 
  44. ^ The Making of Python. Artima Developer. [2007-03-22]. (原始內容存檔於2016-09-01). 
  45. ^ Older source releases (1.0.1 - 1.6). [2023-03-05]. (原始內容存檔於2023-03-05). 
  46. ^ 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())! 
  47. ^ LJ #37: Python 1.4 Update. [2007-04-29]. (原始內容存檔於2007-05-01). 
  48. ^ Kuchling, A. M.; Zadka, Moshe. What's New in Python 2.0. Python Software Foundation. 2000-10-16 [2012-02-11]. (原始內容存檔於2012-10-23). 
  49. ^ Hylton, Jeremy. PEP 227 - Statically Nested Scopes. 2000-11-01 [2007-03-22]. (原始內容存檔於2007-03-29). 
  50. ^ 50.0 50.1 50.2 Guido van Rossum. Unifying types and classes in Python 2.2. [2020-09-26]. (原始內容存檔於2019-09-28). 
  51. ^ What’s New in Python 2.2 - PEP 234: Iterators. [2020-10-21]. (原始內容存檔於2021-02-07). 
  52. ^ What’s New in Python 2.2 - PEP 255: Simple Generators. [2020-10-21]. (原始內容存檔於2021-02-07). 
  53. ^ What’s New in Python 2.2 - Descriptors. [2020-10-21]. (原始內容存檔於2021-02-07). 
  54. ^ 54.0 54.1 54.2 What’s New in Python 2.4 - PEP 318: Decorators for Functions and Methods. [2020-10-21]. (原始內容存檔於2021-02-07). 
  55. ^ What’s New in Python 2.5 - PEP 343: The ‘with’ statement. [2020-10-21]. (原始內容存檔於2021-02-07). 
  56. ^ PEP 339 – Design of the CPython Compiler. 2005 [2023-03-06]. (原始內容存檔於2023-03-06). 
  57. ^ Guido van Rossum. What’s New In Python 3.0. [2023-02-18]. (原始內容存檔於2012-11-02). 
  58. ^ Automated Python 2 to 3 code translation — Python Documentation. [2018-02-11]. (原始內容存檔於2020-06-04). 
  59. ^ What’s New In Python 3.4 - asyncio. [2023-02-22]. (原始內容存檔於2023-06-13). 
  60. ^ What’s New In Python 3.5 - PEP 484 - Type Hints. [2023-02-25]. (原始內容存檔於2016-06-18). 
  61. ^ PEP 492 - Coroutines with async and await syntax. [2019-11-21]. (原始內容存檔於2019-01-05). 
  62. ^ 62.0 62.1 What’s New in Python 3.8 - Assignment expressions. [2023-03-08]. (原始內容存檔於2021-06-01). 
  63. ^ Paul Krill, Guido Van Rossum. Guido van Rossum resigns: What’s next for Python. Jul 27, 2018 [2023-03-19]. (原始內容存檔於2023-03-19). 
  64. ^ 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). 
  65. ^ What’s New In Python 3.9 - New Parser. [2023-02-22]. (原始內容存檔於2020-10-07). 
  66. ^ What’s New In Python 3.10 - PEP 634: Structural Pattern Matching. [2023-02-22]. (原始內容存檔於2023-06-11). 
  67. ^ 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). 
  68. ^ What’s New In Python 3.11 - Faster CPython. [2023-03-24]. (原始內容存檔於2023-06-13). 
  69. ^ What’s New In Python 3.11 - PEP 654: Exception Groups and except*. [2023-10-20]. (原始內容存檔於2023-06-13). 
  70. ^ What’s New In Python 3.12 — PEP 695: Type Parameter Syntax. [2023-10-20]. (原始內容存檔於2023-11-13). 
  71. ^ PEP 373 -- Python 2.7 Release Schedule. python.org. [2017-01-09]. (原始內容存檔於2020-05-19). 
  72. ^ Python Developer's Guide — Status of Python Version. devguide.python.org. [2022-08-26]. (原始內容存檔於2022-08-26). 
  73. ^ PEP 8105 – 2024 Term Steering Council election. Python Software Foundation. 
  74. ^ 74.0 74.1 The Python Language Reference - 3. Data model - Special method names. [2020-09-25]. (原始內容存檔於2012-10-26). 
  75. ^ aspectlib. [2020-09-28]. (原始內容存檔於2014-11-05). aspectlib is an aspect-oriented programming, monkey-patch and decorators library. It is useful when changing behavior in existing code is desired. 
  76. ^ 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. 
    • PyContracts. [2021-01-17]. (原始內容存檔於2021-01-22). PyContracts is a Python package that allows to declare constraints on function parameters and return values. 
    • dpcontracts. [2021-01-17]. (原始內容存檔於2021-01-22). This module provides a collection of decorators that makes it easy to write software using contracts. 
  77. ^ PyDatalog. [2012-07-22]. (原始內容存檔於2020-06-13). 
  78. ^ Extending and Embedding the Python Interpreter: Reference Counts. Docs.python.org. [2020-06-05]. (原始內容存檔於2012-10-18) (英語). Since Python makes heavy use of malloc() and free(), it needs a strategy to avoid memory leaks as well as the use of freed memory. The chosen method is called reference counting. 
  79. ^ Functional Programming HOWTO. [2020-09-26]. (原始內容存檔於2012-10-24). 
  80. ^ van Rossum, Guido. The fate of reduce() in Python 3000. Artima Developer. [2007-03-22]. (原始內容存檔於2007-04-07). 
  81. ^ Functional Programming Modules. Docs.python.org. [2020-09-26]. (原始內容存檔於2020-09-20). 
  82. ^ 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. 
  83. ^ 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. 
  84. ^ The Python Standard Library - Generic Operating System Services - ctypes — A foreign function library for Python. [2022-01-14]. (原始內容存檔於2022-04-27). 
  85. ^ PEP 523 – Adding a frame evaluation API to CPython. [2022-08-29]. (原始內容存檔於2022-08-29). 
  86. ^ The Python Language Reference - 2. Lexical analysis - Explicit line joining. [2023-02-17]. (原始內容存檔於2018-01-09). 
  87. ^ The Python Language Reference - 2. Lexical analysis - Implicit line joining. [2023-03-10]. (原始內容存檔於2018-01-09). 
  88. ^ The Python Language Reference - 2. Lexical analysis - Comments. [2023-03-11]. (原始內容存檔於2018-01-09). 
  89. ^ 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
     
  90. ^ The Python Language Reference - 8. Compound statements. [2023-02-18]. (原始內容存檔於2019-11-27). 
  91. ^ 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
     
  92. ^ PEP 8 – Style Guide for Python Code - Indentation. [2020-09-26]. (原始內容存檔於2018-07-13). 
  93. ^ The Python Language Reference - 2. Lexical analysis - Indentation. [2023-02-18]. (原始內容存檔於2018-01-09). 
  94. ^ The Python Language Reference - 2. Lexical analysis - Keywords. [2020-09-26]. (原始內容存檔於2018-01-09). 
  95. ^ What’s New In Python 3.0 - Overview Of Syntax Changes. [2023-02-18]. (原始內容存檔於2012-11-02). 
  96. ^ What’s What’s New In Python 3.5 - New Keywords. [2016-06-01]. (原始內容存檔於2016-06-18). 
  97. ^ What’s New In Python 3.7. [2019-11-21]. (原始內容存檔於2019-11-28). 
  98. ^ The Python Language Reference - 2. Lexical analysis - Soft Keywords. [2023-03-03]. (原始內容存檔於2018-01-09). 
  99. ^ PEP 8 – Style Guide for Python Code - Naming Conventions. [2017-10-06]. (原始內容存檔於2018-07-13). 
  100. ^ The Python Language Reference - 2. Lexical analysis - Reserved classes of identifiers. [2023-03-03]. (原始內容存檔於2018-01-09). 
  101. ^ 101.0 101.1 9.6. Private Variables. [2020-09-27]. (原始內容存檔於2012-10-23). 
  102. ^ The Python Language Reference - 7. Simple statements - Augmented assignment statements. [2023-03-08]. (原始內容存檔於2023-06-06). 
  103. ^ The Python Tutorial - 5. Data Structures - Tuples and Sequences. [2018-10-17]. (原始內容存檔於2020-06-10). 
  104. ^ The Python Language Reference - 6. Expressions - Yield expressions. [2023-03-15]. (原始內容存檔於2022-09-07). 
  105. ^ 105.0 105.1 PEP 342 - Coroutines via Enhanced Generators. [2019-11-21]. (原始內容存檔於2020-05-29). 
  106. ^ The Python Language Reference - 7. Simple statements - The yield statement. [2023-03-15]. (原始內容存檔於2023-06-06). 
  107. ^ PEP 380 - Syntax for Delegating to a Subgenerator. [2019-11-21]. (原始內容存檔於2020-06-04). 
  108. ^ PEP 3156 – Asynchronous IO Support Rebooted: the “asyncio” Module - Coroutines. [2019-11-21]. (原始內容存檔於2019-11-14). 
  109. ^ Generator-based Coroutines. [2020-10-29]. (原始內容存檔於2018-12-31). Support for generator-based coroutines is deprecated and is scheduled for removal in Python 3.10. 
  110. ^ PEP 525 – Asynchronous Generators. [2023-03-16]. (原始內容存檔於2023-05-21). 
  111. ^ 111.0 111.1 The Python Language Reference - 7. Simple statements - The import Statement. [2020-10-30]. (原始內容存檔於2021-02-07). 
  112. ^ 112.0 112.1 112.2 The Python Tutorial - 6. Modules. [2020-10-30]. (原始內容存檔於2021-02-06). 
  113. ^ PEP 343 – The “with” Statement. [2020-09-26]. (原始內容存檔於2014-12-14). 
  114. ^ The Python Language Reference - 5. The import system - Packages. [2023-03-07]. (原始內容存檔於2022-08-27). 
  115. ^ The Python Standard Library - Python Runtime Services - __main__ — Top-level code environment. [2020-10-30]. (原始內容存檔於2021-02-07). 
  116. ^ 116.0 116.1 116.2 116.3 The Python Language Reference - 4. Execution model - Naming and binding. [2023-03-06]. (原始內容存檔於2022-09-08). 
  117. ^ The Python Standard Library - Built-in Functions. 
  118. ^ 118.0 118.1 What’s New In Python 3.5 - PEP 465 - A dedicated infix operator for matrix multiplication. [2023-03-08]. (原始內容存檔於2016-06-18). 
  119. ^ NumPy Reference - Routines - Linear algebra (numpy.linalg) - numpy.matmul. [2022-01-18]. (原始內容存檔於2022-04-10). 
  120. ^ 120.0 120.1 The Python Language Reference - 6. Expressions - Comparison. [2023-03-21]. (原始內容存檔於2022-09-07). 
  121. ^ The Python Language Reference - 6. Expressions - Displays for lists, sets and dictionaries. [2023-03-13]. (原始內容存檔於2022-09-07). 
  122. ^ What’s New In Python 3.5 - PEP 448 - Additional Unpacking Generalizations. [2023-03-08]. (原始內容存檔於2016-06-18). 
  123. ^ Hettinger, Raymond. PEP 289 – Generator Expressions. Python Enhancement Proposals. Python Software Foundation. 2002-01-30 [2012-02-19]. (原始內容存檔於2020-06-14). 
  124. ^ The Python Language Reference - 6. Expressions - Parenthesized forms. [2023-03-13]. (原始內容存檔於2022-09-07). 
  125. ^ The Python Language Reference - 6. Expressions - Assignment expressions. [2023-03-08]. (原始內容存檔於2022-09-07). 
  126. ^ The Python Language Reference - 6. Expressions - Operator precedence. [2023-03-12]. (原始內容存檔於2022-09-07). 
  127. ^ The Python Standard Library - Built-in Types - Common Sequence Operations. [2023-03-17]. (原始內容存檔於2020-06-14). 
  128. ^ What’s New in Python 3.9 - Dictionary Merge & Update Operators. [2021-06-12]. (原始內容存檔於2020-10-07). 
  129. ^ The Python Language Reference - 2. Lexical analysis - String literal concatenation. [2023-03-12]. (原始內容存檔於2018-01-09). 
  130. ^ The Python Standard Library - Built-in Types - printf-style String Formatting. [2023-03-21]. (原始內容存檔於2020-06-14). 
  131. ^ 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). 
  132. ^ The Python Language Reference - 2. Lexical analysis - Formatted string literals. [2023-03-13]. (原始內容存檔於2018-01-09). 
  133. ^ PEP 498 - Literal String Interpolation. python.org. [2017-03-08]. (原始內容存檔於2020-06-15). 
  134. ^ van Rossum, Guido. Tail Recursion Elimination. Neopythonic.blogspot.be. 2009-04-22 [2012-12-03]. (原始內容存檔於2018-05-19). 
    van Rossum, Guido. Language Design Is Not Just Solving Puzzles. Artima forums. Artima. 2006-02-09 [2007-03-21]. (原始內容存檔於2020-01-17). 
  135. ^ 135.0 135.1 Tail recursion package for python with a simple decorator api. [2023-03-06]. (原始內容存檔於2023-03-06). 
  136. ^ The Python Tutorial - 4. More Control Flow Tools - Defining Functions. [2023-03-06]. (原始內容存檔於2023-06-10). 
  137. ^ Positional-only parameters. [2020-09-24]. (原始內容存檔於2020-06-08). 
  138. ^ Python 2.4 Decorators: Reducing code duplication and consolidating knowledge. Dr. Dobb's. 2005-05-01 [2007-02-08]. (原始內容存檔於2007-02-06). 
  139. ^ The Python Standard Library - Functional Programming Modules - functools — Higher-order functions and operations on callable objects. [2023-03-18]. (原始內容存檔於2021-06-02). 
  140. ^ PEP 3107 -- Function Annotations. [2021-03-01]. (原始內容存檔於2015-01-06). 
  141. ^ 141.0 141.1 PEP 484 -- Type Hints. [2021-03-01]. (原始內容存檔於2021-02-09). 
  142. ^ PEP 3115 – Metaclasses in Python 3000. [2023-03-21]. (原始內容存檔於2023-04-02). 
  143. ^ 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). 
  144. ^ The Python Standard Library - Built-in Types - Special Attributes. [2020-09-12]. (原始內容存檔於2020-06-14). 
  145. ^ Why must 'self' be used explicitly in method definitions and calls?. Design and History FAQ. Python Software Foundation. [2012-02-19]. (原始內容存檔於2012-10-24). 
  146. ^ The Python Standard Library - Built-in Functions - class super. [2020-09-25]. (原始內容存檔於2018-10-26). 
  147. ^ Descriptor HowTo Guide. [2020-09-26]. (原始內容存檔於2020-09-18). 
  148. ^ The Python Standard Library - Built-in Functions - class property. [2020-09-25]. (原始內容存檔於2018-10-26). 
  149. ^ The Python Language Reference - 3. Data model - The standard type hierarchy. 
  150. ^ The Python Language Reference, section 3.3. New-style and classic classes, for release 2.7.18. [2020-09-25]. (原始內容存檔於2020-05-05). 
  151. ^ mypy - Optional Static Typing for Python. [2017-01-28]. (原始內容存檔於2020-06-06). 
  152. ^ Moshe Zadka, Guido van Rossum. PEP 237 - Unifying Long Integers and Integers. 2001-03-11. (原始內容存檔於2020-05-28). 
  153. ^ 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」. 
  154. ^ The Python Standard Library - Built-in Types - Ranges. [2019-10-03]. (原始內容存檔於2020-06-14). 
  155. ^ NumPy fundamentals - Indexing on ndarrays - Dimensional indexing tools. [2023-03-23]. (原始內容存檔於2023-06-01). 
  156. ^ The Python Standard Library - Built-in Types - The Null Object. [2023-03-24]. (原始內容存檔於2023-03-24). 
  157. ^ Moshe Zadka, Guido van Rossum. PEP 238 - Changing the Division Operator. 2001-03-11 [2013-10-23]. (原始內容存檔於2020-05-28). 
  158. ^ The Python Standard Library - Built-in Functions - round(), [2023-03-21], (原始內容存檔於2012-10-25) 
  159. ^ 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. 
  160. ^ PEP 327 – Decimal Data Type. [2015-09-26]. (原始內容存檔於2020-06-04). 
  161. ^ The Python Standard Library - Numeric and Mathematical Modules - decimal — Decimal fixed point and floating point arithmetic. [2023-03-21]. (原始內容存檔於2023-06-13). 
  162. ^ The Python Standard Library - Numeric and Mathematical Modules - fractions — Rational numbers. [2023-03-21]. (原始內容存檔於2023-05-26). 
  163. ^ 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). 
  164. ^ Shell, Scott. An introduction to Python for scientific computing (PDF). 2014-06-17 [2019-02-03]. (原始內容存檔 (PDF)於2019-02-04). 
  165. ^ The Python Standard Library. [2023-03-09]. (原始內容存檔於2023-06-06). 
  166. ^ Python Interpreters Benchmarks. [2022-08-30]. (原始內容存檔於2022-08-20). 
  167. ^ 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). 
  168. ^ 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). 
  169. ^ The Computer Language Benchmarks Game. [2023-01-31]. (原始內容存檔於2023-05-22). 
  170. ^ Glossary — global interpreter lock. [2023-09-19]. (原始內容存檔於2020-06-25). 
  171. ^ Announcing 3.7-3.10 support and a new direction. September 29, 2022 [2023-01-15]. (原始內容存檔於2023-01-15). We’re very excited to announce that today we are releasing a new version of Pyston-lite, our Python JIT-as-an-extension-module, with the headline feature of supporting Python versions 3.7 through 3.10 (Mac and Linux). Previously we only supported Python 3.8, and support for other versions was one of our most-requested features. 
  172. ^ Cinder is Meta's internal performance-oriented production version of CPython. [2022-08-26]. (原始內容存檔於2021-05-04). 
  173. ^ Codon - A high-performance, zero-overhead, extensible Python compiler using LLVM. [2023-03-24]. (原始內容存檔於2023-05-25). 
  174. ^ Rachel Gordon. Python-based compiler achieves orders-of-magnitude speedups. MIT CSAIL. March 14, 2023 [2023-03-25]. (原始內容存檔於2023-03-26). 
  175. ^ Pyodide is a Python distribution for the browser and Node.js based on WebAssembly. 
  176. ^ Brython (Browser Python) is an implementation of Python 3 running in the browser. [2023-06-17]. (原始內容存檔於2023-10-28). 
  177. ^ Cython Users Guide — Using Parallelism. [2023-09-19]. (原始內容存檔於2023-10-11). 
  178. ^ Pythran - Ahead of Time compiler for numeric kernels. [2022-08-29]. (原始內容存檔於2022-08-29). 
  179. ^ Nuitka is a Python compiler written in Python. [2023-09-18]. (原始內容存檔於2023-11-11). 
  180. ^ Pyjion - A JIT for Python based upon CoreCLR. [2022-08-29]. (原始內容存檔於2022-08-29). 
  181. ^ Transcrypt — Python 3.9 to JavaScript compiler - Lean, fast, open!. [2023-09-18]. (原始內容存檔於2023-09-19). 
  182. ^ MyHDL - From Python to Silicon!. [2023-03-05]. (原始內容存檔於2023-06-05). 
  183. ^ Tool recommendations. python.org. [21 April 2022]. (原始內容存檔於2022-09-06) (英語). 
  184. ^ venv — Creation of virtual environments. [2023-05-07]. (原始內容存檔於2023-06-13). 
  185. ^ virtualenv — A tool for creating isolated virtual python environments. [2023-05-07]. (原始內容存檔於2023-06-11). 
  186. ^ Pipenv — Python Development Workflow for Humans. [2022-08-29]. (原始內容存檔於2019-11-17). 
  187. ^ 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). 
  188. ^ uvloop is a fast, drop-in replacement of the built-in asyncio event loop. [2023-03-24]. (原始內容存檔於2023-05-25). 
  189. ^ Asynchronous HTTP Client/Server for asyncio and Python. [2021-01-14]. (原始內容存檔於2021-01-15). 
  190. ^ 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). 
  191. ^ Remi - Python REMote Interface library. [2022-08-28]. (原始內容存檔於2022-08-28). 
  192. ^ PySimpleGUI - Python GUIs for Humans. [2022-08-28]. (原始內容存檔於2022-08-28). 
  193. ^ Gooey - Turn (almost) any Python command line program into a full GUI application with one line. [2022-08-28]. (原始內容存檔於2022-08-28). 
  194. ^ Dear PyGui: A fast and powerful Graphical User Interface Toolkit for Python with minimal dependencies. [2023-03-18]. (原始內容存檔於2023-05-18). 
  195. ^ 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). 
  196. ^ 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. 
  197. ^ CuPy: NumPy & SciPy for GPU. [2022-08-31]. (原始內容存檔於2022-08-31). 
  198. ^ 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. 
  199. ^ Python tools for data visualization — High-level tools. [2023-09-19]. (原始內容存檔於2023-09-28). 
  200. ^ Dask - Parallel computing with task scheduling. [2022-08-31]. (原始內容存檔於2022-08-31). 
  201. ^ Python tools for data visualization. 
  202. ^ Bokeh — Interactive Data Visualization in the browser, from Python. [2023-09-19]. (原始內容存檔於2023-10-12). 
  203. ^ HoloViz — High-level tools to simplify visualization in Python. [2023-09-19]. (原始內容存檔於2023-10-11). 
  204. ^ Panel - A high-level app and dashboarding solution for Python. [2022-09-21]. (原始內容存檔於2023-01-16). 
  205. ^ Dash - Analytical Web Apps for Python, R, Julia, and Jupyter. [2022-09-21]. (原始內容存檔於2022-12-05). 
  206. ^ Plotly.js - Open-source JavaScript charting library behind Plotly and Dash. [2022-09-21]. (原始內容存檔於2022-12-21). 
  207. ^ Streamlit — The fastest way to build data apps in Python. [2022-09-21]. (原始內容存檔於2023-01-17). 
  208. ^ Voilà - Voilà turns Jupyter notebooks into standalone web applications. [2022-09-21]. (原始內容存檔於2022-12-31). 
  209. ^ VisPy - interactive scientific visualization in Python. [2022-08-30]. (原始內容存檔於2022-07-13). 
  210. ^ glumpy — Python+Numpy+OpenGL: fast, scalable and beautiful scientific visualization. [2023-09-18]. (原始內容存檔於2023-09-19). 
  211. ^ Joblib: running Python functions as pipeline jobs. [2022-09-19]. (原始內容存檔於2022-12-07). 
  212. ^ Thread-pool Controls. [2022-09-19]. (原始內容存檔於2022-11-02). 
  213. ^ TensorFlow API Documentation - Module: tf. [2022-08-31]. (原始內容存檔於2022-09-05). 
  214. ^ TensorFlow API Documentation - Module: tf.keras. [2022-08-31]. (原始內容存檔於2020-01-22). 
  215. ^ JAX - Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more. [2022-08-28]. (原始內容存檔於2021-02-05). 
  216. ^ Autograd - Efficiently computes derivatives of numpy code. [2022-08-28]. (原始內容存檔於2022-07-18). 
  217. ^ XLA: Optimizing Compiler for Machine Learning. [2022-08-28]. (原始內容存檔於2022-09-01). 
  218. ^ 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). 
  219. ^ PeachPy - Portable Efficient Assembly Code-generator in Higher-level Python. [2023-04-04]. (原始內容存檔於2023-04-04). 
  220. ^ SimPy — Discrete event simulation for Python. [2023-08-17]. (原始內容存檔於2016-12-12). 
  221. ^ PyOpenGL is the most common cross platform Python binding to OpenGL and related APIs. [2022-01-07]. (原始內容存檔於2011-06-15). 
  222. ^ ModernGL - Modern OpenGL binding for python. [2022-01-07]. (原始內容存檔於2022-04-15). 
  223. ^ CUDA Python Manual. [2022-08-30]. (原始內容存檔於2022-08-30). 
  224. ^ PyCUDA gives you easy, Pythonic access to Nvidia’s CUDA parallel computation API. [2022-05-29]. (原始內容存檔於2022-06-28). 
  225. ^ PyOpenCL gives you easy, Pythonic access to the OpenCL parallel computation API. [2021-07-29]. (原始內容存檔於2022-03-08). 
  226. ^ PySPH — A framework for Smoothed Particle Hydrodynamics in Python. 
  227. ^ Vulkan Kompute: Blazing fast, mobile-enabled, asynchronous, and optimized for advanced GPU processing usecases. [2023-02-10]. (原始內容存檔於2023-03-05). 
  228. ^ Pillow: a modern fork of PIL. [December 8, 2013]. (原始內容存檔於2016-04-27). 
  229. ^ Graphene — GraphQL framework for Python. 
  230. ^ GQL — A GraphQL client in Python. 
  231. ^ pypdf - A pure-python PDF library capable of splitting, merging, cropping, and transforming the pages of PDF files. [2023-02-24]. (原始內容存檔於2023-04-10). 
  232. ^ PyFilesystem2 — Python's Filesystem abstraction layer. [2023-10-10]. (原始內容存檔於2023-10-13). 
  233. ^ Fabric - Pythonic remote execution. [2013-04-08]. (原始內容存檔於2014-04-11). 
  234. ^ Prefect - The easiest way to coordinate your dataflow. [2022-09-22]. (原始內容存檔於2023-01-11). 
  235. ^ SDL Language Bindings. [2022-02-16]. (原始內容存檔於2019-03-12). 
  236. ^ Arcade — Easy to use Python library for creating 2D arcade games. [2023-10-10]. (原始內容存檔於2023-11-08). 
  237. ^ Panda3D Manual. [2022-09-04]. (原始內容存檔於2018-12-29). 
  238. ^ pythonnet - Python.NET. [2022-08-30]. (原始內容存檔於2022-09-01). 
  239. ^ PyInstaller bundles a Python application and all its dependencies into a single package. [2021-03-13]. (原始內容存檔於2021-06-07). 
  240. ^ LSB — Runtime Languages — Python Interpreter. [2023-06-16]. (原始內容存檔於2016-05-01). 
  241. ^ pipx — Install and Run Python Applications in Isolated Environmentspipenv. [2023-05-07]. (原始內容存檔於2023-06-05). 
  242. ^ XONSH is a Python-powered shell. [2022-08-28]. (原始內容存檔於2022-09-03). 
  243. ^ 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). 
  244. ^ Mayavi: 3D scientific data visualization and plotting in Python. [2023-09-20]. (原始內容存檔於2023-10-11). 
  245. ^ Ray - Effortlessly scale your most complex workloads. [2022-09-19]. (原始內容存檔於2022-12-13). 
  246. ^ Transformers — State-of-the-art Machine Learning for PyTorch, TensorFlow, and JAX. [2023-10-19]. (原始內容存檔於2023-09-27). 
  247. ^ Kornia - Open Source Differentiable Computer Vision Library. [2022-09-22]. (原始內容存檔於2023-01-10). 
  248. ^ spaCy: Industrial-strength NLP. [2023-09-22]. (原始內容存檔於2023-10-11). 
  249. ^ Argos Translate — Open-source offline translation library written in Python. [2023-10-01]. (原始內容存檔於2023-11-13). 
  250. ^ Generative Models by Stability AI. [2023-10-14]. (原始內容存檔於2023-11-11). 
  251. ^ CLIP (Contrastive Language-Image Pretraining), Predict the most relevant text snippet given an image. [2023-10-18]. (原始內容存檔於2023-09-05). 
  252. ^ Buniatyan, Davit. Code Understanding Using LangChain. Activeloop. 2023. 
  253. ^ Gradio: The New Frontier in Interactive Python Data Apps. 
  254. ^ Python library for easily interacting with trained machine learning models https://pypi.org/project/gradio/
  255. ^ 255.0 255.1 TIOBE Index. TIOBE - The Software Quality Company. [2021-10-06]. (原始內容存檔於2020-06-14). 
  256. ^ Python Discord is a large community focused around the Python programming language. [2021-01-13]. (原始內容存檔於2021-02-01). 
  257. ^ Gotchas for Python Users. boo.codehaus.org. Codehaus Foundation. [2008-11-24]. (原始內容存檔於2008-12-11). 
  258. ^ Esterbrook, Charles. Acknowledgements. cobra-language.com. Cobra Language. [2010-04-07]. (原始內容存檔於2008-02-08). 
  259. ^ Proposals: iterators and generators [ES4 Wiki]. wiki.ecmascript.org. [2008-11-24]. (原始內容存檔於2007-10-20). 
  260. ^ FAQ: What is GDScript and why should I use it?. [2020-09-13]. (原始內容存檔於2020-05-19). 
  261. ^ Kincaid, Jason. Google's Go: A New Programming Language That's Python Meets C++. TechCrunch. 2009-11-10 [2010-01-29]. (原始內容存檔於2010-01-18). 
  262. ^ Strachan, James. Groovy – the birth of a new dynamic language for the Java platform. 2003-08-29 [2007-06-11]. (原始內容存檔於2007-04-05). 
  263. ^ The Mojo Programming Language. github.com. Modular. 2023 [2023-09-26]. (原始內容存檔於2023-10-25). Mojo is still young, but it is designed to become a superset of Python over time. 
  264. ^ 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). 

延伸閱讀 編輯

參閲 編輯

外部連接 編輯