typesDynamic type creation and names for built-in types动态类型创建和内置类型的名称

Source code: Lib/types.py


This module defines utility functions to assist in dynamic creation of new types.本模块定义实用程序函数,以帮助动态创建新类型。

It also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are.它还定义了标准Python解释器使用的一些对象类型的名称,但这些对象类型没有公开为intstr等内置类型。

Finally, it provides some additional type-related utility classes and functions that are not fundamental enough to be builtins.最后,它提供了一些额外的与类型相关的实用程序类和函数,这些类和函数还不够基本,无法内置。

Dynamic Type Creation动态类型创建

types.new_class(name, bases=(), kwds=None, exec_body=None)

Creates a class object dynamically using the appropriate metaclass.使用适当的元类动态创建类对象。

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).前三个参数是组成类定义头的组件:类名、基类(按顺序)、关键字参数(如metaclass)。

The exec_body argument is a callback that is used to populate the freshly created class namespace. exec_body参数是一个回调,用于填充新创建的类命名空间。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.如果未提供回调,则其效果与传入lambda ns: None相同。

New in version 3.3.版本3.3中新增。

types.prepare_class(name, bases=(), kwds=None)

Calculates the appropriate metaclass and creates the class namespace.计算适当的元类并创建类命名空间。

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).参数是组成类定义头的组件:类名、基类(按顺序)和关键字参数(如metaclass)。

The return value is a 3-tuple: 返回值为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. metaclass是适当的元类,namespace是准备好的类命名空间,kwds是传入的kwds参数的更新副本,删除了任何'metaclass'条目。If no kwds argument is passed in, this will be an empty dict.如果没有传入kwds参数,这将是一个空dict。

New in version 3.3.版本3.3中新增。

Changed in version 3.6:版本3.6中更改: The default value for the namespace element of the returned tuple has changed. 返回的元组的namespace元素的默认值已更改。Now an insertion-order-preserving mapping is used when the metaclass does not have a __prepare__ method.现在,当元类没有__prepare__方法时,将使用保留插入顺序的映射。

See also

Metaclasses

Full details of the class creation process supported by these functions这些函数支持的类创建过程的完整详细信息

PEP 3115 - Metaclasses in Python 3000Python 3000中的元类

Introduced the __prepare__ namespace hook介绍了__prepare__命名空间挂钩

types.resolve_bases(bases)

Resolve MRO entries dynamically as specified by PEP 560.按照PEP 560的规定动态解析MRO条目。

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. 此函数在bases中查找不是type实例的项,并返回一个元组,其中每个具有__mro_entries__方法的此类对象都被替换为调用此方法的未打包结果。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.如果bases项是type的实例,或者它没有__mro_entries__方法,那么它将包含在返回元组中,保持不变。

New in version 3.7.版本3.7中新增。

See also

PEP 560 - Core support for typing module and generic types对类型化模块和泛型类型的核心支持

Standard Interpreter Types标准解释器类型

This module provides names for many of the types that are required to implement a Python interpreter. 该模块提供了实现Python解释器所需的许多类型的名称。It deliberately avoids including some of the types that arise only incidentally during processing such as the listiterator type.它故意避免包含一些仅在处理过程中偶然出现的类型,例如listiterator类型。

Typical use of these names is for isinstance() or issubclass() checks.这些名称通常用于isinstance()issubclass()检查。

If you instantiate any of these types, note that signatures may vary between Python versions.如果实例化这些类型中的任何一种,请注意签名可能在Python版本之间有所不同。

Standard names are defined for the following types:为以下类型定义了标准名称:

types.NoneType

The type of None.None的类型。

New in version 3.10.版本3.10中新增。

types.FunctionType
types.LambdaType

The type of user-defined functions and functions created by lambda expressions.用户定义函数和lambda表达式创建的函数的类型。

Raises an auditing event function.__new__ with argument code.引发审核事件function.__new__,带有参数code

