diff options
author | Cheryl Sabella <cheryl.sabella@gmail.com> | 2018-01-27 02:45:24 (GMT) |
---|---|---|
committer | Nick Coghlan <ncoghlan@gmail.com> | 2018-01-27 02:45:24 (GMT) |
commit | 8f68cb7db37322cfeeb8338e78474e5f25d930c5 (patch) | |
tree | aac17f8a9f76f4d2ecd66c710b5da8bcc381bc62 | |
parent | 995c60d2656c022359aac3fe713d8464c8db5716 (diff) | |
download | cpython-8f68cb7db37322cfeeb8338e78474e5f25d930c5.zip cpython-8f68cb7db37322cfeeb8338e78474e5f25d930c5.tar.gz cpython-8f68cb7db37322cfeeb8338e78474e5f25d930c5.tar.bz2 |
[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.
-rw-r--r-- | Doc/reference/datamodel.rst | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index cd11020..9752494 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1500,6 +1500,39 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances. returned. :func:`dir` converts the returned sequence to a list and sorts it. +Customizing module attribute access +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. index:: + single: __class__ (module attribute) + +For a more fine grained customization of the module behavior (setting +attributes, properties, etc.), one can set the ``__class__`` attribute of +a module object to a subclass of :class:`types.ModuleType`. For example:: + + import sys + from types import ModuleType + + class VerboseModule(ModuleType): + def __repr__(self): + return f'Verbose {self.__name__}' + + def __setattr__(self, attr, value): + print(f'Setting {attr}...') + setattr(self, attr, value) + + sys.modules[__name__].__class__ = VerboseModule + +.. note:: + Setting module ``__class__`` only affects lookups made using the attribute + access syntax -- directly accessing the module globals (whether by code + within the module, or via a reference to the module's globals dictionary) + is unaffected. + +.. versionchanged:: 3.5 + ``__class__`` module attribute is now writable. + + .. _descriptors: Implementing Descriptors |