術語表¶
>>>¶互動式 shell 的預設 Python 提示字元。常見於能在直譯器中以互動方式被執行的程式碼範例。
...¶可以表示:
在一個被縮排的程式碼區塊、在一對匹配的左右定界符(delimiter,例如括號、方括號、花括號或三引號)內部,或是在指定一個裝飾器 (decorator) 之後,要輸入程式碼時,互動式 shell 顯示的預設 Python 提示字元。
The three dots form of the Ellipsis object.
- abstract base class(抽象基底類別)¶
抽象基底類別(又稱為 ABC)提供了一種定義介面的方法,作為 duck-typing(鴨子型別)的補充。其他類似的技術,像是
hasattr(),則顯得笨拙或是帶有細微的錯誤(例如使用魔術方法 (magic method))。ABC 採用虛擬的 subclass(子類別),它們並不繼承自另一個 class(類別),但仍可被isinstance()及issubclass()辨識;請參閱abc模組的說明文件。Python 有許多內建的 ABC,用於資料結構(在collections.abc模組)、數字(在numbers模組)、串流(在io模組)及 import 尋檢器和載入器(在importlib.abc模組)。你可以使用abc模組建立自己的 ABC。- annotate function(註釋函式)¶
A function that can be called to retrieve the annotations of an object. This function is accessible as the
__annotate__attribute of functions, classes, and modules. Annotate functions are a subset of evaluate functions.- annotation(註釋)¶
一個與變數、class 屬性、函式的參數或回傳值相關聯的標籤。照慣例,它被用來作為 type hint(型別提示)。
在 runtime 的區域變數註釋無法被存取,但全域變數、類別屬性和函式的註釋,分別能夠以對模組、類別和函式呼叫
annotationlib.get_annotations()來取得。請參閱 variable annotation、function annotation、PEP 484、PEP 526 和 PEP 649,這些章節皆有此功能的說明。關於註釋的最佳實踐方法也請參閱 註釋 (annotation) 最佳實踐。
- argument(引數)¶
呼叫函式時被傳遞給 function(或 method)的值。引數有兩種:
關鍵字引數 (keyword argument):在函式呼叫中,以識別字(identifier,例如
name=)開頭的引數,或是以**後面 dictionary(字典)內的值被傳遞的引數。例如,3和5都是以下complex()呼叫中的關鍵字引數:complex(real=3, imag=5) complex(**{'real': 3, 'imag': 5})
位置引數 (positional argument):不是關鍵字引數的引數。位置引數可在一個引數列表的起始處出現,和(或)作為
*之後的 iterable(可疊代物件)中的元素被傳遞。例如,3和5都是以下呼叫中的位置引數:complex(3, 5) complex(*(3, 5))
引數會被指定給函式主體中的附名區域變數。關於支配這個指定過程的規則,請參閱Calls章節。在語法上,任何運算式都可以被用來表示一個引數;其評估值會被指定給區域變數。
另請參閱術語表的 parameter(參數)條目、常見問題中的引數和參數之間的差異,以及 PEP 362。
- asynchronous context manager(非同步情境管理器)¶
一個可以控制
async with陳述式中所見環境的物件,而它是透過定義__aenter__()和__aexit__()method(方法)來控制的。由 PEP 492 引入。- asynchronous generator(非同步產生器)¶
一個會回傳 asynchronous generator iterator(非同步產生器疊代器)的函式。它看起來像一個以
async def定義的協程函式 (coroutine function),但不同的是它包含了yield運算式,能生成一系列可用於async for迴圈的值。這個術語通常用來表示一個非同步產生器函式,但在某些情境中,也可能是表示非同步產生器疊代器 (asynchronous generator iterator)。萬一想表達的意思不夠清楚,那就使用完整的術語,以避免歧義。
一個非同步產生器函式可能包含
await運算式,以及async for和async with陳述式。- asynchronous generator iterator(非同步產生器疊代器)¶
一個由 asynchronous generator(非同步產生器)函式所建立的物件。
這是一個 asynchronous iterator(非同步疊代器),當它以
__anext__()method 被呼叫時,會回傳一個可等待物件 (awaitable object),該物件將執行非同步產生器的函式主體,直到遇到下一個yield運算式。每個
yield會暫停處理程序,並記住執行狀態(包括區域變數及擱置中的 try 陳述式)。當非同步產生器疊代器以另一個被__anext__()回傳的可等待物件有效地回復時,它會從停止的地方繼續執行。請參閱 PEP 492 和 PEP 525。- asynchronous iterable(非同步可疊代物件)¶
一個物件,它可以在
async for陳述式中被使用。必須從它的__aiter__()method 回傳一個 asynchronous iterator(非同步疊代器)。由 PEP 492 引入。- asynchronous iterator(非同步疊代器)¶
一個實作
__aiter__()和__anext__()method 的物件。__anext__()必須回傳一個 awaitable(可等待物件)。async for會解析非同步疊代器的__anext__()method 所回傳的可等待物件,直到它引發StopAsyncIteration例外。由 PEP 492 引入。- atomic operation¶
An operation that appears to execute as a single, indivisible step: no other thread can observe it half-done, and its effects become visible all at once. Python does not guarantee that high-level statements are atomic (for example,
x += 1performs multiple bytecode operations and is not atomic). Atomicity is only guaranteed where explicitly documented. See also race condition and data race.- attached thread state¶
A thread state that is active for the current OS thread.
When a thread state is attached, the OS thread has access to the full Python C API and can safely invoke the bytecode interpreter.
Unless a function explicitly notes otherwise, attempting to call the C API without an attached thread state will result in a fatal error or undefined behavior. A thread state can be attached and detached explicitly by the user through the C API, or implicitly by the runtime, including during blocking C calls and by the bytecode interpreter in between calls.
On most builds of Python, having an attached thread state implies that the caller holds the GIL for the current interpreter, so only one OS thread can have an attached thread state at a given moment. In free-threaded builds of Python, threads can concurrently hold an attached thread state, allowing for true parallelism of the bytecode interpreter.
- attribute(屬性)¶
一個與某物件相關聯的值,該值大多能透過使用點分隔運算式 (dotted expression) 的名稱被參照。例如,如果物件 o 有一個屬性 a,則該屬性能以 o.a 被參照。
如果一個物件允許,給予該物件一個名稱不是由Names (identifiers and keywords)所定義之識別符 (identifier) 的屬性是有可能的,例如使用
setattr()。像這樣的屬性將無法使用點分隔運算式來存取,而是需要使用getattr()來取得它。- awaitable(可等待物件)¶
一個可以在
await運算式中被使用的物件。它可以是一個 coroutine(協程),或是一個有__await__()method 的物件。另請參閱 PEP 492。- BDFL¶
Benevolent Dictator For Life(終身仁慈獨裁者),又名 Guido van Rossum,Python 的創造者。
- binary file(二進位檔案)¶
一個能夠讀取和寫入 bytes-like objects(類位元組串物件)的 file object(檔案物件)。二進位檔案的例子有:以二進位模式(
'rb'、'wb'或'rb+')開啟的檔案、sys.stdin.buffer、sys.stdout.buffer,以及io.BytesIO和gzip.GzipFile實例。- borrowed reference(借用參照)¶
在 Python 的 C API 中,借用參照是一個對物件的參照,其中使用該物件的程式碼並不擁有這個參照。如果該物件被銷毀,它會成為一個迷途指標 (dangling pointer)。例如,一次垃圾回收 (garbage collection) 可以移除對物件的最後一個 strong reference(強參照),而將該物件銷毀。
對 borrowed reference 呼叫
Py_INCREF()以將它原地 (in-place) 轉換為 strong reference 是被建議的做法,除非該物件不能在最後一次使用借用參照之前被銷毀。Py_NewRef()函式可用於建立一個新的 strong reference。- bytes-like object(類位元組串物件)¶
一個支援緩衝協定 (Buffer Protocol)且能夠匯出 C-contiguous 緩衝區的物件。這包括所有的
bytes、bytearray和array.array物件,以及許多常見的memoryview物件。類位元組串物件可用於處理二進位資料的各種運算;這些運算包括壓縮、儲存至二進位檔案和透過 socket(插座)發送。有些運算需要二進位資料是可變的。說明文件通常會將這些物件稱為「可讀寫的類位元組串物件」。可變緩衝區的物件包括
bytearray,以及bytearray的memoryview。其他的運算需要讓二進位資料被儲存在不可變物件(「唯讀的類位元組串物件」)中;這些物件包括bytes,以及bytes物件的memoryview。- bytecode(位元組碼)¶
Python 的原始碼會被編譯成位元組碼,它是 Python 程式在 CPython 直譯器中的內部表示法。該位元組碼也會被暫存在
.pyc檔案中,以便第二次執行同一個檔案時能夠更快速(可以不用從原始碼重新編譯為位元組碼)。這種「中間語言 (intermediate language)」據說是運行在一個 virtual machine(虛擬機器)上,該虛擬機器會執行與每個位元組碼對應的機器碼 (machine code)。要注意的是,位元組碼理論上是無法在不同的 Python 虛擬機器之間運作的,也不能在不同版本的 Python 之間保持穩定。位元組碼的指令列表可以在 dis 模組的說明文件中找到。
- callable(可呼叫物件)¶
一個 callable 是可以被呼叫的物件,呼叫時可能以下列形式帶有一組引數(請見 argument):
callable(argument1, argument2, argumentN)
一個 function 與其延伸的 method 都是 callable。一個有實作
__call__()方法的 class 之實例也是個 callable。- callback(回呼)¶
作為引數被傳遞的一個副程式 (subroutine) 函式,會在未來的某個時間點被執行。
- class(類別)¶
一個用於建立使用者定義物件的模板。Class 的定義通常會包含 method 的定義,這些 method 可以在 class 的實例上進行操作。
- class variable(類別變數)¶
一個在 class 中被定義,且應該只能在 class 層次(意即不是在 class 的實例中)被修改的變數。
- closure variable(閉包變數)¶
從外部作用域中定義且從巢狀作用域參照的自由變數,不是於 runtime 從全域或內建命名空間解析。可以使用
nonlocal關鍵字明確定義以允許寫入存取,或者如果僅需讀取變數則隱式定義即可。例如在下面程式碼中的
inner函式中,x和print都是自由變數,但只有x是閉包變數:def outer(): x = 0 def inner(): nonlocal x x += 1 print(x) return inner
由於
codeobject.co_freevars屬性(儘管名稱如此,但它僅包含閉包變數的名稱,而不是列出所有參照的自由變數),當預期含義是特指閉包變數時,有時候甚至也會使用更通用的自由變數一詞。- complex number(複數)¶
一個我們熟悉的實數系統的擴充,在此所有數字都會被表示為一個實部和一個虛部之和。虛數就是虛數單位(
-1的平方根)的實數倍,此單位通常在數學中被寫為i,在工程學中被寫為j。Python 內建了對複數的支援,它是用後者的記法來表示複數;虛部會帶著一個後綴的j被編寫,例如3+1j。若要將math模組內的工具等效地用於複數,請使用cmath模組。複數的使用是一個相當進階的數學功能。如果你沒有察覺到對它們的需求,那麼幾乎能確定你可以安全地忽略它們。- concurrency(並行性)¶
The ability of a computer program to perform multiple tasks at the same time. Python provides libraries for writing programs that make use of different forms of concurrency.
asynciois a library for dealing with asynchronous tasks and coroutines.threadingprovides access to operating system threads andmultiprocessingto operating system processes. Multi-core processors can execute threads and processes on different CPU cores at the same time (see parallelism).- concurrent modification¶
When multiple threads modify shared data at the same time. Concurrent modification without proper synchronization can cause race conditions, and might also trigger a data race, data corruption, or both.
- context(情境)¶
This term has different meanings depending on where and how it is used. Some common meanings:
The temporary state or environment established by a context manager via a
withstatement.The collection of keyvalue bindings associated with a particular
contextvars.Contextobject and accessed viaContextVarobjects. Also see context variable.一個
contextvars.Context物件。另請參閱 current context。
- context management protocol(情境管理協定)¶
由
with陳述式所呼叫的__enter__()和__exit__()方法。另請參閱 PEP 343。- context manager(情境管理器)¶
An object which implements the context management protocol and controls the environment seen in a
withstatement. See PEP 343.- context variable(情境變數)¶
A variable whose value depends on which context is the current context. Values are accessed via
contextvars.ContextVarobjects. Context variables are primarily used to isolate state between concurrent asynchronous tasks.- contiguous(連續的)¶
如果一個緩衝區是 C-contiguous 或是 Fortran contiguous,則它會確切地被視為是連續的。零維 (zero-dimensional) 的緩衝區都是 C 及 Fortran contiguous。在一維 (one-dimensional) 陣列中,各項目必須在記憶體中彼此相鄰地排列,而其索引順序是從零開始遞增。在多維的 (multidimensional) C-contiguous 陣列中,按記憶體位址的順序瀏覽各個項目時,最後一個索引的變化最快。然而,在 Fortran contiguous 陣列中,第一個索引的變化最快。
- coroutine(協程)¶
協程是副程式 (subroutine) 的一種更為廣義的形式。副程式是在某個時間點被進入並在另一個時間點被退出。協程可以在許多不同的時間點被進入、退出和回復。它們能夠以
async def陳述式被實作。另請參閱 PEP 492。- coroutine function(協程函式)¶
一個回傳 coroutine(協程)物件的函式。一個協程函式能以
async def陳述式被定義,並可能會包含await、async for和async with關鍵字。這些關鍵字由 PEP 492 引入。- CPython¶
Python 程式語言的標準實作 (canonical implementation),被發布在 python.org 上。「CPython」這個術語在必要時被使用,以區分此實作與其它語言的實作,例如 Jython 或 IronPython。
- current context¶
The context (
contextvars.Contextobject) that is currently used byContextVarobjects to access (get or set) the values of context variables. Each thread has its own current context. Frameworks for executing asynchronous tasks (seeasyncio) associate each task with a context which becomes the current context whenever the task starts or resumes execution.- cyclic isolate¶
A subgroup of one or more objects that reference each other in a reference cycle, but are not referenced by objects outside the group. The goal of the cyclic garbage collector is to identify these groups and break the reference cycles so that the memory can be reclaimed.
- data race¶
A situation where multiple threads access the same memory location concurrently, at least one of the accesses is a write, and the threads do not use any synchronization to control their access. Data races lead to non-deterministic behavior and can cause data corruption. Proper use of locks and other synchronization primitives prevents data races. Note that data races can only happen in native code, but that native code might be exposed in a Python API. See also race condition and thread-safe.
- deadlock¶
A situation in which two or more tasks (threads, processes, or coroutines) wait indefinitely for each other to release resources or complete actions, preventing any from making progress. For example, if thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1, both threads will wait indefinitely. In Python this often arises from acquiring multiple locks in conflicting orders or from circular join/await dependencies. Deadlocks can be avoided by always acquiring multiple locks in a consistent order. See also lock and reentrant.
- decorator(裝飾器)¶
一個函式,它會回傳另一個函式,通常它會使用
@wrapper語法,被應用為一種函式的變換 (function transformation)。裝飾器的常見範例是classmethod()和staticmethod()。裝飾器語法只是語法糖。以下兩個函式定義在語義上是等效的:
def f(arg): ... f = staticmethod(f) @staticmethod def f(arg): ...
- descriptor(描述器)¶
任何定義了
__get__()、__set__()或__delete__()method 的物件。當一個 class 屬性是一個描述器時,它的特殊連結行為會在屬性查找時被觸發。通常,使用 a.b 來取得、設定或刪除某個屬性時,會在 a 的 class 字典中查找名稱為 b 的物件,但如果 b 是一個描述器,則相對應的描述器 method 會被呼叫。對描述器的理解是深入理解 Python 的關鍵,因為它們是許多功能的基礎,這些功能包括函式、method、屬性 (property)、class method、靜態 method,以及對 super class(父類別)的參照。- dictionary(字典)¶
一個關聯陣列 (associative array),其中任意的鍵會被對映到值。鍵可以是任何帶有
__hash__()和__eq__()method 的物件。在 Perl 中被稱為雜湊 (hash)。- dictionary comprehension(字典綜合運算)¶
一種緊密的方法,用來處理一個可疊代物件中的全部或部分元素,並將處理結果以一個字典回傳。
results = {n: n ** 2 for n in range(10)}會產生一個字典,它包含了鍵n對映到值n ** 2。請參閱Displays for lists, sets and dictionaries。- dictionary view(字典檢視)¶
從
dict.keys()、dict.values()及dict.items()回傳的物件被稱為字典檢視。它們提供了字典中項目的動態檢視,這表示當字典有變動時,該檢視會反映這些變動。若要強制將字典檢視轉為完整的 list(串列),須使用list(dictview)。請參閱字典視圖物件。- docstring(說明字串)¶
一個在 class、函式或模組中,作為第一個運算式出現的字串文本。雖然它在套件執行時會被忽略,但它會被編譯器辨識,並被放入所屬 class、函式或模組的
__doc__屬性中。由於說明字串可以透過內省 (introspection) 來瀏覽,因此它是物件的說明文件存放的標準位置。- duck-typing(鴨子型別)¶
一種程式設計風格,它不是藉由檢查一個物件的型別來確定它是否具有正確的介面;取而代之的是,method 或屬性會單純地被呼叫或使用。(「如果它看起來像一隻鴨子而且叫起來像一隻鴨子,那麼它一定是一隻鴨子。」)因為強調介面而非特定型別,精心設計的程式碼能讓多形替代 (polymorphic substitution) 來增進它的靈活性。鴨子型別要避免使用
type()或isinstance()進行測試。(但是請注意,鴨子型別可以用抽象基底類別 (abstract base class) 來補充。)然而,它通常會採用hasattr()測試,或是 EAFP 程式設計風格。- dunder(雙底線)¶
一個非正式的縮寫,代表「雙底線 (double underscore)」,當談論到特殊方法時使用。例如,
__init__通常被叫做 "dunder init"。- EAFP¶
Easier to ask for forgiveness than permission.(請求寬恕比請求許可更容易。)這種常見的 Python 編碼風格會先假設有效的鍵或屬性的存在,並在該假設被推翻時再捕獲例外。這種乾淨且快速的風格,其特色是存在許多的
try和except陳述式。該技術與許多其他語言(例如 C)常見的 LBYL 風格形成了對比。- evaluate function(求值函式)¶
A function that can be called to evaluate a lazily evaluated attribute of an object, such as the value of type aliases created with the
typestatement.- expression(運算式)¶
一段可以被評估並求值的語法。換句話說,一個運算式就是文字、名稱、屬性存取、運算子或函式呼叫等運算式元件的累積,而這些元件都能回傳一個值。與許多其他語言不同的是,並非所有的 Python 語言構造都是運算式。另外有一些 statement(陳述式)不能被用作運算式,例如
while。賦值 (assignment) 也是陳述式,而不是運算式。- extension module(擴充模組)¶
一個以 C 或 C++ 編寫的模組,它使用 Python 的 C API 來與核心及使用者程式碼進行互動。
- f-string(f 字串)¶
- f-strings(f 字串)¶
- file object(檔案物件)¶
一個讓使用者透過檔案導向 (file-oriented) API(如
read()或write()等 method)來操作底層資源的物件。根據檔案物件被建立的方式,它能夠協調對真實磁碟檔案或是其他類型的儲存器或通訊裝置(例如標準輸入/輸出、記憶體內緩衝區、socket(插座)、管線 (pipe) 等)的存取。檔案物件也被稱為類檔案物件 (file-like object) 或串流 (stream)。實際上,有三種檔案物件:原始的二進位檔案、緩衝的二進位檔案和文字檔案。它們的介面在
io模組中被定義。建立檔案物件的標準方法是使用open()函式。- file-like object(類檔案物件)¶
file object(檔案物件)的同義字。
- filesystem encoding and error handler(檔案系統編碼和錯誤處理函式)¶
Python 所使用的一種編碼和錯誤處理函式,用來解碼來自作業系統的位元組,以及將 Unicode 編碼到作業系統。
檔案系統編碼必須保證能成功解碼所有小於 128 的位元組。如果檔案系統編碼無法提供此保證,則 API 函式會引發
UnicodeError。sys.getfilesystemencoding()和sys.getfilesystemencodeerrors()函式可用於取得檔案系統編碼和錯誤處理函式。filesystem encoding and error handler(檔案系統編碼和錯誤處理函式)會在 Python 啟動時由
PyConfig_Read()函式來配置:請參閱filesystem_encoding,以及PyConfig的成員filesystem_errors。另請參閱 locale encoding(區域編碼)。
- finder(尋檢器)¶
一個物件,它會嘗試為正在被 import 的模組尋找 loader(載入器)。
有兩種類型的尋檢器:元路徑尋檢器 (meta path finder) 會使用
sys.meta_path,而路徑項目尋檢器 (path entry finder) 會使用sys.path_hooks。請參閱 尋檢器 (Finder) 與載入器 (Loader) 和
importlib以了解更多細節。- floor division(向下取整除法)¶
向下無條件捨去到最接近整數的數學除法。向下取整除法的運算子是
//。例如,運算式11 // 4的計算結果為2,與 float(浮點數)真除法所回傳的2.75不同。請注意,(-11) // 4的結果是-3,因為是-2.75被向下無條件捨去。請參閱 PEP 238。- free threading(自由執行緒)¶
為一種執行緒模型,多個執行緒可以在同一直譯器中同時運行 Python 位元組碼。這與全域直譯器鎖形成對比,後者一次只允許一個執行緒執行 Python 位元組碼。請參閱 PEP 703。
- free-threaded build(自由執行緒建置)¶
A build of CPython that supports free threading, configured using the
--disable-giloption before compilation.See Python 自由執行緒的支援.
- free variable(自由變數)¶
Formally, as defined in the language execution model, a free variable is any variable used in a namespace which is not a local variable in that namespace. See closure variable for an example. Pragmatically, due to the name of the
codeobject.co_freevarsattribute, the term is also sometimes used as a synonym for closure variable.- function(函式)¶
一連串的陳述式,它能夠向呼叫者回傳一些值。它也可以被傳遞零個或多個引數,這些引數可被使用於函式本體的執行。另請參閱 parameter(參數)、method(方法),以及函式定義章節。
- function annotation(函式註釋)¶
函式參數或回傳值的一個 annotation(註釋)。
函式註釋通常被使用於型別提示:例如,這個函式預期會得到兩個
int引數,並會有一個int回傳值:def sum_two_numbers(a: int, b: int) -> int: return a + b
函式註釋的語法在函式定義章節有詳細解釋。
請參閱 variable annotation 和 PEP 484,皆有此功能的描述。關於註釋的最佳實踐方法,另請參閱 註釋 (annotation) 最佳實踐。
- __future__¶
future 陳述式:
from __future__ import <feature>,會指示編譯器使用那些在 Python 未來的發布版本中將成為標準的語法或語義,來編譯目前的模組。而__future__模組則記錄了 feature(功能)可能的值。透過 import 此模組並對其變數求值,你可以看見一個新的功能是何時首次被新增到此語言中,以及它何時將會(或已經)成為預設的功能:>>> import __future__ >>> __future__.division _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
- garbage collection(垃圾回收)¶
當記憶體不再被使用時,將其釋放的過程。Python 執行垃圾回收,是透過參照計數 (reference counting),以及一個能夠檢測和中斷參照循環 (reference cycle) 的循環垃圾回收器 (cyclic garbage collector) 來完成。垃圾回收器可以使用
gc模組對其進行控制。- generator(產生器)¶
一個會回傳 generator iterator(產生器疊代器)的函式。它看起來像一個正常的函式,但不同的是它包含了
yield運算式,能產生一系列的值,這些值可用於 for 迴圈,或是以next()函式,每次檢索其中的一個值。這個術語通常用來表示一個產生器函式,但在某些情境中,也可能是表示產生器疊代器。萬一想表達的意思不夠清楚,那就使用完整的術語,以避免歧義。
- generator iterator(產生器疊代器)¶
一個由 generator(產生器)函式所建立的物件。
每個
yield會暫停處理程序,並記住執行狀態(包括區域變數及擱置中的 try 陳述式)。當產生器疊代器回復時,它會從停止的地方繼續執行(與那些每次呼叫時都要重新開始的函式有所不同)。- generator expression(產生器運算式)¶
一個會回傳疊代器的運算式。它看起來像一個正常的運算式,後面接著一個
for子句,該子句定義了迴圈變數、範圍以及一個選擇性的if子句。該組合運算式會為外層函式產生多個值:>>> sum(i*i for i in range(10)) # 平方之和 0, 1, 4, ... 81 285
- generic function(泛型函式)¶
一個由多個函式組成的函式,該函式會對不同的型別實作相同的運算。呼叫期間應該使用哪種實作,是由調度演算法 (dispatch algorithm) 來決定。
另請參閱 single dispatch(單一調度)術語表條目、
functools.singledispatch()裝飾器和 PEP 443。- generic type(泛型型別)¶
一個能夠被參數化 (parameterized) 的 type(型別);通常是一個 容器型別,像是
list和dict。它被用於型別提示和註釋。- GIL¶
請參閱 global interpreter lock(全域直譯器鎖)。
- global interpreter lock(全域直譯器鎖)¶
CPython 直譯器所使用的機制,用以確保每次都只有一個執行緒能執行 Python 的 bytecode(位元組碼)。透過使物件模型(包括關鍵的內建型別,如
dict)自動地避免並行存取 (concurrent access) 的危險,此機制可以簡化 CPython 的實作。鎖定整個直譯器,會使直譯器更容易成為多執行緒 (multi-threaded),但代價是會犧牲掉多處理器的機器能夠提供的一大部分平行性 (parallelism)。然而,有些擴充模組,無論是標準的或是第三方的,它們被設計成在執行壓縮或雜湊等計算密集 (computationally intensive) 的任務時,可以解除 GIL。另外,在執行 I/O 時,GIL 總是會被解除。
從 Python 3.13 開始可以使用
--disable-gil建置設定來停用 GIL。使用此選項建立 Python 後,必須使用-X gil=0來執行程式碼,或者設定PYTHON_GIL=0環境變數後再執行程式碼。此功能可以提高多執行緒應用程式的效能,並使多核心 CPU 的高效使用變得更加容易。有關更多詳細資訊,請參閱 PEP 703。In prior versions of Python's C API, a function might declare that it requires the GIL to be held in order to use it. This refers to having an attached thread state.
- global state¶
Data that is accessible throughout a program, such as module-level variables, class variables, or C static variables in extension modules. In multi-threaded programs, global state shared between threads typically requires synchronization to avoid