### 导航
- [索引](../genindex.xhtml "总目录")
- [模块](../py-modindex.xhtml "Python 模块索引") |
- [下一页](pydoc.xhtml "pydoc --- Documentation generator and online help system") |
- [上一页](development.xhtml "开发工具") |
- ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png)
- [Python](https://www.python.org/) »
- zh\_CN 3.7.3 [文档](../index.xhtml) »
- [Python 标准库](index.xhtml) »
- [开发工具](development.xhtml) »
- $('.inline-search').show(0); |
# [`typing`](#module-typing "typing: Support for type hints (see PEP 484).") --- 类型标注支持
3\.5 新版功能.
**源码:** [Lib/typing.py](https://github.com/python/cpython/tree/3.7/Lib/typing.py) \[https://github.com/python/cpython/tree/3.7/Lib/typing.py\]
注解
typing 模块以 [暂定状态](../glossary.xhtml#term-provisional-api) 包含在标准库中。如果核心开发人员认为有必要,可能会添加新功能,甚至可能会在次要版本之间改变 API。
- - - - - -
此模块支持 [**PEP 484**](https://www.python.org/dev/peps/pep-0484) \[https://www.python.org/dev/peps/pep-0484\] 和 [**PEP 526**](https://www.python.org/dev/peps/pep-0526) \[https://www.python.org/dev/peps/pep-0526\] 指定的类型提示。最基本的支持由 [`Any`](#typing.Any "typing.Any"),[`Union`](#typing.Union "typing.Union"),[`Tuple`](#typing.Tuple "typing.Tuple"),[`Callable`](#typing.Callable "typing.Callable"),[`TypeVar`](#typing.TypeVar "typing.TypeVar") 和 [`Generic`](#typing.Generic "typing.Generic") 类型组成。有关完整的规范,请参阅 [**PEP 484**](https://www.python.org/dev/peps/pep-0484) \[https://www.python.org/dev/peps/pep-0484\]。有关类型提示的简单介绍,请参阅 [**PEP 483**](https://www.python.org/dev/peps/pep-0483) \[https://www.python.org/dev/peps/pep-0483\]。
函数接受并返回一个字符串,注释像下面这样:
```
def greeting(name: str) -> str:
return 'Hello ' + name
```
在函数 `greeting` 中,参数 `name` 预期是 [`str`](stdtypes.xhtml#str "str") 类型,并且返回 [`str`](stdtypes.xhtml#str "str") 类型。子类型允许作为参数。
## 类型别名
类型别名通过将类型分配给别名来定义。在这个例子中, `Vector` 和 `List[float]` 将被视为可互换的同义词:
```
from typing import List
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
```
类型别名可用于简化复杂类型签名。例如:
```
from typing import Dict, Tuple, Sequence
ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: Sequence[Server]) -> None:
...
# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
message: str,
servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
...
```
请注意,`None` 作为类型提示是一种特殊情况,并且由 `type(None)` 取代。
## NewType
使用 [`NewType()`](#typing.NewType "typing.NewType") 辅助函数创建不同的类型:
```
from typing import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
```
静态类型检查器会将新类型视为它是原始类型的子类。这对于帮助捕捉逻辑错误非常有用:
```
def get_user_name(user_id: UserId) -> str:
...
# typechecks
user_a = get_user_name(UserId(42351))
# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
```
您仍然可以对 `UserId` 类型的变量执行所有的 `int` 支持的操作,但结果将始终为 `int` 类型。这可以让你在需要 `int` 的地方传入 `UserId`,但会阻止你以无效的方式无意中创建 `UserId`:
```
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
```
请注意,这些检查仅通过静态类型检查程序强制执行。在运行时,`Derived = NewType('Derived',Base)` 将 `Derived` 一个函数,该函数立即返回您传递它的任何参数。这意味着表达式 `Derived(some_value)` 不会创建一个新的类或引入任何超出常规函数调用的开销。
更确切地说,表达式 `some_value is Derived(some_value)` 在运行时总是为真。
这也意味着无法创建 `Derived` 的子类型,因为它是运行时的标识函数,而不是实际的类型:
```
from typing import NewType
UserId = NewType('UserId', int)
# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
```
但是,可以基于'derived' `NewType` 创建 [`NewType()`](#typing.NewType "typing.NewType")
```
from typing import NewType
UserId = NewType('UserId', int)
ProUserId = NewType('ProUserId', UserId)
```
并且 `ProUserId` 的类型检查将按预期工作。
有关更多详细信息,请参阅 [**PEP 484**](https://www.python.org/dev/peps/pep-0484) \[https://www.python.org/dev/peps/pep-0484\]。
注解
回想一下,使用类型别名声明两种类型彼此 *等效* 。`Alias = Original` 将使静态类型检查对待所有情况下 `Alias` *完全等同于*`Original`。当您想简化复杂类型签名时,这很有用。
相反,`NewType` 声明一种类型是另一种类型的子类型。`Derived = NewType('Derived', Original)` 将使静态类型检查器将 `Derived` 当作 `Original` 的 *子类* ,这意味着 `Original` 类型的值不能用于 `Derived` 类型的值需要的地方。当您想以最小的运行时间成本防止逻辑错误时,这非常有用。
3\.5.2 新版功能.
## Callable
期望特定签名的回调函数的框架可以将类型标注为 `Callable[[Arg1Type, Arg2Type], ReturnType]`。
例如:
```
from typing import Callable
def feeder(get_next_item: Callable[[], str]) -> None:
# Body
def async_query(on_success: Callable[[int], None],
on_error: Callable[[int, Exception], None]) -> None:
# Body
```
通过用文字省略号替换类型提示中的参数列表: `Callable[...,ReturnType]`,可以声明可调用的返回类型,而无需指定调用签名。
## 泛型(Generic)
由于无法以通用方式静态推断有关保存在容器中的对象的类型信息,因此抽象基类已扩展为支持订阅以表示容器元素的预期类型。
```
from typing import Mapping, Sequence
def notify_by_email(employees: Sequence[Employee],
overrides: Mapping[str, str]) -> None: ...
```
泛型可以通过使用typing模块中名为 [`TypeVar`](#typing.TypeVar "typing.TypeVar") 的新工厂进行参数化。
```
from typing import Sequence, TypeVar
T = TypeVar('T') # Declare type variable
def first(l: Sequence[T]) -> T: # Generic function
return l[0]
```
## 用户定义的泛型类型
用户定义的类可以定义为泛型类。
```
from typing import TypeVar, Generic
from logging import Logger
T = TypeVar('T')
class LoggedVar(Generic[T]):
def __init__(self, value: T, name: str, logger: Logger) -> None:
self.name = name
self.logger = logger
self.value = value
def set(self, new: T) -> None:
self.log('Set ' + repr(self.value))
self.value = new
def get(self) -> T:
self.log('Get ' + repr(self.value))
return self.value
def log(self, message: str) -> None:
self.logger.info('%s: %s', self.name, message)
```
`Generic[T]` 作为基类定义了类 `LoggedVar` 采用单个类型参数 `T`。这也使得 `T` 作为类体内的一个类型有效。
[`Generic`](#typing.Generic "typing.Generic") 基类使用定义了 [`__getitem__()`](../reference/datamodel.xhtml#object.__getitem__ "object.__getitem__") 的元类,以便 `LoggedVar[t]` 作为类型有效:
```
from typing import Iterable
def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
for var in vars:
var.set(0)
```
泛型类型可以有任意数量的类型变量,并且类型变量可能会受到限制:
```
from typing import TypeVar, Generic
...
T = TypeVar('T')
S = TypeVar('S', int, str)
class StrangePair(Generic[T, S]):
...
```
[`Generic`](#typing.Generic "typing.Generic") 每个参数的类型变量必须是不同的。这是无效的:
```
from typing import TypeVar, Generic
...
T = TypeVar('T')
class Pair(Generic[T, T]): # INVALID
...
```
您可以对 [`Generic`](#typing.Generic "typing.Generic") 使用多重继承:
```
from typing import TypeVar, Generic, Sized
T = TypeVar('T')
class LinkedList(Sized, Generic[T]):
...
```
从泛型类继承时,某些类型变量可能是固定的:
```
from typing import TypeVar, Mapping
T = TypeVar('T')
class MyDict(Mapping[str, T]):
...
```
在这种情况下,`MyDict` 只有一个参数,`T`。
在不指定类型参数的情况下使用泛型类别会为每个位置假设 [`Any`](#typing.Any "typing.Any")。在下面的例子中,`MyIterable` 不是泛型,但是隐式继承自 `Iterable[Any]`:
```
from typing import Iterable
class MyIterable(Iterable): # Same as Iterable[Any]
```
用户定义的通用类型别名也受支持。例子:
```
from typing import TypeVar, Iterable, Tuple, Union
S = TypeVar('S')
Response = Union[Iterable[S], int]
# Return type here is same as Union[Iterable[str], int]
def response(query: str) -> Response[str]:
...
T = TypeVar('T', int, float, complex)
Vec = Iterable[Tuple[T, T]]
def inproduct(v: Vec[T]) -> T: # Same as Iterable[Tuple[T, T]]
return sum(x*y for x, y in v)
```
[`Generic`](#typing.Generic "typing.Generic") 使用的元类是 [`abc.ABCMeta`](abc.xhtml#abc.ABCMeta "abc.ABCMeta") 的子类。泛型类可以通过包含抽象方法或属性成为ABC,并且泛型类也可以使用ABCs作为基类而不存在元类冲突。不支持泛型元类。参数化泛型的结果被缓存,并且typing模块中的大部分类型都是可散列的,并且可以比较是否相等。
## [`Any`](#typing.Any "typing.Any") 类型
[`Any`](#typing.Any "typing.Any") 是一种特殊的类型。静态类型检查器将所有类型视为与 [`Any`](#typing.Any "typing.Any") 兼容,反之亦然, [`Any`](#typing.Any "typing.Any") 也与所有类型相兼容。
这意味着可对类型为 [`Any`](#typing.Any "typing.Any") 的值执行任何操作或方法调用,并将其赋值给任何变量:
```
from typing import Any
a = None # type: Any
a = [] # OK
a = 2 # OK
s = '' # type: str
s = a # OK
def foo(item: Any) -> int:
# Typechecks; 'item' could be any type,
# and that type might have a 'bar' method
item.bar()
...
```
需要注意的是,将 [`Any`](#typing.Any "typing.Any") 类型的值赋值给另一个更具体的类型时,Python不会执行类型检查。例如,当把 `a` 赋值给 `s` 时,即使 `s` 被声明为 [`str`](stdtypes.xhtml#str "str") 类型,在运行时接收到的是 [`int`](functions.xhtml#int "int") 值,静态类型检查器也不会报错。
此外,所有返回值无类型或形参无类型的函数将隐式地默认使用 [`Any`](#typing.Any "typing.Any") 类型:
```
def legacy_parser(text):
...
return data
# A static type checker will treat the above
# as having the same signature as:
def legacy_parser(text: Any) -> Any:
...
return data
```
当需要混用动态类型和静态类型的代码时,上述行为可以让 [`Any`](#typing.Any "typing.Any") 被用作 *应急出口* 。
[`Any`](#typing.Any "typing.Any") 和 [`object`](functions.xhtml#object "object") 的行为对比。与 [`Any`](#typing.Any "typing.Any") 相似,所有的类型都是 [`object`](functions.xhtml#object "object") 的子类型。然而不同于 [`Any`](#typing.Any "typing.Any"),反之并不成立: [`object`](functions.xhtml#object "object") *不是* 其他所有类型的子类型。
这意味着当一个值的类型是 [`object`](functions.xhtml#object "object") 的时候,类型检查器会拒绝对它的几乎所有的操作。把它赋值给一个指定了类型的变量(或者当作返回值)是一个类型错误。比如说:
```
def hash_a(item: object) -> int:
# Fails; an object does not have a 'magic' method.
item.magic()
...
def hash_b(item: Any) -> int:
# Typechecks
item.magic()
...
# Typechecks, since ints and strs are subclasses of object
hash_a(42)
hash_a("foo")
# Typechecks, since Any is compatible with all types
hash_b(42)
hash_b("foo")
```
使用 [`object`](functions.xhtml#object "object") 示意一个值可以类型安全地兼容任何类型。使用 [`Any`](#typing.Any "typing.Any") 示意一个值地类型是动态定义的。
## 类,函数和修饰器.
这个模块定义了如下的类,模块和修饰器.
*class* `typing.``TypeVar`类型变量
用法:
```
T = TypeVar('T') # Can be anything
A = TypeVar('A', str, bytes) # Must be str or bytes
```
Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows:
```
def repeat(x: T, n: int) -> Sequence[T]:
"""Return a list containing n references to x."""
return [x]*n
def longest(x: A, y: A) -> A:
"""Return the longest of two strings."""
return x if len(x) >= len(y) else y
```
The latter example's signature is essentially the overloading of `(str, str) -> str` and `(bytes, bytes) -> bytes`. Also note that if the arguments are instances of some subclass of [`str`](stdtypes.xhtml#str "str"), the return type is still plain [`str`](stdtypes.xhtml#str "str").
`isinstance(x, T)` 会在运行时抛出 [`TypeError`](exceptions.xhtml#TypeError "TypeError") 异常。一般地说, [`isinstance()`](functions.xhtml#isinstance "isinstance") 和 [`issubclass()`](functions.xhtml#issubclass "issubclass") 不应该和类型一起使用。
Type variables may be marked covariant or contravariant by passing `covariant=True` or `contravariant=True`. See [**PEP 484**](https://www.python.org/dev/peps/pep-0484) \[https://www.python.org/dev/peps/pep-0484\] for more details. By default type variables are invariant. Alternatively, a type variable may specify an upper bound using `bound=<type>`. This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type, see [**PEP 484**](https://www.python.org/dev/peps/pep-0484) \[https://www.python.org/dev/peps/pep-0484\].
*class* `typing.``Generic`Abstract base class for generic types.
A generic type is typically declared by inheriting from an instantiation of this class with one or more type variables. For example, a generic mapping type might be defined as:
```
class Mapping(Generic[KT, VT]):
def __getitem__(self, key: KT) -> VT:
...
# Etc.
```
这个类之后可以被这样用:
```
X = TypeVar('X')
Y = TypeVar('Y')
def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:
try:
return mapping[key]
except KeyError:
return default
```
*class* `typing.``Type`(*Generic\[CT\_co\]*)A variable annotated with `C` may accept a value of type `C`. In contrast, a variable annotated with `Type[C]` may accept values that are classes themselves -- specifically, it will accept the *class object* of `C`. For example:
```
a = 3 # Has type 'int'
b = int # Has type 'Type[int]'
c = type(a) # Also has type 'Type[int]'
```
Note that `Type[C]` is covariant:
```
class User: ...
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...
# Accepts User, BasicUser, ProUser, TeamUser, ...
def make_new_user(user_class: Type[User]) -> User:
# ...
return user_class()
```
The fact that `Type[C]` is covariant implies that all subclasses of `C` should implement the same constructor signature and class method signatures as `C`. The type checker should flag violations of this, but should also allow constructor calls in subclasses that match the constructor calls in the indicated base class. How the type checker is required to handle this particular case may change in future revisions of [**PEP 484**](https://www.python.org/dev/peps/pep-0484) \[https://www.python.org/dev/peps/pep-0484\].
The only legal parameters for [`Type`](#typing.Type "typing.Type") are classes, [`Any`](#typing.Any "typing.Any"), [type variables](#generics), and unions of any of these types. For example:
```
def new_non_team_user(user_class: Type[Union[BaseUser, ProUser]]): ...
```
`Type[Any]` is equivalent to `Type` which in turn is equivalent to `type`, which is the root of Python's metaclass hierarchy.
3\.5.2 新版功能.
*class* `typing.``Iterable`(*Generic\[T\_co\]*)[`collections.abc.Iterable`](collections.abc.xhtml#collections.abc.Iterable "collections.abc.Iterable") 的泛型版本。
*class* `typing.``Iterator`(*Iterable\[T\_co\]*)[`collections.abc.Iterator`](collections.abc.xhtml#collections.abc.Iterator "collections.abc.Iterator") 的泛型版本。
*class* `typing.``Reversible`(*Iterable\[T\_co\]*)[`collections.abc.Reversible`](collections.abc.xhtml#collections.abc.Reversible "collections.abc.Reversible") 的泛型版本。
*class* `typing.``SupportsInt`An ABC with one abstract method `__int__`.
*class* `typing.``SupportsFloat`An ABC with one abstract method `__float__`.
*class* `typing.``SupportsComplex`An ABC with one abstract method `__complex__`.
*class* `typing.``SupportsBytes`An ABC with one abstract method `__bytes__`.
*class* `typing.``SupportsAbs`An ABC with one abstract method `__abs__` that is covariant in its return type.
*class* `typing.``SupportsRound`An ABC with one abstract method `__round__`that is covariant in its return type.
*class* `typing.``Container`(*Generic\[T\_co\]*)[`collections.abc.Container`](collections.abc.xhtml#collections.abc.Container "collections.abc.Container") 的泛型版本。
*class* `typing.``Hashable`[`collections.abc.Hashable`](collections.abc.xhtml#collections.abc.Hashable "collections.abc.Hashable") 的别名。
*class* `typing.``Sized`[`collections.abc.Sized`](collections.abc.xhtml#collections.abc.Sized "collections.abc.Sized") 的别名。
*class* `typing.``Collection`(*Sized, Iterable\[T\_co\], Container\[T\_co\]*)[`collections.abc.Collection`](collections.abc.xhtml#collections.abc.Collection "collections.abc.Collection") 的泛型版本。
3\.6 新版功能.
*class* `typing.``AbstractSet`(*Sized, Collection\[T\_co\]*)[`collections.abc.Set`](collections.abc.xhtml#collections.abc.Set "collections.abc.Set") 的泛型版本。
*class* `typing.``MutableSet`(*AbstractSet\[T\]*)[`collections.abc.MutableSet`](collections.abc.xhtml#collections.abc.MutableSet "collections.abc.MutableSet") 的泛型版本。
*class* `typing.``Mapping`(*Sized, Collection\[KT\], Generic\[VT\_co\]*)[`collections.abc.Mapping`](collections.abc.xhtml#collections.abc.Mapping "collections.abc.Mapping") 的泛型版本。这个类型可以如下使用:
```
def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
return word_list[word]
```
*class* `typing.``MutableMapping`(*Mapping\[KT, VT\]*)[`collections.abc.MutableMapping`](collections.abc.xhtml#collections.abc.MutableMapping "collections.abc.MutableMapping") 的泛型版本。
*class* `typing.``Sequence`(*Reversible\[T\_co\], Collection\[T\_co\]*)[`collections.abc.Sequence`](collections.abc.xhtml#collections.abc.Sequence "collections.abc.Sequence") 的泛型版本。
*class* `typing.``MutableSequence`(*Sequence\[T\]*)[`collections.abc.MutableSequence`](collections.abc.xhtml#collections.abc.MutableSequence "collections.abc.MutableSequence") 的泛型版本。
*class* `typing.``ByteString`(*Sequence\[int\]*)[`collections.abc.ByteString`](collections.abc.xhtml#collections.abc.ByteString "collections.abc.ByteString") 的泛型版本。
This type represents the types [`bytes`](stdtypes.xhtml#bytes "bytes"), [`bytearray`](stdtypes.xhtml#bytearray "bytearray"), and [`memoryview`](stdtypes.xhtml#memoryview "memoryview").
As a shorthand for this type, [`bytes`](stdtypes.xhtml#bytes "bytes") can be used to annotate arguments of any of the types mentioned above.
*class* `typing.``Deque`(*deque, MutableSequence\[T\]*)[`collections.deque`](collections.xhtml#collections.deque "collections.deque") 的泛型版本。
3\.6.1 新版功能.
*class* `typing.``List`(*list, MutableSequence\[T\]*)Generic version of [`list`](stdtypes.xhtml#list "list"). Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as [`Sequence`](#typing.Sequence "typing.Sequence") or [`Iterable`](#typing.Iterable "typing.Iterable").
这个类型可以这样用:
```
T = TypeVar('T', int, float)
def vec2(x: T, y: T) -> List[T]:
return [x, y]
def keep_positives(vector: Sequence[T]) -> List[T]:
return [item for item in vector if item > 0]
```
*class* `typing.``Set`(*set, MutableSet\[T\]*)A generic version of [`builtins.set`](stdtypes.xhtml#set "set"). Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as [`AbstractSet`](#typing.AbstractSet "typing.AbstractSet").
*class* `typing.``FrozenSet`(*frozenset, AbstractSet\[T\_co\]*)A generic version of [`builtins.frozenset`](stdtypes.xhtml#frozenset "frozenset").
*class* `typing.``MappingView`(*Sized, Iterable\[T\_co\]*)[`collections.abc.MappingView`](collections.abc.xhtml#collections.abc.MappingView "collections.abc.MappingView") 的泛型版本。
*class* `typing.``KeysView`(*MappingView\[KT\_co\], AbstractSet\[KT\_co\]*)[`collections.abc.KeysView`](collections.abc.xhtml#collections.abc.KeysView "collections.abc.KeysView") 的泛型版本。
*class* `typing.``ItemsView`(*MappingView, Generic\[KT\_co, VT\_co\]*)[`collections.abc.ItemsView`](collections.abc.xhtml#collections.abc.ItemsView "collections.abc.ItemsView") 的泛型版本。
*class* `typing.``ValuesView`(*MappingView\[VT\_co\]*)[`collections.abc.ValuesView`](collections.abc.xhtml#collections.abc.ValuesView "collections.abc.ValuesView") 的泛型版本。
*class* `typing.``Awaitable`(*Generic\[T\_co\]*)[`collections.abc.Awaitable`](collections.abc.xhtml#collections.abc.Awaitable "collections.abc.Awaitable") 的泛型版本。
*class* `typing.``Coroutine`(*Awaitable\[V\_co\], Generic\[T\_co T\_contra, V\_co\]*)A generic version of [`collections.abc.Coroutine`](collections.abc.xhtml#collections.abc.Coroutine "collections.abc.Coroutine"). The variance and order of type variables correspond to those of [`Generator`](#typing.Generator "typing.Generator"), for example:
```
from typing import List, Coroutine
c = None # type: Coroutine[List[str], str, int]
...
x = c.send('hi') # type: List[str]
async def bar() -> None:
x = await c # type: int
```
*class* `typing.``AsyncIterable`(*Generic\[T\_co\]*)[`collections.abc.AsyncIterable`](collections.abc.xhtml#collections.abc.AsyncIterable "collections.abc.AsyncIterable") 的泛型版本。
*class* `typing.``AsyncIterator`(*AsyncIterable\[T\_co\]*)[`collections.abc.AsyncIterator`](collections.abc.xhtml#collections.abc.AsyncIterator "collections.abc.AsyncIterator") 的泛型版本。
*class* `typing.``ContextManager`(*Generic\[T\_co\]*)[`contextlib.AbstractContextManager`](contextlib.xhtml#contextlib.AbstractContextManager "contextlib.AbstractContextManager") 的泛型版本。
3\.6 新版功能.
*class* `typing.``AsyncContextManager`(*Generic\[T\_co\]*)[`contextlib.AbstractAsyncContextManager`](contextlib.xhtml#contextlib.AbstractAsyncContextManager "contextlib.AbstractAsyncContextManager") 的泛型版本。
3\.6 新版功能.
*class* `typing.``Dict`(*dict, MutableMapping\[KT, VT\]*)[`dict`](stdtypes.xhtml#dict "dict") 的泛型版本。对标注返回类型比较有用。如果要标注参数的话,使用如 [`Mapping`](#typing.Mapping "typing.Mapping") 的抽象容器类型是更好的选择。
这个类型可以这样使用:
```
def count_words(text: str) -> Dict[str, int]:
...
```
*class* `typing.``DefaultDict`(*collections.defaultdict, MutableMapping\[KT, VT\]*)[`collections.defaultdict`](collections.xhtml#collections.defaultdict "collections.defaultdict") 的泛型版本。
3\.5.2 新版功能.
*class* `typing.``OrderedDict`(*collections.OrderedDict, MutableMapping\[KT, VT\]*)[`collections.OrderedDict`](collections.xhtml#collections.OrderedDict "collections.OrderedDict") 的泛型版本。
3\.7.2 新版功能.
*class* `typing.``Counter`(*collections.Counter, Dict\[T, int\]*)[`collections.Counter`](collections.xhtml#collections.Counter "collections.Counter") 的泛型版本。
3\.6.1 新版功能.
*class* `typing.``ChainMap`(*collections.ChainMap, MutableMapping\[KT, VT\]*)[`collections.ChainMap`](collections.xhtml#collections.ChainMap "collections.ChainMap") 的泛型版本。
3\.6.1 新版功能.
*class* `typing.``Generator`(*Iterator\[T\_co\], Generic\[T\_co, T\_contra, V\_co\]*)A generator can be annotated by the generic type `Generator[YieldType, SendType, ReturnType]`. For example:
```
def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
```
Note that unlike many other generics in the typing module, the `SendType`of [`Generator`](#typing.Generator "typing.Generator") behaves contravariantly, not covariantly or invariantly.
If your generator will only yield values, set the `SendType` and `ReturnType` to `None`:
```
def infinite_stream(start: int) -> Generator[int, None, None]:
while True:
yield start
start += 1
```
Alternatively, annotate your generator as having a return type of either `Iterable[YieldType]` or `Iterator[YieldType]`:
```
def infinite_stream(start: int) -> Iterator[int]:
while True:
yield start
start += 1
```
*class* `typing.``AsyncGenerator`(*AsyncIterator\[T\_co\], Generic\[T\_co, T\_contra\]*)An async generator can be annotated by the generic type `AsyncGenerator[YieldType, SendType]`. For example:
```
async def echo_round() -> AsyncGenerator[int, float]:
sent = yield 0
while sent >= 0.0:
rounded = await round(sent)
sent = yield rounded
```
Unlike normal generators, async generators cannot return a value, so there is no `ReturnType` type parameter. As with [`Generator`](#typing.Generator "typing.Generator"), the `SendType` behaves contravariantly.
If your generator will only yield values, set the `SendType` to `None`:
```
async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
while True:
yield start
start = await increment(start)
```
Alternatively, annotate your generator as having a return type of either `AsyncIterable[YieldType]` or `AsyncIterator[YieldType]`:
```
async def infinite_stream(start: int) -> AsyncIterator[int]:
while True:
yield start
start = await increment(start)
```
3\.5.4 新版功能.
*class* `typing.``Text``Text` is an alias for `str`. It is provided to supply a forward compatible path for Python 2 code: in Python 2, `Text` is an alias for `unicode`.
Use `Text` to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:
```
def add_unicode_checkmark(text: Text) -> Text:
return text + u' \u2713'
```
3\.5.2 新版功能.
*class* `typing.``IO`*class* `typing.``TextIO`*class* `typing.``BinaryIO`Generic type `IO[AnyStr]` and its subclasses `TextIO(IO[str])`and `BinaryIO(IO[bytes])`represent the types of I/O streams such as returned by [`open()`](functions.xhtml#open "open").
*class* `typing.``Pattern`*class* `typing.``Match`These type aliases correspond to the return types from [`re.compile()`](re.xhtml#re.compile "re.compile") and [`re.match()`](re.xhtml#re.match "re.match"). These types (and the corresponding functions) are generic in `AnyStr` and can be made specific by writing `Pattern[str]`, `Pattern[bytes]`, `Match[str]`, or `Match[bytes]`.
*class* `typing.``NamedTuple`Typed version of [`collections.namedtuple()`](collections.xhtml#collections.namedtuple "collections.namedtuple").
用法:
```
class Employee(NamedTuple):
name: str
id: int
```
This is equivalent to:
```
Employee = collections.namedtuple('Employee', ['name', 'id'])
```
To give a field a default value, you can assign to it in the class body:
```
class Employee(NamedTuple):
name: str
id: int = 3
employee = Employee('Guido')
assert employee.id == 3
```
Fields with a default value must come after any fields without a default.
The resulting class has two extra attributes: `_field_types`, giving a dict mapping field names to types, and `_field_defaults`, a dict mapping field names to default values. (The field names are in the `_fields` attribute, which is part of the namedtuple API.)
`NamedTuple` subclasses can also have docstrings and methods:
```
class Employee(NamedTuple):
"""Represents an employee."""
name: str
id: int = 3
def __repr__(self) -> str:
return f'<Employee {self.name}, id={self.id}>'
```
Backward-compatible usage:
```
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
```
在 3.6 版更改: Added support for [**PEP 526**](https://www.python.org/dev/peps/pep-0526) \[https://www.python.org/dev/peps/pep-0526\] variable annotation syntax.
在 3.6.1 版更改: Added support for default values, methods, and docstrings.
`typing.``NewType`(*typ*)A helper function to indicate a distinct types to a typechecker, see [NewType](#distinct). At runtime it returns a function that returns its argument. Usage:
```
UserId = NewType('UserId', int)
first_user = UserId(1)
```
3\.5.2 新版功能.
`typing.``cast`(*typ*, *val*)Cast a value to a type.
This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible).
`typing.``get_type_hints`(*obj*\[, *globals*\[, *locals*\]\])返回一个字典,字典内含有函数、方法、模块或类对象的类型提示。
This is often the same as `obj.__annotations__`. In addition, forward references encoded as string literals are handled by evaluating them in `globals` and `locals` namespaces. If necessary, `Optional[t]` is added for function and method annotations if a default value equal to `None` is set. For a class `C`, return a dictionary constructed by merging all the `__annotations__` along `C.__mro__` in reverse order.
`@``typing.``overload`The `@overload` decorator allows describing functions and methods that support multiple different combinations of argument types. A series of `@overload`-decorated definitions must be followed by exactly one non-`@overload`-decorated definition (for the same function/method). The `@overload`-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-`@overload`-decorated definition, while the latter is used at runtime but should be ignored by a type checker. At runtime, calling a `@overload`-decorated function directly will raise [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError"). An example of overload that gives a more precise type than can be expressed using a union or a type variable:
```
@overload
def process(response: None) -> None:
...
@overload
def process(response: int) -> Tuple[int, str]:
...
@overload
def process(response: bytes) -> str:
...
def process(response):
<actual implementation>
```
See [**PEP 484**](https://www.python.org/dev/peps/pep-0484) \[https://www.python.org/dev/peps/pep-0484\] for details and comparison with other typing semantics.
`@``typing.``no_type_check`用于指明标注不是类型提示的装饰器。
此 [decorator](../glossary.xhtml#term-decorator) 装饰器生效于类或函数上。如果作用于类上的话,它会递归地作用于这个类的所定义的所有方法上(但是对于超类或子类所定义的方法不会生效)。
此方法会就地地修改函数。
`@``typing.``no_type_check_decorator`使其它装饰器起到 [`no_type_check()`](#typing.no_type_check "typing.no_type_check") 效果的装饰器。
This wraps the decorator with something that wraps the decorated function in [`no_type_check()`](#typing.no_type_check "typing.no_type_check").
`@``typing.``type_check_only`标记一个类或函数在运行时内不可用的装饰器。
This decorator is itself not available at runtime. It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class:
```
@type_check_only
class Response: # private or not available at runtime
code: int
def get_header(self, name: str) -> str: ...
def fetch_response() -> Response: ...
```
Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public.
`typing.``Any`特殊类型,表明类型没有任何限制。
- 每一个类型都对 [`Any`](#typing.Any "typing.Any") 兼容。
- [`Any`](#typing.Any "typing.Any") 对每一个类型都兼容。
`typing.``NoReturn`标记一个函数没有返回值的特殊类型。比如说:
```
from typing import NoReturn
def stop() -> NoReturn:
raise RuntimeError('no way')
```
3\.5.4 新版功能.
`typing.``Union`联合类型; `Union[X, Y]` 意味着:要不是 X,要不是 Y。
使用形如 `Union[int, str]` 的形式来定义一个联合类型。细节如下:
- 参数必须是类型,而且必须至少有一个参数。
- 联合类型的联合类型会被展开打平,比如:
```
Union[Union[int, str], float] == Union[int, str, float]
```
- 仅有一个参数的联合类型会坍缩成参数自身,比如:
```
Union[int] == int # The constructor actually returns int
```
- 多余的参数会被跳过,比如:
```
Union[int, str, int] == Union[int, str]
```
- 在比较联合类型的时候,参数顺序会被忽略,比如:
```
Union[int, str] == Union[str, int]
```
- 你不能继承或者实例化一个联合类型。
- 你不能写成 `Union[X][Y]` 。
- 你可以使用 `Optional[X]` 作为 `Union[X, None]` 的缩写。
在 3.7 版更改: 不要在运行时内从联合类型中移除显式说明的子类。
`typing.``Optional`Optional type.
`Optional[X]` is equivalent to `Union[X, None]`.
Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the `Optional` qualifier on its type annotation just because it is optional. For example:
```
def foo(arg: int = 0) -> None:
...
```
On the other hand, if an explicit value of `None` is allowed, the use of `Optional` is appropriate, whether the argument is optional or not. For example:
```
def foo(arg: Optional[int] = None) -> None:
...
```
`typing.``Tuple`Tuple type; `Tuple[X, Y]` is the type of a tuple of two items with the first item of type X and the second of type Y.
Example: `Tuple[T1, T2]` is a tuple of two elements corresponding to type variables T1 and T2. `Tuple[int, float, str]` is a tuple of an int, a float and a string.
To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. `Tuple[int, ...]`. A plain [`Tuple`](#typing.Tuple "typing.Tuple")is equivalent to `Tuple[Any, ...]`, and in turn to [`tuple`](stdtypes.xhtml#tuple "tuple").
`typing.``Callable`Callable type; `Callable[[int], str]` is a function of (int) -> str.
The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or an ellipsis; the return type must be a single type.
There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. `Callable[..., ReturnType]` (literal ellipsis) can be used to type hint a callable taking any number of arguments and returning `ReturnType`. A plain [`Callable`](#typing.Callable "typing.Callable") is equivalent to `Callable[..., Any]`, and in turn to [`collections.abc.Callable`](collections.abc.xhtml#collections.abc.Callable "collections.abc.Callable").
`typing.``ClassVar`Special type construct to mark class variables.
As introduced in [**PEP 526**](https://www.python.org/dev/peps/pep-0526) \[https://www.python.org/dev/peps/pep-0526\], a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:
```
class Starship:
stats: ClassVar[Dict[str, int]] = {} # class variable
damage: int = 10 # instance variable
```
[`ClassVar`](#typing.ClassVar "typing.ClassVar") accepts only types and cannot be further subscribed.
[`ClassVar`](#typing.ClassVar "typing.ClassVar") is not a class itself, and should not be used with [`isinstance()`](functions.xhtml#isinstance "isinstance") or [`issubclass()`](functions.xhtml#issubclass "issubclass"). [`ClassVar`](#typing.ClassVar "typing.ClassVar") does not change Python runtime behavior, but it can be used by third-party type checkers. For example, a type checker might flag the following code as an error:
```
enterprise_d = Starship(3000)
enterprise_d.stats = {} # Error, setting class variable on instance
Starship.stats = {} # This is OK
```
3\.5.3 新版功能.
`typing.``AnyStr``AnyStr` is a type variable defined as `AnyStr = TypeVar('AnyStr', str, bytes)`.
It is meant to be used for functions that may accept any kind of string without allowing different kinds of strings to mix. For example:
```
def concat(a: AnyStr, b: AnyStr) -> AnyStr:
return a + b
concat(u"foo", u"bar") # Ok, output has type 'unicode'
concat(b"foo", b"bar") # Ok, output has type 'bytes'
concat(u"foo", b"bar") # Error, cannot mix unicode and bytes
```
`typing.``TYPE_CHECKING`A special constant that is assumed to be `True` by 3rd party static type checkers. It is `False` at runtime. Usage:
```
if TYPE_CHECKING:
import expensive_mod
def fun(arg: 'expensive_mod.SomeType') -> None:
local_var: expensive_mod.AnotherType = other_fun()
```
Note that the first type annotation must be enclosed in quotes, making it a "forward reference", to hide the `expensive_mod` reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.
3\.5.2 新版功能.
### 导航
- [索引](../genindex.xhtml "总目录")
- [模块](../py-modindex.xhtml "Python 模块索引") |
- [下一页](pydoc.xhtml "pydoc --- Documentation generator and online help system") |
- [上一页](development.xhtml "开发工具") |
- ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png)
- [Python](https://www.python.org/) »
- zh\_CN 3.7.3 [文档](../index.xhtml) »
- [Python 标准库](index.xhtml) »
- [开发工具](development.xhtml) »
- $('.inline-search').show(0); |
© [版权所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 软件基金会是一个非盈利组织。 [请捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [发现了问题](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 创建。
- Python文档内容
- Python 有什么新变化?
- Python 3.7 有什么新变化
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- C API 的改变
- 构建的改变
- 性能优化
- 其他 CPython 实现的改变
- 已弃用的 Python 行为
- 已弃用的 Python 模块、函数和方法
- 已弃用的 C API 函数和类型
- 平台支持的移除
- API 与特性的移除
- 移除的模块
- Windows 专属的改变
- 移植到 Python 3.7
- Python 3.7.1 中的重要变化
- Python 3.7.2 中的重要变化
- Python 3.6 有什么新变化A
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- 性能优化
- Build and C API Changes
- 其他改进
- 弃用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要变化
- Python 3.6.4 中的重要变化
- Python 3.6.5 中的重要变化
- Python 3.6.7 中的重要变化
- Python 3.5 有什么新变化
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- Other module-level changes
- 性能优化
- Build and C API Changes
- 弃用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 发布重点
- 新的特性
- 新增模块
- 改进的模块
- CPython Implementation Changes
- 弃用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 发布重点
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他语言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模块
- 改进的模块
- 性能优化
- Build and C API Changes
- 弃用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- 多线程
- 性能优化
- Unicode
- Codecs
- 文档
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- 性能优化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他语言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新变化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他语言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他语言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推导式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最终版
- Python 3.7.3 发布候选版 1
- Python 3.7.2 最终版
- Python 3.7.2 发布候选版 1
- Python 3.7.1 最终版
- Python 3.7.1 RC 2版本
- Python 3.7.1 发布候选版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 课前甜点
- 使用 Python 解释器
- 调用解释器
- 解释器的运行环境
- Python 的非正式介绍
- Python 作为计算器使用
- 走向编程的第一步
- 其他流程控制工具
- if 语句
- for 语句
- range() 函数
- break 和 continue 语句,以及循环中的 else 子句
- pass 语句
- 定义函数
- 函数定义的更多形式
- 小插曲:编码风格
- 数据结构
- 列表的更多特性
- del 语句
- 元组和序列
- 集合
- 字典
- 循环的技巧
- 深入条件控制
- 序列和其它类型的比较
- 模块
- 有关模块的更多信息
- 标准模块
- dir() 函数
- 包
- 输入输出
- 更漂亮的输出格式
- 读写文件
- 错误和异常
- 语法错误
- 异常
- 处理异常
- 抛出异常
- 用户自定义异常
- 定义清理操作
- 预定义的清理操作
- 类
- 名称和对象
- Python 作用域和命名空间
- 初探类
- 补充说明
- 继承
- 私有变量
- 杂项说明
- 迭代器
- 生成器
- 生成器表达式
- 标准库简介
- 操作系统接口
- 文件通配符
- 命令行参数
- 错误输出重定向和程序终止
- 字符串模式匹配
- 数学
- 互联网访问
- 日期和时间
- 数据压缩
- 性能测量
- 质量控制
- 自带电池
- 标准库简介 —— 第二部分
- 格式化输出
- 模板
- 使用二进制数据记录格式
- 多线程
- 日志
- 弱引用
- 用于操作列表的工具
- 十进制浮点运算
- 虚拟环境和包
- 概述
- 创建虚拟环境
- 使用pip管理包
- 接下来?
- 交互式编辑和编辑历史
- Tab 补全和编辑历史
- 默认交互式解释器的替代品
- 浮点算术:争议和限制
- 表示性错误
- 附录
- 交互模式
- 安装和使用 Python
- 命令行与环境
- 命令行
- 环境变量
- 在Unix平台中使用Python
- 获取最新版本的Python
- 构建Python
- 与Python相关的路径和文件
- 杂项
- 编辑器和集成开发环境
- 在Windows上使用 Python
- 完整安装程序
- Microsoft Store包
- nuget.org 安装包
- 可嵌入的包
- 替代捆绑包
- 配置Python
- 适用于Windows的Python启动器
- 查找模块
- 附加模块
- 在Windows上编译Python
- 其他平台
- 在苹果系统上使用 Python
- 获取和安装 MacPython
- IDE
- 安装额外的 Python 包
- Mac 上的图形界面编程
- 在 Mac 上分发 Python 应用程序
- 其他资源
- Python 语言参考
- 概述
- 其他实现
- 标注
- 词法分析
- 行结构
- 其他形符
- 标识符和关键字
- 字面值
- 运算符
- 分隔符
- 数据模型
- 对象、值与类型
- 标准类型层级结构
- 特殊方法名称
- 协程
- 执行模型
- 程序的结构
- 命名与绑定
- 异常
- 导入系统
- importlib
- 包
- 搜索
- 加载
- 基于路径的查找器
- 替换标准导入系统
- Package Relative Imports
- 有关 main 的特殊事项
- 开放问题项
- 参考文献
- 表达式
- 算术转换
- 原子
- 原型
- await 表达式
- 幂运算符
- 一元算术和位运算
- 二元算术运算符
- 移位运算
- 二元位运算
- 比较运算
- 布尔运算
- 条件表达式
- lambda 表达式
- 表达式列表
- 求值顺序
- 运算符优先级
- 简单语句
- 表达式语句
- 赋值语句
- assert 语句
- pass 语句
- del 语句
- return 语句
- yield 语句
- raise 语句
- break 语句
- continue 语句
- import 语句
- global 语句
- nonlocal 语句
- 复合语句
- if 语句
- while 语句
- for 语句
- try 语句
- with 语句
- 函数定义
- 类定义
- 协程
- 最高层级组件
- 完整的 Python 程序
- 文件输入
- 交互式输入
- 表达式输入
- 完整的语法规范
- Python 标准库
- 概述
- 可用性注释
- 内置函数
- 内置常量
- 由 site 模块添加的常量
- 内置类型
- 逻辑值检测
- 布尔运算 — and, or, not
- 比较
- 数字类型 — int, float, complex
- 迭代器类型
- 序列类型 — list, tuple, range
- 文本序列类型 — str
- 二进制序列类型 — bytes, bytearray, memoryview
- 集合类型 — set, frozenset
- 映射类型 — dict
- 上下文管理器类型
- 其他内置类型
- 特殊属性
- 内置异常
- 基类
- 具体异常
- 警告
- 异常层次结构
- 文本处理服务
- string — 常见的字符串操作
- re — 正则表达式操作
- 模块 difflib 是一个计算差异的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 数据库
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函数
- 二进制数据服务
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 数据类型
- datetime — 基础日期/时间数据类型
- calendar — General calendar-related functions
- collections — 容器数据类型
- collections.abc — 容器的抽象基类
- heapq — 堆队列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 浅层 (shallow) 和深层 (deep) 复制操作
- pprint — 数据美化输出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 数字和数学模块
- numbers — 数字的抽象基类
- math — 数学函数
- cmath — Mathematical functions for complex numbers
- decimal — 十进制定点和浮点运算
- fractions — 分数
- random — 生成伪随机数
- statistics — Mathematical statistics functions
- 函数式编程模块
- itertools — 为高效循环而创建迭代器的函数
- functools — 高阶函数和可调用对象上的操作
- operator — 标准运算符替代函数
- 文件和目录访问
- pathlib — 面向对象的文件系统路径
- os.path — 常见路径操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路径操作函数
- 数据持久化
- pickle —— Python 对象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 数据库 DB-API 2.0 接口模块
- 数据压缩和存档
- zlib — 与 gzip 兼容的压缩
- gzip — 对 gzip 格式的支持
- bz2 — 对 bzip2 压缩算法的支持
- lzma — 用 LZMA 算法压缩
- zipfile — 在 ZIP 归档中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件读写
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服务
- hashlib — 安全哈希与消息摘要
- hmac — 基于密钥的消息验证
- secrets — Generate secure random numbers for managing secrets
- 通用操作系统服务
- os — 操作系统接口模块
- io — 处理流的核心工具
- time — 时间的访问和转换
- argparse — 命令行选项、参数和子命令解析器
- getopt — C-style parser for command line options
- 模块 logging — Python 的日志记录工具
- logging.config — 日志记录配置
- logging.handlers — Logging handlers
- getpass — 便携式密码输入工具
- curses — 终端字符单元显示的处理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函数库
- 并发执行
- threading — 基于线程的并行
- multiprocessing — 基于进程的并行
- concurrent 包
- concurrent.futures — 启动并行任务
- subprocess — 子进程管理
- sched — 事件调度器
- queue — 一个同步的队列类
- _thread — 底层多线程 API
- _dummy_thread — _thread 的替代模块
- dummy_threading — 可直接替代 threading 模块。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 网络和进程间通信
- asyncio — 异步 I/O
- socket — 底层网络接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高级 I/O 复用库
- asyncore — 异步socket处理器
- asynchat — 异步 socket 指令/响应 处理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互联网数据处理
- email — 电子邮件与 MIME 处理包
- json — JSON 编码和解码器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 数据编码
- binhex — 对binhex4文件进行编码和解码
- binascii — 二进制和 ASCII 码互转
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 结构化标记处理工具
- html — 超文本标记语言支持
- html.parser — 简单的 HTML 和 XHTML 解析器
- html.entities — HTML 一般实体的定义
- XML处理模块
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互联网协议和支持
- webbrowser — 方便的Web浏览器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 处理模块
- urllib.request — 用于打开 URL 的可扩展库
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模块
- http.client — HTTP协议客户端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP协议客户端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服务器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服务端与客户端模块
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒体服务
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 读写 Sun AU 文件
- wave — 读写WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推测图像类型
- sndhdr — 推测声音文件的类型
- ossaudiodev — Access to OSS-compatible audio devices
- 国际化
- gettext — 多语种国际化服务
- locale — 国际化服务
- 程序框架
- turtle — 海龟绘图
- cmd — 支持面向行的命令解释器
- shlex — Simple lexical analysis
- Tk图形用户界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滚动文字控件
- IDLE
- 其他图形用户界面(GUI)包
- 开发工具
- typing — 类型标注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 单元测试框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自动将 Python 2 代码转为 Python 3 代码
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 调试和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 测量小代码片段的执行时间
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 软件打包和分发
- distutils — 构建和安装 Python 模块
- ensurepip — Bootstrapping the pip installer
- venv — 创建虚拟环境
- zipapp — Manage executable Python zip archives
- Python运行时服务
- sys — 系统相关的参数和函数
- sysconfig — Provide access to Python's configuration information
- builtins — 内建对象
- main — 顶层脚本环境
- warnings — Warning control
- dataclasses — 数据类
- contextlib — Utilities for with-statement contexts
- abc — 抽象基类
- atexit — 退出处理器
- traceback — Print or retrieve a stack traceback
- future — Future 语句定义
- gc — 垃圾回收器接口
- inspect — 检查对象
- site — Site-specific configuration hook
- 自定义 Python 解释器
- code — Interpreter base classes
- codeop — Compile Python code
- 导入模块
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找脚本使用的模块
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 语言服务
- parser — Access Python parse trees
- ast — 抽象语法树
- symtable — Access to the compiler's symbol tables
- symbol — 与 Python 解析树一起使用的常量
- token — 与Python解析树一起使用的常量
- keyword — 检验Python关键字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊缩进检测
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字节码反汇编器
- pickletools — Tools for pickle developers
- 杂项服务
- formatter — Generic output formatting
- Windows系统相关模块
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注册表访问
- winsound — Sound-playing interface for Windows
- Unix 专有服务
- posix — The most common POSIX system calls
- pwd — 用户密码数据库
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 终端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 库例程
- 被取代的模块
- optparse — Parser for command line options
- imp — Access the import internals
- 未创建文档的模块
- 平台特定模块
- 扩展和嵌入 Python 解释器
- 推荐的第三方工具
- 不使用第三方工具创建扩展
- 使用 C 或 C++ 扩展 Python
- 自定义扩展类型:教程
- 定义扩展类型:已分类主题
- 构建C/C++扩展
- 在Windows平台编译C和C++扩展
- 在更大的应用程序中嵌入 CPython 运行时
- Embedding Python in Another Application
- Python/C API 参考手册
- 概述
- 代码标准
- 包含文件
- 有用的宏
- 对象、类型和引用计数
- 异常
- 嵌入Python
- 调试构建
- 稳定的应用程序二进制接口
- The Very High Level Layer
- Reference Counting
- 异常处理
- Printing and clearing
- 抛出异常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 标准异常
- 标准警告类别
- 工具
- 操作系统实用程序
- 系统功能
- 过程控制
- 导入模块
- Data marshalling support
- 语句解释及变量编译
- 字符串转换与格式化
- 反射
- 编解码器注册与支持功能
- 抽象对象层
- Object Protocol
- 数字协议
- Sequence Protocol
- Mapping Protocol
- 迭代器协议
- 缓冲协议
- Old Buffer Protocol
- 具体的对象层
- 基本对象
- 数值对象
- 序列对象
- 容器对象
- 函数对象
- 其他对象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置变量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 内存管理
- 概述
- 原始内存接口
- Memory Interface
- 对象分配器
- 默认内存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 对象实现支持
- 在堆中分配对象
- Common Object Structures
- Type 对象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使对象类型支持循环垃圾回收
- API 和 ABI 版本管理
- 分发 Python 模块
- 关键术语
- 开源许可与协作
- 安装工具
- 阅读指南
- 我该如何...?
- ...为我的项目选择一个名字?
- ...创建和分发二进制扩展?
- 安装 Python 模块
- 关键术语
- 基本使用
- 我应如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安装 pip ?
- ... 只为当前用户安装软件包?
- ... 安装科学计算类 Python 软件包?
- ... 使用并行安装的多个 Python 版本?
- 常见的安装问题
- 在 Linux 的系统 Python 版本上安装
- 未安装 pip
- 安装二进制编译扩展
- Python 常用指引
- 将 Python 2 代码迁移到 Python 3
- 简要说明
- 详情
- 将扩展模块移植到 Python 3
- 条件编译
- 对象API的更改
- 模块初始化和状态
- CObject 替换为 Capsule
- 其他选项
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 实现描述器
- 摘要
- 定义和简介
- 描述器协议
- 发起调用描述符
- 描述符示例
- Properties
- 函数和方法
- Static Methods and Class Methods
- 函数式编程指引
- 概述
- 迭代器
- 生成器表达式和列表推导式
- 生成器
- 内置函数
- itertools 模块
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文献
- 日志 HOWTO
- 日志基础教程
- 进阶日志教程
- 日志级别
- 有用的处理程序
- 记录日志中引发的异常
- 使用任意对象作为消息
- 优化
- 日志操作手册
- 在多个模块中使用日志
- 在多线程中使用日志
- 使用多个日志处理器和多种格式化
- 在多个地方记录日志
- 日志服务器配置示例
- 处理日志处理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正则表达式HOWTO
- 概述
- 简单模式
- 使用正则表达式
- 更多模式能力
- 修改字符串
- 常见问题
- 反馈
- 套接字编程指南
- 套接字
- 创建套接字
- 使用一个套接字
- 断开连接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 关键函数
- Operator 模块函数
- 升序和降序
- 排序稳定性和排序复杂度
- 使用装饰-排序-去装饰的旧方法
- 使用 cmp 参数的旧方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包获取网络资源
- 概述
- Fetching URLs
- 处理异常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 脚注
- Argparse 教程
- 概念
- 基础
- 位置参数介绍
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模块介绍
- 创建 Address/Network/Interface 对象
- 审查 Address/Network/Interface 对象
- Network 作为 Address 列表
- 比较
- 将IP地址与其他模块一起使用
- 实例创建失败时获取更多详细信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 检测CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常见问题
- Python常见问题
- 一般信息
- 现实世界中的 Python
- 编程常见问题
- 一般问题
- 核心语言
- 数字和字符串
- 性能
- 序列(元组/列表)
- 对象
- 模块
- 设计和历史常见问题
- 为什么Python使用缩进来分组语句?
- 为什么简单的算术运算得到奇怪的结果?
- 为什么浮点计算不准确?
- 为什么Python字符串是不可变的?
- 为什么必须在方法定义和调用中显式使用“self”?
- 为什么不能在表达式中赋值?
- 为什么Python对某些功能(例如list.index())使用方法来实现,而其他功能(例如len(List))使用函数实现?
- 为什么 join()是一个字符串方法而不是列表或元组方法?
- 异常有多快?
- 为什么Python中没有switch或case语句?
- 难道不能在解释器中模拟线程,而非得依赖特定于操作系统的线程实现吗?
- 为什么lambda表达式不能包含语句?
- 可以将Python编译为机器代码,C或其他语言吗?
- Python如何管理内存?
- 为什么CPython不使用更传统的垃圾回收方案?
- CPython退出时为什么不释放所有内存?
- 为什么有单独的元组和列表数据类型?
- 列表是如何在CPython中实现的?
- 字典是如何在CPython中实现的?
- 为什么字典key必须是不可变的?
- 为什么 list.sort() 没有返回排序列表?
- 如何在Python中指定和实施接口规范?
- 为什么没有goto?
- 为什么原始字符串(r-strings)不能以反斜杠结尾?
- 为什么Python没有属性赋值的“with”语句?
- 为什么 if/while/def/class语句需要冒号?
- 为什么Python在列表和元组的末尾允许使用逗号?
- 代码库和插件 FAQ
- 通用的代码库问题
- 通用任务
- 线程相关
- 输入输出
- 网络 / Internet 编程
- 数据库
- 数学和数字
- 扩展/嵌入常见问题
- 可以使用C语言中创建自己的函数吗?
- 可以使用C++语言中创建自己的函数吗?
- C很难写,有没有其他选择?
- 如何从C执行任意Python语句?
- 如何从C中评估任意Python表达式?
- 如何从Python对象中提取C的值?
- 如何使用Py_BuildValue()创建任意长度的元组?
- 如何从C调用对象的方法?
- 如何捕获PyErr_Print()(或打印到stdout / stderr的任何内容)的输出?
- 如何从C访问用Python编写的模块?
- 如何从Python接口到C ++对象?
- 我使用Setup文件添加了一个模块,为什么make失败了?
- 如何调试扩展?
- 我想在Linux系统上编译一个Python模块,但是缺少一些文件。为什么?
- 如何区分“输入不完整”和“输入无效”?
- 如何找到未定义的g++符号__builtin_new或__pure_virtual?
- 能否创建一个对象类,其中部分方法在C中实现,而其他方法在Python中实现(例如通过继承)?
- Python在Windows上的常见问题
- 我怎样在Windows下运行一个Python程序?
- 我怎么让 Python 脚本可执行?
- 为什么有时候 Python 程序会启动缓慢?
- 我怎样使用Python脚本制作可执行文件?
- *.pyd 文件和DLL文件相同吗?
- 我怎样将Python嵌入一个Windows程序?
- 如何让编辑器不要在我的 Python 源代码中插入 tab ?
- 如何在不阻塞的情况下检查按键?
- 图形用户界面(GUI)常见问题
- 图形界面常见问题
- Python 是否有平台无关的图形界面工具包?
- 有哪些Python的GUI工具是某个平台专用的?
- 有关Tkinter的问题
- “为什么我的电脑上安装了 Python ?”
- 什么是Python?
- 为什么我的电脑上安装了 Python ?
- 我能删除 Python 吗?
- 术语对照表
- 文档说明
- Python 文档贡献者
- 解决 Bug
- 文档错误
- 使用 Python 的错误追踪系统
- 开始为 Python 贡献您的知识
- 版权
- 历史和许可证
- 软件历史
- 访问Python或以其他方式使用Python的条款和条件
- Python 3.7.3 的 PSF 许可协议
- Python 2.0 的 BeOpen.com 许可协议
- Python 1.6.1 的 CNRI 许可协议
- Python 0.9.0 至 1.2 的 CWI 许可协议
- 集成软件的许可和认可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec