Skip to content

Commit 8f68cb7

Browse files
csabellancoghlan
authored andcommitted
[3.6] bpo-27505: Retrofit module __class__ documentation from 3.7 (GH-5321)
The module `__class__` attribute documentation added to 3.7 for PEP 562 (dynamic module attributes) also applies to earlier versions. This backports that subset of the new docs to the 3.6 branch so that it will appear in the main online documentation and in the final 3.6 binary release. Patch by Cheryl Sabella.
1 parent 995c60d commit 8f68cb7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Doc/reference/datamodel.rst

+33
Original file line numberDiff line numberDiff line change
@@ -1500,6 +1500,39 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.
15001500
returned. :func:`dir` converts the returned sequence to a list and sorts it.
15011501

15021502

1503+
Customizing module attribute access
1504+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1505+
1506+
.. index::
1507+
single: __class__ (module attribute)
1508+
1509+
For a more fine grained customization of the module behavior (setting
1510+
attributes, properties, etc.), one can set the ``__class__`` attribute of
1511+
a module object to a subclass of :class:`types.ModuleType`. For example::
1512+
1513+
import sys
1514+
from types import ModuleType
1515+
1516+
class VerboseModule(ModuleType):
1517+
def __repr__(self):
1518+
return f'Verbose {self.__name__}'
1519+
1520+
def __setattr__(self, attr, value):
1521+
print(f'Setting {attr}...')
1522+
setattr(self, attr, value)
1523+
1524+
sys.modules[__name__].__class__ = VerboseModule
1525+
1526+
.. note::
1527+
Setting module ``__class__`` only affects lookups made using the attribute
1528+
access syntax -- directly accessing the module globals (whether by code
1529+
within the module, or via a reference to the module's globals dictionary)
1530+
is unaffected.
1531+
1532+
.. versionchanged:: 3.5
1533+
``__class__`` module attribute is now writable.
1534+
1535+
15031536
.. _descriptors:
15041537

15051538
Implementing Descriptors

0 commit comments

Comments
 (0)