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 .

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.

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.

3.7 版新增。

另请参阅

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

标准解释器类型

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

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

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

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

类型。 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 函数。

3.5 版新增。

类型。 AsyncGeneratorType

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

3.6 版新增。

class 类型。 CodeType ( **kwargs )

The type for code objects such as returned by 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.

replace ( **kwargs )

Return a copy of the code object with new values for the specified fields.

3.8 版新增。

类型。 CellType

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

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__() .

3.7 版新增。

类型。 MethodWrapperType

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

3.7 版新增。

类型。 MethodDescriptorType

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

3.7 版新增。

类型。 ClassMethodDescriptorType

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

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 attr: __spec__ 对象。

注意

A future version of Python may stop setting this attribute by default. To guard against this potential change, preferrably 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 attr: __spec__ 对象。

注意

A future version of Python may stop setting this attribute by default. To guard against this potential change, preferrably 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 the module’s import-system-related state. Expected to be an instance of importlib.machinery.ModuleSpec .

3.4 版新增。

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

The type of traceback objects such as found in sys.exc_info()[2] .

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

类型。 FrameType

The type of frame objects such as found in tb.tb_frame if tb is a traceback object.

语言参考 for details of the available attributes and operations.

类型。 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.

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

class 类型。 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.

3.3 版新增。

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 .

( )

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

keys ( )

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

( )

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

额外实用类和函数

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):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        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() 代替。

3.3 版新增。

类型。 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 for an example).

3.4 版新增。

协程实用函数

类型。 协程 ( gen_func )

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

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

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

3.5 版新增。