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

2019-04-24 Thread Arup Rakshit
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?

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

I can see a use of its when I play with the module as. Am I thinking it right, 
or there are other reasons of this setup?

import fine_grained_module

fine_grained_module.foo = "foo”
# Setting foo…

repr(fine_grained_module)
# 'Verbose fine_grained_module'



Thanks,

Arup Rakshit
a...@zeit.io



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


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

2019-04-24 Thread Alan Gauld via Tutor
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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor