[Tutor] When you think to setup the __class__ of a module object to a subclass of ModuleType

Arup Rakshit ar at zeit.io
Fri Apr 26 08:48:32 EDT 2019


On 26/04/19 11:10 AM, Steven D'Aprano wrote:
> 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.


Well I believed it, but I was not sure if I understood it correctly. So 
I was trying to confirm myself by those who understand the language.


BTW, one thing I would like to know about this list is that, everytime I 
send an email I see it the in list after 2 hours approx. Is this for me 
or everybody? I am just curious.


>
> 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'
>
>
>

-- 
Thanks,

Arup Rakshit



More information about the Tutor mailing list