The audit event only occurs for direct instantiation of function objects, and is not raised for normal compilation.审计事件仅在函数对象的直接实例化时发生,在正常编译时不会引发。

types.GeneratorType

The type of generator-iterator objects, created by generator functions.生成器迭代器对象的类型,由生成器函数创建。

types.CoroutineType

The type of coroutine objects, created by async def functions.async def函数创建的协同路由对象的类型。

New in version 3.5.版本3.5中新增。

types.AsyncGeneratorType

The type of asynchronous generator-iterator objects, created by asynchronous generator functions.异步生成器迭代器对象的类型,由异步生成器函数创建。

New in version 3.6.版本3.6中新增。

classtypes.CodeType(**kwargs)

The type for code objects such as returned by compile().compile()返回的代码对象的类型。

Raises an auditing event code.__new__ with arguments code, filename, name, argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize, flags.引发审核事件code.__new__,带参数codefilenamenameargcountposonlyargcountkwonlyargcountnlocalsstacksizeflags

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.审计事件仅在直接实例化代码对象时发生,在正常编译时不会引发。

replace(**kwargs)

Return a copy of the code object with new values for the specified fields.返回代码对象的副本,其中包含指定字段的新值。

New in version 3.8.版本3.8中新增。

types.CellType

The type for cell objects: such objects are used as containers for a function’s free variables.单元对象的类型:此类对象用作函数自由变量的容器。

New in version 3.8.版本3.8中新增。

types.MethodType

The type of methods of user-defined class instances.用户定义的类实例的方法类型。

types.BuiltinFunctionType
types.BuiltinMethodType

The type of built-in functions like len() or sys.exit(), and methods of built-in classes. 内置函数的类型,如len()sys.exit(),以及内置类的方法。(Here, the term “built-in” means “written in C”.)(这里,术语“内置”是指“用C编写”。)

types.WrapperDescriptorType

The type of methods of some built-in data types and base classes such as object.__init__() or object.__lt__().某些内置数据类型和基类(如object.__init__()object.__lt__())的方法类型。

New in version 3.7.版本3.7中新增。

types.MethodWrapperType

The type of bound methods of some built-in data types and base classes. 某些内置数据类型和基类的bound方法的类型。For example it is the type of object().__str__.例如,它是object().__str__的类型。

New in version 3.7.版本3.7中新增。

types.NotImplementedType

The type of NotImplemented.NotImplemented的类型。

New in version 3.10.版本3.10中新增。

types.MethodDescriptorType

The type of methods of some built-in data types such as str.join().一些内置数据类型的方法类型,例如str.join()

New in version 3.7.版本3.7中新增。

types.ClassMethodDescriptorType

The type of unbound class methods of some built-in data types such as dict.__dict__['fromkeys'].某些内置数据类型的unbound类方法的类型,例如dict.__dict__['fromkeys']

New in version 3.7.版本3.7中新增。

classtypes.ModuleType(name, doc=None)

The type of modules. 模块的类型。The constructor takes the name of the module to be created and optionally its docstring.构造函数获取要创建的模块的名称以及可选的docstring

Note

Use importlib.util.module_from_spec() to create a new module if you wish to set the various import-controlled attributes.如果希望设置各种导入控制属性,请使用importlib.util.module_from_spec()创建新模块。

__doc__

The docstring of the module. 模块的docstringDefaults to None.默认为None

__loader__

The loader which loaded the module. 加载模块的加载程序Defaults to None.默认为None

This attribute is to match importlib.machinery.ModuleSpec.loader as stored in the attr:__spec__ object.此属性与存储在__spec__对象中的importlib.machinery.ModuleSpec.loader匹配。

Note

A future version of Python may stop setting this attribute by default. 默认情况下,Python的未来版本可能会停止设置此属性。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.为了防止这种潜在的变化,如果您明确需要使用此属性,最好从__spec__属性中读取,或者使用getattr(module, "__loader__", None)

Changed in version 3.4:版本3.4中更改: Defaults to None. 默认为NonePreviously the attribute was optional.以前,该属性是可选的。

__name__

The name of the module. 模块的名称。Expected to match importlib.machinery.ModuleSpec.name.应与importlib.machinery.ModuleSpec.name匹配。

__package__

Which package 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). 如果模块是顶级的(即不是任何特定包的一部分),则属性应设置为'',否则应设置为包的名称(如果模块本身是包,则可以为__name__)。Defaults to None.默认为None

This attribute is to match importlib.machinery.ModuleSpec.parent as stored in the attr:__spec__ object.此属性与存储在__spec__对象中的importlib.machinery.ModuleSpec.parent匹配。

Note

A future version of Python may stop setting this attribute by default. 默认情况下,Python的未来版本可能会停止设置此属性。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.为了防止这种潜在的变化,如果您明确需要使用此属性,最好从__spec__属性中读取,或者使用getattr(module, "__package__", None)

Changed in version 3.4:版本3.4中更改: Defaults to None. 默认为NonePreviously the attribute was optional.以前,该属性是可选的。

__spec__

A record of the module’s import-system-related state. 模块导入系统相关状态的记录。Expected to be an instance of importlib.machinery.ModuleSpec.应为importlib.machinery.ModuleSpec的实例。

New in version 3.4.版本3.4中新增。

types.EllipsisType

The type of Ellipsis.Ellipsis的类型。

New in version 3.10.版本3.10中新增。

classtypes.GenericAlias(t_origin, t_args)

The type of parameterized generics such as list[int].参数化泛型的类型,例如list[int]

t_origin should be a non-parameterized generic class, such as list, tuple or dict. 应该是非参数化泛型类,例如listtupledictt_args should be a tuple (possibly of length 1) of types which parameterize t_origin:应该是参数化t_origin的类型的tuple(可能长度为1):

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

New in version 3.9.版本3.9中新增。

Changed in version 3.9.2:版本3.9.2中更改: This type can now be subclassed.现在可以对该类型进行子分类。

classtypes.UnionType

The type of union type expressions.联合类型表达式的类型。

New in version 3.10.版本3.10中新增。

classtypes.TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)

The type of traceback objects such as found in sys.exc_info()[2].sys.exc_info()[2]中找到的回溯对象的类型[2]。

See the language reference for details of the available attributes and operations, and guidance on creating tracebacks dynamically.有关可用属性和操作的详细信息,以及动态创建回溯的指导,请参阅语言参考

types.FrameType

The type of frame objects such as found in tb.tb_frame if tb is a traceback object.如果tb是回溯对象,则在tb.tb_frame中找到的帧对象类型。

See the language reference for details of the available attributes and operations.有关可用属性和操作的详细信息,请参阅语言参考

types.GetSetDescriptorType

The type of objects defined in extension modules with PyGetSetDef, such as FrameType.f_locals or array.array.typecode. 使用PyGetSetDef在扩展模块中定义的对象类型,例如FrameType.f_localsarray.array.typecodeThis type is used as descriptor for object attributes; it has the same purpose as the property type, but for classes defined in extension modules.该类型用作对象属性的描述符;它的用途与property类型相同,但用于扩展模块中定义的类。

types.MemberDescriptorType

The type of objects defined in extension modules with PyMemberDef, such as datetime.timedelta.days. 使用PyMemberDef在扩展模块中定义的对象类型,例如datetime.timedelta.daysThis 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.这种类型用作使用标准转换函数的简单C数据成员的描述符;它的用途与property类型相同,但用于扩展模块中定义的类。

CPython implementation detail:CPython实施细节: In other implementations of Python, this type may be identical to GetSetDescriptorType.在Python的其他实现中,此类型可能与GetSetDescriptorType相同。

