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). 

延伸閱讀 編輯

參閲 編輯

外部連接 編輯