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

Arup Rakshit ar at zeit.io
Thu Apr 25 02:00:28 EDT 2019


On 25/04/19 3:52 AM, Alan Gauld via Tutor wrote:
> On 24/04/2019 12:22, Arup Rakshit wrote:
>> In the simple code like what are the advantages we get from?
> I'm not really sure what you are asking about?
Ok. My question is that when people add such a class to the module? What 
is the goal/intention they met by setting such __class__ attribute of a 
module. The documentation I am reading just shown this technique but 
didn't dig into this. They didn't explain why/when should we use this 
technique, but the how.
>
>> Is this so that we can implement more special methods
>> than just __getattr__ and __dir__ in the module level?
> Is it just the inheritance from ModuleType?
>
> Or is it the assignment of the __class__ attribute?
Yes the reason of this assignment.
>
> Or something else?
>
>> 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}...')
>>          super().__setattr__(attr, value)
>> sys.modules[__name__].__class__ = VerboseModule
> There are many things in Python that are not generally used
> by ordinary Python programmers. In many cases these are things
> used by the core developers or are intended for advanced meta
> programming type tasks. As a general rule of thumb any time
> you see code that accesses dunder attributes (ie those with
> leading and trailing __ markers) directly it's probably an
> advanced technique you are unlikely to ever need...

That's a good catch. I am currently reading 
https://docs.python.org/3/reference/index.html source, and it seems like 
they touched everything possible in Python, without saying which is 
advance and which is basic part. Very often I get stuck, and coming here 
to ask and understand it. As the author didn't give the hints anything 
about what is advanced part, I am assuming these all a Python developer 
should know irrespective of their years of Python experience and keep 
readiing. But it feels like a lot in one go.


>
> But if you want to increase your understanding carry on
> asking but please be as specific as possible about what
> it is you want the answer to.
>

-- 
Thanks,

Arup Rakshit



More information about the Tutor mailing list