classtypes.MappingProxyType(mapping)

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.它提供了映射条目的动态视图,这意味着当映射更改时,视图会反映这些更改。

New in version 3.3.版本3.3中新增。

Changed in version 3.9:版本3.9中更改: Updated to support the new union (|) operator from PEP 584, which simply delegates to the underlying mapping.更新以支持PEP 584中的新联合(|)运算符,该运算符仅委托给底层映射。

key in proxy

Return True if the underlying mapping has a key key, else False.如果基础映射具有键key,则返回True,否则返回False

proxy[key]

Return the item of the underlying mapping with key key. 返回带有键key的基础映射项。Raises a KeyError if key is not in the underlying mapping.如果key不在基础映射中,则引发KeyError

iter(proxy)

Return an iterator over the keys of the underlying mapping. 在基础映射的键上返回迭代器。This is a shortcut for iter(proxy.keys()).这是iter(proxy.keys())的快捷方式。

len(proxy)

Return the number of items in the underlying mapping.返回基础映射中的项数。

copy()

Return a shallow copy of the underlying mapping.返回基础映射的浅层副本。

get(key[, default])

Return the value for key if key is in the underlying mapping, else default. 如果key在基础映射中,则返回key的值,否则返回defaultIf default is not given, it defaults to None, so that this method never raises a KeyError.如果未给定default,则默认为None,因此此方法不会引发KeyError

items()

Return a new view of the underlying mapping’s items ((key, value) pairs).返回基础映射项((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.在基础映射的键上返回反向迭代器。

New in version 3.9.版本3.9中新增。

Additional Utility Classes and Functions其他实用程序类和函数

classtypes.SimpleNamespace

A simple object subclass that provides attribute access to its namespace, as well as a meaningful repr.一个简单的object子类,提供对其命名空间的属性访问,以及有意义的repr。

Unlike object, with SimpleNamespace you can add and remove attributes. object不同,使用SimpleNamespace可以添加和删除属性。If a SimpleNamespace object is initialized with keyword arguments, those are directly added to the underlying namespace.如果使用关键字参数初始化SimpleNamespace对象,则这些参数将直接添加到基础命名空间中。

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. 可能有助于替代class NS: passHowever, for a structured record type use namedtuple() instead.但是,对于结构化记录类型,请改用namedtuple()

New in version 3.3.版本3.3中新增。

Changed in version 3.9:版本3.9中更改: Attribute order in the repr changed from alphabetical to insertion (like dict).repr中的属性顺序从字母顺序更改为插入顺序(如dict)。

types.DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)

Route attribute access on a class to __getattr__.将类上的属性访问路由到__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.实例访问保持正常,但通过类对属性的访问将路由到类的__getattr__方法;这是通过提高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 for an example).这允许一个实例上的属性处于活动状态,并且类上的虚拟属性具有相同的名称(有关示例,请参阅enum.Enum)。

New in version 3.4.版本3.4中新增。

Coroutine Utility Functions协程效用函数

types.coroutine(gen_func)

This function transforms a generator function into a coroutine function which returns a generator-based coroutine. 该函数将生成器函数转换为协程函数,该函数返回基于生成器的协程。The generator-based coroutine is still a generator iterator, but is also considered to be a coroutine object and is awaitable. 基于生成器的协同路由仍然是生成器迭代器,但也被视为协同路由对象,可以等待However, it may not necessarily implement the __await__() method.但是,它可能不一定实现__await__()方法。

If gen_func is a generator function, it will be modified in-place.如果gen_func是生成器函数,则将对其进行就地修改。

If gen_func is not a generator function, it will be wrapped. 如果gen_func不是生成函数,则它将被包装。If it returns an instance of collections.abc.Generator, the instance will be wrapped in an awaitable proxy object. 如果它返回collections.abc.Generator的实例,则该实例将包装在等待的代理对象中。All other types of objects will be returned as is.所有其他类型的对象将按原样返回。

New in version 3.5.版本3.5中新增。