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

Alan Gauld alan.gauld at yahoo.co.uk
Wed Apr 24 18:22:44 EDT 2019


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?

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

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

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.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list