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

源代码: 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.

Finally, it provides some additional type-related utility classes and functions that are not fundamental enough to be builtins.

Dynamic Type Creation

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

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 )

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

The return value is a 3-tuple: 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__ 方法。

另请参阅

元类

Full details of the class creation process supported by these functions

PEP 3115 - Python 3000 中的元类

引入 __prepare__ 名称空间挂钩

类型。 resolve_bases ( bases )

Resolve MRO entries dynamically as specified by 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 - 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. It deliberately avoids including some of the types that arise only incidentally during processing such as the listiterator 类型。

Typical use of these names is for isinstance() or issubclass() checks.

If you instantiate any of these types, note that signatures may vary between Python versions.

Standard names are defined for the following types:

类型。 FunctionType
类型。 LambdaType

The type of user-defined functions and functions created by lambda expressions.

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

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

类型。 GeneratorType

The type of generator -iterator objects, created by generator functions.

类型。 CoroutineType

The type of 协程 objects, created by async def 函数。

3.5 版新增。

类型。 AsyncGeneratorType

The type of 异步生成器 -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

The type for cell objects: such objects are used as containers for a function’s free variables.

3.8 版新增。

类型。 MethodType

The type of methods of user-defined class instances.

类型。 BuiltinFunctionType
类型。 BuiltinMethodType

The type of built-in functions like 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

The type of 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

The type of unbound class methods of some built-in data types such as dict.__dict__['fromkeys'] .

3.7 版新增。

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

The type of 模块 . 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__

docstring of the module. Defaults to None .

__loader__

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 . Previously the attribute was optional.

__name__

The name of the module. Expected to match 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). 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 . 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 .

3.4 版新增。

class 类型。 GenericAlias ( t_origin , t_args )

The type of parameterized generics 譬如 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
										

3.9 版新增。

Changed in version 3.9.2: This type can now be subclassed.

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

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

the language reference 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.

the language reference 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 版新增。

3.9 版改变: Updated to support the new union ( | ) operator from 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 ( )

Return a shallow copy of the underlying mapping.

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) pairs).

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.

3.9 版新增。

Additional Utility Classes and Functions

class 类型。 SimpleNamespace

A simple 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() 代替。

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

3.4 版新增。

Coroutine Utility Functions

类型。 协程 ( gen_func )

This function transforms a generator function into a 协程函数 which returns a generator-based coroutine. The generator-based coroutine is still a 生成器迭代器 , but is also considered to be a 协程 object and is awaitable . However, it may not necessarily implement the __await__() 方法。

gen_func is a generator function, it will be modified in-place.

gen_func is not a generator function, it will be wrapped. If it returns an instance of collections.abc.Generator , the instance will be wrapped in an awaitable proxy object. All other types of objects will be returned as is.

3.5 版新增。