types
weakref — 弱引用
weakref
源代码: Lib/types.py
此模块定义新类型动态创建的辅助实用函数。
它还定义用于标准 Python 解释器的一些对象类型的名称,但未暴露作为内置像 int or str are.
int
str
最后,它提供了一些不够基础内置的额外类型相关实用类和函数。
使用适当元类动态创建类对象。
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. 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
Added in version 3.3.
计算适当元类并创建类名称空间。
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, 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.
'metaclass'
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__ 方法。
namespace
__prepare__
另请参阅
由这些函数支持的类的创建过程的完整细节
引入 __prepare__ 名称空间挂钩
动态解析 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.
type
__mro_entries__()
Added in version 3.7.
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__ 被返回。
__orig_bases__
cls.__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 类型。
listiterator
这些名称的典型用法是进行 isinstance() or issubclass() 校验。
isinstance()
issubclass()
若实例化这些任一类型,注意签名可能因 Python 版本而异。
下列类型是定义的标准名称:
类型对于 None .
None
Added in version 3.10.
用户定义函数和函数的类型,创建通过 lambda 表达式。
lambda
引发 审计事件 function.__new__ 采用自变量 code .
function.__new__
code
The audit event only occurs for direct instantiation of function objects, and is not raised for normal compilation.
类型对于 generator 迭代器对象,由生成器函数创建。
类型对于 协程 对象,创建通过 async def 函数。
async def
Added in version 3.5.
类型对于 异步生成器 -iterator objects, created by asynchronous generator functions.
Added in version 3.6.
类型对于 code objects 譬如返回通过 compile() .
compile()
引发 审计事件 code.__new__ 采用自变量 code , filename , name , argcount , posonlyargcount , kwonlyargcount , nlocals , stacksize , flags .
code.__new__
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.
用于单元格对象的类型:这种对象用作函数自由自变量的容器。
Added in version 3.8.
用户定义类实例方法的类型。
内置函数的类型像 len() or sys.exit() , and methods of built-in classes. (Here, the term “built-in” means “written in C”.)
len()
sys.exit()
The type of methods of some built-in data types and base classes such as object.__init__() or object.__lt__() .
object.__init__()
object.__lt__()
类型对于 bound methods of some built-in data types and base classes. For example it is the type of object().__str__ .
object().__str__
类型对于 NotImplemented .
NotImplemented
The type of methods of some built-in data types such as str.join() .
str.join()
类型对于 unbound class methods of some built-in data types such as dict.__dict__['fromkeys'] .
dict.__dict__['fromkeys']
类型对于 模块 . 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.
importlib.util.module_from_spec()
The docstring 对于模块。默认为 None .
The loader which loaded the module. Defaults to None .
This attribute is to match importlib.machinery.ModuleSpec.loader as stored in the __spec__ 对象。
importlib.machinery.ModuleSpec.loader
__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.
getattr(module, "__loader__", None)
3.4 版改变: 默认为 None 。先前,属性是可选的。
The name of the module. Expected to match importlib.machinery.ModuleSpec.name .
importlib.machinery.ModuleSpec.name
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 .
''
__name__
This attribute is to match importlib.machinery.ModuleSpec.parent as stored in the __spec__ 对象。
importlib.machinery.ModuleSpec.parent
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.
getattr(module, "__package__", None)
A record of the module’s import-system-related state. Expected to be an instance of importlib.machinery.ModuleSpec .
importlib.machinery.ModuleSpec
Added in version 3.4.
类型对于 Ellipsis .
Ellipsis
类型对于 参数化泛型 譬如 list[int] .
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 :
t_origin
list
tuple
dict
t_args
>>> 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 版改变: 此类型现在可以被子类化。
In-depth documentation on instances of types.GenericAlias
types.GenericAlias
Introducing the types.GenericAlias class
类型对于 union type expressions .
The type of traceback objects such as found in sys.exception().__traceback__ .
sys.exception().__traceback__
见 语言参考 for details of the available attributes and operations, and guidance on creating tracebacks dynamically.
类型对于 frame objects such as found in tb.tb_frame if tb is a traceback object.
tb.tb_frame
tb
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.
PyGetSetDef
FrameType.f_locals
array.array.typecode
property
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.
PyMemberDef
datetime.timedelta.days
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__ .
__slots__
MemberDescriptorType
__dict__
CPython 实现细节: In other implementations of Python, this type may be identical to GetSetDescriptorType .
GetSetDescriptorType
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.9 版改变: 更新支持新的 Union ( | ) 运算符从 PEP 584 , which simply delegates to the underlying mapping.
|
返回 True if the underlying mapping has a key key ,否则 False .
True
False
Return the item of the underlying mapping with key key 。引发 KeyError if key is not in the underlying mapping.
KeyError
Return an iterator over the keys of the underlying mapping. This is a shortcut for iter(proxy.keys()) .
iter(proxy.keys())
Return the number of items in the underlying mapping.
返回底层映射的浅拷贝。
返回值为 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) 对)。
(key, value)
Return a new view of the underlying mapping’s keys.
Return a new view of the underlying mapping’s values.
Return a reverse iterator over the keys of the underlying mapping.
Return a hash of the underlying mapping.
简单 object subclass that provides attribute access to its namespace, as well as a meaningful repr.
object
不像 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.
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 . However, for a structured record type use namedtuple() 代替。
class NS: pass
namedtuple()
3.9 版改变: Attribute order in the repr changed from alphabetical to insertion (like dict ).
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 了解范例)。
enum.Enum
此函数变换 generator 函数成 协程函数 返回基于生成器的协程。基于生成器的协程仍是 生成器迭代器 ,但也被认为是 协程 对象和 awaitable 。不管怎样,它可能不必实现 __await__() 方法。
__await__()
若 gen_func 是生成器函数,它将被原位修改。
若 gen_func 不是生成器函数,它会被包裹。若它返回实例化 collections.abc.Generator ,实例将包裹在 awaitable 代理对象。所有其它类型对象将按原样返回。
collections.abc.Generator
copy — 浅拷贝和深拷贝操作
copy
键入搜索术语或模块、类、函数名称。