]> granicus.if.org Git - python/commitdiff
Add a default __prepare__() method to 'type', so it can be called
authorGuido van Rossum <guido@python.org>
Thu, 2 Aug 2007 16:48:17 +0000 (16:48 +0000)
committerGuido van Rossum <guido@python.org>
Thu, 2 Aug 2007 16:48:17 +0000 (16:48 +0000)
using super().  (See recent conversation on python-3000 with Talin
and Phillip Eby about PEP 3115 chaining rules.)

Lib/test/test_metaclass.py
Objects/typeobject.c

index 9126cf6524ca47a3120fc9d512b4110e61b1b451..abb333032852fcf8ba6b5193b4badf838353184c 100644 (file)
@@ -207,6 +207,29 @@ And again, with a __prepare__ attribute.
     kw: [('other', 'booh')]
     >>>
 
+The default metaclass must define a __prepare__() method.
+
+    >>> type.__prepare__()
+    {}
+    >>>
+
+Make sure it works with subclassing.
+
+    >>> class M(type):
+    ...     @classmethod
+    ...     def __prepare__(cls, *args, **kwds):
+    ...         d = super().__prepare__(*args, **kwds)
+    ...         d["hello"] = 42
+    ...         return d
+    ...
+    >>> class C(metaclass=M):
+    ...     print(hello)
+    ...
+    42
+    >>> print(C.hello)
+    42
+    >>>
+
 """
 
 __test__ = {'doctests' : doctests}
index 3ad5efcfc1403cf923ed9cf23ca5bfd510091145..8cf28fca7fd9296cb0cc87ede70382cbe9c66425 100644 (file)
@@ -2200,11 +2200,21 @@ type_subclasses(PyTypeObject *type, PyObject *args_ignored)
        return list;
 }
 
+static PyObject *
+type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
+{
+       return PyDict_New();
+}
+
 static PyMethodDef type_methods[] = {
        {"mro", (PyCFunction)mro_external, METH_NOARGS,
         PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
        {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
         PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
+        {"__prepare__", (PyCFunction)type_prepare,
+        METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+         PyDoc_STR("__prepare__() -> dict\n"
+                   "used to create the namespace for the class statement")},
        {0}
 };