types
— Dynamic 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 它还定义了标准Python解释器使用的一些对象类型的名称,但这些对象类型没有公开为int
or str
are.int
或str
等内置类型。
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 anymetaclass是适当的元类,namespace是准备好的类命名空间,kwds是传入的kwds参数的更新副本,删除了任何'metaclass'
entry removed.'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此函数在bases中查找不是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.type
实例的项,并返回一个元组,其中每个具有__mro_entries__
方法的此类对象都被替换为调用此方法的未打包结果。If a bases item is an instance of如果bases项是type
, or it doesn’t have an__mro_entries__
method, then it is included in the return tuple unchanged.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.
FunctionType
¶ -
types.
LambdaType
¶ The type of user-defined functions and functions created by用户定义函数和lambda
expressions.lambda
表达式创建的函数的类型。Raises an auditing event引发审核事件function.__new__
with argumentcode
.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中新增。
-
class
types.
CodeType
(**kwargs)¶ -
The type for code objects such as returned bycompile()
.compile()
返回的代码对象的类型。Raises an auditing event引发审核事件code.__new__
with argumentscode
,filename
,name
,argcount
,posonlyargcount
,kwonlyargcount
,nlocals
,stacksize
,flags
.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.审计事件仅在直接实例化代码对象时发生,在正常编译时不会引发。-
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()
orsys.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__()
orobject.__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 ofNotImplemented
.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某些内置数据类型的unbound类方法的类型,例如dict.__dict__['fromkeys']
.dict.__dict__['fromkeys']
。New in version 3.7.版本3.7中新增。
-
class
types.
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()
创建新模块。-
__loader__
¶ The loader which loaded the module.加载模块的加载程序。Defaults to默认为None
.None
。This attribute is to match此属性与存储在__spec__对象中的importlib.machinery.ModuleSpec.loader
as stored in the attr:__spec__ object.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 usegetattr(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
.None
。Previously 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此属性与存储在__spec__对象中的importlib.machinery.ModuleSpec.parent
as stored in the attr:__spec__ object.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 usegetattr(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
.None
。Previously 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中新增。
-
-
class
types.
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
ordict
.list
、tuple
或dict
。t_args
should be a应该是参数化tuple
(possibly of length 1) of types which parameterizet_origin
:t_origin
的类型的tuple
(可能长度为1):>>> from types import GenericAlias
>>> list[int] == GenericAlias(list, (int,))
True
>>> dict[str, int] == GenericAlias(dict, (str, int))
TrueNew in version 3.9.版本3.9中新增。Changed in version 3.9.2:版本3.9.2中更改:This type can now be subclassed.现在可以对该类型进行子分类。
-
class
types.
UnionType
¶ The type of union type expressions.联合类型表达式的类型。New in version 3.10.版本3.10中新增。
-
class
types.
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
iftb
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 asFrameType.f_locals
orarray.array.typecode
.PyGetSetDef
在扩展模块中定义的对象类型,例如FrameType.f_locals
或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.property
类型相同,但用于扩展模块中定义的类。
-
types.
MemberDescriptorType
¶ The type of objects defined in extension modules with使用PyMemberDef
, such asdatetime.timedelta.days
.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这种类型用作使用标准转换函数的简单C数据成员的描述符;它的用途与property
type, but for classes defined in extension modules.property
类型相同,但用于扩展模块中定义的类。CPython implementation detail:CPython实施细节:In other implementations of Python, this type may be identical to在Python的其他实现中,此类型可能与GetSetDescriptorType
.GetSetDescriptorType
相同。
-
class
types.
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 (更新以支持PEP 584中的新联合(|
) operator from PEP 584, which simply delegates to the underlying mapping.|
)运算符,该运算符仅委托给底层映射。-
key in proxy
Return如果基础映射具有键key,则返回True
if the underlying mapping has a key key, elseFalse
.True
,否则返回False
。
-
proxy[key]
Return the item of the underlying mapping with key key.返回带有键key的基础映射项。Raises a如果key不在基础映射中,则引发KeyError
if key is not in the underlying mapping.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的值,否则返回default。If default is not given, it defaults to如果未给定default,则默认为None
, so that this method never raises aKeyError
.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其他实用程序类和函数¶
-
class
types.
SimpleNamespace
¶ A simple一个简单的object
subclass that provides attribute access to its namespace, as well as a meaningful repr.object
子类,提供对其命名空间的属性访问,以及有意义的repr。Unlike与object
, withSimpleNamespace
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 NotImplementedSimpleNamespace
may be useful as a replacement for可能有助于替代class NS: pass
.class NS: pass
。However, 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 (likerepr中的属性顺序从字母顺序更改为插入顺序(如dict
).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中新增。