bpo-33816: Remove outdated metaclass example (GH-7566) · python/cpython@46fa7a6 (original) (raw)
`` @@ -1918,46 +1918,14 @@ becomes the :attr:~object.__dict__
attribute of the class object.
``
1918
1918
``` Describes the implicit __class__
closure reference
`1919`
`1919`
``
`1920`
`1920`
``
`1921`
``
`-
Metaclass example
`
`1922`
``
`-
^^^^^^^^^^^^^^^^^
`
``
`1921`
`+
Uses for metaclasses
`
``
`1922`
`+
^^^^^^^^^^^^^^^^^^^^
`
`1923`
`1923`
``
`1924`
`1924`
`The potential uses for metaclasses are boundless. Some ideas that have been
`
`1925`
`1925`
`explored include enum, logging, interface checking, automatic delegation,
`
`1926`
`1926`
`automatic property creation, proxies, frameworks, and automatic resource
`
`1927`
`1927`
`locking/synchronization.
`
`1928`
`1928`
``
`1929`
``
`` -
Here is an example of a metaclass that uses an :class:`collections.OrderedDict`
``
`1930`
``
`-
to remember the order that class variables are defined::
`
`1931`
``
`-`
`1932`
``
`-
class OrderedClass(type):
`
`1933`
``
`-`
`1934`
``
`-
@classmethod
`
`1935`
``
`-
def __prepare__(metacls, name, bases, **kwds):
`
`1936`
``
`-
return collections.OrderedDict()
`
`1937`
``
`-`
`1938`
``
`-
def __new__(cls, name, bases, namespace, **kwds):
`
`1939`
``
`-
result = type.__new__(cls, name, bases, dict(namespace))
`
`1940`
``
`-
result.members = tuple(namespace)
`
`1941`
``
`-
return result
`
`1942`
``
`-`
`1943`
``
`-
class A(metaclass=OrderedClass):
`
`1944`
``
`-
def one(self): pass
`
`1945`
``
`-
def two(self): pass
`
`1946`
``
`-
def three(self): pass
`
`1947`
``
`-
def four(self): pass
`
`1948`
``
`-`
`1949`
``
`-
>>> A.members
`
`1950`
``
`-
('__module__', 'one', 'two', 'three', 'four')
`
`1951`
``
`-`
`1952`
``
`-
When the class definition for *A* gets executed, the process begins with
`
`1953`
``
`` -
calling the metaclass's :meth:`__prepare__` method which returns an empty
``
`1954`
``
`` -
:class:`collections.OrderedDict`. That mapping records the methods and
``
`1955`
``
`-
attributes of *A* as they are defined within the body of the class statement.
`
`1956`
``
`-
Once those definitions are executed, the ordered dictionary is fully populated
`
`1957`
``
`` -
and the metaclass's :meth:`__new__` method gets invoked. That method builds
``
`1958`
``
`-
the new type and it saves the ordered dictionary keys in an attribute
`
`1959`
``
``` -
called ``members``.
1960
``
-
1961
1929
``
1962
1930
`Customizing instance and subclass checks
`
1963
1931
`----------------------------------------
`