bpo-33816: Remove outdated metaclass example (GH-7566) · python/cpython@1b80a37 (original) (raw)

`` @@ -1999,46 +1999,14 @@ becomes the :attr:~object.__dict__ attribute of the class object.

``

1999

1999

``` Describes the implicit __class__ closure reference


`2000`

`2000`

``

`2001`

`2001`

``

`2002`

``

`-

Metaclass example

`

`2003`

``

`-

^^^^^^^^^^^^^^^^^

`

``

`2002`

`+

Uses for metaclasses

`

``

`2003`

`+

^^^^^^^^^^^^^^^^^^^^

`

`2004`

`2004`

``

`2005`

`2005`

`The potential uses for metaclasses are boundless. Some ideas that have been

`

`2006`

`2006`

`explored include enum, logging, interface checking, automatic delegation,

`

`2007`

`2007`

`automatic property creation, proxies, frameworks, and automatic resource

`

`2008`

`2008`

`locking/synchronization.

`

`2009`

`2009`

``

`2010`

``

`` -

Here is an example of a metaclass that uses an :class:`collections.OrderedDict`

``

`2011`

``

`-

to remember the order that class variables are defined::

`

`2012`

``

`-`

`2013`

``

`-

class OrderedClass(type):

`

`2014`

``

`-`

`2015`

``

`-

@classmethod

`

`2016`

``

`-

def __prepare__(metacls, name, bases, **kwds):

`

`2017`

``

`-

return collections.OrderedDict()

`

`2018`

``

`-`

`2019`

``

`-

def __new__(cls, name, bases, namespace, **kwds):

`

`2020`

``

`-

result = type.__new__(cls, name, bases, dict(namespace))

`

`2021`

``

`-

result.members = tuple(namespace)

`

`2022`

``

`-

return result

`

`2023`

``

`-`

`2024`

``

`-

class A(metaclass=OrderedClass):

`

`2025`

``

`-

def one(self): pass

`

`2026`

``

`-

def two(self): pass

`

`2027`

``

`-

def three(self): pass

`

`2028`

``

`-

def four(self): pass

`

`2029`

``

`-`

`2030`

``

`-

>>> A.members

`

`2031`

``

`-

('__module__', 'one', 'two', 'three', 'four')

`

`2032`

``

`-`

`2033`

``

`-

When the class definition for *A* gets executed, the process begins with

`

`2034`

``

`` -

calling the metaclass's :meth:`__prepare__` method which returns an empty

``

`2035`

``

`` -

:class:`collections.OrderedDict`. That mapping records the methods and

``

`2036`

``

`-

attributes of *A* as they are defined within the body of the class statement.

`

`2037`

``

`-

Once those definitions are executed, the ordered dictionary is fully populated

`

`2038`

``

`` -

and the metaclass's :meth:`__new__` method gets invoked. That method builds

``

`2039`

``

`-

the new type and it saves the ordered dictionary keys in an attribute

`

`2040`

``

``` -

called ``members``.

2041

``

-

2042

2010

``

2043

2011

`Customizing instance and subclass checks

`

2044

2012

`----------------------------------------

`