Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7fc570a

Browse files
committed
Close #14588: added a PEP 3115 compliant dynamic type creation mechanism
1 parent 7c5ba51 commit 7fc570a

7 files changed

Lines changed: 486 additions & 51 deletions

File tree

Doc/library/functions.rst

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1324,10 +1324,12 @@ are always available. They are listed here in alphabetical order.
13241324
Accordingly, :func:`super` is undefined for implicit lookups using statements or
13251325
operators such as ``super()[name]``.
13261326

1327-
Also note that :func:`super` is not limited to use inside methods. The two
1328-
argument form specifies the arguments exactly and makes the appropriate
1329-
references. The zero argument form automatically searches the stack frame
1330-
for the class (``__class__``) and the first argument.
1327+
Also note that, aside from the zero argument form, :func:`super` is not
1328+
limited to use inside methods. The two argument form specifies the
1329+
arguments exactly and makes the appropriate references. The zero
1330+
argument form only works inside a class definition, as the compiler fills
1331+
in the necessary details to correctly retrieve the class being defined,
1332+
as well as accessing the current instance for ordinary methods.
13311333

13321334
For practical suggestions on how to design cooperative classes using
13331335
:func:`super`, see `guide to using super()

Doc/library/types.rst

Lines changed: 58 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
:mod:`types` --- Names for built-in types
2-
=========================================
1+
:mod:`types` --- Dynamic type creation and names for built-in types
2+
===================================================================
33

44
.. module:: types
55
:synopsis: Names for built-in types.
@@ -8,20 +8,69 @@
88

99
--------------
1010

11-
This module defines names for some object types that are used by the standard
11+
This module defines utility function to assist in dynamic creation of
12+
new types.
13+
14+
It also defines names for some object types that are used by the standard
1215
Python interpreter, but not exposed as builtins like :class:`int` or
13-
:class:`str` are. Also, it does not include some of the types that arise
14-
transparently during processing such as the ``listiterator`` type.
16+
:class:`str` are.
17+
18+
19+
Dynamic Type Creation
20+
---------------------
21+
22+
.. function:: new_class(name, bases=(), kwds=None, exec_body=None)
23+
24+
Creates a class object dynamically using the appropriate metaclass.
25+
26+
The arguments are the components that make up a class definition: the
27+
class name, the base classes (in order), the keyword arguments (such as
28+
``metaclass``) and the callback function to populate the class namespace.
29+
30+
The *exec_body* callback should accept the class namespace as its sole
31+
argument and update the namespace directly with the class contents.
32+
33+
.. function:: prepare_class(name, bases=(), kwds=None)
34+
35+
Calculates the appropriate metaclass and creates the class namespace.
36+
37+
The arguments are the components that make up a class definition: the
38+
class name, the base classes (in order) and the keyword arguments (such as
39+
``metaclass``).
40+
41+
The return value is a 3-tuple: ``metaclass, namespace, kwds``
42+
43+
*metaclass* is the appropriate metaclass
44+
*namespace* is the prepared class namespace
45+
*kwds* is an updated copy of the passed in *kwds* argument with any
46+
``'metaclass'`` entry removed. If no *kwds* argument is passed in, this
47+
will be an empty dict.
48+
49+
50+
.. seealso::
51+
52+
:pep:`3115` - Metaclasses in Python 3000
53+
Introduced the ``__prepare__`` namespace hook
54+
55+
56+
Standard Interpreter Types
57+
--------------------------
58+
59+
This module provides names for many of the types that are required to
60+
implement a Python interpreter. It deliberately avoids including some of
61+
the types that arise only incidentally during processing such as the
62+
``listiterator`` type.
1563

16-
Typical use is for :func:`isinstance` or :func:`issubclass` checks.
64+
Typical use is of these names is for :func:`isinstance` or
65+
:func:`issubclass` checks.
1766

18-
The module defines the following names:
67+
Standard names are defined for the following types:
1968

2069
.. data:: FunctionType
2170
LambdaType
2271

23-
The type of user-defined functions and functions created by :keyword:`lambda`
24-
expressions.
72+
The type of user-defined functions and functions created by
73+
:keyword:`lambda` expressions.
2574

2675

2776
.. data:: GeneratorType

Doc/reference/datamodel.rst

Lines changed: 99 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1550,53 +1550,115 @@ Notes on using *__slots__*
15501550
Customizing 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

15981660
The 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
16001662
property creation, proxies, frameworks, and automatic resource
16011663
locking/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):

Doc/whatsnew/3.3.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1239,6 +1239,10 @@ Add a new :class:`types.MappingProxyType` class: Read-only proxy of a mapping.
12391239
(:issue:`14386`)
12401240

12411241

1242+
The new functions `types.new_class` and `types.prepare_class` provide support
1243+
for PEP 3115 compliant dynamic type creation. (:issue:`14588`)
1244+
1245+
12421246
urllib
12431247
------
12441248

0 commit comments

Comments
 (0)