[Tutor] When you think to setup the __class__ of a module object to a subclass of ModuleType
Steven D'Aprano
steve at pearwood.info
Fri Apr 26 01:40:57 EDT 2019
On Thu, Apr 25, 2019 at 02:52:07PM +0530, Arup Rakshit wrote:
> Here it is: *3.3.2.1. Customizing module attribute access*
> (https://docs.python.org/3/reference/datamodel.html#customizing-module-attribute-access)
Oh! That's brand new in 3.7, no wonder I didn't know about it.
I did see the core developers talking about adding this feature, but I
didn't know that they had done so.
Your original question was:
> In the simple code like what are the advantages we get from? Is this
> so that we can implement more special methods than just __getattr__
> and __dir__ in the module level?
Yes, that's what the documentation says. I don't see any reason not to
believe it.
Oh, this is cool! I'm going to enjoy playing with this...
py> from types import ModuleType
py> class Magic(ModuleType):
... count = 0
... @property
... def spam(self):
... self.count += 1
... return ' '.join(['spam']*self.count)
...
py> import sys
py> sys.modules['__main__'].__class__ = Magic
py> import __main__
py> __main__.spam
'spam'
py> __main__.spam
'spam spam'
py> __main__.spam
'spam spam spam'
--
Steven
More information about the Tutor
mailing list