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

Arup Rakshit ar at zeit.io
Wed Apr 24 07:22:33 EDT 2019


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
ar at zeit.io





More information about the Tutor mailing list