@@ -1550,53 +1550,115 @@ Notes on using *__slots__*
15501550Customizing class creation
15511551--------------------------
15521552
1553- By default, classes are constructed using :func: `type `. A class definition is
1554- read into a separate namespace and the value of class name is bound to the
1555- result of ``type(name, bases, dict ) ``.
1553+ By default, classes are constructed using :func: `type `. The class body is
1554+ executed in a new namespace and the class name is bound locally to the
1555+ result of ``type(name, bases, namespace ) ``.
15561556
1557- When the class definition is read, if a callable ``metaclass `` keyword argument
1558- is passed after the bases in the class definition, the callable given will be
1559- called instead of :func: `type `. If other keyword arguments are passed, they
1560- will also be passed to the metaclass. This allows classes or functions to be
1561- written which monitor or alter the class creation process:
1557+ The class creation process can be customised by passing the ``metaclass ``
1558+ keyword argument in the class definition line, or by inheriting from an
1559+ existing class that included such an argument. In the following example,
1560+ both ``MyClass `` and ``MySubclass `` are instances of ``Meta ``::
15621561
1563- * Modifying the class dictionary prior to the class being created.
1562+ class Meta(type):
1563+ pass
15641564
1565- * Returning an instance of another class -- essentially performing the role of a
1566- factory function.
1565+ class MyClass(metaclass=Meta):
1566+ pass
15671567
1568- These steps will have to be performed in the metaclass's :meth: `__new__ ` method
1569- -- :meth: `type.__new__ ` can then be called from this method to create a class
1570- with different properties. This example adds a new element to the class
1571- dictionary before creating the class::
1568+ class MySubclass(MyClass):
1569+ pass
15721570
1573- class metacls(type):
1574- def __new__(mcs, name, bases, dict):
1575- dict['foo'] = 'metacls was here'
1576- return type.__new__(mcs, name, bases, dict)
1571+ Any other keyword arguments that are specified in the class definition are
1572+ passed through to all metaclass operations described below.
15771573
1578- You can of course also override other class methods (or add new methods); for
1579- example defining a custom :meth: `__call__ ` method in the metaclass allows custom
1580- behavior when the class is called, e.g. not always creating a new instance.
1574+ When a class definition is executed, the following steps occur:
15811575
1582- If the metaclass has a :meth: `__prepare__ ` attribute (usually implemented as a
1583- class or static method), it is called before the class body is evaluated with
1584- the name of the class and a tuple of its bases for arguments. It should return
1585- an object that supports the mapping interface that will be used to store the
1586- namespace of the class. The default is a plain dictionary. This could be used,
1587- for example, to keep track of the order that class attributes are declared in by
1588- returning an ordered dictionary.
1576+ * the appropriate metaclass is determined
1577+ * the class namespace is prepared
1578+ * the class body is executed
1579+ * the class object is created
15891580
1590- The appropriate metaclass is determined by the following precedence rules:
1581+ Determining the appropriate metaclass
1582+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
15911583
1592- * If the `` metaclass `` keyword argument is passed with the bases, it is used.
1584+ The appropriate metaclass for a class definition is determined as follows:
15931585
1594- * Otherwise, if there is at least one base class, its metaclass is used.
1586+ * if no bases and no explicit metaclass are given, then :func: `type ` is used
1587+ * if an explicit metaclass is given and it is *not * an instance of
1588+ :func: `type `, then it is used directly as the metaclass
1589+ * if an instance of :func: `type ` is given as the explicit metaclass, or
1590+ bases are defined, then the most derived metaclass is used
15951591
1596- * Otherwise, the default metaclass (:class: `type `) is used.
1592+ The most derived metaclass is selected from the explicitly specified
1593+ metaclass (if any) and the metaclasses (i.e. ``type(cls) ``) of all specified
1594+ base classes. The most derived metaclass is one which is a subtype of *all *
1595+ of these candidate metaclasses. If none of the candidate metaclasses meets
1596+ that criterion, then the class definition will fail with ``TypeError ``.
1597+
1598+
1599+ Preparing the class namespace
1600+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1601+
1602+ Once the appropriate metaclass has been identified, then the class namespace
1603+ is prepared. If the metaclass has a ``__prepare__ `` attribute, it is called
1604+ as ``namespace = metaclass.__prepare__(name, bases, **kwds) `` (where the
1605+ additional keyword arguments, if any, come from the class definition).
1606+
1607+ If the metaclass has no ``__prepare__ `` attribute, then the class namespace
1608+ is initialised as an empty :func: `dict ` instance.
1609+
1610+ .. seealso ::
1611+
1612+ :pep: `3115 ` - Metaclasses in Python 3000
1613+ Introduced the ``__prepare__ `` namespace hook
1614+
1615+
1616+ Executing the class body
1617+ ^^^^^^^^^^^^^^^^^^^^^^^^
1618+
1619+ The class body is executed (approximately) as
1620+ ``exec(body, globals(), namespace) ``. The key difference from a normal
1621+ call to :func: `exec ` is that lexical scoping allows the class body (including
1622+ any methods) to reference names from the current and outer scopes when the
1623+ class definition occurs inside a function.
1624+
1625+ However, even when the class definition occurs inside the function, methods
1626+ defined inside the class still cannot see names defined at the class scope.
1627+ Class variables must be accessed through the first parameter of instance or
1628+ class methods, and cannot be accessed at all from static methods.
1629+
1630+
1631+ Creating the class object
1632+ ^^^^^^^^^^^^^^^^^^^^^^^^^
1633+
1634+ Once the class namespace has been populated by executing the class body,
1635+ the class object is created by calling
1636+ ``metaclass(name, bases, namespace, **kwds) `` (the additional keywords
1637+ passed here are the same as those passed to ``__prepate__ ``).
1638+
1639+ This class object is the one that will be referenced by the zero-argument
1640+ form of :func: `super `. ``__class__ `` is an implicit closure reference
1641+ created by the compiler if any methods in a class body refer to either
1642+ ``__class__ `` or ``super ``. This allows the zero argument form of
1643+ :func: `super ` to correctly identify the class being defined based on
1644+ lexical scoping, while the class or instance that was used to make the
1645+ current call is identified based on the first argument passed to the method.
1646+
1647+ After the class object is created, any class decorators included in the
1648+ function definition are invoked and the resulting object is bound in the
1649+ local namespace to the name of the class.
1650+
1651+ .. seealso ::
1652+
1653+ :pep: `3135 ` - New super
1654+ Describes the implicit ``__class__ `` closure reference
1655+
1656+
1657+ Metaclass example
1658+ ^^^^^^^^^^^^^^^^^
15971659
15981660The potential uses for metaclasses are boundless. Some ideas that have been
1599- explored including logging, interface checking, automatic delegation, automatic
1661+ explored include logging, interface checking, automatic delegation, automatic
16001662property creation, proxies, frameworks, and automatic resource
16011663locking/synchronization.
16021664
@@ -1609,9 +1671,9 @@ to remember the order that class members were defined::
16091671 def __prepare__(metacls, name, bases, **kwds):
16101672 return collections.OrderedDict()
16111673
1612- def __new__(cls, name, bases, classdict ):
1613- result = type.__new__(cls, name, bases, dict(classdict ))
1614- result.members = tuple(classdict )
1674+ def __new__(cls, name, bases, namespace, **kwds ):
1675+ result = type.__new__(cls, name, bases, dict(namespace ))
1676+ result.members = tuple(namespace )
16151677 return result
16161678
16171679 class A(metaclass=OrderedClass):
0 commit comments