summaryrefslogtreecommitdiffstats
path: root/Doc/reference/datamodel.rst
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2009-04-07 02:08:23 (GMT)
committerRaymond Hettinger <python@rcn.com>2009-04-07 02:08:23 (GMT)
commit958e368a68239161cc0114567ff032b24964426a (patch)
tree080dbd825394de444d6664024c6793d5d80dc3c8 /Doc/reference/datamodel.rst
parenta7e33fec94dc81bd9bb840baadc9f0e922e19d29 (diff)
downloadcpython-958e368a68239161cc0114567ff032b24964426a.zip
cpython-958e368a68239161cc0114567ff032b24964426a.tar.gz
cpython-958e368a68239161cc0114567ff032b24964426a.tar.bz2
Add an example metaclass showing a use of __prepare__() as outlined in PEP 3115.
Diffstat (limited to 'Doc/reference/datamodel.rst')
-rw-r--r--Doc/reference/datamodel.rst32
1 files changed, 32 insertions, 0 deletions
diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst
index 2bce677..c2c3241 100644
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -1541,6 +1541,38 @@ explored including logging, interface checking, automatic delegation, automatic
property creation, proxies, frameworks, and automatic resource
locking/synchronization.
+Here is an example of a metaclass that uses an :class:`OrderedDict` to
+remember the order that class members were defined::
+
+ class OrderedClass(type):
+
+ @classmethod
+ def __prepare__(metacls, name, bases, **kwds):
+ return collections.OrderedDict()
+
+ def __new__(cls, name, bases, classdict):
+ result = type.__new__(cls, name, bases, dict(classdict))
+ result.members = tuple(classdict)
+ return result
+
+ class A(metaclass=OrderedClass):
+ def one(self): pass
+ def two(self): pass
+ def three(self): pass
+ def four(self): pass
+
+ >>> A.members
+ ('__module__', 'one', 'two', 'three', 'four')
+
+When the class definition for *A* get executed, the first step is calling the
+metaclass's :meth:`__prepare__` method which returns an empty
+:class:`collections.OrderedDict`. That mapping records the methods and
+attributes of *A* as they are defined within the body of the class statement.
+Once those definitions are executed, the ordered dict is fully populated, and
+then the metaclass's :meth:`__new__ ` method gets invoked. That method builds
+the new type and saves the keys for the ordered dictionary in an attribute
+called *members*.
+
.. _callable-types: