内容表

  • types — 动态类型的创建和内置类型的名称
    • 动态类型的创建
    • 标准解释器类型
    • 额外实用类和函数
    • 协程实用函数

上一话题

weakref — 弱引用

下一话题
就业培训     下载中心     Wiki     联络
登录   注册

Log
  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 数据类型
  9. types — 动态类型的创建和内置类型的名称

types — 动态类型的创建和内置类型的名称 ¶

源代码: Lib/types.py


此模块定义新类型动态创建的辅助实用函数。

它还定义用于标准 Python 解释器的一些对象类型的名称,但未暴露作为内置像 int or str are.

最后,它提供了一些不够基础内置的额外类型相关实用类和函数。

动态类型的创建 ¶

类型。 new_class ( name , bases = () , kwds = None , exec_body = None ) ¶

使用适当元类动态创建类对象。

The first three arguments are the components that make up a class definition header: the class name, the base classes (in order), the keyword arguments (such as metaclass ).

The exec_body argument is a callback that is used to populate the freshly created class namespace. It should accept the class namespace as its sole argument and update the namespace directly with the class contents. If no callback is provided, it has the same effect as passing in lambda ns: None .

Added in version 3.3.

类型。 prepare_class ( name , bases = () , kwds = None ) ¶

计算适当元类并创建类名称空间。

The arguments are the components that make up a class definition header: the class name, the base classes (in order) and the keyword arguments (such as metaclass ).

返回值是 3 元组: metaclass, namespace, kwds

metaclass is the appropriate metaclass, namespace is the prepared class namespace and kwds is an updated copy of the passed in kwds argument with any 'metaclass' entry removed. If no kwds argument is passed in, this will be an empty dict.

Added in version 3.3.

3.6 版改变: 默认值对于 namespace element of the returned tuple has changed. Now an insertion-order-preserving mapping is used when the metaclass does not have a __prepare__ 方法。

另请参阅

元类

由这些函数支持的类的创建过程的完整细节

PEP 3115 - Python 3000 的元类

引入 __prepare__ 名称空间挂钩

类型。 resolve_bases ( bases ) ¶

动态解析 MRO 条目按指定通过 PEP 560 .

This function looks for items in bases that are not instances of type , and returns a tuple where each such object that has an __mro_entries__() method is replaced with an unpacked result of calling this method. If a bases item is an instance of type , or it doesn’t have an __mro_entries__() method, then it is included in the return tuple unchanged.

Added in version 3.7.

类型。 get_original_bases ( cls , / ) ¶

Return the tuple of objects originally given as the bases of cls 先于 __mro_entries__() method has been called on any bases (following the mechanisms laid out in PEP 560 ). This is useful for introspecting 一般 .

For classes that have an __orig_bases__ attribute, this function returns the value of cls.__orig_bases__ . For classes without the __orig_bases__ 属性, cls.__bases__ 被返回。

范例:

from typing import TypeVar, Generic, NamedTuple, TypedDict
T = TypeVar("T")
class Foo(Generic[T]): ...
class Bar(Foo[int], float): ...
class Baz(list[str]): ...
Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
Spam = TypedDict("Spam", {"a": int, "b": str})
assert Bar.__bases__ == (Foo, float)
assert get_original_bases(Bar) == (Foo[int], float)
assert Baz.__bases__ == (list,)
assert get_original_bases(Baz) == (list[str],)
assert Eggs.__bases__ == (tuple,)
assert get_original_bases(Eggs) == (NamedTuple,)
assert Spam.__bases__ == (dict,)
assert get_original_bases(Spam) == (TypedDict,)
assert int.__bases__ == (object,)
assert get_original_bases(int) == (object,)
												

3.12 版添加。

另请参阅

PEP 560 - 对类型化模块和一般类型的核心支持

标准解释器类型 ¶

此模块为实现 Python 解释器要求的许多类型提供名称。它故意避免包括在处理期间偶然出现的一些类型,譬如 listiterator 类型。

这些名称的典型用法是进行 isinstance() or issubclass() 校验。

若实例化这些任一类型,注意签名可能因 Python 版本而异。

下列类型是定义的标准名称:

类型。 NoneType ¶

类型对于 None .

Added in version 3.10.

类型。 FunctionType ¶
类型。 LambdaType ¶

用户定义函数和函数的类型,创建通过 lambda 表达式。

引发 审计事件 function.__new__ 采用自变量 code .

The audit event only occurs for direct instantiation of function objects, and is not raised for normal compilation.

类型。 GeneratorType ¶

类型对于 generator 迭代器对象,由生成器函数创建。

类型。 CoroutineType ¶

类型对于 协程 对象,创建通过 async def 函数。

