Movatterモバイル変換


[0]ホーム

URL:


Navigation

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 ofnew types.

It also defines names for some object types that are used by the standardPython interpreter, but not exposed as builtins likeint orstr 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 classdefinition header: the class name, the base classes (in order), thekeyword arguments (such asmetaclass).

Theexec_body argument is a callback that is used to populate thefreshly created class namespace. It should accept the class namespaceas its sole argument and update the namespace directly with the classcontents. If no callback is provided, it has the same effect as passinginlambdans:ns.

New in version 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 asmetaclass).

The return value is a 3-tuple:metaclass,namespace,kwds

metaclass is the appropriate metaclass,namespace is theprepared class namespace andkwds is an updated copy of the passedinkwds argument with any'metaclass' entry removed. If nokwdsargument is passed in, this will be an empty dict.

New in version 3.3.

See also

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 toimplement a Python interpreter. It deliberately avoids including some ofthe types that arise only incidentally during processing such as thelistiterator type.

Typical use of these names is forisinstance() orissubclass() checks.

Standard names are defined for the following types:

types.FunctionType
types.LambdaType

The type of user-defined functions and functions created bylambda expressions.

types.GeneratorType

The type ofgenerator-iterator objects, produced by calling agenerator function.

types.CodeType

The type for code objects such as returned bycompile().

types.MethodType

The type of methods of user-defined class instances.

types.BuiltinFunctionType
types.BuiltinMethodType

The type of built-in functions likelen() orsys.exit(), andmethods of built-in classes. (Here, the term “built-in” means “written inC”.)

types.ModuleType

The type of modules.

types.TracebackType

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

types.FrameType

The type of frame objects such as found intb.tb_frame iftb is atraceback object.

types.GetSetDescriptorType

The type of objects defined in extension modules withPyGetSetDef, suchasFrameType.f_locals orarray.array.typecode. This type is used asdescriptor 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 withPyMemberDef, suchasdatetime.timedelta.days. This type is used as descriptor for simple Cdata members which use standard conversion functions; it has the same purposeas theproperty type, but for classes defined in extension modules.

CPython implementation detail: In other implementations of Python, this type may be identical toGetSetDescriptorType.

classtypes.MappingProxyType(mapping)

Read-only proxy of a mapping. It provides a dynamic view on the mapping’sentries, which means that when the mapping changes, the view reflects thesechanges.

New in version 3.3.

key in proxy

ReturnTrue if the underlying mapping has a keykey, elseFalse.

proxy[key]

Return the item of the underlying mapping with keykey. Raises aKeyError ifkey is not in the underlying mapping.

iter(proxy)

Return an iterator over the keys of the underlying mapping. This is ashortcut foriter(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 forkey ifkey is in the underlying mapping, elsedefault. Ifdefault is not given, it defaults toNone, so thatthis 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.

classtypes.SimpleNamespace

A simpleobject subclass that provides attribute access to itsnamespace, as well as a meaningful repr.

Unlikeobject, withSimpleNamespace you can add and removeattributes. If aSimpleNamespace object is initialized with keywordarguments, those are directly added to the underlying namespace.

The type is roughly equivalent to the following code:

classSimpleNamespace:def__init__(self,**kwargs):self.__dict__.update(kwargs)def__repr__(self):keys=sorted(self.__dict__)items=("{}={!r}".format(k,self.__dict__[k])forkinkeys)return"{}({})".format(type(self).__name__,", ".join(items))

SimpleNamespace may be useful as a replacement forclassNS:pass.However, for a structured record type usenamedtuple()instead.

New in version 3.3.

Table Of Contents

Previous topic

8.8.weakref — Weak references

Next topic

8.10.copy — Shallow and deep copy operations

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp