Skip to content

[3.6] bpo-33816: Remove outdated metaclass example (GH-7566) #10568

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 16, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 2 additions & 34 deletions Doc/reference/datamodel.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1918,46 +1918,14 @@ becomes the :attr:`~object.__dict__` attribute of the class object.
Describes the implicit ``__class__`` closure reference


Metaclass example
^^^^^^^^^^^^^^^^^
Uses for metaclasses
^^^^^^^^^^^^^^^^^^^^

The potential uses for metaclasses are boundless. Some ideas that have been
explored include enum, logging, interface checking, automatic delegation,
automatic property creation, proxies, frameworks, and automatic resource
locking/synchronization.

Here is an example of a metaclass that uses an :class:`collections.OrderedDict`
to remember the order that class variables are defined::

class OrderedClass(type):

@classmethod
def __prepare__(metacls, name, bases, **kwds):
return collections.OrderedDict()

def __new__(cls, name, bases, namespace, **kwds):
result = type.__new__(cls, name, bases, dict(namespace))
result.members = tuple(namespace)
return result

class A(metaclass=OrderedClass):
def one(self): pass
def two(self): pass
def three(self): pass
def four(self): pass

>>> A.members
('__module__', 'one', 'two', 'three', 'four')

When the class definition for *A* gets executed, the process begins with
calling the metaclass's :meth:`__prepare__` method which returns an empty
:class:`collections.OrderedDict`. That mapping records the methods and
attributes of *A* as they are defined within the body of the class statement.
Once those definitions are executed, the ordered dictionary is fully populated
and the metaclass's :meth:`__new__` method gets invoked. That method builds
the new type and it saves the ordered dictionary keys in an attribute
called ``members``.


Customizing instance and subclass checks
----------------------------------------
Expand Down