Added in version 3.5.

类型。 AsyncGeneratorType ¶

类型对于 异步生成器 -iterator objects, created by asynchronous generator functions.

Added in version 3.6.

class 类型。 CodeType ( ** kwargs ) ¶

类型对于 code objects 譬如返回通过 compile() .

引发 审计事件 code.__new__ 采用自变量 code , filename , name , argcount , posonlyargcount , kwonlyargcount , nlocals , stacksize , flags .

Note that the audited arguments may not match the names or positions required by the initializer. The audit event only occurs for direct instantiation of code objects, and is not raised for normal compilation.

类型。 CellType ¶

用于单元格对象的类型:这种对象用作函数自由自变量的容器。

Added in version 3.8.

类型。 MethodType ¶

用户定义类实例方法的类型。

类型。 BuiltinFunctionType ¶
类型。 BuiltinMethodType ¶

内置函数的类型像 len() or sys.exit() , and methods of built-in classes. (Here, the term “built-in” means “written in C”.)

类型。 WrapperDescriptorType ¶

The type of methods of some built-in data types and base classes such as object.__init__() or object.__lt__() .

Added in version 3.7.

类型。 MethodWrapperType ¶

类型对于 bound methods of some built-in data types and base classes. For example it is the type of object().__str__ .

Added in version 3.7.

类型。 NotImplementedType ¶

类型对于 NotImplemented .

Added in version 3.10.

类型。 MethodDescriptorType ¶

The type of methods of some built-in data types such as str.join() .

Added in version 3.7.

类型。 ClassMethodDescriptorType ¶

类型对于 unbound class methods of some built-in data types such as dict.__dict__['fromkeys'] .

Added in version 3.7.

class 类型。 ModuleType ( name , doc = None ) ¶

类型对于 模块 . The constructor takes the name of the module to be created and optionally its docstring .

注意

使用 importlib.util.module_from_spec() to create a new module if you wish to set the various import-controlled attributes.

__doc__ ¶

The docstring 对于模块。默认为 None .

__loader__ ¶

The loader which loaded the module. Defaults to None .

This attribute is to match importlib.machinery.ModuleSpec.loader as stored in the __spec__ 对象。

注意

A future version of Python may stop setting this attribute by default. To guard against this potential change, preferably read from the __spec__ attribute instead or use getattr(module, "__loader__", None) if you explicitly need to use this attribute.

3.4 版改变: 默认为 None 。先前,属性是可选的。

__name__ ¶

The name of the module. Expected to match importlib.machinery.ModuleSpec.name .

__package__ ¶

Which 包 a module belongs to. If the module is top-level (i.e. not a part of any specific package) then the attribute should be set to '' , else it should be set to the name of the package (which can be __name__ if the module is a package itself). Defaults to None .

This attribute is to match importlib.machinery.ModuleSpec.parent as stored in the __spec__ 对象。

注意

A future version of Python may stop setting this attribute by default. To guard against this potential change, preferably read from the __spec__ attribute instead or use getattr(module, "__package__", None) if you explicitly need to use this attribute.

3.4 版改变: 默认为 None 。先前,属性是可选的。

__spec__ ¶

A record of the module’s import-system-related state. Expected to be an instance of importlib.machinery.ModuleSpec .

Added in version 3.4.

类型。 EllipsisType ¶

类型对于 Ellipsis .

Added in version 3.10.

class 类型。 GenericAlias ( t_origin , t_args ) ¶

类型对于 参数化泛型 譬如 list[int] .

t_origin should be a non-parameterized generic class, such as list , tuple or dict . t_args 应该为 tuple (possibly of length 1) of types which parameterize t_origin :

>>> from types import GenericAlias
>>> list[int] == GenericAlias(list, (int,))
True
>>> dict[str, int] == GenericAlias(dict, (str, int))
True
											

Added in version 3.9.

3.9.2 版改变: 此类型现在可以被子类化。

另请参阅

Generic Alias Types

In-depth documentation on instances of types.GenericAlias

PEP 585 - Type Hinting Generics In Standard Collections

Introducing the types.GenericAlias class

class 类型。 UnionType ¶

类型对于 union type expressions .

Added in version 3.10.

class 类型。 TracebackType ( tb_next , tb_frame , tb_lasti , tb_lineno ) ¶

The type of traceback objects such as found in sys.exception().__traceback__ .

见 语言参考 for details of the available attributes and operations, and guidance on creating tracebacks dynamically.

类型。 FrameType ¶

类型对于 frame objects such as found in tb.tb_frame if tb is a traceback object.

类型。 GetSetDescriptorType ¶

