bpo-33816: Remove outdated metaclass example (GH-7566) · python/cpython@c2ccac7 (original) (raw)
`` @@ -1998,46 +1998,14 @@ becomes the :attr:~object.__dict__
attribute of the class object.
``
1998
1998
``` Describes the implicit __class__
closure reference
`1999`
`1999`
``
`2000`
`2000`
``
`2001`
``
`-
Metaclass example
`
`2002`
``
`-
^^^^^^^^^^^^^^^^^
`
``
`2001`
`+
Uses for metaclasses
`
``
`2002`
`+
^^^^^^^^^^^^^^^^^^^^
`
`2003`
`2003`
``
`2004`
`2004`
`The potential uses for metaclasses are boundless. Some ideas that have been
`
`2005`
`2005`
`explored include enum, logging, interface checking, automatic delegation,
`
`2006`
`2006`
`automatic property creation, proxies, frameworks, and automatic resource
`
`2007`
`2007`
`locking/synchronization.
`
`2008`
`2008`
``
`2009`
``
`` -
Here is an example of a metaclass that uses an :class:`collections.OrderedDict`
``
`2010`
``
`-
to remember the order that class variables are defined::
`
`2011`
``
`-`
`2012`
``
`-
class OrderedClass(type):
`
`2013`
``
`-`
`2014`
``
`-
@classmethod
`
`2015`
``
`-
def __prepare__(metacls, name, bases, **kwds):
`
`2016`
``
`-
return collections.OrderedDict()
`
`2017`
``
`-`
`2018`
``
`-
def __new__(cls, name, bases, namespace, **kwds):
`
`2019`
``
`-
result = type.__new__(cls, name, bases, dict(namespace))
`
`2020`
``
`-
result.members = tuple(namespace)
`
`2021`
``
`-
return result
`
`2022`
``
`-`
`2023`
``
`-
class A(metaclass=OrderedClass):
`
`2024`
``
`-
def one(self): pass
`
`2025`
``
`-
def two(self): pass
`
`2026`
``
`-
def three(self): pass
`
`2027`
``
`-
def four(self): pass
`
`2028`
``
`-`
`2029`
``
`-
>>> A.members
`
`2030`
``
`-
('__module__', 'one', 'two', 'three', 'four')
`
`2031`
``
`-`
`2032`
``
`-
When the class definition for *A* gets executed, the process begins with
`
`2033`
``
`` -
calling the metaclass's :meth:`__prepare__` method which returns an empty
``
`2034`
``
`` -
:class:`collections.OrderedDict`. That mapping records the methods and
``
`2035`
``
`-
attributes of *A* as they are defined within the body of the class statement.
`
`2036`
``
`-
Once those definitions are executed, the ordered dictionary is fully populated
`
`2037`
``
`` -
and the metaclass's :meth:`__new__` method gets invoked. That method builds
``
`2038`
``
`-
the new type and it saves the ordered dictionary keys in an attribute
`
`2039`
``
``` -
called ``members``.
2040
``
-
2041
2009
``
2042
2010
`Customizing instance and subclass checks
`
2043
2011
`----------------------------------------
`