8.9. types — Dynamic type creation and names for built-in types¶
Source code: Lib/types.py
This module defines utility function 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.
8.9.1. 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: ns.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, kwdsmetaclass 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 版新加入.
也參考
- Customizing class creation
- Full details of the class creation process supported by these functions
- PEP 3115 - Metaclasses in Python 3000
- Introduced the
__prepare__namespace hook
8.9.2. 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.
Standard names are defined for the following types:
-
types.FunctionType¶ -
types.LambdaType¶ The type of user-defined functions and functions created by
lambdaexpressions.
-
types.GeneratorType¶ The type of generator-iterator objects, produced by calling a generator function.
-
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.ModuleType¶ The type of modules.
-
types.TracebackType¶ The type of traceback objects such as found in
sys.exc_info()[2].
-
types.FrameType¶ The type of frame objects such as found in
tb.tb_frameiftbis a traceback object.
-
types.GetSetDescriptorType¶ The type of objects defined in extension modules with
PyGetSetDef, such asFrameType.f_localsorarray.array.typecode. This type is used as descriptor for object attributes; it has the same purpose as thepropertytype, 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 thepropertytype, but for classes defined in extension modules.CPython implementation detail: 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 版新加入.
-
key in proxy Return
Trueif the underlying mapping has a key key, elseFalse.
-
proxy[key] Return the item of the underlying mapping with key key. Raises a
KeyErrorif 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.
-
-
class
types.SimpleNamespace¶ A simple
objectsubclass that provides attribute access to its namespace, as well as a meaningful repr.Unlike
object, withSimpleNamespaceyou can add and remove attributes. If aSimpleNamespaceobject 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))
SimpleNamespacemay be useful as a replacement forclass NS: pass. However, for a structured record type usenamedtuple()instead.3.3 版新加入.