The type of objects defined in extension modules with PyGetSetDef ,譬如 FrameType.f_locals or array.array.typecode . This type is used as descriptor for object attributes; it has the same purpose as the property type, but for classes defined in extension modules.

类型。 MemberDescriptorType ¶

The type of objects defined in extension modules with PyMemberDef ,譬如 datetime.timedelta.days . This type is used as descriptor for simple C data members which use standard conversion functions; it has the same purpose as the property type, but for classes defined in extension modules.

In addition, when a class is defined with a __slots__ attribute, then for each slot, an instance of MemberDescriptorType will be added as an attribute on the class. This allows the slot to appear in the class’s __dict__ .

CPython 实现细节: In other implementations of Python, this type may be identical to GetSetDescriptorType .

class 类型。 MappingProxyType ( 映射 ) ¶

Read-only proxy of a mapping. It provides a dynamic view on the mapping’s entries, which means that when the mapping changes, the view reflects these changes.

Added in version 3.3.

3.9 版改变: 更新支持新的 Union ( | ) 运算符从 PEP 584 , which simply delegates to the underlying mapping.

key in proxy

返回 True if the underlying mapping has a key key ,否则 False .

proxy[key]

Return the item of the underlying mapping with key key 。引发 KeyError if key is not in the underlying mapping.

iter(proxy)

Return an iterator over the keys of the underlying mapping. This is a shortcut for iter(proxy.keys()) .

len(proxy)

Return the number of items in the underlying mapping.

copy ( ) ¶

返回底层映射的浅拷贝。

get ( key [ , default ] ) ¶

返回值为 key if key is in the underlying mapping, else default 。若 default 不给定,默认为 None ,因此此方法从不引发 KeyError .

items ( ) ¶

Return a new view of the underlying mapping’s items ( (key, value) 对)。

keys ( ) ¶

Return a new view of the underlying mapping’s keys.

values ( ) ¶

Return a new view of the underlying mapping’s values.

reversed(proxy)

Return a reverse iterator over the keys of the underlying mapping.

Added in version 3.9.

hash(proxy)

Return a hash of the underlying mapping.

3.12 版添加。

额外实用类和函数 ¶

class 类型。 SimpleNamespace ¶

简单 object subclass that provides attribute access to its namespace, as well as a meaningful repr.

不像 object ,采用 SimpleNamespace you can add and remove attributes. If a SimpleNamespace object is initialized with keyword arguments, those are directly added to the underlying namespace.

The type is roughly equivalent to the following code:

class SimpleNamespace:
    def __init__(self, /, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        items = (f"{k}={v!r}" for k, v in self.__dict__.items())
        return "{}({})".format(type(self).__name__, ", ".join(items))
    def __eq__(self, other):
        if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
           return self.__dict__ == other.__dict__
        return NotImplemented
											

SimpleNamespace may be useful as a replacement for class NS: pass . However, for a structured record type use namedtuple() 代替。

Added in version 3.3.

3.9 版改变: Attribute order in the repr changed from alphabetical to insertion (like dict ).

类型。 DynamicClassAttribute ( fget = None , fset = None , fdel = None , doc = None ) ¶

Route attribute access on a class to __getattr__.

This is a descriptor, used to define attributes that act differently when accessed through an instance and through a class. Instance access remains normal, but access to an attribute through a class will be routed to the class’s __getattr__ method; this is done by raising AttributeError.

This allows one to have properties active on an instance, and have virtual attributes on the class with the same name (see enum.Enum 了解范例)。

Added in version 3.4.

协程实用函数 ¶

类型。 协程 ( gen_func ) ¶

此函数变换 generator 函数成 协程函数 返回基于生成器的协程。基于生成器的协程仍是 生成器迭代器 ,但也被认为是 协程 对象和 awaitable 。不管怎样,它可能不必实现 __await__() 方法。

若 gen_func 是生成器函数,它将被原位修改。

若 gen_func 不是生成器函数,它会被包裹。若它返回实例化 collections.abc.Generator ,实例将包裹在 awaitable 代理对象。所有其它类型对象将按原样返回。

Added in version 3.5.

内容表

  • types — 动态类型的创建和内置类型的名称
    • 动态类型的创建
    • 标准解释器类型
    • 额外实用类和函数
    • 协程实用函数

上一话题

weakref — 弱引用

下一话题

copy — 浅拷贝和深拷贝操作

本页

  • 报告 Bug
  • 展示源

快速搜索

键入搜索术语或模块、类、函数名称。

  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 数据类型
  9. types — 动态类型的创建和内置类型的名称
  10. 版权所有  © 2014-2026 乐数软件    

    工业和信息化部: 粤ICP备14079481号-1