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¶
- 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
).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 版被加入.
- 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
).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 版的變更: The default value for the
namespace
element of the returned tuple has changed. Now an insertion-order-preserving mapping is used when the metaclass does not have a__prepare__
method.
也參考
- Metaclasses
Full details of the class creation process supported by these functions
- PEP 3115 - Metaclasses in Python 3000
Introduced the
__prepare__
namespace hook
- types.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 oftype
, or it doesn't have an__mro_entries__()
method, then it is included in the return tuple unchanged.在 3.7 版被加入.
- types.get_original_bases(cls, /)¶
Return the tuple of objects originally given as the bases of cls before the
__mro_entries__()
method has been called on any bases (following the mechanisms laid out in PEP 560). This is useful for introspecting Generics.For classes that have an
__orig_bases__
attribute, this function returns the value ofcls.__orig_bases__
. For classes without the__orig_bases__
attribute,cls.__bases__
is returned.舉例來說:
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 - 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
type.
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:
- types.FunctionType¶
- types.LambdaType¶
The type of user-defined functions and functions created by
lambda
expressions.引發一個附帶引數
code
的稽核事件function.__new__
。The audit event only occurs for direct instantiation of function objects, and is not raised for normal compilation.
- types.AsyncGeneratorType¶
The type of asynchronous generator-iterator objects, created by asynchronous generator functions.
在 3.6 版被加入.
- class types.CodeType(**kwargs)¶
The type of code objects such as returned by
compile()
.引發一個附帶引數
code
、filename
、name
、argcount
、posonlyargcount
、kwonlyargcount
、nlocals
、stacksize
、flags
的稽核事件code.__new__
。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.
- types.CellType¶
The type for cell objects: such objects are used as containers for a function's free variables.
在 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. (Here, the term "built-in" means "written in C".)
- types.WrapperDescriptorType¶
The type of methods of some built-in data types and base classes such as
object.__init__()
orobject.__lt__()
.在 3.7 版被加入.
- types.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 版被加入.
- types.NotImplementedType¶
The type of
NotImplemented
.在 3.10 版被加入.
- types.MethodDescriptorType¶
The type of methods of some built-in data types such as
str.join()
.在 3.7 版被加入.
- types.ClassMethodDescriptorType¶
The type of unbound class methods of some built-in data types such as
dict.__dict__['fromkeys']
.在 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.
也參考
- Documentation on module objects
Provides details on the special attributes that can be found on instances of
ModuleType
.importlib.util.module_from_spec()
Modules created using the
ModuleType
constructor are created with many of their special attributes unset or set to default values.module_from_spec()
provides a more robust way of creatingModuleType
instances which ensures the various attributes are set appropriately.
- class types.GenericAlias(t_origin, t_args)¶
The type of parameterized generics such as
list[int]
.t_origin
should be a non-parameterized generic class, such aslist
,tuple
ordict
.t_args
should be atuple
(possibly of length 1) of types which parameterizet_origin
:>>> from types import GenericAlias >>> list[int] == GenericAlias(list, (int,)) True >>> dict[str, int] == GenericAlias(dict, (str, int)) True
在 3.9 版被加入.
在 3.9.2 版的變更: This type can now be subclassed.
也參考
- Generic Alias Types
In-depth documentation on instances of
types.GenericAlias
- PEP 585 - Type Hinting Generics In Standard Collections
Introducing the
types.GenericAlias
class
- class types.UnionType¶
The type of union type expressions.
在 3.10 版被加入.
- class types.TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)¶
The type of traceback objects such as found in
sys.exception().__traceback__
.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.
- types.GetSetDescriptorType¶
The type of objects defined in extension modules with
PyGetSetDef
, such asFrameType.f_locals
orarray.array.typecode
. This type is used as descriptor for object attributes; it has the same purpose as theproperty
type, but for classes defined in extension modules.
- types.MemberDescriptorType¶
The type of objects defined in extension modules with
PyMemberDef
, such asdatetime.timedelta.days
. This type is used as descriptor for simple C data members which use standard conversion functions; it has the same purpose as theproperty
type, but for classes defined in extension modules.In addition, when a class is defined with a
__slots__
attribute, then for each slot, an instance ofMemberDescriptorType
will be added as an attribute on the class. This allows the slot to appear in the class's__dict__
.CPython 實作細節: In other implementations of Python, this type may be identical to
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.
在 3.3 版被加入.
在 3.9 版的變更: Updated to support the new union (
|
) operator from PEP 584, which simply delegates to the underlying mapping.- key in proxy
Return
True
if the underlying mapping has a key key, elseFalse
.
- proxy[key]
Return the item of the underlying mapping with key key. Raises a
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])¶
Return the value for key if key is in the underlying mapping, else default. If default is not given, it defaults to
None
, so that this method never raises aKeyError
.
- 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 版被加入.
- hash(proxy)
Return a hash of the underlying mapping.
在 3.12 版被加入.
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.Unlike
object
, withSimpleNamespace
you can add and remove attributes. If aSimpleNamespace
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 forclass NS: pass
. However, for a structured record type usenamedtuple()
instead.在 3.3 版被加入.
在 3.9 版的變更: Attribute order in the repr changed from alphabetical to insertion (like
dict
).
- types.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¶
- 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.If gen_func is a generator function, it will be modified in-place.
If 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 版被加入.