From 5e4b5754f4bb34f5f43f412e07064644ee797367 Mon Sep 17 00:00:00 2001 From: Cheryl Sabella Date: Thu, 25 Jan 2018 10:50:08 -0500 Subject: [PATCH 1/2] bpo-27505: Retrofit module __class__ documentation from 3.7 --- Doc/reference/datamodel.rst | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index cd11020e0dbc66..6c7089ef6c5b71 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. + +.. versionadded:: 3.5 + ``__class__`` module attribute. + + .. _descriptors: Implementing Descriptors From 0543bd7002865721bd167d0291778ae589ec3d90 Mon Sep 17 00:00:00 2001 From: Cheryl Sabella Date: Fri, 26 Jan 2018 09:24:13 -0500 Subject: [PATCH 2/2] Change from versionadded to versionchanged --- Doc/reference/datamodel.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 6c7089ef6c5b71..9752494972fff5 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1529,8 +1529,8 @@ a module object to a subclass of :class:`types.ModuleType`. For example:: within the module, or via a reference to the module's globals dictionary) is unaffected. -.. versionadded:: 3.5 - ``__class__`` module attribute. +.. versionchanged:: 3.5 + ``__class__`` module attribute is now writable. .. _descriptors: